import { createRequire } from "node:module";
var __create = Object.create;
var __getProtoOf = Object.getPrototypeOf;
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __toESM = (mod, isNodeMode, target) => {
  target = mod != null ? __create(__getProtoOf(mod)) : {};
  const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
  for (let key of __getOwnPropNames(mod))
    if (!__hasOwnProp.call(to, key))
      __defProp(to, key, {
        get: () => mod[key],
        enumerable: true
      });
  return to;
};
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, {
      get: all[name],
      enumerable: true,
      configurable: true,
      set: (newValue) => all[name] = () => newValue
    });
};
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __require = /* @__PURE__ */ createRequire(import.meta.url);

// node_modules/ssf/ssf.js
var require_ssf = __commonJS((exports, module) => {
  var SSF = {};
  var make_ssf = function make_ssf(SSF2) {
    SSF2.version = "0.11.2";
    function _strrev(x) {
      var o = "", i = x.length - 1;
      while (i >= 0)
        o += x.charAt(i--);
      return o;
    }
    function fill(c, l) {
      var o = "";
      while (o.length < l)
        o += c;
      return o;
    }
    function pad0(v, d) {
      var t = "" + v;
      return t.length >= d ? t : fill("0", d - t.length) + t;
    }
    function pad_(v, d) {
      var t = "" + v;
      return t.length >= d ? t : fill(" ", d - t.length) + t;
    }
    function rpad_(v, d) {
      var t = "" + v;
      return t.length >= d ? t : t + fill(" ", d - t.length);
    }
    function pad0r1(v, d) {
      var t = "" + Math.round(v);
      return t.length >= d ? t : fill("0", d - t.length) + t;
    }
    function pad0r2(v, d) {
      var t = "" + v;
      return t.length >= d ? t : fill("0", d - t.length) + t;
    }
    var p2_32 = Math.pow(2, 32);
    function pad0r(v, d) {
      if (v > p2_32 || v < -p2_32)
        return pad0r1(v, d);
      var i = Math.round(v);
      return pad0r2(i, d);
    }
    function isgeneral(s, i) {
      i = i || 0;
      return s.length >= 7 + i && (s.charCodeAt(i) | 32) === 103 && (s.charCodeAt(i + 1) | 32) === 101 && (s.charCodeAt(i + 2) | 32) === 110 && (s.charCodeAt(i + 3) | 32) === 101 && (s.charCodeAt(i + 4) | 32) === 114 && (s.charCodeAt(i + 5) | 32) === 97 && (s.charCodeAt(i + 6) | 32) === 108;
    }
    var days = [
      ["Sun", "Sunday"],
      ["Mon", "Monday"],
      ["Tue", "Tuesday"],
      ["Wed", "Wednesday"],
      ["Thu", "Thursday"],
      ["Fri", "Friday"],
      ["Sat", "Saturday"]
    ];
    var months = [
      ["J", "Jan", "January"],
      ["F", "Feb", "February"],
      ["M", "Mar", "March"],
      ["A", "Apr", "April"],
      ["M", "May", "May"],
      ["J", "Jun", "June"],
      ["J", "Jul", "July"],
      ["A", "Aug", "August"],
      ["S", "Sep", "September"],
      ["O", "Oct", "October"],
      ["N", "Nov", "November"],
      ["D", "Dec", "December"]
    ];
    function init_table(t) {
      t[0] = "General";
      t[1] = "0";
      t[2] = "0.00";
      t[3] = "#,##0";
      t[4] = "#,##0.00";
      t[9] = "0%";
      t[10] = "0.00%";
      t[11] = "0.00E+00";
      t[12] = "# ?/?";
      t[13] = "# ??/??";
      t[14] = "m/d/yy";
      t[15] = "d-mmm-yy";
      t[16] = "d-mmm";
      t[17] = "mmm-yy";
      t[18] = "h:mm AM/PM";
      t[19] = "h:mm:ss AM/PM";
      t[20] = "h:mm";
      t[21] = "h:mm:ss";
      t[22] = "m/d/yy h:mm";
      t[37] = "#,##0 ;(#,##0)";
      t[38] = "#,##0 ;[Red](#,##0)";
      t[39] = "#,##0.00;(#,##0.00)";
      t[40] = "#,##0.00;[Red](#,##0.00)";
      t[45] = "mm:ss";
      t[46] = "[h]:mm:ss";
      t[47] = "mmss.0";
      t[48] = "##0.0E+0";
      t[49] = "@";
      t[56] = '"上午/下午 "hh"時"mm"分"ss"秒 "';
    }
    var table_fmt = {};
    init_table(table_fmt);
    var default_map = [];
    var defi = 0;
    for (defi = 5;defi <= 8; ++defi)
      default_map[defi] = 32 + defi;
    for (defi = 23;defi <= 26; ++defi)
      default_map[defi] = 0;
    for (defi = 27;defi <= 31; ++defi)
      default_map[defi] = 14;
    for (defi = 50;defi <= 58; ++defi)
      default_map[defi] = 14;
    for (defi = 59;defi <= 62; ++defi)
      default_map[defi] = defi - 58;
    for (defi = 67;defi <= 68; ++defi)
      default_map[defi] = defi - 58;
    for (defi = 72;defi <= 75; ++defi)
      default_map[defi] = defi - 58;
    for (defi = 67;defi <= 68; ++defi)
      default_map[defi] = defi - 57;
    for (defi = 76;defi <= 78; ++defi)
      default_map[defi] = defi - 56;
    for (defi = 79;defi <= 81; ++defi)
      default_map[defi] = defi - 34;
    var default_str = [];
    default_str[5] = default_str[63] = '"$"#,##0_);\\("$"#,##0\\)';
    default_str[6] = default_str[64] = '"$"#,##0_);[Red]\\("$"#,##0\\)';
    default_str[7] = default_str[65] = '"$"#,##0.00_);\\("$"#,##0.00\\)';
    default_str[8] = default_str[66] = '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)';
    default_str[41] = '_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)';
    default_str[42] = '_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)';
    default_str[43] = '_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)';
    default_str[44] = '_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)';
    function frac(x, D, mixed) {
      var sgn = x < 0 ? -1 : 1;
      var B = x * sgn;
      var P_2 = 0, P_1 = 1, P = 0;
      var Q_2 = 1, Q_1 = 0, Q = 0;
      var A = Math.floor(B);
      while (Q_1 < D) {
        A = Math.floor(B);
        P = A * P_1 + P_2;
        Q = A * Q_1 + Q_2;
        if (B - A < 0.00000005)
          break;
        B = 1 / (B - A);
        P_2 = P_1;
        P_1 = P;
        Q_2 = Q_1;
        Q_1 = Q;
      }
      if (Q > D) {
        if (Q_1 > D) {
          Q = Q_2;
          P = P_2;
        } else {
          Q = Q_1;
          P = P_1;
        }
      }
      if (!mixed)
        return [0, sgn * P, Q];
      var q = Math.floor(sgn * P / Q);
      return [q, sgn * P - q * Q, Q];
    }
    function parse_date_code(v, opts, b2) {
      if (v > 2958465 || v < 0)
        return null;
      var date = v | 0, time = Math.floor(86400 * (v - date)), dow = 0;
      var dout = [];
      var out = { D: date, T: time, u: 86400 * (v - date) - time, y: 0, m: 0, d: 0, H: 0, M: 0, S: 0, q: 0 };
      if (Math.abs(out.u) < 0.000001)
        out.u = 0;
      if (opts && opts.date1904)
        date += 1462;
      if (out.u > 0.9999) {
        out.u = 0;
        if (++time == 86400) {
          out.T = time = 0;
          ++date;
          ++out.D;
        }
      }
      if (date === 60) {
        dout = b2 ? [1317, 10, 29] : [1900, 2, 29];
        dow = 3;
      } else if (date === 0) {
        dout = b2 ? [1317, 8, 29] : [1900, 1, 0];
        dow = 6;
      } else {
        if (date > 60)
          --date;
        var d = new Date(1900, 0, 1);
        d.setDate(d.getDate() + date - 1);
        dout = [d.getFullYear(), d.getMonth() + 1, d.getDate()];
        dow = d.getDay();
        if (date < 60)
          dow = (dow + 6) % 7;
        if (b2)
          dow = fix_hijri(d, dout);
      }
      out.y = dout[0];
      out.m = dout[1];
      out.d = dout[2];
      out.S = time % 60;
      time = Math.floor(time / 60);
      out.M = time % 60;
      time = Math.floor(time / 60);
      out.H = time;
      out.q = dow;
      return out;
    }
    SSF2.parse_date_code = parse_date_code;
    var basedate = new Date(1899, 11, 31, 0, 0, 0);
    var dnthresh = basedate.getTime();
    var base1904 = new Date(1900, 2, 1, 0, 0, 0);
    function datenum_local(v, date1904) {
      var epoch = v.getTime();
      if (date1904)
        epoch -= 1461 * 24 * 60 * 60 * 1000;
      else if (v >= base1904)
        epoch += 24 * 60 * 60 * 1000;
      return (epoch - (dnthresh + (v.getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000)) / (24 * 60 * 60 * 1000);
    }
    function general_fmt_int(v) {
      return v.toString(10);
    }
    SSF2._general_int = general_fmt_int;
    var general_fmt_num = function make_general_fmt_num() {
      var trailing_zeroes_and_decimal = /(?:\.0*|(\.\d*[1-9])0+)$/;
      function strip_decimal(o) {
        return o.indexOf(".") == -1 ? o : o.replace(trailing_zeroes_and_decimal, "$1");
      }
      var mantissa_zeroes_and_decimal = /(?:\.0*|(\.\d*[1-9])0+)[Ee]/;
      var exp_with_single_digit = /(E[+-])(\d)$/;
      function normalize_exp(o) {
        if (o.indexOf("E") == -1)
          return o;
        return o.replace(mantissa_zeroes_and_decimal, "$1E").replace(exp_with_single_digit, "$10$2");
      }
      function small_exp(v) {
        var w = v < 0 ? 12 : 11;
        var o = strip_decimal(v.toFixed(12));
        if (o.length <= w)
          return o;
        o = v.toPrecision(10);
        if (o.length <= w)
          return o;
        return v.toExponential(5);
      }
      function large_exp(v) {
        var o = strip_decimal(v.toFixed(11));
        return o.length > (v < 0 ? 12 : 11) || o === "0" || o === "-0" ? v.toPrecision(6) : o;
      }
      function general_fmt_num_base(v) {
        var V = Math.floor(Math.log(Math.abs(v)) * Math.LOG10E), o;
        if (V >= -4 && V <= -1)
          o = v.toPrecision(10 + V);
        else if (Math.abs(V) <= 9)
          o = small_exp(v);
        else if (V === 10)
          o = v.toFixed(10).substr(0, 12);
        else
          o = large_exp(v);
        return strip_decimal(normalize_exp(o.toUpperCase()));
      }
      return general_fmt_num_base;
    }();
    SSF2._general_num = general_fmt_num;
    function general_fmt(v, opts) {
      switch (typeof v) {
        case "string":
          return v;
        case "boolean":
          return v ? "TRUE" : "FALSE";
        case "number":
          return (v | 0) === v ? v.toString(10) : general_fmt_num(v);
        case "undefined":
          return "";
        case "object":
          if (v == null)
            return "";
          if (v instanceof Date)
            return format2(14, datenum_local(v, opts && opts.date1904), opts);
      }
      throw new Error("unsupported value in General format: " + v);
    }
    SSF2._general = general_fmt;
    function fix_hijri(date, o) {
      o[0] -= 581;
      var dow = date.getDay();
      if (date < 60)
        dow = (dow + 6) % 7;
      return dow;
    }
    var THAI_DIGITS = "๐๑๒๓๔๕๖๗๘๙".split("");
    function write_date(type, fmt, val, ss0) {
      var o = "", ss = 0, tt = 0, y = val.y, out, outl = 0;
      switch (type) {
        case 98:
          y = val.y + 543;
        case 121:
          switch (fmt.length) {
            case 1:
            case 2:
              out = y % 100;
              outl = 2;
              break;
            default:
              out = y % 1e4;
              outl = 4;
              break;
          }
          break;
        case 109:
          switch (fmt.length) {
            case 1:
            case 2:
              out = val.m;
              outl = fmt.length;
              break;
            case 3:
              return months[val.m - 1][1];
            case 5:
              return months[val.m - 1][0];
            default:
              return months[val.m - 1][2];
          }
          break;
        case 100:
          switch (fmt.length) {
            case 1:
            case 2:
              out = val.d;
              outl = fmt.length;
              break;
            case 3:
              return days[val.q][0];
            default:
              return days[val.q][1];
          }
          break;
        case 104:
          switch (fmt.length) {
            case 1:
            case 2:
              out = 1 + (val.H + 11) % 12;
              outl = fmt.length;
              break;
            default:
              throw "bad hour format: " + fmt;
          }
          break;
        case 72:
          switch (fmt.length) {
            case 1:
            case 2:
              out = val.H;
              outl = fmt.length;
              break;
            default:
              throw "bad hour format: " + fmt;
          }
          break;
        case 77:
          switch (fmt.length) {
            case 1:
            case 2:
              out = val.M;
              outl = fmt.length;
              break;
            default:
              throw "bad minute format: " + fmt;
          }
          break;
        case 115:
          if (fmt != "s" && fmt != "ss" && fmt != ".0" && fmt != ".00" && fmt != ".000")
            throw "bad second format: " + fmt;
          if (val.u === 0 && (fmt == "s" || fmt == "ss"))
            return pad0(val.S, fmt.length);
          if (ss0 >= 2)
            tt = ss0 === 3 ? 1000 : 100;
          else
            tt = ss0 === 1 ? 10 : 1;
          ss = Math.round(tt * (val.S + val.u));
          if (ss >= 60 * tt)
            ss = 0;
          if (fmt === "s")
            return ss === 0 ? "0" : "" + ss / tt;
          o = pad0(ss, 2 + ss0);
          if (fmt === "ss")
            return o.substr(0, 2);
          return "." + o.substr(2, fmt.length - 1);
        case 90:
          switch (fmt) {
            case "[h]":
            case "[hh]":
              out = val.D * 24 + val.H;
              break;
            case "[m]":
            case "[mm]":
              out = (val.D * 24 + val.H) * 60 + val.M;
              break;
            case "[s]":
            case "[ss]":
              out = ((val.D * 24 + val.H) * 60 + val.M) * 60 + Math.round(val.S + val.u);
              break;
            default:
              throw "bad abstime format: " + fmt;
          }
          outl = fmt.length === 3 ? 1 : 2;
          break;
        case 101:
          out = y;
          outl = 1;
          break;
      }
      var outstr = outl > 0 ? pad0(out, outl) : "";
      return outstr;
    }
    function commaify(s) {
      var w = 3;
      if (s.length <= w)
        return s;
      var j = s.length % w, o = s.substr(0, j);
      for (;j != s.length; j += w)
        o += (o.length > 0 ? "," : "") + s.substr(j, w);
      return o;
    }
    var write_num = function make_write_num() {
      var pct1 = /%/g;
      function write_num_pct(type, fmt, val) {
        var sfmt = fmt.replace(pct1, ""), mul = fmt.length - sfmt.length;
        return write_num(type, sfmt, val * Math.pow(10, 2 * mul)) + fill("%", mul);
      }
      function write_num_cm(type, fmt, val) {
        var idx = fmt.length - 1;
        while (fmt.charCodeAt(idx - 1) === 44)
          --idx;
        return write_num(type, fmt.substr(0, idx), val / Math.pow(10, 3 * (fmt.length - idx)));
      }
      function write_num_exp(fmt, val) {
        var o;
        var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
        if (fmt.match(/^#+0.0E\+0$/)) {
          if (val == 0)
            return "0.0E+0";
          else if (val < 0)
            return "-" + write_num_exp(fmt, -val);
          var period = fmt.indexOf(".");
          if (period === -1)
            period = fmt.indexOf("E");
          var ee = Math.floor(Math.log(val) * Math.LOG10E) % period;
          if (ee < 0)
            ee += period;
          o = (val / Math.pow(10, ee)).toPrecision(idx + 1 + (period + ee) % period);
          if (o.indexOf("e") === -1) {
            var fakee = Math.floor(Math.log(val) * Math.LOG10E);
            if (o.indexOf(".") === -1)
              o = o.charAt(0) + "." + o.substr(1) + "E+" + (fakee - o.length + ee);
            else
              o += "E+" + (fakee - ee);
            while (o.substr(0, 2) === "0.") {
              o = o.charAt(0) + o.substr(2, period) + "." + o.substr(2 + period);
              o = o.replace(/^0+([1-9])/, "$1").replace(/^0+\./, "0.");
            }
            o = o.replace(/\+-/, "-");
          }
          o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/, function($$, $1, $2, $3) {
            return $1 + $2 + $3.substr(0, (period + ee) % period) + "." + $3.substr(ee) + "E";
          });
        } else
          o = val.toExponential(idx);
        if (fmt.match(/E\+00$/) && o.match(/e[+-]\d$/))
          o = o.substr(0, o.length - 1) + "0" + o.charAt(o.length - 1);
        if (fmt.match(/E\-/) && o.match(/e\+/))
          o = o.replace(/e\+/, "e");
        return o.replace("e", "E");
      }
      var frac1 = /# (\?+)( ?)\/( ?)(\d+)/;
      function write_num_f1(r, aval, sign) {
        var den = parseInt(r[4], 10), rr = Math.round(aval * den), base = Math.floor(rr / den);
        var myn = rr - base * den, myd = den;
        return sign + (base === 0 ? "" : "" + base) + " " + (myn === 0 ? fill(" ", r[1].length + 1 + r[4].length) : pad_(myn, r[1].length) + r[2] + "/" + r[3] + pad0(myd, r[4].length));
      }
      function write_num_f2(r, aval, sign) {
        return sign + (aval === 0 ? "" : "" + aval) + fill(" ", r[1].length + 2 + r[4].length);
      }
      var dec1 = /^#*0*\.([0#]+)/;
      var closeparen = /\).*[0#]/;
      var phone = /\(###\) ###\\?-####/;
      function hashq(str) {
        var o = "", cc;
        for (var i = 0;i != str.length; ++i)
          switch (cc = str.charCodeAt(i)) {
            case 35:
              break;
            case 63:
              o += " ";
              break;
            case 48:
              o += "0";
              break;
            default:
              o += String.fromCharCode(cc);
          }
        return o;
      }
      function rnd(val, d) {
        var dd = Math.pow(10, d);
        return "" + Math.round(val * dd) / dd;
      }
      function dec(val, d) {
        var _frac = val - Math.floor(val), dd = Math.pow(10, d);
        if (d < ("" + Math.round(_frac * dd)).length)
          return 0;
        return Math.round(_frac * dd);
      }
      function carry(val, d) {
        if (d < ("" + Math.round((val - Math.floor(val)) * Math.pow(10, d))).length) {
          return 1;
        }
        return 0;
      }
      function flr(val) {
        if (val < 2147483647 && val > -2147483648)
          return "" + (val >= 0 ? val | 0 : val - 1 | 0);
        return "" + Math.floor(val);
      }
      function write_num_flt(type, fmt, val) {
        if (type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
          var ffmt = fmt.replace(/\( */, "").replace(/ \)/, "").replace(/\)/, "");
          if (val >= 0)
            return write_num_flt("n", ffmt, val);
          return "(" + write_num_flt("n", ffmt, -val) + ")";
        }
        if (fmt.charCodeAt(fmt.length - 1) === 44)
          return write_num_cm(type, fmt, val);
        if (fmt.indexOf("%") !== -1)
          return write_num_pct(type, fmt, val);
        if (fmt.indexOf("E") !== -1)
          return write_num_exp(fmt, val);
        if (fmt.charCodeAt(0) === 36)
          return "$" + write_num_flt(type, fmt.substr(fmt.charAt(1) == " " ? 2 : 1), val);
        var o;
        var r, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : "";
        if (fmt.match(/^00+$/))
          return sign + pad0r(aval, fmt.length);
        if (fmt.match(/^[#?]+$/)) {
          o = pad0r(val, 0);
          if (o === "0")
            o = "";
          return o.length > fmt.length ? o : hashq(fmt.substr(0, fmt.length - o.length)) + o;
        }
        if (r = fmt.match(frac1))
          return write_num_f1(r, aval, sign);
        if (fmt.match(/^#+0+$/))
          return sign + pad0r(aval, fmt.length - fmt.indexOf("0"));
        if (r = fmt.match(dec1)) {
          o = rnd(val, r[1].length).replace(/^([^\.]+)$/, "$1." + hashq(r[1])).replace(/\.$/, "." + hashq(r[1])).replace(/\.(\d*)$/, function($$, $1) {
            return "." + $1 + fill("0", hashq(r[1]).length - $1.length);
          });
          return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./, ".");
        }
        fmt = fmt.replace(/^#+([0.])/, "$1");
        if (r = fmt.match(/^(0*)\.(#*)$/)) {
          return sign + rnd(aval, r[2].length).replace(/\.(\d*[1-9])0*$/, ".$1").replace(/^(-?\d*)$/, "$1.").replace(/^0\./, r[1].length ? "0." : ".");
        }
        if (r = fmt.match(/^#{1,3},##0(\.?)$/))
          return sign + commaify(pad0r(aval, 0));
        if (r = fmt.match(/^#,##0\.([#0]*0)$/)) {
          return val < 0 ? "-" + write_num_flt(type, fmt, -val) : commaify("" + (Math.floor(val) + carry(val, r[1].length))) + "." + pad0(dec(val, r[1].length), r[1].length);
        }
        if (r = fmt.match(/^#,#*,#0/))
          return write_num_flt(type, fmt.replace(/^#,#*,/, ""), val);
        if (r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/)) {
          o = _strrev(write_num_flt(type, fmt.replace(/[\\-]/g, ""), val));
          ri = 0;
          return _strrev(_strrev(fmt.replace(/\\/g, "")).replace(/[0#]/g, function(x2) {
            return ri < o.length ? o.charAt(ri++) : x2 === "0" ? "0" : "";
          }));
        }
        if (fmt.match(phone)) {
          o = write_num_flt(type, "##########", val);
          return "(" + o.substr(0, 3) + ") " + o.substr(3, 3) + "-" + o.substr(6);
        }
        var oa = "";
        if (r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/)) {
          ri = Math.min(r[4].length, 7);
          ff = frac(aval, Math.pow(10, ri) - 1, false);
          o = "" + sign;
          oa = write_num("n", r[1], ff[1]);
          if (oa.charAt(oa.length - 1) == " ")
            oa = oa.substr(0, oa.length - 1) + "0";
          o += oa + r[2] + "/" + r[3];
          oa = rpad_(ff[2], ri);
          if (oa.length < r[4].length)
            oa = hashq(r[4].substr(r[4].length - oa.length)) + oa;
          o += oa;
          return o;
        }
        if (r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/)) {
          ri = Math.min(Math.max(r[1].length, r[4].length), 7);
          ff = frac(aval, Math.pow(10, ri) - 1, true);
          return sign + (ff[0] || (ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1], ri) + r[2] + "/" + r[3] + rpad_(ff[2], ri) : fill(" ", 2 * ri + 1 + r[2].length + r[3].length));
        }
        if (r = fmt.match(/^[#0?]+$/)) {
          o = pad0r(val, 0);
          if (fmt.length <= o.length)
            return o;
          return hashq(fmt.substr(0, fmt.length - o.length)) + o;
        }
        if (r = fmt.match(/^([#0?]+)\.([#0]+)$/)) {
          o = "" + val.toFixed(Math.min(r[2].length, 10)).replace(/([^0])0+$/, "$1");
          ri = o.indexOf(".");
          var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres;
          return hashq(fmt.substr(0, lres) + o + fmt.substr(fmt.length - rres));
        }
        if (r = fmt.match(/^00,000\.([#0]*0)$/)) {
          ri = dec(val, r[1].length);
          return val < 0 ? "-" + write_num_flt(type, fmt, -val) : commaify(flr(val)).replace(/^\d,\d{3}$/, "0$&").replace(/^\d*$/, function($$) {
            return "00," + ($$.length < 3 ? pad0(0, 3 - $$.length) : "") + $$;
          }) + "." + pad0(ri, r[1].length);
        }
        switch (fmt) {
          case "###,##0.00":
            return write_num_flt(type, "#,##0.00", val);
          case "###,###":
          case "##,###":
          case "#,###":
            var x = commaify(pad0r(aval, 0));
            return x !== "0" ? sign + x : "";
          case "###,###.00":
            return write_num_flt(type, "###,##0.00", val).replace(/^0\./, ".");
          case "#,###.00":
            return write_num_flt(type, "#,##0.00", val).replace(/^0\./, ".");
          default:
        }
        throw new Error("unsupported format |" + fmt + "|");
      }
      function write_num_cm2(type, fmt, val) {
        var idx = fmt.length - 1;
        while (fmt.charCodeAt(idx - 1) === 44)
          --idx;
        return write_num(type, fmt.substr(0, idx), val / Math.pow(10, 3 * (fmt.length - idx)));
      }
      function write_num_pct2(type, fmt, val) {
        var sfmt = fmt.replace(pct1, ""), mul = fmt.length - sfmt.length;
        return write_num(type, sfmt, val * Math.pow(10, 2 * mul)) + fill("%", mul);
      }
      function write_num_exp2(fmt, val) {
        var o;
        var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
        if (fmt.match(/^#+0.0E\+0$/)) {
          if (val == 0)
            return "0.0E+0";
          else if (val < 0)
            return "-" + write_num_exp2(fmt, -val);
          var period = fmt.indexOf(".");
          if (period === -1)
            period = fmt.indexOf("E");
          var ee = Math.floor(Math.log(val) * Math.LOG10E) % period;
          if (ee < 0)
            ee += period;
          o = (val / Math.pow(10, ee)).toPrecision(idx + 1 + (period + ee) % period);
          if (!o.match(/[Ee]/)) {
            var fakee = Math.floor(Math.log(val) * Math.LOG10E);
            if (o.indexOf(".") === -1)
              o = o.charAt(0) + "." + o.substr(1) + "E+" + (fakee - o.length + ee);
            else
              o += "E+" + (fakee - ee);
            o = o.replace(/\+-/, "-");
          }
          o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/, function($$, $1, $2, $3) {
            return $1 + $2 + $3.substr(0, (period + ee) % period) + "." + $3.substr(ee) + "E";
          });
        } else
          o = val.toExponential(idx);
        if (fmt.match(/E\+00$/) && o.match(/e[+-]\d$/))
          o = o.substr(0, o.length - 1) + "0" + o.charAt(o.length - 1);
        if (fmt.match(/E\-/) && o.match(/e\+/))
          o = o.replace(/e\+/, "e");
        return o.replace("e", "E");
      }
      function write_num_int(type, fmt, val) {
        if (type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
          var ffmt = fmt.replace(/\( */, "").replace(/ \)/, "").replace(/\)/, "");
          if (val >= 0)
            return write_num_int("n", ffmt, val);
          return "(" + write_num_int("n", ffmt, -val) + ")";
        }
        if (fmt.charCodeAt(fmt.length - 1) === 44)
          return write_num_cm2(type, fmt, val);
        if (fmt.indexOf("%") !== -1)
          return write_num_pct2(type, fmt, val);
        if (fmt.indexOf("E") !== -1)
          return write_num_exp2(fmt, val);
        if (fmt.charCodeAt(0) === 36)
          return "$" + write_num_int(type, fmt.substr(fmt.charAt(1) == " " ? 2 : 1), val);
        var o;
        var r, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : "";
        if (fmt.match(/^00+$/))
          return sign + pad0(aval, fmt.length);
        if (fmt.match(/^[#?]+$/)) {
          o = "" + val;
          if (val === 0)
            o = "";
          return o.length > fmt.length ? o : hashq(fmt.substr(0, fmt.length - o.length)) + o;
        }
        if (r = fmt.match(frac1))
          return write_num_f2(r, aval, sign);
        if (fmt.match(/^#+0+$/))
          return sign + pad0(aval, fmt.length - fmt.indexOf("0"));
        if (r = fmt.match(dec1)) {
          o = ("" + val).replace(/^([^\.]+)$/, "$1." + hashq(r[1])).replace(/\.$/, "." + hashq(r[1]));
          o = o.replace(/\.(\d*)$/, function($$, $1) {
            return "." + $1 + fill("0", hashq(r[1]).length - $1.length);
          });
          return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./, ".");
        }
        fmt = fmt.replace(/^#+([0.])/, "$1");
        if (r = fmt.match(/^(0*)\.(#*)$/)) {
          return sign + ("" + aval).replace(/\.(\d*[1-9])0*$/, ".$1").replace(/^(-?\d*)$/, "$1.").replace(/^0\./, r[1].length ? "0." : ".");
        }
        if (r = fmt.match(/^#{1,3},##0(\.?)$/))
          return sign + commaify("" + aval);
        if (r = fmt.match(/^#,##0\.([#0]*0)$/)) {
          return val < 0 ? "-" + write_num_int(type, fmt, -val) : commaify("" + val) + "." + fill("0", r[1].length);
        }
        if (r = fmt.match(/^#,#*,#0/))
          return write_num_int(type, fmt.replace(/^#,#*,/, ""), val);
        if (r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/)) {
          o = _strrev(write_num_int(type, fmt.replace(/[\\-]/g, ""), val));
          ri = 0;
          return _strrev(_strrev(fmt.replace(/\\/g, "")).replace(/[0#]/g, function(x2) {
            return ri < o.length ? o.charAt(ri++) : x2 === "0" ? "0" : "";
          }));
        }
        if (fmt.match(phone)) {
          o = write_num_int(type, "##########", val);
          return "(" + o.substr(0, 3) + ") " + o.substr(3, 3) + "-" + o.substr(6);
        }
        var oa = "";
        if (r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/)) {
          ri = Math.min(r[4].length, 7);
          ff = frac(aval, Math.pow(10, ri) - 1, false);
          o = "" + sign;
          oa = write_num("n", r[1], ff[1]);
          if (oa.charAt(oa.length - 1) == " ")
            oa = oa.substr(0, oa.length - 1) + "0";
          o += oa + r[2] + "/" + r[3];
          oa = rpad_(ff[2], ri);
          if (oa.length < r[4].length)
            oa = hashq(r[4].substr(r[4].length - oa.length)) + oa;
          o += oa;
          return o;
        }
        if (r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/)) {
          ri = Math.min(Math.max(r[1].length, r[4].length), 7);
          ff = frac(aval, Math.pow(10, ri) - 1, true);
          return sign + (ff[0] || (ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1], ri) + r[2] + "/" + r[3] + rpad_(ff[2], ri) : fill(" ", 2 * ri + 1 + r[2].length + r[3].length));
        }
        if (r = fmt.match(/^[#0?]+$/)) {
          o = "" + val;
          if (fmt.length <= o.length)
            return o;
          return hashq(fmt.substr(0, fmt.length - o.length)) + o;
        }
        if (r = fmt.match(/^([#0]+)\.([#0]+)$/)) {
          o = "" + val.toFixed(Math.min(r[2].length, 10)).replace(/([^0])0+$/, "$1");
          ri = o.indexOf(".");
          var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres;
          return hashq(fmt.substr(0, lres) + o + fmt.substr(fmt.length - rres));
        }
        if (r = fmt.match(/^00,000\.([#0]*0)$/)) {
          return val < 0 ? "-" + write_num_int(type, fmt, -val) : commaify("" + val).replace(/^\d,\d{3}$/, "0$&").replace(/^\d*$/, function($$) {
            return "00," + ($$.length < 3 ? pad0(0, 3 - $$.length) : "") + $$;
          }) + "." + pad0(0, r[1].length);
        }
        switch (fmt) {
          case "###,###":
          case "##,###":
          case "#,###":
            var x = commaify("" + aval);
            return x !== "0" ? sign + x : "";
          default:
            if (fmt.match(/\.[0#?]*$/))
              return write_num_int(type, fmt.slice(0, fmt.lastIndexOf(".")), val) + hashq(fmt.slice(fmt.lastIndexOf(".")));
        }
        throw new Error("unsupported format |" + fmt + "|");
      }
      return function write_num(type, fmt, val) {
        return (val | 0) === val ? write_num_int(type, fmt, val) : write_num_flt(type, fmt, val);
      };
    }();
    function split_fmt(fmt) {
      var out = [];
      var in_str = false;
      for (var i = 0, j = 0;i < fmt.length; ++i)
        switch (fmt.charCodeAt(i)) {
          case 34:
            in_str = !in_str;
            break;
          case 95:
          case 42:
          case 92:
            ++i;
            break;
          case 59:
            out[out.length] = fmt.substr(j, i - j);
            j = i + 1;
        }
      out[out.length] = fmt.substr(j);
      if (in_str === true)
        throw new Error("Format |" + fmt + "| unterminated string ");
      return out;
    }
    SSF2._split = split_fmt;
    var abstime = /\[[HhMmSs\u0E0A\u0E19\u0E17]*\]/;
    function fmt_is_date(fmt) {
      var i = 0, c = "", o = "";
      while (i < fmt.length) {
        switch (c = fmt.charAt(i)) {
          case "G":
            if (isgeneral(fmt, i))
              i += 6;
            i++;
            break;
          case '"':
            for (;fmt.charCodeAt(++i) !== 34 && i < fmt.length; ) {}
            ++i;
            break;
          case "\\":
            i += 2;
            break;
          case "_":
            i += 2;
            break;
          case "@":
            ++i;
            break;
          case "B":
          case "b":
            if (fmt.charAt(i + 1) === "1" || fmt.charAt(i + 1) === "2")
              return true;
          case "M":
          case "D":
          case "Y":
          case "H":
          case "S":
          case "E":
          case "m":
          case "d":
          case "y":
          case "h":
          case "s":
          case "e":
          case "g":
            return true;
          case "A":
          case "a":
          case "上":
            if (fmt.substr(i, 3).toUpperCase() === "A/P")
              return true;
            if (fmt.substr(i, 5).toUpperCase() === "AM/PM")
              return true;
            if (fmt.substr(i, 5).toUpperCase() === "上午/下午")
              return true;
            ++i;
            break;
          case "[":
            o = c;
            while (fmt.charAt(i++) !== "]" && i < fmt.length)
              o += fmt.charAt(i);
            if (o.match(abstime))
              return true;
            break;
          case ".":
          case "0":
          case "#":
            while (i < fmt.length && ("0#?.,E+-%".indexOf(c = fmt.charAt(++i)) > -1 || c == "\\" && fmt.charAt(i + 1) == "-" && "0#".indexOf(fmt.charAt(i + 2)) > -1)) {}
            break;
          case "?":
            while (fmt.charAt(++i) === c) {}
            break;
          case "*":
            ++i;
            if (fmt.charAt(i) == " " || fmt.charAt(i) == "*")
              ++i;
            break;
          case "(":
          case ")":
            ++i;
            break;
          case "1":
          case "2":
          case "3":
          case "4":
          case "5":
          case "6":
          case "7":
          case "8":
          case "9":
            while (i < fmt.length && "0123456789".indexOf(fmt.charAt(++i)) > -1) {}
            break;
          case " ":
            ++i;
            break;
          default:
            ++i;
            break;
        }
      }
      return false;
    }
    SSF2.is_date = fmt_is_date;
    function eval_fmt(fmt, v, opts, flen) {
      var out = [], o = "", i = 0, c = "", lst = "t", dt, j, cc;
      var hr = "H";
      while (i < fmt.length) {
        switch (c = fmt.charAt(i)) {
          case "G":
            if (!isgeneral(fmt, i))
              throw new Error("unrecognized character " + c + " in " + fmt);
            out[out.length] = { t: "G", v: "General" };
            i += 7;
            break;
          case '"':
            for (o = "";(cc = fmt.charCodeAt(++i)) !== 34 && i < fmt.length; )
              o += String.fromCharCode(cc);
            out[out.length] = { t: "t", v: o };
            ++i;
            break;
          case "\\":
            var w = fmt.charAt(++i), t = w === "(" || w === ")" ? w : "t";
            out[out.length] = { t, v: w };
            ++i;
            break;
          case "_":
            out[out.length] = { t: "t", v: " " };
            i += 2;
            break;
          case "@":
            out[out.length] = { t: "T", v };
            ++i;
            break;
          case "B":
          case "b":
            if (fmt.charAt(i + 1) === "1" || fmt.charAt(i + 1) === "2") {
              if (dt == null) {
                dt = parse_date_code(v, opts, fmt.charAt(i + 1) === "2");
                if (dt == null)
                  return "";
              }
              out[out.length] = { t: "X", v: fmt.substr(i, 2) };
              lst = c;
              i += 2;
              break;
            }
          case "M":
          case "D":
          case "Y":
          case "H":
          case "S":
          case "E":
            c = c.toLowerCase();
          case "m":
          case "d":
          case "y":
          case "h":
          case "s":
          case "e":
          case "g":
            if (v < 0)
              return "";
            if (dt == null) {
              dt = parse_date_code(v, opts);
              if (dt == null)
                return "";
            }
            o = c;
            while (++i < fmt.length && fmt.charAt(i).toLowerCase() === c)
              o += c;
            if (c === "m" && lst.toLowerCase() === "h")
              c = "M";
            if (c === "h")
              c = hr;
            out[out.length] = { t: c, v: o };
            lst = c;
            break;
          case "A":
          case "a":
          case "上":
            var q = { t: c, v: c };
            if (dt == null)
              dt = parse_date_code(v, opts);
            if (fmt.substr(i, 3).toUpperCase() === "A/P") {
              if (dt != null)
                q.v = dt.H >= 12 ? "P" : "A";
              q.t = "T";
              hr = "h";
              i += 3;
            } else if (fmt.substr(i, 5).toUpperCase() === "AM/PM") {
              if (dt != null)
                q.v = dt.H >= 12 ? "PM" : "AM";
              q.t = "T";
              i += 5;
              hr = "h";
            } else if (fmt.substr(i, 5).toUpperCase() === "上午/下午") {
              if (dt != null)
                q.v = dt.H >= 12 ? "下午" : "上午";
              q.t = "T";
              i += 5;
              hr = "h";
            } else {
              q.t = "t";
              ++i;
            }
            if (dt == null && q.t === "T")
              return "";
            out[out.length] = q;
            lst = c;
            break;
          case "[":
            o = c;
            while (fmt.charAt(i++) !== "]" && i < fmt.length)
              o += fmt.charAt(i);
            if (o.slice(-1) !== "]")
              throw 'unterminated "[" block: |' + o + "|";
            if (o.match(abstime)) {
              if (dt == null) {
                dt = parse_date_code(v, opts);
                if (dt == null)
                  return "";
              }
              out[out.length] = { t: "Z", v: o.toLowerCase() };
              lst = o.charAt(1);
            } else if (o.indexOf("$") > -1) {
              o = (o.match(/\$([^-\[\]]*)/) || [])[1] || "$";
              if (!fmt_is_date(fmt))
                out[out.length] = { t: "t", v: o };
            }
            break;
          case ".":
            if (dt != null) {
              o = c;
              while (++i < fmt.length && (c = fmt.charAt(i)) === "0")
                o += c;
              out[out.length] = { t: "s", v: o };
              break;
            }
          case "0":
          case "#":
            o = c;
            while (++i < fmt.length && "0#?.,E+-%".indexOf(c = fmt.charAt(i)) > -1)
              o += c;
            out[out.length] = { t: "n", v: o };
            break;
          case "?":
            o = c;
            while (fmt.charAt(++i) === c)
              o += c;
            out[out.length] = { t: c, v: o };
            lst = c;
            break;
          case "*":
            ++i;
            if (fmt.charAt(i) == " " || fmt.charAt(i) == "*")
              ++i;
            break;
          case "(":
          case ")":
            out[out.length] = { t: flen === 1 ? "t" : c, v: c };
            ++i;
            break;
          case "1":
          case "2":
          case "3":
          case "4":
          case "5":
          case "6":
          case "7":
          case "8":
          case "9":
            o = c;
            while (i < fmt.length && "0123456789".indexOf(fmt.charAt(++i)) > -1)
              o += fmt.charAt(i);
            out[out.length] = { t: "D", v: o };
            break;
          case " ":
            out[out.length] = { t: c, v: c };
            ++i;
            break;
          case "$":
            out[out.length] = { t: "t", v: "$" };
            ++i;
            break;
          default:
            if (",$-+/():!^&'~{}<>=€acfijklopqrtuvwxzP".indexOf(c) === -1)
              throw new Error("unrecognized character " + c + " in " + fmt);
            out[out.length] = { t: "t", v: c };
            ++i;
            break;
        }
      }
      var bt = 0, ss0 = 0, ssm;
      for (i = out.length - 1, lst = "t";i >= 0; --i) {
        switch (out[i].t) {
          case "h":
          case "H":
            out[i].t = hr;
            lst = "h";
            if (bt < 1)
              bt = 1;
            break;
          case "s":
            if (ssm = out[i].v.match(/\.0+$/))
              ss0 = Math.max(ss0, ssm[0].length - 1);
            if (bt < 3)
              bt = 3;
          case "d":
          case "y":
          case "M":
          case "e":
            lst = out[i].t;
            break;
          case "m":
            if (lst === "s") {
              out[i].t = "M";
              if (bt < 2)
                bt = 2;
            }
            break;
          case "X":
            break;
          case "Z":
            if (bt < 1 && out[i].v.match(/[Hh]/))
              bt = 1;
            if (bt < 2 && out[i].v.match(/[Mm]/))
              bt = 2;
            if (bt < 3 && out[i].v.match(/[Ss]/))
              bt = 3;
        }
      }
      switch (bt) {
        case 0:
          break;
        case 1:
          if (dt.u >= 0.5) {
            dt.u = 0;
            ++dt.S;
          }
          if (dt.S >= 60) {
            dt.S = 0;
            ++dt.M;
          }
          if (dt.M >= 60) {
            dt.M = 0;
            ++dt.H;
          }
          break;
        case 2:
          if (dt.u >= 0.5) {
            dt.u = 0;
            ++dt.S;
          }
          if (dt.S >= 60) {
            dt.S = 0;
            ++dt.M;
          }
          break;
      }
      var nstr = "", jj;
      for (i = 0;i < out.length; ++i) {
        switch (out[i].t) {
          case "t":
          case "T":
          case " ":
          case "D":
            break;
          case "X":
            out[i].v = "";
            out[i].t = ";";
            break;
          case "d":
          case "m":
          case "y":
          case "h":
          case "H":
          case "M":
          case "s":
          case "e":
          case "b":
          case "Z":
            out[i].v = write_date(out[i].t.charCodeAt(0), out[i].v, dt, ss0);
            out[i].t = "t";
            break;
          case "n":
          case "?":
            jj = i + 1;
            while (out[jj] != null && ((c = out[jj].t) === "?" || c === "D" || (c === " " || c === "t") && out[jj + 1] != null && (out[jj + 1].t === "?" || out[jj + 1].t === "t" && out[jj + 1].v === "/") || out[i].t === "(" && (c === " " || c === "n" || c === ")") || c === "t" && (out[jj].v === "/" || out[jj].v === " " && out[jj + 1] != null && out[jj + 1].t == "?"))) {
              out[i].v += out[jj].v;
              out[jj] = { v: "", t: ";" };
              ++jj;
            }
            nstr += out[i].v;
            i = jj - 1;
            break;
          case "G":
            out[i].t = "t";
            out[i].v = general_fmt(v, opts);
            break;
        }
      }
      var vv = "", myv, ostr;
      if (nstr.length > 0) {
        if (nstr.charCodeAt(0) == 40) {
          myv = v < 0 && nstr.charCodeAt(0) === 45 ? -v : v;
          ostr = write_num("n", nstr, myv);
        } else {
          myv = v < 0 && flen > 1 ? -v : v;
          ostr = write_num("n", nstr, myv);
          if (myv < 0 && out[0] && out[0].t == "t") {
            ostr = ostr.substr(1);
            out[0].v = "-" + out[0].v;
          }
        }
        jj = ostr.length - 1;
        var decpt = out.length;
        for (i = 0;i < out.length; ++i)
          if (out[i] != null && out[i].t != "t" && out[i].v.indexOf(".") > -1) {
            decpt = i;
            break;
          }
        var lasti = out.length;
        if (decpt === out.length && ostr.indexOf("E") === -1) {
          for (i = out.length - 1;i >= 0; --i) {
            if (out[i] == null || "n?".indexOf(out[i].t) === -1)
              continue;
            if (jj >= out[i].v.length - 1) {
              jj -= out[i].v.length;
              out[i].v = ostr.substr(jj + 1, out[i].v.length);
            } else if (jj < 0)
              out[i].v = "";
            else {
              out[i].v = ostr.substr(0, jj + 1);
              jj = -1;
            }
            out[i].t = "t";
            lasti = i;
          }
          if (jj >= 0 && lasti < out.length)
            out[lasti].v = ostr.substr(0, jj + 1) + out[lasti].v;
        } else if (decpt !== out.length && ostr.indexOf("E") === -1) {
          jj = ostr.indexOf(".") - 1;
          for (i = decpt;i >= 0; --i) {
            if (out[i] == null || "n?".indexOf(out[i].t) === -1)
              continue;
            j = out[i].v.indexOf(".") > -1 && i === decpt ? out[i].v.indexOf(".") - 1 : out[i].v.length - 1;
            vv = out[i].v.substr(j + 1);
            for (;j >= 0; --j) {
              if (jj >= 0 && (out[i].v.charAt(j) === "0" || out[i].v.charAt(j) === "#"))
                vv = ostr.charAt(jj--) + vv;
            }
            out[i].v = vv;
            out[i].t = "t";
            lasti = i;
          }
          if (jj >= 0 && lasti < out.length)
            out[lasti].v = ostr.substr(0, jj + 1) + out[lasti].v;
          jj = ostr.indexOf(".") + 1;
          for (i = decpt;i < out.length; ++i) {
            if (out[i] == null || "n?(".indexOf(out[i].t) === -1 && i !== decpt)
              continue;
            j = out[i].v.indexOf(".") > -1 && i === decpt ? out[i].v.indexOf(".") + 1 : 0;
            vv = out[i].v.substr(0, j);
            for (;j < out[i].v.length; ++j) {
              if (jj < ostr.length)
                vv += ostr.charAt(jj++);
            }
            out[i].v = vv;
            out[i].t = "t";
            lasti = i;
          }
        }
      }
      for (i = 0;i < out.length; ++i)
        if (out[i] != null && "n?".indexOf(out[i].t) > -1) {
          myv = flen > 1 && v < 0 && i > 0 && out[i - 1].v === "-" ? -v : v;
          out[i].v = write_num(out[i].t, out[i].v, myv);
          out[i].t = "t";
        }
      var retval = "";
      for (i = 0;i !== out.length; ++i)
        if (out[i] != null)
          retval += out[i].v;
      return retval;
    }
    SSF2._eval = eval_fmt;
    var cfregex = /\[[=<>]/;
    var cfregex2 = /\[(=|>[=]?|<[>=]?)(-?\d+(?:\.\d*)?)\]/;
    function chkcond(v, rr) {
      if (rr == null)
        return false;
      var thresh = parseFloat(rr[2]);
      switch (rr[1]) {
        case "=":
          if (v == thresh)
            return true;
          break;
        case ">":
          if (v > thresh)
            return true;
          break;
        case "<":
          if (v < thresh)
            return true;
          break;
        case "<>":
          if (v != thresh)
            return true;
          break;
        case ">=":
          if (v >= thresh)
            return true;
          break;
        case "<=":
          if (v <= thresh)
            return true;
          break;
      }
      return false;
    }
    function choose_fmt(f, v) {
      var fmt = split_fmt(f);
      var l = fmt.length, lat = fmt[l - 1].indexOf("@");
      if (l < 4 && lat > -1)
        --l;
      if (fmt.length > 4)
        throw new Error("cannot find right format for |" + fmt.join("|") + "|");
      if (typeof v !== "number")
        return [4, fmt.length === 4 || lat > -1 ? fmt[fmt.length - 1] : "@"];
      switch (fmt.length) {
        case 1:
          fmt = lat > -1 ? ["General", "General", "General", fmt[0]] : [fmt[0], fmt[0], fmt[0], "@"];
          break;
        case 2:
          fmt = lat > -1 ? [fmt[0], fmt[0], fmt[0], fmt[1]] : [fmt[0], fmt[1], fmt[0], "@"];
          break;
        case 3:
          fmt = lat > -1 ? [fmt[0], fmt[1], fmt[0], fmt[2]] : [fmt[0], fmt[1], fmt[2], "@"];
          break;
        case 4:
          break;
      }
      var ff = v > 0 ? fmt[0] : v < 0 ? fmt[1] : fmt[2];
      if (fmt[0].indexOf("[") === -1 && fmt[1].indexOf("[") === -1)
        return [l, ff];
      if (fmt[0].match(cfregex) != null || fmt[1].match(cfregex) != null) {
        var m1 = fmt[0].match(cfregex2);
        var m2 = fmt[1].match(cfregex2);
        return chkcond(v, m1) ? [l, fmt[0]] : chkcond(v, m2) ? [l, fmt[1]] : [l, fmt[m1 != null && m2 != null ? 2 : 1]];
      }
      return [l, ff];
    }
    function format2(fmt, v, o) {
      if (o == null)
        o = {};
      var sfmt = "";
      switch (typeof fmt) {
        case "string":
          if (fmt == "m/d/yy" && o.dateNF)
            sfmt = o.dateNF;
          else
            sfmt = fmt;
          break;
        case "number":
          if (fmt == 14 && o.dateNF)
            sfmt = o.dateNF;
          else
            sfmt = (o.table != null ? o.table : table_fmt)[fmt];
          if (sfmt == null)
            sfmt = o.table && o.table[default_map[fmt]] || table_fmt[default_map[fmt]];
          if (sfmt == null)
            sfmt = default_str[fmt] || "General";
          break;
      }
      if (isgeneral(sfmt, 0))
        return general_fmt(v, o);
      if (v instanceof Date)
        v = datenum_local(v, o.date1904);
      var f = choose_fmt(sfmt, v);
      if (isgeneral(f[1]))
        return general_fmt(v, o);
      if (v === true)
        v = "TRUE";
      else if (v === false)
        v = "FALSE";
      else if (v === "" || v == null)
        return "";
      return eval_fmt(f[1], v, o, f[0]);
    }
    function load_entry(fmt, idx) {
      if (typeof idx != "number") {
        idx = +idx || -1;
        for (var i = 0;i < 392; ++i) {
          if (table_fmt[i] == undefined) {
            if (idx < 0)
              idx = i;
            continue;
          }
          if (table_fmt[i] == fmt) {
            idx = i;
            break;
          }
        }
        if (idx < 0)
          idx = 391;
      }
      table_fmt[idx] = fmt;
      return idx;
    }
    SSF2.load = load_entry;
    SSF2._table = table_fmt;
    SSF2.get_table = function get_table() {
      return table_fmt;
    };
    SSF2.load_table = function load_table(tbl) {
      for (var i = 0;i != 392; ++i)
        if (tbl[i] !== undefined)
          load_entry(tbl[i], i);
    };
    SSF2.init_table = init_table;
    SSF2.format = format2;
  };
  make_ssf(SSF);
  if (typeof module !== "undefined" && typeof DO_NOT_EXPORT_SSF === "undefined")
    module.exports = SSF;
});

// node_modules/@oai/granola/dist/spreadsheet/spreadsheet-utils.js
function colWidthToPx(width) {
  if (width == null || width <= 0)
    return FALLBACK_COL_W_PX;
  const w = width;
  if (w >= 1) {
    const pixels2 = Math.floor((w * 256 + Math.floor(128 / 7)) / 256 * 7) + 5;
    return pixels2;
  }
  const pixels = Math.floor(w * 12) + 5;
  return Math.max(0, pixels);
}
function pxToColWidth(px) {
  if (!Number.isFinite(px) || px <= 0) {
    return 0;
  }
  let bestWidth = Math.max((px - 5) / 7, 0);
  let bestDiff = Math.abs(colWidthToPx(bestWidth) - px);
  const maxWidth = 150;
  for (let candidate = 0;candidate <= maxWidth; candidate += 0.05) {
    const diff = Math.abs(colWidthToPx(candidate) - px);
    if (diff < bestDiff) {
      bestDiff = diff;
      bestWidth = candidate;
    }
  }
  return Math.round(bestWidth * 100) / 100;
}
function pointsToPx(pt) {
  const size = pt == null || pt === 0 ? FALLBACK_ROW_H_PT : pt;
  return size * 96 / 72;
}
function pxToPoints(px) {
  if (!Number.isFinite(px ?? 0)) {
    return FALLBACK_ROW_H_PT;
  }
  return (px ?? 0) * 72 / 96;
}
function resolveCellPadding(fontPx) {
  const base = fontPx > 0 ? fontPx : 11;
  return {
    padLr: Math.max(CELL_PAD_LR_MIN, Math.floor(base * CELL_PAD_LR_RATIO)),
    padTb: Math.max(CELL_PAD_TB_MIN, Math.floor(base * CELL_PAD_TB_RATIO))
  };
}
function columnLabel(idx) {
  let s = "";
  idx += 1;
  while (idx) {
    const r = (idx - 1) % 26;
    s = String.fromCharCode(65 + r) + s;
    idx = Math.floor((idx - r) / 26);
  }
  return s;
}
function columnIndex(address) {
  const m = address.match(/[A-Z]+/);
  if (!m)
    return 0;
  let col = 0;
  for (const ch of m[0])
    col = col * 26 + (ch.charCodeAt(0) - 64);
  return col - 1;
}
function rowIndex(address) {
  const m = address.match(/\d+/);
  return m ? parseInt(m[0], 10) - 1 : 0;
}
function argbHexToCss(argb) {
  const hex2 = argb.replace(/^0x/i, "");
  if (hex2.length === 8) {
    const a = 1;
    const r = parseInt(hex2.slice(2, 4), 16);
    const g = parseInt(hex2.slice(4, 6), 16);
    const b = parseInt(hex2.slice(6, 8), 16);
    return `rgba(${r}, ${g}, ${b}, ${a.toFixed(3)})`;
  }
  if (hex2.length === 6)
    return `#${hex2}`;
  return "#ffffff";
}
function excelIndexedColorToCss(index) {
  if (index == null)
    return;
  if (index === 64)
    return "#000000";
  const palette = [
    "#000000",
    "#FFFFFF",
    "#FF0000",
    "#00FF00",
    "#0000FF",
    "#FFFF00",
    "#FF00FF",
    "#00FFFF",
    "#000000",
    "#FFFFFF",
    "#FF0000",
    "#00FF00",
    "#0000FF",
    "#FFFF00",
    "#FF00FF",
    "#00FFFF",
    "#800000",
    "#008000",
    "#000080",
    "#808000",
    "#800080",
    "#008080",
    "#C0C0C0",
    "#808080",
    "#9999FF",
    "#993366",
    "#FFFFCC",
    "#CCFFFF",
    "#660066",
    "#FF8080",
    "#0066CC",
    "#CCCCFF",
    "#000080",
    "#FF00FF",
    "#FFFF00",
    "#00FFFF",
    "#800080",
    "#800000",
    "#008080",
    "#0000FF",
    "#00CCFF",
    "#CCFFFF",
    "#CCFFCC",
    "#FFFF99",
    "#99CCFF",
    "#FF99CC",
    "#CC99FF",
    "#FFCC99",
    "#3366FF",
    "#33CCCC",
    "#99CC00",
    "#FFCC00",
    "#FF9900",
    "#FF6600",
    "#666699",
    "#969696",
    "#003366",
    "#339966",
    "#003300",
    "#333300",
    "#993300",
    "#993366",
    "#333399",
    "#333333"
  ];
  return palette[index];
}
var FALLBACK_COL_W_PX = 64, FALLBACK_COL_W_PX_RAW = 59, FALLBACK_ROW_H_PT = 15, ROW_HEADER_W = 40, COL_HEADER_H = 20, CELL_PAD_LR_RATIO = 0.1, CELL_PAD_TB_RATIO = 0, CELL_PAD_LR_MIN = 2, CELL_PAD_TB_MIN = 0;

// node_modules/@oai/granola/dist/models/address-utils.js
function parseRangeAddress(address) {
  const normalized = normalizeAddress(address);
  if (!normalized)
    return null;
  const parts = normalized.split(":");
  const startRef = parts[0];
  if (!startRef)
    return null;
  const endRef = parts[1] ?? startRef;
  const startRow = rowIndex(startRef);
  const startCol = columnIndex(startRef);
  const endRow = rowIndex(endRef);
  const endCol = columnIndex(endRef);
  const bounds = {
    startRow: Math.min(startRow, endRow),
    startCol: Math.min(startCol, endCol),
    endRow: Math.max(startRow, endRow),
    endCol: Math.max(startCol, endCol)
  };
  return { ref: buildRangeRef(bounds), bounds };
}
function buildRangeRef(bounds) {
  const startAddr = makeCellAddress(bounds.startRow, bounds.startCol);
  const endAddr = makeCellAddress(bounds.endRow, bounds.endCol);
  return startAddr === endAddr ? startAddr : `${startAddr}:${endAddr}`;
}
function makeCellAddress(rowIdx, colIdx) {
  return `${columnLabel(colIdx)}${rowIdx + 1}`;
}
function normalizeAddress(address) {
  const trimmed = address.trim();
  if (!trimmed)
    return null;
  const withoutSheet = trimmed.includes("!") ? trimmed.slice(trimmed.indexOf("!") + 1) : trimmed;
  return withoutSheet.replace(/\$/g, "").toUpperCase();
}
function boundsDimensions(bounds) {
  return {
    rows: bounds.endRow - bounds.startRow + 1,
    cols: bounds.endCol - bounds.startCol + 1
  };
}
function splitSheetAddress(address) {
  const trimmed = address.startsWith("=") ? address.slice(1) : address;
  const bang = trimmed.indexOf("!");
  if (bang === -1) {
    const parsed2 = parseRangeAddress(trimmed);
    return { ref: parsed2?.ref ?? trimmed };
  }
  const rawSheet = trimmed.slice(0, bang);
  const refPart = trimmed.slice(bang + 1);
  const parsed = parseRangeAddress(refPart);
  return {
    sheetName: unescapeSheetName(rawSheet),
    ref: parsed?.ref ?? refPart
  };
}
function unescapeSheetName(sheet) {
  if (sheet.startsWith("'") && sheet.endsWith("'") && sheet.length >= 2) {
    return sheet.slice(1, -1).replace(/''/g, "'");
  }
  return sheet;
}
var init_address_utils = () => {};

// node_modules/yaml/dist/nodes/identity.js
var require_identity = __commonJS((exports) => {
  var ALIAS = Symbol.for("yaml.alias");
  var DOC = Symbol.for("yaml.document");
  var MAP = Symbol.for("yaml.map");
  var PAIR = Symbol.for("yaml.pair");
  var SCALAR = Symbol.for("yaml.scalar");
  var SEQ = Symbol.for("yaml.seq");
  var NODE_TYPE = Symbol.for("yaml.node.type");
  var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS;
  var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC;
  var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP;
  var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR;
  var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR;
  var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ;
  function isCollection(node) {
    if (node && typeof node === "object")
      switch (node[NODE_TYPE]) {
        case MAP:
        case SEQ:
          return true;
      }
    return false;
  }
  function isNode2(node) {
    if (node && typeof node === "object")
      switch (node[NODE_TYPE]) {
        case ALIAS:
        case MAP:
        case SCALAR:
        case SEQ:
          return true;
      }
    return false;
  }
  var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
  exports.ALIAS = ALIAS;
  exports.DOC = DOC;
  exports.MAP = MAP;
  exports.NODE_TYPE = NODE_TYPE;
  exports.PAIR = PAIR;
  exports.SCALAR = SCALAR;
  exports.SEQ = SEQ;
  exports.hasAnchor = hasAnchor;
  exports.isAlias = isAlias;
  exports.isCollection = isCollection;
  exports.isDocument = isDocument;
  exports.isMap = isMap;
  exports.isNode = isNode2;
  exports.isPair = isPair;
  exports.isScalar = isScalar;
  exports.isSeq = isSeq;
});

// node_modules/yaml/dist/visit.js
var require_visit = __commonJS((exports) => {
  var identity3 = require_identity();
  var BREAK = Symbol("break visit");
  var SKIP = Symbol("skip children");
  var REMOVE = Symbol("remove node");
  function visit(node, visitor) {
    const visitor_ = initVisitor(visitor);
    if (identity3.isDocument(node)) {
      const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
      if (cd === REMOVE)
        node.contents = null;
    } else
      visit_(null, node, visitor_, Object.freeze([]));
  }
  visit.BREAK = BREAK;
  visit.SKIP = SKIP;
  visit.REMOVE = REMOVE;
  function visit_(key, node, visitor, path3) {
    const ctrl = callVisitor(key, node, visitor, path3);
    if (identity3.isNode(ctrl) || identity3.isPair(ctrl)) {
      replaceNode(key, path3, ctrl);
      return visit_(key, ctrl, visitor, path3);
    }
    if (typeof ctrl !== "symbol") {
      if (identity3.isCollection(node)) {
        path3 = Object.freeze(path3.concat(node));
        for (let i = 0;i < node.items.length; ++i) {
          const ci = visit_(i, node.items[i], visitor, path3);
          if (typeof ci === "number")
            i = ci - 1;
          else if (ci === BREAK)
            return BREAK;
          else if (ci === REMOVE) {
            node.items.splice(i, 1);
            i -= 1;
          }
        }
      } else if (identity3.isPair(node)) {
        path3 = Object.freeze(path3.concat(node));
        const ck = visit_("key", node.key, visitor, path3);
        if (ck === BREAK)
          return BREAK;
        else if (ck === REMOVE)
          node.key = null;
        const cv = visit_("value", node.value, visitor, path3);
        if (cv === BREAK)
          return BREAK;
        else if (cv === REMOVE)
          node.value = null;
      }
    }
    return ctrl;
  }
  async function visitAsync(node, visitor) {
    const visitor_ = initVisitor(visitor);
    if (identity3.isDocument(node)) {
      const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
      if (cd === REMOVE)
        node.contents = null;
    } else
      await visitAsync_(null, node, visitor_, Object.freeze([]));
  }
  visitAsync.BREAK = BREAK;
  visitAsync.SKIP = SKIP;
  visitAsync.REMOVE = REMOVE;
  async function visitAsync_(key, node, visitor, path3) {
    const ctrl = await callVisitor(key, node, visitor, path3);
    if (identity3.isNode(ctrl) || identity3.isPair(ctrl)) {
      replaceNode(key, path3, ctrl);
      return visitAsync_(key, ctrl, visitor, path3);
    }
    if (typeof ctrl !== "symbol") {
      if (identity3.isCollection(node)) {
        path3 = Object.freeze(path3.concat(node));
        for (let i = 0;i < node.items.length; ++i) {
          const ci = await visitAsync_(i, node.items[i], visitor, path3);
          if (typeof ci === "number")
            i = ci - 1;
          else if (ci === BREAK)
            return BREAK;
          else if (ci === REMOVE) {
            node.items.splice(i, 1);
            i -= 1;
          }
        }
      } else if (identity3.isPair(node)) {
        path3 = Object.freeze(path3.concat(node));
        const ck = await visitAsync_("key", node.key, visitor, path3);
        if (ck === BREAK)
          return BREAK;
        else if (ck === REMOVE)
          node.key = null;
        const cv = await visitAsync_("value", node.value, visitor, path3);
        if (cv === BREAK)
          return BREAK;
        else if (cv === REMOVE)
          node.value = null;
      }
    }
    return ctrl;
  }
  function initVisitor(visitor) {
    if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) {
      return Object.assign({
        Alias: visitor.Node,
        Map: visitor.Node,
        Scalar: visitor.Node,
        Seq: visitor.Node
      }, visitor.Value && {
        Map: visitor.Value,
        Scalar: visitor.Value,
        Seq: visitor.Value
      }, visitor.Collection && {
        Map: visitor.Collection,
        Seq: visitor.Collection
      }, visitor);
    }
    return visitor;
  }
  function callVisitor(key, node, visitor, path3) {
    if (typeof visitor === "function")
      return visitor(key, node, path3);
    if (identity3.isMap(node))
      return visitor.Map?.(key, node, path3);
    if (identity3.isSeq(node))
      return visitor.Seq?.(key, node, path3);
    if (identity3.isPair(node))
      return visitor.Pair?.(key, node, path3);
    if (identity3.isScalar(node))
      return visitor.Scalar?.(key, node, path3);
    if (identity3.isAlias(node))
      return visitor.Alias?.(key, node, path3);
    return;
  }
  function replaceNode(key, path3, node) {
    const parent = path3[path3.length - 1];
    if (identity3.isCollection(parent)) {
      parent.items[key] = node;
    } else if (identity3.isPair(parent)) {
      if (key === "key")
        parent.key = node;
      else
        parent.value = node;
    } else if (identity3.isDocument(parent)) {
      parent.contents = node;
    } else {
      const pt = identity3.isAlias(parent) ? "alias" : "scalar";
      throw new Error(`Cannot replace node with ${pt} parent`);
    }
  }
  exports.visit = visit;
  exports.visitAsync = visitAsync;
});

// node_modules/yaml/dist/doc/directives.js
var require_directives = __commonJS((exports) => {
  var identity3 = require_identity();
  var visit = require_visit();
  var escapeChars = {
    "!": "%21",
    ",": "%2C",
    "[": "%5B",
    "]": "%5D",
    "{": "%7B",
    "}": "%7D"
  };
  var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]);

  class Directives {
    constructor(yaml, tags) {
      this.docStart = null;
      this.docEnd = false;
      this.yaml = Object.assign({}, Directives.defaultYaml, yaml);
      this.tags = Object.assign({}, Directives.defaultTags, tags);
    }
    clone() {
      const copy3 = new Directives(this.yaml, this.tags);
      copy3.docStart = this.docStart;
      return copy3;
    }
    atDocument() {
      const res = new Directives(this.yaml, this.tags);
      switch (this.yaml.version) {
        case "1.1":
          this.atNextDocument = true;
          break;
        case "1.2":
          this.atNextDocument = false;
          this.yaml = {
            explicit: Directives.defaultYaml.explicit,
            version: "1.2"
          };
          this.tags = Object.assign({}, Directives.defaultTags);
          break;
      }
      return res;
    }
    add(line, onError) {
      if (this.atNextDocument) {
        this.yaml = { explicit: Directives.defaultYaml.explicit, version: "1.1" };
        this.tags = Object.assign({}, Directives.defaultTags);
        this.atNextDocument = false;
      }
      const parts = line.trim().split(/[ \t]+/);
      const name = parts.shift();
      switch (name) {
        case "%TAG": {
          if (parts.length !== 2) {
            onError(0, "%TAG directive should contain exactly two parts");
            if (parts.length < 2)
              return false;
          }
          const [handle, prefix] = parts;
          this.tags[handle] = prefix;
          return true;
        }
        case "%YAML": {
          this.yaml.explicit = true;
          if (parts.length !== 1) {
            onError(0, "%YAML directive should contain exactly one part");
            return false;
          }
          const [version2] = parts;
          if (version2 === "1.1" || version2 === "1.2") {
            this.yaml.version = version2;
            return true;
          } else {
            const isValid = /^\d+\.\d+$/.test(version2);
            onError(6, `Unsupported YAML version ${version2}`, isValid);
            return false;
          }
        }
        default:
          onError(0, `Unknown directive ${name}`, true);
          return false;
      }
    }
    tagName(source, onError) {
      if (source === "!")
        return "!";
      if (source[0] !== "!") {
        onError(`Not a valid tag: ${source}`);
        return null;
      }
      if (source[1] === "<") {
        const verbatim = source.slice(2, -1);
        if (verbatim === "!" || verbatim === "!!") {
          onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);
          return null;
        }
        if (source[source.length - 1] !== ">")
          onError("Verbatim tags must end with a >");
        return verbatim;
      }
      const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);
      if (!suffix)
        onError(`The ${source} tag has no suffix`);
      const prefix = this.tags[handle];
      if (prefix) {
        try {
          return prefix + decodeURIComponent(suffix);
        } catch (error48) {
          onError(String(error48));
          return null;
        }
      }
      if (handle === "!")
        return source;
      onError(`Could not resolve tag: ${source}`);
      return null;
    }
    tagString(tag) {
      for (const [handle, prefix] of Object.entries(this.tags)) {
        if (tag.startsWith(prefix))
          return handle + escapeTagName(tag.substring(prefix.length));
      }
      return tag[0] === "!" ? tag : `!<${tag}>`;
    }
    toString(doc2) {
      const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : [];
      const tagEntries = Object.entries(this.tags);
      let tagNames;
      if (doc2 && tagEntries.length > 0 && identity3.isNode(doc2.contents)) {
        const tags = {};
        visit.visit(doc2.contents, (_key, node) => {
          if (identity3.isNode(node) && node.tag)
            tags[node.tag] = true;
        });
        tagNames = Object.keys(tags);
      } else
        tagNames = [];
      for (const [handle, prefix] of tagEntries) {
        if (handle === "!!" && prefix === "tag:yaml.org,2002:")
          continue;
        if (!doc2 || tagNames.some((tn) => tn.startsWith(prefix)))
          lines.push(`%TAG ${handle} ${prefix}`);
      }
      return lines.join(`
`);
    }
  }
  Directives.defaultYaml = { explicit: false, version: "1.2" };
  Directives.defaultTags = { "!!": "tag:yaml.org,2002:" };
  exports.Directives = Directives;
});

// node_modules/yaml/dist/doc/anchors.js
var require_anchors = __commonJS((exports) => {
  var identity3 = require_identity();
  var visit = require_visit();
  function anchorIsValid(anchor) {
    if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
      const sa = JSON.stringify(anchor);
      const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
      throw new Error(msg);
    }
    return true;
  }
  function anchorNames(root) {
    const anchors = new Set;
    visit.visit(root, {
      Value(_key, node) {
        if (node.anchor)
          anchors.add(node.anchor);
      }
    });
    return anchors;
  }
  function findNewAnchor(prefix, exclude) {
    for (let i = 1;; ++i) {
      const name = `${prefix}${i}`;
      if (!exclude.has(name))
        return name;
    }
  }
  function createNodeAnchors(doc2, prefix) {
    const aliasObjects = [];
    const sourceObjects = new Map;
    let prevAnchors = null;
    return {
      onAnchor: (source) => {
        aliasObjects.push(source);
        prevAnchors ?? (prevAnchors = anchorNames(doc2));
        const anchor = findNewAnchor(prefix, prevAnchors);
        prevAnchors.add(anchor);
        return anchor;
      },
      setAnchors: () => {
        for (const source of aliasObjects) {
          const ref = sourceObjects.get(source);
          if (typeof ref === "object" && ref.anchor && (identity3.isScalar(ref.node) || identity3.isCollection(ref.node))) {
            ref.node.anchor = ref.anchor;
          } else {
            const error48 = new Error("Failed to resolve repeated object (this should not happen)");
            error48.source = source;
            throw error48;
          }
        }
      },
      sourceObjects
    };
  }
  exports.anchorIsValid = anchorIsValid;
  exports.anchorNames = anchorNames;
  exports.createNodeAnchors = createNodeAnchors;
  exports.findNewAnchor = findNewAnchor;
});

// node_modules/yaml/dist/doc/applyReviver.js
var require_applyReviver = __commonJS((exports) => {
  function applyReviver(reviver, obj, key, val) {
    if (val && typeof val === "object") {
      if (Array.isArray(val)) {
        for (let i = 0, len = val.length;i < len; ++i) {
          const v0 = val[i];
          const v1 = applyReviver(reviver, val, String(i), v0);
          if (v1 === undefined)
            delete val[i];
          else if (v1 !== v0)
            val[i] = v1;
        }
      } else if (val instanceof Map) {
        for (const k of Array.from(val.keys())) {
          const v0 = val.get(k);
          const v1 = applyReviver(reviver, val, k, v0);
          if (v1 === undefined)
            val.delete(k);
          else if (v1 !== v0)
            val.set(k, v1);
        }
      } else if (val instanceof Set) {
        for (const v0 of Array.from(val)) {
          const v1 = applyReviver(reviver, val, v0, v0);
          if (v1 === undefined)
            val.delete(v0);
          else if (v1 !== v0) {
            val.delete(v0);
            val.add(v1);
          }
        }
      } else {
        for (const [k, v0] of Object.entries(val)) {
          const v1 = applyReviver(reviver, val, k, v0);
          if (v1 === undefined)
            delete val[k];
          else if (v1 !== v0)
            val[k] = v1;
        }
      }
    }
    return reviver.call(obj, key, val);
  }
  exports.applyReviver = applyReviver;
});

// node_modules/yaml/dist/nodes/toJS.js
var require_toJS = __commonJS((exports) => {
  var identity3 = require_identity();
  function toJS(value, arg, ctx) {
    if (Array.isArray(value))
      return value.map((v, i) => toJS(v, String(i), ctx));
    if (value && typeof value.toJSON === "function") {
      if (!ctx || !identity3.hasAnchor(value))
        return value.toJSON(arg, ctx);
      const data = { aliasCount: 0, count: 1, res: undefined };
      ctx.anchors.set(value, data);
      ctx.onCreate = (res2) => {
        data.res = res2;
        delete ctx.onCreate;
      };
      const res = value.toJSON(arg, ctx);
      if (ctx.onCreate)
        ctx.onCreate(res);
      return res;
    }
    if (typeof value === "bigint" && !ctx?.keep)
      return Number(value);
    return value;
  }
  exports.toJS = toJS;
});

// node_modules/yaml/dist/nodes/Node.js
var require_Node = __commonJS((exports) => {
  var applyReviver = require_applyReviver();
  var identity3 = require_identity();
  var toJS = require_toJS();

  class NodeBase {
    constructor(type) {
      Object.defineProperty(this, identity3.NODE_TYPE, { value: type });
    }
    clone() {
      const copy3 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
      if (this.range)
        copy3.range = this.range.slice();
      return copy3;
    }
    toJS(doc2, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
      if (!identity3.isDocument(doc2))
        throw new TypeError("A document argument is required");
      const ctx = {
        anchors: new Map,
        doc: doc2,
        keep: true,
        mapAsMap: mapAsMap === true,
        mapKeyWarned: false,
        maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
      };
      const res = toJS.toJS(this, "", ctx);
      if (typeof onAnchor === "function")
        for (const { count: count3, res: res2 } of ctx.anchors.values())
          onAnchor(res2, count3);
      return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
    }
  }
  exports.NodeBase = NodeBase;
});

// node_modules/yaml/dist/nodes/Alias.js
var require_Alias = __commonJS((exports) => {
  var anchors = require_anchors();
  var visit = require_visit();
  var identity3 = require_identity();
  var Node2 = require_Node();
  var toJS = require_toJS();

  class Alias extends Node2.NodeBase {
    constructor(source) {
      super(identity3.ALIAS);
      this.source = source;
      Object.defineProperty(this, "tag", {
        set() {
          throw new Error("Alias nodes cannot have tags");
        }
      });
    }
    resolve(doc2, ctx) {
      let nodes;
      if (ctx?.aliasResolveCache) {
        nodes = ctx.aliasResolveCache;
      } else {
        nodes = [];
        visit.visit(doc2, {
          Node: (_key, node) => {
            if (identity3.isAlias(node) || identity3.hasAnchor(node))
              nodes.push(node);
          }
        });
        if (ctx)
          ctx.aliasResolveCache = nodes;
      }
      let found = undefined;
      for (const node of nodes) {
        if (node === this)
          break;
        if (node.anchor === this.source)
          found = node;
      }
      return found;
    }
    toJSON(_arg, ctx) {
      if (!ctx)
        return { source: this.source };
      const { anchors: anchors2, doc: doc2, maxAliasCount } = ctx;
      const source = this.resolve(doc2, ctx);
      if (!source) {
        const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
        throw new ReferenceError(msg);
      }
      let data = anchors2.get(source);
      if (!data) {
        toJS.toJS(source, null, ctx);
        data = anchors2.get(source);
      }
      if (data?.res === undefined) {
        const msg = "This should not happen: Alias anchor was not resolved?";
        throw new ReferenceError(msg);
      }
      if (maxAliasCount >= 0) {
        data.count += 1;
        if (data.aliasCount === 0)
          data.aliasCount = getAliasCount(doc2, source, anchors2);
        if (data.count * data.aliasCount > maxAliasCount) {
          const msg = "Excessive alias count indicates a resource exhaustion attack";
          throw new ReferenceError(msg);
        }
      }
      return data.res;
    }
    toString(ctx, _onComment, _onChompKeep) {
      const src = `*${this.source}`;
      if (ctx) {
        anchors.anchorIsValid(this.source);
        if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
          const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
          throw new Error(msg);
        }
        if (ctx.implicitKey)
          return `${src} `;
      }
      return src;
    }
  }
  function getAliasCount(doc2, node, anchors2) {
    if (identity3.isAlias(node)) {
      const source = node.resolve(doc2);
      const anchor = anchors2 && source && anchors2.get(source);
      return anchor ? anchor.count * anchor.aliasCount : 0;
    } else if (identity3.isCollection(node)) {
      let count3 = 0;
      for (const item of node.items) {
        const c = getAliasCount(doc2, item, anchors2);
        if (c > count3)
          count3 = c;
      }
      return count3;
    } else if (identity3.isPair(node)) {
      const kc = getAliasCount(doc2, node.key, anchors2);
      const vc = getAliasCount(doc2, node.value, anchors2);
      return Math.max(kc, vc);
    }
    return 1;
  }
  exports.Alias = Alias;
});

// node_modules/yaml/dist/nodes/Scalar.js
var require_Scalar = __commonJS((exports) => {
  var identity3 = require_identity();
  var Node2 = require_Node();
  var toJS = require_toJS();
  var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object";

  class Scalar extends Node2.NodeBase {
    constructor(value) {
      super(identity3.SCALAR);
      this.value = value;
    }
    toJSON(arg, ctx) {
      return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx);
    }
    toString() {
      return String(this.value);
    }
  }
  Scalar.BLOCK_FOLDED = "BLOCK_FOLDED";
  Scalar.BLOCK_LITERAL = "BLOCK_LITERAL";
  Scalar.PLAIN = "PLAIN";
  Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE";
  Scalar.QUOTE_SINGLE = "QUOTE_SINGLE";
  exports.Scalar = Scalar;
  exports.isScalarValue = isScalarValue;
});

// node_modules/yaml/dist/doc/createNode.js
var require_createNode = __commonJS((exports) => {
  var Alias = require_Alias();
  var identity3 = require_identity();
  var Scalar = require_Scalar();
  var defaultTagPrefix = "tag:yaml.org,2002:";
  function findTagObject(value, tagName, tags) {
    if (tagName) {
      const match = tags.filter((t) => t.tag === tagName);
      const tagObj = match.find((t) => !t.format) ?? match[0];
      if (!tagObj)
        throw new Error(`Tag ${tagName} not found`);
      return tagObj;
    }
    return tags.find((t) => t.identify?.(value) && !t.format);
  }
  function createNode(value, tagName, ctx) {
    if (identity3.isDocument(value))
      value = value.contents;
    if (identity3.isNode(value))
      return value;
    if (identity3.isPair(value)) {
      const map4 = ctx.schema[identity3.MAP].createNode?.(ctx.schema, null, ctx);
      map4.items.push(value);
      return map4;
    }
    if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) {
      value = value.valueOf();
    }
    const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;
    let ref = undefined;
    if (aliasDuplicateObjects && value && typeof value === "object") {
      ref = sourceObjects.get(value);
      if (ref) {
        ref.anchor ?? (ref.anchor = onAnchor(value));
        return new Alias.Alias(ref.anchor);
      } else {
        ref = { anchor: null, node: null };
        sourceObjects.set(value, ref);
      }
    }
    if (tagName?.startsWith("!!"))
      tagName = defaultTagPrefix + tagName.slice(2);
    let tagObj = findTagObject(value, tagName, schema.tags);
    if (!tagObj) {
      if (value && typeof value.toJSON === "function") {
        value = value.toJSON();
      }
      if (!value || typeof value !== "object") {
        const node2 = new Scalar.Scalar(value);
        if (ref)
          ref.node = node2;
        return node2;
      }
      tagObj = value instanceof Map ? schema[identity3.MAP] : (Symbol.iterator in Object(value)) ? schema[identity3.SEQ] : schema[identity3.MAP];
    }
    if (onTagObj) {
      onTagObj(tagObj);
      delete ctx.onTagObj;
    }
    const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar.Scalar(value);
    if (tagName)
      node.tag = tagName;
    else if (!tagObj.default)
      node.tag = tagObj.tag;
    if (ref)
      ref.node = node;
    return node;
  }
  exports.createNode = createNode;
});

// node_modules/yaml/dist/nodes/Collection.js
var require_Collection = __commonJS((exports) => {
  var createNode = require_createNode();
  var identity3 = require_identity();
  var Node2 = require_Node();
  function collectionFromPath(schema, path3, value) {
    let v = value;
    for (let i = path3.length - 1;i >= 0; --i) {
      const k = path3[i];
      if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
        const a = [];
        a[k] = v;
        v = a;
      } else {
        v = new Map([[k, v]]);
      }
    }
    return createNode.createNode(v, undefined, {
      aliasDuplicateObjects: false,
      keepUndefined: false,
      onAnchor: () => {
        throw new Error("This should not happen, please report a bug.");
      },
      schema,
      sourceObjects: new Map
    });
  }
  var isEmptyPath = (path3) => path3 == null || typeof path3 === "object" && !!path3[Symbol.iterator]().next().done;

  class Collection extends Node2.NodeBase {
    constructor(type, schema) {
      super(type);
      Object.defineProperty(this, "schema", {
        value: schema,
        configurable: true,
        enumerable: false,
        writable: true
      });
    }
    clone(schema) {
      const copy3 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
      if (schema)
        copy3.schema = schema;
      copy3.items = copy3.items.map((it) => identity3.isNode(it) || identity3.isPair(it) ? it.clone(schema) : it);
      if (this.range)
        copy3.range = this.range.slice();
      return copy3;
    }
    addIn(path3, value) {
      if (isEmptyPath(path3))
        this.add(value);
      else {
        const [key, ...rest] = path3;
        const node = this.get(key, true);
        if (identity3.isCollection(node))
          node.addIn(rest, value);
        else if (node === undefined && this.schema)
          this.set(key, collectionFromPath(this.schema, rest, value));
        else
          throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
      }
    }
    deleteIn(path3) {
      const [key, ...rest] = path3;
      if (rest.length === 0)
        return this.delete(key);
      const node = this.get(key, true);
      if (identity3.isCollection(node))
        return node.deleteIn(rest);
      else
        throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
    }
    getIn(path3, keepScalar) {
      const [key, ...rest] = path3;
      const node = this.get(key, true);
      if (rest.length === 0)
        return !keepScalar && identity3.isScalar(node) ? node.value : node;
      else
        return identity3.isCollection(node) ? node.getIn(rest, keepScalar) : undefined;
    }
    hasAllNullValues(allowScalar) {
      return this.items.every((node) => {
        if (!identity3.isPair(node))
          return false;
        const n = node.value;
        return n == null || allowScalar && identity3.isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag;
      });
    }
    hasIn(path3) {
      const [key, ...rest] = path3;
      if (rest.length === 0)
        return this.has(key);
      const node = this.get(key, true);
      return identity3.isCollection(node) ? node.hasIn(rest) : false;
    }
    setIn(path3, value) {
      const [key, ...rest] = path3;
      if (rest.length === 0) {
        this.set(key, value);
      } else {
        const node = this.get(key, true);
        if (identity3.isCollection(node))
          node.setIn(rest, value);
        else if (node === undefined && this.schema)
          this.set(key, collectionFromPath(this.schema, rest, value));
        else
          throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
      }
    }
  }
  exports.Collection = Collection;
  exports.collectionFromPath = collectionFromPath;
  exports.isEmptyPath = isEmptyPath;
});

// node_modules/yaml/dist/stringify/stringifyComment.js
var require_stringifyComment = __commonJS((exports) => {
  var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#");
  function indentComment(comment, indent) {
    if (/^\n+$/.test(comment))
      return comment.substring(1);
    return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
  }
  var lineComment = (str, indent, comment) => str.endsWith(`
`) ? indentComment(comment, indent) : comment.includes(`
`) ? `
` + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment;
  exports.indentComment = indentComment;
  exports.lineComment = lineComment;
  exports.stringifyComment = stringifyComment;
});

// node_modules/yaml/dist/stringify/foldFlowLines.js
var require_foldFlowLines = __commonJS((exports) => {
  var FOLD_FLOW = "flow";
  var FOLD_BLOCK = "block";
  var FOLD_QUOTED = "quoted";
  function foldFlowLines(text2, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
    if (!lineWidth || lineWidth < 0)
      return text2;
    if (lineWidth < minContentWidth)
      minContentWidth = 0;
    const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
    if (text2.length <= endStep)
      return text2;
    const folds = [];
    const escapedFolds = {};
    let end = lineWidth - indent.length;
    if (typeof indentAtStart === "number") {
      if (indentAtStart > lineWidth - Math.max(2, minContentWidth))
        folds.push(0);
      else
        end = lineWidth - indentAtStart;
    }
    let split = undefined;
    let prev = undefined;
    let overflow = false;
    let i = -1;
    let escStart = -1;
    let escEnd = -1;
    if (mode === FOLD_BLOCK) {
      i = consumeMoreIndentedLines(text2, i, indent.length);
      if (i !== -1)
        end = i + endStep;
    }
    for (let ch;ch = text2[i += 1]; ) {
      if (mode === FOLD_QUOTED && ch === "\\") {
        escStart = i;
        switch (text2[i + 1]) {
          case "x":
            i += 3;
            break;
          case "u":
            i += 5;
            break;
          case "U":
            i += 9;
            break;
          default:
            i += 1;
        }
        escEnd = i;
      }
      if (ch === `
`) {
        if (mode === FOLD_BLOCK)
          i = consumeMoreIndentedLines(text2, i, indent.length);
        end = i + indent.length + endStep;
        split = undefined;
      } else {
        if (ch === " " && prev && prev !== " " && prev !== `
` && prev !== "\t") {
          const next = text2[i + 1];
          if (next && next !== " " && next !== `
` && next !== "\t")
            split = i;
        }
        if (i >= end) {
          if (split) {
            folds.push(split);
            end = split + endStep;
            split = undefined;
          } else if (mode === FOLD_QUOTED) {
            while (prev === " " || prev === "\t") {
              prev = ch;
              ch = text2[i += 1];
              overflow = true;
            }
            const j = i > escEnd + 1 ? i - 2 : escStart - 1;
            if (escapedFolds[j])
              return text2;
            folds.push(j);
            escapedFolds[j] = true;
            end = j + endStep;
            split = undefined;
          } else {
            overflow = true;
          }
        }
      }
      prev = ch;
    }
    if (overflow && onOverflow)
      onOverflow();
    if (folds.length === 0)
      return text2;
    if (onFold)
      onFold();
    let res = text2.slice(0, folds[0]);
    for (let i2 = 0;i2 < folds.length; ++i2) {
      const fold = folds[i2];
      const end2 = folds[i2 + 1] || text2.length;
      if (fold === 0)
        res = `
${indent}${text2.slice(0, end2)}`;
      else {
        if (mode === FOLD_QUOTED && escapedFolds[fold])
          res += `${text2[fold]}\\`;
        res += `
${indent}${text2.slice(fold + 1, end2)}`;
      }
    }
    return res;
  }
  function consumeMoreIndentedLines(text2, i, indent) {
    let end = i;
    let start = i + 1;
    let ch = text2[start];
    while (ch === " " || ch === "\t") {
      if (i < start + indent) {
        ch = text2[++i];
      } else {
        do {
          ch = text2[++i];
        } while (ch && ch !== `
`);
        end = i;
        start = i + 1;
        ch = text2[start];
      }
    }
    return end;
  }
  exports.FOLD_BLOCK = FOLD_BLOCK;
  exports.FOLD_FLOW = FOLD_FLOW;
  exports.FOLD_QUOTED = FOLD_QUOTED;
  exports.foldFlowLines = foldFlowLines;
});

// node_modules/yaml/dist/stringify/stringifyString.js
var require_stringifyString = __commonJS((exports) => {
  var Scalar = require_Scalar();
  var foldFlowLines = require_foldFlowLines();
  var getFoldOptions = (ctx, isBlock) => ({
    indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,
    lineWidth: ctx.options.lineWidth,
    minContentWidth: ctx.options.minContentWidth
  });
  var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str);
  function lineLengthOverLimit(str, lineWidth, indentLength) {
    if (!lineWidth || lineWidth < 0)
      return false;
    const limit = lineWidth - indentLength;
    const strLen = str.length;
    if (strLen <= limit)
      return false;
    for (let i = 0, start = 0;i < strLen; ++i) {
      if (str[i] === `
`) {
        if (i - start > limit)
          return true;
        start = i + 1;
        if (strLen - start <= limit)
          return false;
      }
    }
    return true;
  }
  function doubleQuotedString(value, ctx) {
    const json2 = JSON.stringify(value);
    if (ctx.options.doubleQuotedAsJSON)
      return json2;
    const { implicitKey } = ctx;
    const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
    const indent = ctx.indent || (containsDocumentMarker(value) ? "  " : "");
    let str = "";
    let start = 0;
    for (let i = 0, ch = json2[i];ch; ch = json2[++i]) {
      if (ch === " " && json2[i + 1] === "\\" && json2[i + 2] === "n") {
        str += json2.slice(start, i) + "\\ ";
        i += 1;
        start = i;
        ch = "\\";
      }
      if (ch === "\\")
        switch (json2[i + 1]) {
          case "u":
            {
              str += json2.slice(start, i);
              const code = json2.substr(i + 2, 4);
              switch (code) {
                case "0000":
                  str += "\\0";
                  break;
                case "0007":
                  str += "\\a";
                  break;
                case "000b":
                  str += "\\v";
                  break;
                case "001b":
                  str += "\\e";
                  break;
                case "0085":
                  str += "\\N";
                  break;
                case "00a0":
                  str += "\\_";
                  break;
                case "2028":
                  str += "\\L";
                  break;
                case "2029":
                  str += "\\P";
                  break;
                default:
                  if (code.substr(0, 2) === "00")
                    str += "\\x" + code.substr(2);
                  else
                    str += json2.substr(i, 6);
              }
              i += 5;
              start = i + 1;
            }
            break;
          case "n":
            if (implicitKey || json2[i + 2] === '"' || json2.length < minMultiLineLength) {
              i += 1;
            } else {
              str += json2.slice(start, i) + `

`;
              while (json2[i + 2] === "\\" && json2[i + 3] === "n" && json2[i + 4] !== '"') {
                str += `
`;
                i += 2;
              }
              str += indent;
              if (json2[i + 2] === " ")
                str += "\\";
              i += 1;
              start = i + 1;
            }
            break;
          default:
            i += 1;
        }
    }
    str = start ? str + json2.slice(start) : json2;
    return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false));
  }
  function singleQuotedString(value, ctx) {
    if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes(`
`) || /[ \t]\n|\n[ \t]/.test(value))
      return doubleQuotedString(value, ctx);
    const indent = ctx.indent || (containsDocumentMarker(value) ? "  " : "");
    const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&
${indent}`) + "'";
    return ctx.implicitKey ? res : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
  }
  function quotedString(value, ctx) {
    const { singleQuote } = ctx.options;
    let qs;
    if (singleQuote === false)
      qs = doubleQuotedString;
    else {
      const hasDouble = value.includes('"');
      const hasSingle = value.includes("'");
      if (hasDouble && !hasSingle)
        qs = singleQuotedString;
      else if (hasSingle && !hasDouble)
        qs = doubleQuotedString;
      else
        qs = singleQuote ? singleQuotedString : doubleQuotedString;
    }
    return qs(value, ctx);
  }
  var blockEndNewlines;
  try {
    blockEndNewlines = new RegExp(`(^|(?<!
))
+(?!
|$)`, "g");
  } catch {
    blockEndNewlines = /\n+(?!\n|$)/g;
  }
  function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
    const { blockQuote, commentString, lineWidth } = ctx.options;
    if (!blockQuote || /\n[\t ]+$/.test(value)) {
      return quotedString(value, ctx);
    }
    const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? "  " : "");
    const literal2 = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.Scalar.BLOCK_FOLDED ? false : type === Scalar.Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, lineWidth, indent.length);
    if (!value)
      return literal2 ? `|
` : `>
`;
    let chomp;
    let endStart;
    for (endStart = value.length;endStart > 0; --endStart) {
      const ch = value[endStart - 1];
      if (ch !== `
` && ch !== "\t" && ch !== " ")
        break;
    }
    let end = value.substring(endStart);
    const endNlPos = end.indexOf(`
`);
    if (endNlPos === -1) {
      chomp = "-";
    } else if (value === end || endNlPos !== end.length - 1) {
      chomp = "+";
      if (onChompKeep)
        onChompKeep();
    } else {
      chomp = "";
    }
    if (end) {
      value = value.slice(0, -end.length);
      if (end[end.length - 1] === `
`)
        end = end.slice(0, -1);
      end = end.replace(blockEndNewlines, `$&${indent}`);
    }
    let startWithSpace = false;
    let startEnd;
    let startNlPos = -1;
    for (startEnd = 0;startEnd < value.length; ++startEnd) {
      const ch = value[startEnd];
      if (ch === " ")
        startWithSpace = true;
      else if (ch === `
`)
        startNlPos = startEnd;
      else
        break;
    }
    let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
    if (start) {
      value = value.substring(start.length);
      start = start.replace(/\n+/g, `$&${indent}`);
    }
    const indentSize = indent ? "2" : "1";
    let header = (startWithSpace ? indentSize : "") + chomp;
    if (comment) {
      header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " "));
      if (onComment)
        onComment();
    }
    if (!literal2) {
      const foldedValue = value.replace(/\n+/g, `
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`);
      let literalFallback = false;
      const foldOptions = getFoldOptions(ctx, true);
      if (blockQuote !== "folded" && type !== Scalar.Scalar.BLOCK_FOLDED) {
        foldOptions.onOverflow = () => {
          literalFallback = true;
        };
      }
      const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions);
      if (!literalFallback)
        return `>${header}
${indent}${body}`;
    }
    value = value.replace(/\n+/g, `$&${indent}`);
    return `|${header}
${indent}${start}${value}${end}`;
  }
  function plainString(item, ctx, onComment, onChompKeep) {
    const { type, value } = item;
    const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
    if (implicitKey && value.includes(`
`) || inFlow && /[[\]{},]/.test(value)) {
      return quotedString(value, ctx);
    }
    if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
      return implicitKey || inFlow || !value.includes(`
`) ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep);
    }
    if (!implicitKey && !inFlow && type !== Scalar.Scalar.PLAIN && value.includes(`
`)) {
      return blockString(item, ctx, onComment, onChompKeep);
    }
    if (containsDocumentMarker(value)) {
      if (indent === "") {
        ctx.forceBlockIndent = true;
        return blockString(item, ctx, onComment, onChompKeep);
      } else if (implicitKey && indent === indentStep) {
        return quotedString(value, ctx);
      }
    }
    const str = value.replace(/\n+/g, `$&
${indent}`);
    if (actualString) {
      const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str);
      const { compat: compat2, tags } = ctx.doc.schema;
      if (tags.some(test) || compat2?.some(test))
        return quotedString(value, ctx);
    }
    return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
  }
  function stringifyString(item, ctx, onComment, onChompKeep) {
    const { implicitKey, inFlow } = ctx;
    const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) });
    let { type } = item;
    if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
      if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
        type = Scalar.Scalar.QUOTE_DOUBLE;
    }
    const _stringify = (_type) => {
      switch (_type) {
        case Scalar.Scalar.BLOCK_FOLDED:
        case Scalar.Scalar.BLOCK_LITERAL:
          return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep);
        case Scalar.Scalar.QUOTE_DOUBLE:
          return doubleQuotedString(ss.value, ctx);
        case Scalar.Scalar.QUOTE_SINGLE:
          return singleQuotedString(ss.value, ctx);
        case Scalar.Scalar.PLAIN:
          return plainString(ss, ctx, onComment, onChompKeep);
        default:
          return null;
      }
    };
    let res = _stringify(type);
    if (res === null) {
      const { defaultKeyType, defaultStringType } = ctx.options;
      const t = implicitKey && defaultKeyType || defaultStringType;
      res = _stringify(t);
      if (res === null)
        throw new Error(`Unsupported default string type ${t}`);
    }
    return res;
  }
  exports.stringifyString = stringifyString;
});

// node_modules/yaml/dist/stringify/stringify.js
var require_stringify = __commonJS((exports) => {
  var anchors = require_anchors();
  var identity3 = require_identity();
  var stringifyComment = require_stringifyComment();
  var stringifyString = require_stringifyString();
  function createStringifyContext(doc2, options) {
    const opt = Object.assign({
      blockQuote: true,
      commentString: stringifyComment.stringifyComment,
      defaultKeyType: null,
      defaultStringType: "PLAIN",
      directives: null,
      doubleQuotedAsJSON: false,
      doubleQuotedMinMultiLineLength: 40,
      falseStr: "false",
      flowCollectionPadding: true,
      indentSeq: true,
      lineWidth: 80,
      minContentWidth: 20,
      nullStr: "null",
      simpleKeys: false,
      singleQuote: null,
      trailingComma: false,
      trueStr: "true",
      verifyAliasOrder: true
    }, doc2.schema.toStringOptions, options);
    let inFlow;
    switch (opt.collectionStyle) {
      case "block":
        inFlow = false;
        break;
      case "flow":
        inFlow = true;
        break;
      default:
        inFlow = null;
    }
    return {
      anchors: new Set,
      doc: doc2,
      flowCollectionPadding: opt.flowCollectionPadding ? " " : "",
      indent: "",
      indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : "  ",
      inFlow,
      options: opt
    };
  }
  function getTagObject(tags, item) {
    if (item.tag) {
      const match = tags.filter((t) => t.tag === item.tag);
      if (match.length > 0)
        return match.find((t) => t.format === item.format) ?? match[0];
    }
    let tagObj = undefined;
    let obj;
    if (identity3.isScalar(item)) {
      obj = item.value;
      let match = tags.filter((t) => t.identify?.(obj));
      if (match.length > 1) {
        const testMatch = match.filter((t) => t.test);
        if (testMatch.length > 0)
          match = testMatch;
      }
      tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format);
    } else {
      obj = item;
      tagObj = tags.find((t) => t.nodeClass && obj instanceof t.nodeClass);
    }
    if (!tagObj) {
      const name = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj);
      throw new Error(`Tag not resolved for ${name} value`);
    }
    return tagObj;
  }
  function stringifyProps(node, tagObj, { anchors: anchors$1, doc: doc2 }) {
    if (!doc2.directives)
      return "";
    const props = [];
    const anchor = (identity3.isScalar(node) || identity3.isCollection(node)) && node.anchor;
    if (anchor && anchors.anchorIsValid(anchor)) {
      anchors$1.add(anchor);
      props.push(`&${anchor}`);
    }
    const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);
    if (tag)
      props.push(doc2.directives.tagString(tag));
    return props.join(" ");
  }
  function stringify(item, ctx, onComment, onChompKeep) {
    if (identity3.isPair(item))
      return item.toString(ctx, onComment, onChompKeep);
    if (identity3.isAlias(item)) {
      if (ctx.doc.directives)
        return item.toString(ctx);
      if (ctx.resolvedAliases?.has(item)) {
        throw new TypeError(`Cannot stringify circular structure without alias nodes`);
      } else {
        if (ctx.resolvedAliases)
          ctx.resolvedAliases.add(item);
        else
          ctx.resolvedAliases = new Set([item]);
        item = item.resolve(ctx.doc);
      }
    }
    let tagObj = undefined;
    const node = identity3.isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o });
    tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));
    const props = stringifyProps(node, tagObj, ctx);
    if (props.length > 0)
      ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
    const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : identity3.isScalar(node) ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep);
    if (!props)
      return str;
    return identity3.isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props}
${ctx.indent}${str}`;
  }
  exports.createStringifyContext = createStringifyContext;
  exports.stringify = stringify;
});

// node_modules/yaml/dist/stringify/stringifyPair.js
var require_stringifyPair = __commonJS((exports) => {
  var identity3 = require_identity();
  var Scalar = require_Scalar();
  var stringify = require_stringify();
  var stringifyComment = require_stringifyComment();
  function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
    const { allNullValues, doc: doc2, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
    let keyComment = identity3.isNode(key) && key.comment || null;
    if (simpleKeys) {
      if (keyComment) {
        throw new Error("With simple keys, key nodes cannot have comments");
      }
      if (identity3.isCollection(key) || !identity3.isNode(key) && typeof key === "object") {
        const msg = "With simple keys, collection cannot be used as a key value";
        throw new Error(msg);
      }
    }
    let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || identity3.isCollection(key) || (identity3.isScalar(key) ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL : typeof key === "object"));
    ctx = Object.assign({}, ctx, {
      allNullValues: false,
      implicitKey: !explicitKey && (simpleKeys || !allNullValues),
      indent: indent + indentStep
    });
    let keyCommentDone = false;
    let chompKeep = false;
    let str = stringify.stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true);
    if (!explicitKey && !ctx.inFlow && str.length > 1024) {
      if (simpleKeys)
        throw new Error("With simple keys, single line scalar must not span more than 1024 characters");
      explicitKey = true;
    }
    if (ctx.inFlow) {
      if (allNullValues || value == null) {
        if (keyCommentDone && onComment)
          onComment();
        return str === "" ? "?" : explicitKey ? `? ${str}` : str;
      }
    } else if (allNullValues && !simpleKeys || value == null && explicitKey) {
      str = `? ${str}`;
      if (keyComment && !keyCommentDone) {
        str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
      } else if (chompKeep && onChompKeep)
        onChompKeep();
      return str;
    }
    if (keyCommentDone)
      keyComment = null;
    if (explicitKey) {
      if (keyComment)
        str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
      str = `? ${str}
${indent}:`;
    } else {
      str = `${str}:`;
      if (keyComment)
        str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
    }
    let vsb, vcb, valueComment;
    if (identity3.isNode(value)) {
      vsb = !!value.spaceBefore;
      vcb = value.commentBefore;
      valueComment = value.comment;
    } else {
      vsb = false;
      vcb = null;
      valueComment = null;
      if (value && typeof value === "object")
        value = doc2.createNode(value);
    }
    ctx.implicitKey = false;
    if (!explicitKey && !keyComment && identity3.isScalar(value))
      ctx.indentAtStart = str.length + 1;
    chompKeep = false;
    if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && identity3.isSeq(value) && !value.flow && !value.tag && !value.anchor) {
      ctx.indent = ctx.indent.substring(2);
    }
    let valueCommentDone = false;
    const valueStr = stringify.stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true);
    let ws = " ";
    if (keyComment || vsb || vcb) {
      ws = vsb ? `
` : "";
      if (vcb) {
        const cs = commentString(vcb);
        ws += `
${stringifyComment.indentComment(cs, ctx.indent)}`;
      }
      if (valueStr === "" && !ctx.inFlow) {
        if (ws === `
` && valueComment)
          ws = `

`;
      } else {
        ws += `
${ctx.indent}`;
      }
    } else if (!explicitKey && identity3.isCollection(value)) {
      const vs0 = valueStr[0];
      const nl0 = valueStr.indexOf(`
`);
      const hasNewline = nl0 !== -1;
      const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;
      if (hasNewline || !flow) {
        let hasPropsLine = false;
        if (hasNewline && (vs0 === "&" || vs0 === "!")) {
          let sp0 = valueStr.indexOf(" ");
          if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") {
            sp0 = valueStr.indexOf(" ", sp0 + 1);
          }
          if (sp0 === -1 || nl0 < sp0)
            hasPropsLine = true;
        }
        if (!hasPropsLine)
          ws = `
${ctx.indent}`;
      }
    } else if (valueStr === "" || valueStr[0] === `
`) {
      ws = "";
    }
    str += ws + valueStr;
    if (ctx.inFlow) {
      if (valueCommentDone && onComment)
        onComment();
    } else if (valueComment && !valueCommentDone) {
      str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment));
    } else if (chompKeep && onChompKeep) {
      onChompKeep();
    }
    return str;
  }
  exports.stringifyPair = stringifyPair;
});

// node_modules/yaml/dist/log.js
var require_log = __commonJS((exports) => {
  var node_process = __require("process");
  function debug(logLevel, ...messages) {
    if (logLevel === "debug")
      console.log(...messages);
  }
  function warn3(logLevel, warning) {
    if (logLevel === "debug" || logLevel === "warn") {
      if (typeof node_process.emitWarning === "function")
        node_process.emitWarning(warning);
      else
        console.warn(warning);
    }
  }
  exports.debug = debug;
  exports.warn = warn3;
});

// node_modules/yaml/dist/schema/yaml-1.1/merge.js
var require_merge = __commonJS((exports) => {
  var identity3 = require_identity();
  var Scalar = require_Scalar();
  var MERGE_KEY = "<<";
  var merge2 = {
    identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY,
    default: "key",
    tag: "tag:yaml.org,2002:merge",
    test: /^<<$/,
    resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), {
      addToJSMap: addMergeToJSMap
    }),
    stringify: () => MERGE_KEY
  };
  var isMergeKey = (ctx, key) => (merge2.identify(key) || identity3.isScalar(key) && (!key.type || key.type === Scalar.Scalar.PLAIN) && merge2.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge2.tag && tag.default);
  function addMergeToJSMap(ctx, map4, value) {
    value = ctx && identity3.isAlias(value) ? value.resolve(ctx.doc) : value;
    if (identity3.isSeq(value))
      for (const it of value.items)
        mergeValue(ctx, map4, it);
    else if (Array.isArray(value))
      for (const it of value)
        mergeValue(ctx, map4, it);
    else
      mergeValue(ctx, map4, value);
  }
  function mergeValue(ctx, map4, value) {
    const source = ctx && identity3.isAlias(value) ? value.resolve(ctx.doc) : value;
    if (!identity3.isMap(source))
      throw new Error("Merge sources must be maps or map aliases");
    const srcMap = source.toJSON(null, ctx, Map);
    for (const [key, value2] of srcMap) {
      if (map4 instanceof Map) {
        if (!map4.has(key))
          map4.set(key, value2);
      } else if (map4 instanceof Set) {
        map4.add(key);
      } else if (!Object.prototype.hasOwnProperty.call(map4, key)) {
        Object.defineProperty(map4, key, {
          value: value2,
          writable: true,
          enumerable: true,
          configurable: true
        });
      }
    }
    return map4;
  }
  exports.addMergeToJSMap = addMergeToJSMap;
  exports.isMergeKey = isMergeKey;
  exports.merge = merge2;
});

// node_modules/yaml/dist/nodes/addPairToJSMap.js
var require_addPairToJSMap = __commonJS((exports) => {
  var log = require_log();
  var merge2 = require_merge();
  var stringify = require_stringify();
  var identity3 = require_identity();
  var toJS = require_toJS();
  function addPairToJSMap(ctx, map4, { key, value }) {
    if (identity3.isNode(key) && key.addToJSMap)
      key.addToJSMap(ctx, map4, value);
    else if (merge2.isMergeKey(ctx, key))
      merge2.addMergeToJSMap(ctx, map4, value);
    else {
      const jsKey = toJS.toJS(key, "", ctx);
      if (map4 instanceof Map) {
        map4.set(jsKey, toJS.toJS(value, jsKey, ctx));
      } else if (map4 instanceof Set) {
        map4.add(jsKey);
      } else {
        const stringKey = stringifyKey(key, jsKey, ctx);
        const jsValue = toJS.toJS(value, stringKey, ctx);
        if (stringKey in map4)
          Object.defineProperty(map4, stringKey, {
            value: jsValue,
            writable: true,
            enumerable: true,
            configurable: true
          });
        else
          map4[stringKey] = jsValue;
      }
    }
    return map4;
  }
  function stringifyKey(key, jsKey, ctx) {
    if (jsKey === null)
      return "";
    if (typeof jsKey !== "object")
      return String(jsKey);
    if (identity3.isNode(key) && ctx?.doc) {
      const strCtx = stringify.createStringifyContext(ctx.doc, {});
      strCtx.anchors = new Set;
      for (const node of ctx.anchors.keys())
        strCtx.anchors.add(node.anchor);
      strCtx.inFlow = true;
      strCtx.inStringifyKey = true;
      const strKey = key.toString(strCtx);
      if (!ctx.mapKeyWarned) {
        let jsonStr = JSON.stringify(strKey);
        if (jsonStr.length > 40)
          jsonStr = jsonStr.substring(0, 36) + '..."';
        log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
        ctx.mapKeyWarned = true;
      }
      return strKey;
    }
    return JSON.stringify(jsKey);
  }
  exports.addPairToJSMap = addPairToJSMap;
});

// node_modules/yaml/dist/nodes/Pair.js
var require_Pair = __commonJS((exports) => {
  var createNode = require_createNode();
  var stringifyPair = require_stringifyPair();
  var addPairToJSMap = require_addPairToJSMap();
  var identity3 = require_identity();
  function createPair(key, value, ctx) {
    const k = createNode.createNode(key, undefined, ctx);
    const v = createNode.createNode(value, undefined, ctx);
    return new Pair2(k, v);
  }

  class Pair2 {
    constructor(key, value = null) {
      Object.defineProperty(this, identity3.NODE_TYPE, { value: identity3.PAIR });
      this.key = key;
      this.value = value;
    }
    clone(schema) {
      let { key, value } = this;
      if (identity3.isNode(key))
        key = key.clone(schema);
      if (identity3.isNode(value))
        value = value.clone(schema);
      return new Pair2(key, value);
    }
    toJSON(_, ctx) {
      const pair = ctx?.mapAsMap ? new Map : {};
      return addPairToJSMap.addPairToJSMap(ctx, pair, this);
    }
    toString(ctx, onComment, onChompKeep) {
      return ctx?.doc ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this);
    }
  }
  exports.Pair = Pair2;
  exports.createPair = createPair;
});

// node_modules/yaml/dist/stringify/stringifyCollection.js
var require_stringifyCollection = __commonJS((exports) => {
  var identity3 = require_identity();
  var stringify = require_stringify();
  var stringifyComment = require_stringifyComment();
  function stringifyCollection(collection, ctx, options) {
    const flow = ctx.inFlow ?? collection.flow;
    const stringify2 = flow ? stringifyFlowCollection : stringifyBlockCollection;
    return stringify2(collection, ctx, options);
  }
  function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
    const { indent, options: { commentString } } = ctx;
    const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
    let chompKeep = false;
    const lines = [];
    for (let i = 0;i < items.length; ++i) {
      const item = items[i];
      let comment2 = null;
      if (identity3.isNode(item)) {
        if (!chompKeep && item.spaceBefore)
          lines.push("");
        addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
        if (item.comment)
          comment2 = item.comment;
      } else if (identity3.isPair(item)) {
        const ik = identity3.isNode(item.key) ? item.key : null;
        if (ik) {
          if (!chompKeep && ik.spaceBefore)
            lines.push("");
          addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
        }
      }
      chompKeep = false;
      let str2 = stringify.stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true);
      if (comment2)
        str2 += stringifyComment.lineComment(str2, itemIndent, commentString(comment2));
      if (chompKeep && comment2)
        chompKeep = false;
      lines.push(blockItemPrefix + str2);
    }
    let str;
    if (lines.length === 0) {
      str = flowChars.start + flowChars.end;
    } else {
      str = lines[0];
      for (let i = 1;i < lines.length; ++i) {
        const line = lines[i];
        str += line ? `
${indent}${line}` : `
`;
      }
    }
    if (comment) {
      str += `
` + stringifyComment.indentComment(commentString(comment), indent);
      if (onComment)
        onComment();
    } else if (chompKeep && onChompKeep)
      onChompKeep();
    return str;
  }
  function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {
    const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
    itemIndent += indentStep;
    const itemCtx = Object.assign({}, ctx, {
      indent: itemIndent,
      inFlow: true,
      type: null
    });
    let reqNewline = false;
    let linesAtValue = 0;
    const lines = [];
    for (let i = 0;i < items.length; ++i) {
      const item = items[i];
      let comment = null;
      if (identity3.isNode(item)) {
        if (item.spaceBefore)
          lines.push("");
        addCommentBefore(ctx, lines, item.commentBefore, false);
        if (item.comment)
          comment = item.comment;
      } else if (identity3.isPair(item)) {
        const ik = identity3.isNode(item.key) ? item.key : null;
        if (ik) {
          if (ik.spaceBefore)
            lines.push("");
          addCommentBefore(ctx, lines, ik.commentBefore, false);
          if (ik.comment)
            reqNewline = true;
        }
        const iv = identity3.isNode(item.value) ? item.value : null;
        if (iv) {
          if (iv.comment)
            comment = iv.comment;
          if (iv.commentBefore)
            reqNewline = true;
        } else if (item.value == null && ik?.comment) {
          comment = ik.comment;
        }
      }
      if (comment)
        reqNewline = true;
      let str = stringify.stringify(item, itemCtx, () => comment = null);
      reqNewline || (reqNewline = lines.length > linesAtValue || str.includes(`
`));
      if (i < items.length - 1) {
        str += ",";
      } else if (ctx.options.trailingComma) {
        if (ctx.options.lineWidth > 0) {
          reqNewline || (reqNewline = lines.reduce((sum2, line) => sum2 + line.length + 2, 2) + (str.length + 2) > ctx.options.lineWidth);
        }
        if (reqNewline) {
          str += ",";
        }
      }
      if (comment)
        str += stringifyComment.lineComment(str, itemIndent, commentString(comment));
      lines.push(str);
      linesAtValue = lines.length;
    }
    const { start, end } = flowChars;
    if (lines.length === 0) {
      return start + end;
    } else {
      if (!reqNewline) {
        const len = lines.reduce((sum2, line) => sum2 + line.length + 2, 2);
        reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;
      }
      if (reqNewline) {
        let str = start;
        for (const line of lines)
          str += line ? `
${indentStep}${indent}${line}` : `
`;
        return `${str}
${indent}${end}`;
      } else {
        return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`;
      }
    }
  }
  function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
    if (comment && chompKeep)
      comment = comment.replace(/^\n+/, "");
    if (comment) {
      const ic = stringifyComment.indentComment(commentString(comment), indent);
      lines.push(ic.trimStart());
    }
  }
  exports.stringifyCollection = stringifyCollection;
});

// node_modules/yaml/dist/nodes/YAMLMap.js
var require_YAMLMap = __commonJS((exports) => {
  var stringifyCollection = require_stringifyCollection();
  var addPairToJSMap = require_addPairToJSMap();
  var Collection = require_Collection();
  var identity3 = require_identity();
  var Pair2 = require_Pair();
  var Scalar = require_Scalar();
  function findPair(items, key) {
    const k = identity3.isScalar(key) ? key.value : key;
    for (const it of items) {
      if (identity3.isPair(it)) {
        if (it.key === key || it.key === k)
          return it;
        if (identity3.isScalar(it.key) && it.key.value === k)
          return it;
      }
    }
    return;
  }

  class YAMLMap extends Collection.Collection {
    static get tagName() {
      return "tag:yaml.org,2002:map";
    }
    constructor(schema) {
      super(identity3.MAP, schema);
      this.items = [];
    }
    static from(schema, obj, ctx) {
      const { keepUndefined, replacer } = ctx;
      const map4 = new this(schema);
      const add = (key, value) => {
        if (typeof replacer === "function")
          value = replacer.call(obj, key, value);
        else if (Array.isArray(replacer) && !replacer.includes(key))
          return;
        if (value !== undefined || keepUndefined)
          map4.items.push(Pair2.createPair(key, value, ctx));
      };
      if (obj instanceof Map) {
        for (const [key, value] of obj)
          add(key, value);
      } else if (obj && typeof obj === "object") {
        for (const key of Object.keys(obj))
          add(key, obj[key]);
      }
      if (typeof schema.sortMapEntries === "function") {
        map4.items.sort(schema.sortMapEntries);
      }
      return map4;
    }
    add(pair, overwrite) {
      let _pair;
      if (identity3.isPair(pair))
        _pair = pair;
      else if (!pair || typeof pair !== "object" || !("key" in pair)) {
        _pair = new Pair2.Pair(pair, pair?.value);
      } else
        _pair = new Pair2.Pair(pair.key, pair.value);
      const prev = findPair(this.items, _pair.key);
      const sortEntries = this.schema?.sortMapEntries;
      if (prev) {
        if (!overwrite)
          throw new Error(`Key ${_pair.key} already set`);
        if (identity3.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))
          prev.value.value = _pair.value;
        else
          prev.value = _pair.value;
      } else if (sortEntries) {
        const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0);
        if (i === -1)
          this.items.push(_pair);
        else
          this.items.splice(i, 0, _pair);
      } else {
        this.items.push(_pair);
      }
    }
    delete(key) {
      const it = findPair(this.items, key);
      if (!it)
        return false;
      const del = this.items.splice(this.items.indexOf(it), 1);
      return del.length > 0;
    }
    get(key, keepScalar) {
      const it = findPair(this.items, key);
      const node = it?.value;
      return (!keepScalar && identity3.isScalar(node) ? node.value : node) ?? undefined;
    }
    has(key) {
      return !!findPair(this.items, key);
    }
    set(key, value) {
      this.add(new Pair2.Pair(key, value), true);
    }
    toJSON(_, ctx, Type) {
      const map4 = Type ? new Type : ctx?.mapAsMap ? new Map : {};
      if (ctx?.onCreate)
        ctx.onCreate(map4);
      for (const item of this.items)
        addPairToJSMap.addPairToJSMap(ctx, map4, item);
      return map4;
    }
    toString(ctx, onComment, onChompKeep) {
      if (!ctx)
        return JSON.stringify(this);
      for (const item of this.items) {
        if (!identity3.isPair(item))
          throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
      }
      if (!ctx.allNullValues && this.hasAllNullValues(false))
        ctx = Object.assign({}, ctx, { allNullValues: true });
      return stringifyCollection.stringifyCollection(this, ctx, {
        blockItemPrefix: "",
        flowChars: { start: "{", end: "}" },
        itemIndent: ctx.indent || "",
        onChompKeep,
        onComment
      });
    }
  }
  exports.YAMLMap = YAMLMap;
  exports.findPair = findPair;
});

// node_modules/yaml/dist/schema/common/map.js
var require_map = __commonJS((exports) => {
  var identity3 = require_identity();
  var YAMLMap = require_YAMLMap();
  var map4 = {
    collection: "map",
    default: true,
    nodeClass: YAMLMap.YAMLMap,
    tag: "tag:yaml.org,2002:map",
    resolve(map5, onError) {
      if (!identity3.isMap(map5))
        onError("Expected a mapping for this tag");
      return map5;
    },
    createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx)
  };
  exports.map = map4;
});

// node_modules/yaml/dist/nodes/YAMLSeq.js
var require_YAMLSeq = __commonJS((exports) => {
  var createNode = require_createNode();
  var stringifyCollection = require_stringifyCollection();
  var Collection = require_Collection();
  var identity3 = require_identity();
  var Scalar = require_Scalar();
  var toJS = require_toJS();

  class YAMLSeq extends Collection.Collection {
    static get tagName() {
      return "tag:yaml.org,2002:seq";
    }
    constructor(schema) {
      super(identity3.SEQ, schema);
      this.items = [];
    }
    add(value) {
      this.items.push(value);
    }
    delete(key) {
      const idx = asItemIndex(key);
      if (typeof idx !== "number")
        return false;
      const del = this.items.splice(idx, 1);
      return del.length > 0;
    }
    get(key, keepScalar) {
      const idx = asItemIndex(key);
      if (typeof idx !== "number")
        return;
      const it = this.items[idx];
      return !keepScalar && identity3.isScalar(it) ? it.value : it;
    }
    has(key) {
      const idx = asItemIndex(key);
      return typeof idx === "number" && idx < this.items.length;
    }
    set(key, value) {
      const idx = asItemIndex(key);
      if (typeof idx !== "number")
        throw new Error(`Expected a valid index, not ${key}.`);
      const prev = this.items[idx];
      if (identity3.isScalar(prev) && Scalar.isScalarValue(value))
        prev.value = value;
      else
        this.items[idx] = value;
    }
    toJSON(_, ctx) {
      const seq = [];
      if (ctx?.onCreate)
        ctx.onCreate(seq);
      let i = 0;
      for (const item of this.items)
        seq.push(toJS.toJS(item, String(i++), ctx));
      return seq;
    }
    toString(ctx, onComment, onChompKeep) {
      if (!ctx)
        return JSON.stringify(this);
      return stringifyCollection.stringifyCollection(this, ctx, {
        blockItemPrefix: "- ",
        flowChars: { start: "[", end: "]" },
        itemIndent: (ctx.indent || "") + "  ",
        onChompKeep,
        onComment
      });
    }
    static from(schema, obj, ctx) {
      const { replacer } = ctx;
      const seq = new this(schema);
      if (obj && Symbol.iterator in Object(obj)) {
        let i = 0;
        for (let it of obj) {
          if (typeof replacer === "function") {
            const key = obj instanceof Set ? it : String(i++);
            it = replacer.call(obj, key, it);
          }
          seq.items.push(createNode.createNode(it, undefined, ctx));
        }
      }
      return seq;
    }
  }
  function asItemIndex(key) {
    let idx = identity3.isScalar(key) ? key.value : key;
    if (idx && typeof idx === "string")
      idx = Number(idx);
    return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null;
  }
  exports.YAMLSeq = YAMLSeq;
});

// node_modules/yaml/dist/schema/common/seq.js
var require_seq = __commonJS((exports) => {
  var identity3 = require_identity();
  var YAMLSeq = require_YAMLSeq();
  var seq = {
    collection: "seq",
    default: true,
    nodeClass: YAMLSeq.YAMLSeq,
    tag: "tag:yaml.org,2002:seq",
    resolve(seq2, onError) {
      if (!identity3.isSeq(seq2))
        onError("Expected a sequence for this tag");
      return seq2;
    },
    createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx)
  };
  exports.seq = seq;
});

// node_modules/yaml/dist/schema/common/string.js
var require_string = __commonJS((exports) => {
  var stringifyString = require_stringifyString();
  var string4 = {
    identify: (value) => typeof value === "string",
    default: true,
    tag: "tag:yaml.org,2002:str",
    resolve: (str) => str,
    stringify(item, ctx, onComment, onChompKeep) {
      ctx = Object.assign({ actualString: true }, ctx);
      return stringifyString.stringifyString(item, ctx, onComment, onChompKeep);
    }
  };
  exports.string = string4;
});

// node_modules/yaml/dist/schema/common/null.js
var require_null = __commonJS((exports) => {
  var Scalar = require_Scalar();
  var nullTag = {
    identify: (value) => value == null,
    createNode: () => new Scalar.Scalar(null),
    default: true,
    tag: "tag:yaml.org,2002:null",
    test: /^(?:~|[Nn]ull|NULL)?$/,
    resolve: () => new Scalar.Scalar(null),
    stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr
  };
  exports.nullTag = nullTag;
});

// node_modules/yaml/dist/schema/core/bool.js
var require_bool = __commonJS((exports) => {
  var Scalar = require_Scalar();
  var boolTag = {
    identify: (value) => typeof value === "boolean",
    default: true,
    tag: "tag:yaml.org,2002:bool",
    test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
    resolve: (str) => new Scalar.Scalar(str[0] === "t" || str[0] === "T"),
    stringify({ source, value }, ctx) {
      if (source && boolTag.test.test(source)) {
        const sv = source[0] === "t" || source[0] === "T";
        if (value === sv)
          return source;
      }
      return value ? ctx.options.trueStr : ctx.options.falseStr;
    }
  };
  exports.boolTag = boolTag;
});

// node_modules/yaml/dist/stringify/stringifyNumber.js
var require_stringifyNumber = __commonJS((exports) => {
  function stringifyNumber({ format: format2, minFractionDigits, tag, value }) {
    if (typeof value === "bigint")
      return String(value);
    const num = typeof value === "number" ? value : Number(value);
    if (!isFinite(num))
      return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf";
    let n = Object.is(value, -0) ? "-0" : JSON.stringify(value);
    if (!format2 && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^\d/.test(n)) {
      let i = n.indexOf(".");
      if (i < 0) {
        i = n.length;
        n += ".";
      }
      let d = minFractionDigits - (n.length - i - 1);
      while (d-- > 0)
        n += "0";
    }
    return n;
  }
  exports.stringifyNumber = stringifyNumber;
});

// node_modules/yaml/dist/schema/core/float.js
var require_float = __commonJS((exports) => {
  var Scalar = require_Scalar();
  var stringifyNumber = require_stringifyNumber();
  var floatNaN = {
    identify: (value) => typeof value === "number",
    default: true,
    tag: "tag:yaml.org,2002:float",
    test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
    resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
    stringify: stringifyNumber.stringifyNumber
  };
  var floatExp = {
    identify: (value) => typeof value === "number",
    default: true,
    tag: "tag:yaml.org,2002:float",
    format: "EXP",
    test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
    resolve: (str) => parseFloat(str),
    stringify(node) {
      const num = Number(node.value);
      return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
    }
  };
  var float = {
    identify: (value) => typeof value === "number",
    default: true,
    tag: "tag:yaml.org,2002:float",
    test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
    resolve(str) {
      const node = new Scalar.Scalar(parseFloat(str));
      const dot2 = str.indexOf(".");
      if (dot2 !== -1 && str[str.length - 1] === "0")
        node.minFractionDigits = str.length - dot2 - 1;
      return node;
    },
    stringify: stringifyNumber.stringifyNumber
  };
  exports.float = float;
  exports.floatExp = floatExp;
  exports.floatNaN = floatNaN;
});

// node_modules/yaml/dist/schema/core/int.js
var require_int = __commonJS((exports) => {
  var stringifyNumber = require_stringifyNumber();
  var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value);
  var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix);
  function intStringify(node, radix, prefix) {
    const { value } = node;
    if (intIdentify(value) && value >= 0)
      return prefix + value.toString(radix);
    return stringifyNumber.stringifyNumber(node);
  }
  var intOct = {
    identify: (value) => intIdentify(value) && value >= 0,
    default: true,
    tag: "tag:yaml.org,2002:int",
    format: "OCT",
    test: /^0o[0-7]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),
    stringify: (node) => intStringify(node, 8, "0o")
  };
  var int2 = {
    identify: intIdentify,
    default: true,
    tag: "tag:yaml.org,2002:int",
    test: /^[-+]?[0-9]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
    stringify: stringifyNumber.stringifyNumber
  };
  var intHex = {
    identify: (value) => intIdentify(value) && value >= 0,
    default: true,
    tag: "tag:yaml.org,2002:int",
    format: "HEX",
    test: /^0x[0-9a-fA-F]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
    stringify: (node) => intStringify(node, 16, "0x")
  };
  exports.int = int2;
  exports.intHex = intHex;
  exports.intOct = intOct;
});

// node_modules/yaml/dist/schema/core/schema.js
var require_schema = __commonJS((exports) => {
  var map4 = require_map();
  var _null4 = require_null();
  var seq = require_seq();
  var string4 = require_string();
  var bool = require_bool();
  var float = require_float();
  var int2 = require_int();
  var schema = [
    map4.map,
    seq.seq,
    string4.string,
    _null4.nullTag,
    bool.boolTag,
    int2.intOct,
    int2.int,
    int2.intHex,
    float.floatNaN,
    float.floatExp,
    float.float
  ];
  exports.schema = schema;
});

// node_modules/yaml/dist/schema/json/schema.js
var require_schema2 = __commonJS((exports) => {
  var Scalar = require_Scalar();
  var map4 = require_map();
  var seq = require_seq();
  function intIdentify(value) {
    return typeof value === "bigint" || Number.isInteger(value);
  }
  var stringifyJSON = ({ value }) => JSON.stringify(value);
  var jsonScalars = [
    {
      identify: (value) => typeof value === "string",
      default: true,
      tag: "tag:yaml.org,2002:str",
      resolve: (str) => str,
      stringify: stringifyJSON
    },
    {
      identify: (value) => value == null,
      createNode: () => new Scalar.Scalar(null),
      default: true,
      tag: "tag:yaml.org,2002:null",
      test: /^null$/,
      resolve: () => null,
      stringify: stringifyJSON
    },
    {
      identify: (value) => typeof value === "boolean",
      default: true,
      tag: "tag:yaml.org,2002:bool",
      test: /^true$|^false$/,
      resolve: (str) => str === "true",
      stringify: stringifyJSON
    },
    {
      identify: intIdentify,
      default: true,
      tag: "tag:yaml.org,2002:int",
      test: /^-?(?:0|[1-9][0-9]*)$/,
      resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
      stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)
    },
    {
      identify: (value) => typeof value === "number",
      default: true,
      tag: "tag:yaml.org,2002:float",
      test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
      resolve: (str) => parseFloat(str),
      stringify: stringifyJSON
    }
  ];
  var jsonError = {
    default: true,
    tag: "",
    test: /^/,
    resolve(str, onError) {
      onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
      return str;
    }
  };
  var schema = [map4.map, seq.seq].concat(jsonScalars, jsonError);
  exports.schema = schema;
});

// node_modules/yaml/dist/schema/yaml-1.1/binary.js
var require_binary = __commonJS((exports) => {
  var node_buffer = __require("buffer");
  var Scalar = require_Scalar();
  var stringifyString = require_stringifyString();
  var binary = {
    identify: (value) => value instanceof Uint8Array,
    default: false,
    tag: "tag:yaml.org,2002:binary",
    resolve(src, onError) {
      if (typeof node_buffer.Buffer === "function") {
        return node_buffer.Buffer.from(src, "base64");
      } else if (typeof atob === "function") {
        const str = atob(src.replace(/[\n\r]/g, ""));
        const buffer = new Uint8Array(str.length);
        for (let i = 0;i < str.length; ++i)
          buffer[i] = str.charCodeAt(i);
        return buffer;
      } else {
        onError("This environment does not support reading binary tags; either Buffer or atob is required");
        return src;
      }
    },
    stringify({ comment, type, value }, ctx, onComment, onChompKeep) {
      if (!value)
        return "";
      const buf = value;
      let str;
      if (typeof node_buffer.Buffer === "function") {
        str = buf instanceof node_buffer.Buffer ? buf.toString("base64") : node_buffer.Buffer.from(buf.buffer).toString("base64");
      } else if (typeof btoa === "function") {
        let s = "";
        for (let i = 0;i < buf.length; ++i)
          s += String.fromCharCode(buf[i]);
        str = btoa(s);
      } else {
        throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");
      }
      type ?? (type = Scalar.Scalar.BLOCK_LITERAL);
      if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
        const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
        const n = Math.ceil(str.length / lineWidth);
        const lines = new Array(n);
        for (let i = 0, o = 0;i < n; ++i, o += lineWidth) {
          lines[i] = str.substr(o, lineWidth);
        }
        str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? `
` : " ");
      }
      return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
    }
  };
  exports.binary = binary;
});

// node_modules/yaml/dist/schema/yaml-1.1/pairs.js
var require_pairs = __commonJS((exports) => {
  var identity3 = require_identity();
  var Pair2 = require_Pair();
  var Scalar = require_Scalar();
  var YAMLSeq = require_YAMLSeq();
  function resolvePairs(seq, onError) {
    if (identity3.isSeq(seq)) {
      for (let i = 0;i < seq.items.length; ++i) {
        let item = seq.items[i];
        if (identity3.isPair(item))
          continue;
        else if (identity3.isMap(item)) {
          if (item.items.length > 1)
            onError("Each pair must have its own sequence indicator");
          const pair = item.items[0] || new Pair2.Pair(new Scalar.Scalar(null));
          if (item.commentBefore)
            pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore}
${pair.key.commentBefore}` : item.commentBefore;
          if (item.comment) {
            const cn = pair.value ?? pair.key;
            cn.comment = cn.comment ? `${item.comment}
${cn.comment}` : item.comment;
          }
          item = pair;
        }
        seq.items[i] = identity3.isPair(item) ? item : new Pair2.Pair(item);
      }
    } else
      onError("Expected a sequence for this tag");
    return seq;
  }
  function createPairs(schema, iterable, ctx) {
    const { replacer } = ctx;
    const pairs2 = new YAMLSeq.YAMLSeq(schema);
    pairs2.tag = "tag:yaml.org,2002:pairs";
    let i = 0;
    if (iterable && Symbol.iterator in Object(iterable))
      for (let it of iterable) {
        if (typeof replacer === "function")
          it = replacer.call(iterable, String(i++), it);
        let key, value;
        if (Array.isArray(it)) {
          if (it.length === 2) {
            key = it[0];
            value = it[1];
          } else
            throw new TypeError(`Expected [key, value] tuple: ${it}`);
        } else if (it && it instanceof Object) {
          const keys2 = Object.keys(it);
          if (keys2.length === 1) {
            key = keys2[0];
            value = it[key];
          } else {
            throw new TypeError(`Expected tuple with one key, not ${keys2.length} keys`);
          }
        } else {
          key = it;
        }
        pairs2.items.push(Pair2.createPair(key, value, ctx));
      }
    return pairs2;
  }
  var pairs = {
    collection: "seq",
    default: false,
    tag: "tag:yaml.org,2002:pairs",
    resolve: resolvePairs,
    createNode: createPairs
  };
  exports.createPairs = createPairs;
  exports.pairs = pairs;
  exports.resolvePairs = resolvePairs;
});

// node_modules/yaml/dist/schema/yaml-1.1/omap.js
var require_omap = __commonJS((exports) => {
  var identity3 = require_identity();
  var toJS = require_toJS();
  var YAMLMap = require_YAMLMap();
  var YAMLSeq = require_YAMLSeq();
  var pairs = require_pairs();

  class YAMLOMap extends YAMLSeq.YAMLSeq {
    constructor() {
      super();
      this.add = YAMLMap.YAMLMap.prototype.add.bind(this);
      this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this);
      this.get = YAMLMap.YAMLMap.prototype.get.bind(this);
      this.has = YAMLMap.YAMLMap.prototype.has.bind(this);
      this.set = YAMLMap.YAMLMap.prototype.set.bind(this);
      this.tag = YAMLOMap.tag;
    }
    toJSON(_, ctx) {
      if (!ctx)
        return super.toJSON(_);
      const map4 = new Map;
      if (ctx?.onCreate)
        ctx.onCreate(map4);
      for (const pair of this.items) {
        let key, value;
        if (identity3.isPair(pair)) {
          key = toJS.toJS(pair.key, "", ctx);
          value = toJS.toJS(pair.value, key, ctx);
        } else {
          key = toJS.toJS(pair, "", ctx);
        }
        if (map4.has(key))
          throw new Error("Ordered maps must not include duplicate keys");
        map4.set(key, value);
      }
      return map4;
    }
    static from(schema, iterable, ctx) {
      const pairs$1 = pairs.createPairs(schema, iterable, ctx);
      const omap2 = new this;
      omap2.items = pairs$1.items;
      return omap2;
    }
  }
  YAMLOMap.tag = "tag:yaml.org,2002:omap";
  var omap = {
    collection: "seq",
    identify: (value) => value instanceof Map,
    nodeClass: YAMLOMap,
    default: false,
    tag: "tag:yaml.org,2002:omap",
    resolve(seq, onError) {
      const pairs$1 = pairs.resolvePairs(seq, onError);
      const seenKeys = [];
      for (const { key } of pairs$1.items) {
        if (identity3.isScalar(key)) {
          if (seenKeys.includes(key.value)) {
            onError(`Ordered maps must not include duplicate keys: ${key.value}`);
          } else {
            seenKeys.push(key.value);
          }
        }
      }
      return Object.assign(new YAMLOMap, pairs$1);
    },
    createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)
  };
  exports.YAMLOMap = YAMLOMap;
  exports.omap = omap;
});

// node_modules/yaml/dist/schema/yaml-1.1/bool.js
var require_bool2 = __commonJS((exports) => {
  var Scalar = require_Scalar();
  function boolStringify({ value, source }, ctx) {
    const boolObj = value ? trueTag : falseTag;
    if (source && boolObj.test.test(source))
      return source;
    return value ? ctx.options.trueStr : ctx.options.falseStr;
  }
  var trueTag = {
    identify: (value) => value === true,
    default: true,
    tag: "tag:yaml.org,2002:bool",
    test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
    resolve: () => new Scalar.Scalar(true),
    stringify: boolStringify
  };
  var falseTag = {
    identify: (value) => value === false,
    default: true,
    tag: "tag:yaml.org,2002:bool",
    test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,
    resolve: () => new Scalar.Scalar(false),
    stringify: boolStringify
  };
  exports.falseTag = falseTag;
  exports.trueTag = trueTag;
});

// node_modules/yaml/dist/schema/yaml-1.1/float.js
var require_float2 = __commonJS((exports) => {
  var Scalar = require_Scalar();
  var stringifyNumber = require_stringifyNumber();
  var floatNaN = {
    identify: (value) => typeof value === "number",
    default: true,
    tag: "tag:yaml.org,2002:float",
    test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
    resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
    stringify: stringifyNumber.stringifyNumber
  };
  var floatExp = {
    identify: (value) => typeof value === "number",
    default: true,
    tag: "tag:yaml.org,2002:float",
    format: "EXP",
    test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
    resolve: (str) => parseFloat(str.replace(/_/g, "")),
    stringify(node) {
      const num = Number(node.value);
      return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
    }
  };
  var float = {
    identify: (value) => typeof value === "number",
    default: true,
    tag: "tag:yaml.org,2002:float",
    test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
    resolve(str) {
      const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, "")));
      const dot2 = str.indexOf(".");
      if (dot2 !== -1) {
        const f = str.substring(dot2 + 1).replace(/_/g, "");
        if (f[f.length - 1] === "0")
          node.minFractionDigits = f.length;
      }
      return node;
    },
    stringify: stringifyNumber.stringifyNumber
  };
  exports.float = float;
  exports.floatExp = floatExp;
  exports.floatNaN = floatNaN;
});

// node_modules/yaml/dist/schema/yaml-1.1/int.js
var require_int2 = __commonJS((exports) => {
  var stringifyNumber = require_stringifyNumber();
  var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value);
  function intResolve(str, offset, radix, { intAsBigInt }) {
    const sign2 = str[0];
    if (sign2 === "-" || sign2 === "+")
      offset += 1;
    str = str.substring(offset).replace(/_/g, "");
    if (intAsBigInt) {
      switch (radix) {
        case 2:
          str = `0b${str}`;
          break;
        case 8:
          str = `0o${str}`;
          break;
        case 16:
          str = `0x${str}`;
          break;
      }
      const n2 = BigInt(str);
      return sign2 === "-" ? BigInt(-1) * n2 : n2;
    }
    const n = parseInt(str, radix);
    return sign2 === "-" ? -1 * n : n;
  }
  function intStringify(node, radix, prefix) {
    const { value } = node;
    if (intIdentify(value)) {
      const str = value.toString(radix);
      return value < 0 ? "-" + prefix + str.substr(1) : prefix + str;
    }
    return stringifyNumber.stringifyNumber(node);
  }
  var intBin = {
    identify: intIdentify,
    default: true,
    tag: "tag:yaml.org,2002:int",
    format: "BIN",
    test: /^[-+]?0b[0-1_]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),
    stringify: (node) => intStringify(node, 2, "0b")
  };
  var intOct = {
    identify: intIdentify,
    default: true,
    tag: "tag:yaml.org,2002:int",
    format: "OCT",
    test: /^[-+]?0[0-7_]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),
    stringify: (node) => intStringify(node, 8, "0")
  };
  var int2 = {
    identify: intIdentify,
    default: true,
    tag: "tag:yaml.org,2002:int",
    test: /^[-+]?[0-9][0-9_]*$/,
    resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
    stringify: stringifyNumber.stringifyNumber
  };
  var intHex = {
    identify: intIdentify,
    default: true,
    tag: "tag:yaml.org,2002:int",
    format: "HEX",
    test: /^[-+]?0x[0-9a-fA-F_]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
    stringify: (node) => intStringify(node, 16, "0x")
  };
  exports.int = int2;
  exports.intBin = intBin;
  exports.intHex = intHex;
  exports.intOct = intOct;
});

// node_modules/yaml/dist/schema/yaml-1.1/set.js
var require_set = __commonJS((exports) => {
  var identity3 = require_identity();
  var Pair2 = require_Pair();
  var YAMLMap = require_YAMLMap();

  class YAMLSet extends YAMLMap.YAMLMap {
    constructor(schema) {
      super(schema);
      this.tag = YAMLSet.tag;
    }
    add(key) {
      let pair;
      if (identity3.isPair(key))
        pair = key;
      else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null)
        pair = new Pair2.Pair(key.key, null);
      else
        pair = new Pair2.Pair(key, null);
      const prev = YAMLMap.findPair(this.items, pair.key);
      if (!prev)
        this.items.push(pair);
    }
    get(key, keepPair) {
      const pair = YAMLMap.findPair(this.items, key);
      return !keepPair && identity3.isPair(pair) ? identity3.isScalar(pair.key) ? pair.key.value : pair.key : pair;
    }
    set(key, value) {
      if (typeof value !== "boolean")
        throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
      const prev = YAMLMap.findPair(this.items, key);
      if (prev && !value) {
        this.items.splice(this.items.indexOf(prev), 1);
      } else if (!prev && value) {
        this.items.push(new Pair2.Pair(key));
      }
    }
    toJSON(_, ctx) {
      return super.toJSON(_, ctx, Set);
    }
    toString(ctx, onComment, onChompKeep) {
      if (!ctx)
        return JSON.stringify(this);
      if (this.hasAllNullValues(true))
        return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
      else
        throw new Error("Set items must all have null values");
    }
    static from(schema, iterable, ctx) {
      const { replacer } = ctx;
      const set3 = new this(schema);
      if (iterable && Symbol.iterator in Object(iterable))
        for (let value of iterable) {
          if (typeof replacer === "function")
            value = replacer.call(iterable, value, value);
          set3.items.push(Pair2.createPair(value, null, ctx));
        }
      return set3;
    }
  }
  YAMLSet.tag = "tag:yaml.org,2002:set";
  var set2 = {
    collection: "map",
    identify: (value) => value instanceof Set,
    nodeClass: YAMLSet,
    default: false,
    tag: "tag:yaml.org,2002:set",
    createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),
    resolve(map4, onError) {
      if (identity3.isMap(map4)) {
        if (map4.hasAllNullValues(true))
          return Object.assign(new YAMLSet, map4);
        else
          onError("Set items must all have null values");
      } else
        onError("Expected a mapping for this tag");
      return map4;
    }
  };
  exports.YAMLSet = YAMLSet;
  exports.set = set2;
});

// node_modules/yaml/dist/schema/yaml-1.1/timestamp.js
var require_timestamp = __commonJS((exports) => {
  var stringifyNumber = require_stringifyNumber();
  function parseSexagesimal(str, asBigInt) {
    const sign2 = str[0];
    const parts = sign2 === "-" || sign2 === "+" ? str.substring(1) : str;
    const num = (n) => asBigInt ? BigInt(n) : Number(n);
    const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0));
    return sign2 === "-" ? num(-1) * res : res;
  }
  function stringifySexagesimal(node) {
    let { value } = node;
    let num = (n) => n;
    if (typeof value === "bigint")
      num = (n) => BigInt(n);
    else if (isNaN(value) || !isFinite(value))
      return stringifyNumber.stringifyNumber(node);
    let sign2 = "";
    if (value < 0) {
      sign2 = "-";
      value *= num(-1);
    }
    const _60 = num(60);
    const parts = [value % _60];
    if (value < 60) {
      parts.unshift(0);
    } else {
      value = (value - parts[0]) / _60;
      parts.unshift(value % _60);
      if (value >= 60) {
        value = (value - parts[0]) / _60;
        parts.unshift(value);
      }
    }
    return sign2 + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, "");
  }
  var intTime = {
    identify: (value) => typeof value === "bigint" || Number.isInteger(value),
    default: true,
    tag: "tag:yaml.org,2002:int",
    format: "TIME",
    test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
    resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
    stringify: stringifySexagesimal
  };
  var floatTime = {
    identify: (value) => typeof value === "number",
    default: true,
    tag: "tag:yaml.org,2002:float",
    format: "TIME",
    test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
    resolve: (str) => parseSexagesimal(str, false),
    stringify: stringifySexagesimal
  };
  var timestamp = {
    identify: (value) => value instanceof Date,
    default: true,
    tag: "tag:yaml.org,2002:timestamp",
    test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})" + "(?:" + "(?:t|T|[ \\t]+)" + "([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)" + "(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?" + ")?$"),
    resolve(str) {
      const match = str.match(timestamp.test);
      if (!match)
        throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");
      const [, year, month, day, hour, minute, second] = match.map(Number);
      const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0;
      let date5 = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
      const tz = match[8];
      if (tz && tz !== "Z") {
        let d = parseSexagesimal(tz, false);
        if (Math.abs(d) < 30)
          d *= 60;
        date5 -= 60000 * d;
      }
      return new Date(date5);
    },
    stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? ""
  };
  exports.floatTime = floatTime;
  exports.intTime = intTime;
  exports.timestamp = timestamp;
});

// node_modules/yaml/dist/schema/yaml-1.1/schema.js
var require_schema3 = __commonJS((exports) => {
  var map4 = require_map();
  var _null4 = require_null();
  var seq = require_seq();
  var string4 = require_string();
  var binary = require_binary();
  var bool = require_bool2();
  var float = require_float2();
  var int2 = require_int2();
  var merge2 = require_merge();
  var omap = require_omap();
  var pairs = require_pairs();
  var set2 = require_set();
  var timestamp = require_timestamp();
  var schema = [
    map4.map,
    seq.seq,
    string4.string,
    _null4.nullTag,
    bool.trueTag,
    bool.falseTag,
    int2.intBin,
    int2.intOct,
    int2.int,
    int2.intHex,
    float.floatNaN,
    float.floatExp,
    float.float,
    binary.binary,
    merge2.merge,
    omap.omap,
    pairs.pairs,
    set2.set,
    timestamp.intTime,
    timestamp.floatTime,
    timestamp.timestamp
  ];
  exports.schema = schema;
});

// node_modules/yaml/dist/schema/tags.js
var require_tags = __commonJS((exports) => {
  var map4 = require_map();
  var _null4 = require_null();
  var seq = require_seq();
  var string4 = require_string();
  var bool = require_bool();
  var float = require_float();
  var int2 = require_int();
  var schema = require_schema();
  var schema$1 = require_schema2();
  var binary = require_binary();
  var merge2 = require_merge();
  var omap = require_omap();
  var pairs = require_pairs();
  var schema$2 = require_schema3();
  var set2 = require_set();
  var timestamp = require_timestamp();
  var schemas3 = new Map([
    ["core", schema.schema],
    ["failsafe", [map4.map, seq.seq, string4.string]],
    ["json", schema$1.schema],
    ["yaml11", schema$2.schema],
    ["yaml-1.1", schema$2.schema]
  ]);
  var tagsByName = {
    binary: binary.binary,
    bool: bool.boolTag,
    float: float.float,
    floatExp: float.floatExp,
    floatNaN: float.floatNaN,
    floatTime: timestamp.floatTime,
    int: int2.int,
    intHex: int2.intHex,
    intOct: int2.intOct,
    intTime: timestamp.intTime,
    map: map4.map,
    merge: merge2.merge,
    null: _null4.nullTag,
    omap: omap.omap,
    pairs: pairs.pairs,
    seq: seq.seq,
    set: set2.set,
    timestamp: timestamp.timestamp
  };
  var coreKnownTags = {
    "tag:yaml.org,2002:binary": binary.binary,
    "tag:yaml.org,2002:merge": merge2.merge,
    "tag:yaml.org,2002:omap": omap.omap,
    "tag:yaml.org,2002:pairs": pairs.pairs,
    "tag:yaml.org,2002:set": set2.set,
    "tag:yaml.org,2002:timestamp": timestamp.timestamp
  };
  function getTags(customTags, schemaName, addMergeTag) {
    const schemaTags = schemas3.get(schemaName);
    if (schemaTags && !customTags) {
      return addMergeTag && !schemaTags.includes(merge2.merge) ? schemaTags.concat(merge2.merge) : schemaTags.slice();
    }
    let tags = schemaTags;
    if (!tags) {
      if (Array.isArray(customTags))
        tags = [];
      else {
        const keys2 = Array.from(schemas3.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", ");
        throw new Error(`Unknown schema "${schemaName}"; use one of ${keys2} or define customTags array`);
      }
    }
    if (Array.isArray(customTags)) {
      for (const tag of customTags)
        tags = tags.concat(tag);
    } else if (typeof customTags === "function") {
      tags = customTags(tags.slice());
    }
    if (addMergeTag)
      tags = tags.concat(merge2.merge);
    return tags.reduce((tags2, tag) => {
      const tagObj = typeof tag === "string" ? tagsByName[tag] : tag;
      if (!tagObj) {
        const tagName = JSON.stringify(tag);
        const keys2 = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", ");
        throw new Error(`Unknown custom tag ${tagName}; use one of ${keys2}`);
      }
      if (!tags2.includes(tagObj))
        tags2.push(tagObj);
      return tags2;
    }, []);
  }
  exports.coreKnownTags = coreKnownTags;
  exports.getTags = getTags;
});

// node_modules/yaml/dist/schema/Schema.js
var require_Schema = __commonJS((exports) => {
  var identity3 = require_identity();
  var map4 = require_map();
  var seq = require_seq();
  var string4 = require_string();
  var tags = require_tags();
  var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;

  class Schema {
    constructor({ compat: compat2, customTags, merge: merge2, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {
      this.compat = Array.isArray(compat2) ? tags.getTags(compat2, "compat") : compat2 ? tags.getTags(null, compat2) : null;
      this.name = typeof schema === "string" && schema || "core";
      this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};
      this.tags = tags.getTags(customTags, this.name, merge2);
      this.toStringOptions = toStringDefaults ?? null;
      Object.defineProperty(this, identity3.MAP, { value: map4.map });
      Object.defineProperty(this, identity3.SCALAR, { value: string4.string });
      Object.defineProperty(this, identity3.SEQ, { value: seq.seq });
      this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null;
    }
    clone() {
      const copy3 = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));
      copy3.tags = this.tags.slice();
      return copy3;
    }
  }
  exports.Schema = Schema;
});

// node_modules/yaml/dist/stringify/stringifyDocument.js
var require_stringifyDocument = __commonJS((exports) => {
  var identity3 = require_identity();
  var stringify = require_stringify();
  var stringifyComment = require_stringifyComment();
  function stringifyDocument(doc2, options) {
    const lines = [];
    let hasDirectives = options.directives === true;
    if (options.directives !== false && doc2.directives) {
      const dir = doc2.directives.toString(doc2);
      if (dir) {
        lines.push(dir);
        hasDirectives = true;
      } else if (doc2.directives.docStart)
        hasDirectives = true;
    }
    if (hasDirectives)
      lines.push("---");
    const ctx = stringify.createStringifyContext(doc2, options);
    const { commentString } = ctx.options;
    if (doc2.commentBefore) {
      if (lines.length !== 1)
        lines.unshift("");
      const cs = commentString(doc2.commentBefore);
      lines.unshift(stringifyComment.indentComment(cs, ""));
    }
    let chompKeep = false;
    let contentComment = null;
    if (doc2.contents) {
      if (identity3.isNode(doc2.contents)) {
        if (doc2.contents.spaceBefore && hasDirectives)
          lines.push("");
        if (doc2.contents.commentBefore) {
          const cs = commentString(doc2.contents.commentBefore);
          lines.push(stringifyComment.indentComment(cs, ""));
        }
        ctx.forceBlockIndent = !!doc2.comment;
        contentComment = doc2.contents.comment;
      }
      const onChompKeep = contentComment ? undefined : () => chompKeep = true;
      let body = stringify.stringify(doc2.contents, ctx, () => contentComment = null, onChompKeep);
      if (contentComment)
        body += stringifyComment.lineComment(body, "", commentString(contentComment));
      if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") {
        lines[lines.length - 1] = `--- ${body}`;
      } else
        lines.push(body);
    } else {
      lines.push(stringify.stringify(doc2.contents, ctx));
    }
    if (doc2.directives?.docEnd) {
      if (doc2.comment) {
        const cs = commentString(doc2.comment);
        if (cs.includes(`
`)) {
          lines.push("...");
          lines.push(stringifyComment.indentComment(cs, ""));
        } else {
          lines.push(`... ${cs}`);
        }
      } else {
        lines.push("...");
      }
    } else {
      let dc = doc2.comment;
      if (dc && chompKeep)
        dc = dc.replace(/^\n+/, "");
      if (dc) {
        if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "")
          lines.push("");
        lines.push(stringifyComment.indentComment(commentString(dc), ""));
      }
    }
    return lines.join(`
`) + `
`;
  }
  exports.stringifyDocument = stringifyDocument;
});

// node_modules/yaml/dist/doc/Document.js
var require_Document = __commonJS((exports) => {
  var Alias = require_Alias();
  var Collection = require_Collection();
  var identity3 = require_identity();
  var Pair2 = require_Pair();
  var toJS = require_toJS();
  var Schema = require_Schema();
  var stringifyDocument = require_stringifyDocument();
  var anchors = require_anchors();
  var applyReviver = require_applyReviver();
  var createNode = require_createNode();
  var directives = require_directives();

  class Document {
    constructor(value, replacer, options) {
      this.commentBefore = null;
      this.comment = null;
      this.errors = [];
      this.warnings = [];
      Object.defineProperty(this, identity3.NODE_TYPE, { value: identity3.DOC });
      let _replacer = null;
      if (typeof replacer === "function" || Array.isArray(replacer)) {
        _replacer = replacer;
      } else if (options === undefined && replacer) {
        options = replacer;
        replacer = undefined;
      }
      const opt = Object.assign({
        intAsBigInt: false,
        keepSourceTokens: false,
        logLevel: "warn",
        prettyErrors: true,
        strict: true,
        stringKeys: false,
        uniqueKeys: true,
        version: "1.2"
      }, options);
      this.options = opt;
      let { version: version2 } = opt;
      if (options?._directives) {
        this.directives = options._directives.atDocument();
        if (this.directives.yaml.explicit)
          version2 = this.directives.yaml.version;
      } else
        this.directives = new directives.Directives({ version: version2 });
      this.setSchema(version2, options);
      this.contents = value === undefined ? null : this.createNode(value, _replacer, options);
    }
    clone() {
      const copy3 = Object.create(Document.prototype, {
        [identity3.NODE_TYPE]: { value: identity3.DOC }
      });
      copy3.commentBefore = this.commentBefore;
      copy3.comment = this.comment;
      copy3.errors = this.errors.slice();
      copy3.warnings = this.warnings.slice();
      copy3.options = Object.assign({}, this.options);
      if (this.directives)
        copy3.directives = this.directives.clone();
      copy3.schema = this.schema.clone();
      copy3.contents = identity3.isNode(this.contents) ? this.contents.clone(copy3.schema) : this.contents;
      if (this.range)
        copy3.range = this.range.slice();
      return copy3;
    }
    add(value) {
      if (assertCollection(this.contents))
        this.contents.add(value);
    }
    addIn(path3, value) {
      if (assertCollection(this.contents))
        this.contents.addIn(path3, value);
    }
    createAlias(node, name) {
      if (!node.anchor) {
        const prev = anchors.anchorNames(this);
        node.anchor = !name || prev.has(name) ? anchors.findNewAnchor(name || "a", prev) : name;
      }
      return new Alias.Alias(node.anchor);
    }
    createNode(value, replacer, options) {
      let _replacer = undefined;
      if (typeof replacer === "function") {
        value = replacer.call({ "": value }, "", value);
        _replacer = replacer;
      } else if (Array.isArray(replacer)) {
        const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number;
        const asStr = replacer.filter(keyToStr).map(String);
        if (asStr.length > 0)
          replacer = replacer.concat(asStr);
        _replacer = replacer;
      } else if (options === undefined && replacer) {
        options = replacer;
        replacer = undefined;
      }
      const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};
      const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this, anchorPrefix || "a");
      const ctx = {
        aliasDuplicateObjects: aliasDuplicateObjects ?? true,
        keepUndefined: keepUndefined ?? false,
        onAnchor,
        onTagObj,
        replacer: _replacer,
        schema: this.schema,
        sourceObjects
      };
      const node = createNode.createNode(value, tag, ctx);
      if (flow && identity3.isCollection(node))
        node.flow = true;
      setAnchors();
      return node;
    }
    createPair(key, value, options = {}) {
      const k = this.createNode(key, null, options);
      const v = this.createNode(value, null, options);
      return new Pair2.Pair(k, v);
    }
    delete(key) {
      return assertCollection(this.contents) ? this.contents.delete(key) : false;
    }
    deleteIn(path3) {
      if (Collection.isEmptyPath(path3)) {
        if (this.contents == null)
          return false;
        this.contents = null;
        return true;
      }
      return assertCollection(this.contents) ? this.contents.deleteIn(path3) : false;
    }
    get(key, keepScalar) {
      return identity3.isCollection(this.contents) ? this.contents.get(key, keepScalar) : undefined;
    }
    getIn(path3, keepScalar) {
      if (Collection.isEmptyPath(path3))
        return !keepScalar && identity3.isScalar(this.contents) ? this.contents.value : this.contents;
      return identity3.isCollection(this.contents) ? this.contents.getIn(path3, keepScalar) : undefined;
    }
    has(key) {
      return identity3.isCollection(this.contents) ? this.contents.has(key) : false;
    }
    hasIn(path3) {
      if (Collection.isEmptyPath(path3))
        return this.contents !== undefined;
      return identity3.isCollection(this.contents) ? this.contents.hasIn(path3) : false;
    }
    set(key, value) {
      if (this.contents == null) {
        this.contents = Collection.collectionFromPath(this.schema, [key], value);
      } else if (assertCollection(this.contents)) {
        this.contents.set(key, value);
      }
    }
    setIn(path3, value) {
      if (Collection.isEmptyPath(path3)) {
        this.contents = value;
      } else if (this.contents == null) {
        this.contents = Collection.collectionFromPath(this.schema, Array.from(path3), value);
      } else if (assertCollection(this.contents)) {
        this.contents.setIn(path3, value);
      }
    }
    setSchema(version2, options = {}) {
      if (typeof version2 === "number")
        version2 = String(version2);
      let opt;
      switch (version2) {
        case "1.1":
          if (this.directives)
            this.directives.yaml.version = "1.1";
          else
            this.directives = new directives.Directives({ version: "1.1" });
          opt = { resolveKnownTags: false, schema: "yaml-1.1" };
          break;
        case "1.2":
        case "next":
          if (this.directives)
            this.directives.yaml.version = version2;
          else
            this.directives = new directives.Directives({ version: version2 });
          opt = { resolveKnownTags: true, schema: "core" };
          break;
        case null:
          if (this.directives)
            delete this.directives;
          opt = null;
          break;
        default: {
          const sv = JSON.stringify(version2);
          throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
        }
      }
      if (options.schema instanceof Object)
        this.schema = options.schema;
      else if (opt)
        this.schema = new Schema.Schema(Object.assign(opt, options));
      else
        throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
    }
    toJS({ json: json2, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
      const ctx = {
        anchors: new Map,
        doc: this,
        keep: !json2,
        mapAsMap: mapAsMap === true,
        mapKeyWarned: false,
        maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
      };
      const res = toJS.toJS(this.contents, jsonArg ?? "", ctx);
      if (typeof onAnchor === "function")
        for (const { count: count3, res: res2 } of ctx.anchors.values())
          onAnchor(res2, count3);
      return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
    }
    toJSON(jsonArg, onAnchor) {
      return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
    }
    toString(options = {}) {
      if (this.errors.length > 0)
        throw new Error("Document with errors cannot be stringified");
      if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {
        const s = JSON.stringify(options.indent);
        throw new Error(`"indent" option must be a positive integer, not ${s}`);
      }
      return stringifyDocument.stringifyDocument(this, options);
    }
  }
  function assertCollection(contents) {
    if (identity3.isCollection(contents))
      return true;
    throw new Error("Expected a YAML collection as document contents");
  }
  exports.Document = Document;
});

// node_modules/yaml/dist/errors.js
var require_errors = __commonJS((exports) => {
  class YAMLError extends Error {
    constructor(name, pos, code, message) {
      super();
      this.name = name;
      this.code = code;
      this.message = message;
      this.pos = pos;
    }
  }

  class YAMLParseError extends YAMLError {
    constructor(pos, code, message) {
      super("YAMLParseError", pos, code, message);
    }
  }

  class YAMLWarning extends YAMLError {
    constructor(pos, code, message) {
      super("YAMLWarning", pos, code, message);
    }
  }
  var prettifyError2 = (src, lc) => (error48) => {
    if (error48.pos[0] === -1)
      return;
    error48.linePos = error48.pos.map((pos) => lc.linePos(pos));
    const { line, col } = error48.linePos[0];
    error48.message += ` at line ${line}, column ${col}`;
    let ci = col - 1;
    let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, "");
    if (ci >= 60 && lineStr.length > 80) {
      const trimStart = Math.min(ci - 39, lineStr.length - 79);
      lineStr = "…" + lineStr.substring(trimStart);
      ci -= trimStart - 1;
    }
    if (lineStr.length > 80)
      lineStr = lineStr.substring(0, 79) + "…";
    if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
      let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
      if (prev.length > 80)
        prev = prev.substring(0, 79) + `…
`;
      lineStr = prev + lineStr;
    }
    if (/[^ ]/.test(lineStr)) {
      let count3 = 1;
      const end = error48.linePos[1];
      if (end?.line === line && end.col > col) {
        count3 = Math.max(1, Math.min(end.col - col, 80 - ci));
      }
      const pointer = " ".repeat(ci) + "^".repeat(count3);
      error48.message += `:

${lineStr}
${pointer}
`;
    }
  };
  exports.YAMLError = YAMLError;
  exports.YAMLParseError = YAMLParseError;
  exports.YAMLWarning = YAMLWarning;
  exports.prettifyError = prettifyError2;
});

// node_modules/yaml/dist/compose/resolve-props.js
var require_resolve_props = __commonJS((exports) => {
  function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {
    let spaceBefore = false;
    let atNewline = startOnNewline;
    let hasSpace = startOnNewline;
    let comment = "";
    let commentSep = "";
    let hasNewline = false;
    let reqSpace = false;
    let tab = null;
    let anchor = null;
    let tag = null;
    let newlineAfterProp = null;
    let comma = null;
    let found = null;
    let start = null;
    for (const token of tokens) {
      if (reqSpace) {
        if (token.type !== "space" && token.type !== "newline" && token.type !== "comma")
          onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
        reqSpace = false;
      }
      if (tab) {
        if (atNewline && token.type !== "comment" && token.type !== "newline") {
          onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
        }
        tab = null;
      }
      switch (token.type) {
        case "space":
          if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes("\t")) {
            tab = token;
          }
          hasSpace = true;
          break;
        case "comment": {
          if (!hasSpace)
            onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
          const cb = token.source.substring(1) || " ";
          if (!comment)
            comment = cb;
          else
            comment += commentSep + cb;
          commentSep = "";
          atNewline = false;
          break;
        }
        case "newline":
          if (atNewline) {
            if (comment)
              comment += token.source;
            else if (!found || indicator !== "seq-item-ind")
              spaceBefore = true;
          } else
            commentSep += token.source;
          atNewline = true;
          hasNewline = true;
          if (anchor || tag)
            newlineAfterProp = token;
          hasSpace = true;
          break;
        case "anchor":
          if (anchor)
            onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor");
          if (token.source.endsWith(":"))
            onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true);
          anchor = token;
          start ?? (start = token.offset);
          atNewline = false;
          hasSpace = false;
          reqSpace = true;
          break;
        case "tag": {
          if (tag)
            onError(token, "MULTIPLE_TAGS", "A node can have at most one tag");
          tag = token;
          start ?? (start = token.offset);
          atNewline = false;
          hasSpace = false;
          reqSpace = true;
          break;
        }
        case indicator:
          if (anchor || tag)
            onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`);
          if (found)
            onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`);
          found = token;
          atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind";
          hasSpace = false;
          break;
        case "comma":
          if (flow) {
            if (comma)
              onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`);
            comma = token;
            atNewline = false;
            hasSpace = false;
            break;
          }
        default:
          onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`);
          atNewline = false;
          hasSpace = false;
      }
    }
    const last2 = tokens[tokens.length - 1];
    const end = last2 ? last2.offset + last2.source.length : offset;
    if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) {
      onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
    }
    if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq"))
      onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
    return {
      comma,
      found,
      spaceBefore,
      comment,
      hasNewline,
      anchor,
      tag,
      newlineAfterProp,
      end,
      start: start ?? end
    };
  }
  exports.resolveProps = resolveProps;
});

// node_modules/yaml/dist/compose/util-contains-newline.js
var require_util_contains_newline = __commonJS((exports) => {
  function containsNewline(key) {
    if (!key)
      return null;
    switch (key.type) {
      case "alias":
      case "scalar":
      case "double-quoted-scalar":
      case "single-quoted-scalar":
        if (key.source.includes(`
`))
          return true;
        if (key.end) {
          for (const st of key.end)
            if (st.type === "newline")
              return true;
        }
        return false;
      case "flow-collection":
        for (const it of key.items) {
          for (const st of it.start)
            if (st.type === "newline")
              return true;
          if (it.sep) {
            for (const st of it.sep)
              if (st.type === "newline")
                return true;
          }
          if (containsNewline(it.key) || containsNewline(it.value))
            return true;
        }
        return false;
      default:
        return true;
    }
  }
  exports.containsNewline = containsNewline;
});

// node_modules/yaml/dist/compose/util-flow-indent-check.js
var require_util_flow_indent_check = __commonJS((exports) => {
  var utilContainsNewline = require_util_contains_newline();
  function flowIndentCheck(indent, fc, onError) {
    if (fc?.type === "flow-collection") {
      const end = fc.end[0];
      if (end.indent === indent && (end.source === "]" || end.source === "}") && utilContainsNewline.containsNewline(fc)) {
        const msg = "Flow end indicator should be more indented than parent";
        onError(end, "BAD_INDENT", msg, true);
      }
    }
  }
  exports.flowIndentCheck = flowIndentCheck;
});

// node_modules/yaml/dist/compose/util-map-includes.js
var require_util_map_includes = __commonJS((exports) => {
  var identity3 = require_identity();
  function mapIncludes(ctx, items, search) {
    const { uniqueKeys } = ctx.options;
    if (uniqueKeys === false)
      return false;
    const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || identity3.isScalar(a) && identity3.isScalar(b) && a.value === b.value;
    return items.some((pair) => isEqual(pair.key, search));
  }
  exports.mapIncludes = mapIncludes;
});

// node_modules/yaml/dist/compose/resolve-block-map.js
var require_resolve_block_map = __commonJS((exports) => {
  var Pair2 = require_Pair();
  var YAMLMap = require_YAMLMap();
  var resolveProps = require_resolve_props();
  var utilContainsNewline = require_util_contains_newline();
  var utilFlowIndentCheck = require_util_flow_indent_check();
  var utilMapIncludes = require_util_map_includes();
  var startColMsg = "All mapping items must start at the same column";
  function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {
    const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap;
    const map4 = new NodeClass(ctx.schema);
    if (ctx.atRoot)
      ctx.atRoot = false;
    let offset = bm.offset;
    let commentEnd = null;
    for (const collItem of bm.items) {
      const { start, key, sep, value } = collItem;
      const keyProps = resolveProps.resolveProps(start, {
        indicator: "explicit-key-ind",
        next: key ?? sep?.[0],
        offset,
        onError,
        parentIndent: bm.indent,
        startOnNewline: true
      });
      const implicitKey = !keyProps.found;
      if (implicitKey) {
        if (key) {
          if (key.type === "block-seq")
            onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key");
          else if ("indent" in key && key.indent !== bm.indent)
            onError(offset, "BAD_INDENT", startColMsg);
        }
        if (!keyProps.anchor && !keyProps.tag && !sep) {
          commentEnd = keyProps.end;
          if (keyProps.comment) {
            if (map4.comment)
              map4.comment += `
` + keyProps.comment;
            else
              map4.comment = keyProps.comment;
          }
          continue;
        }
        if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) {
          onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line");
        }
      } else if (keyProps.found?.indent !== bm.indent) {
        onError(offset, "BAD_INDENT", startColMsg);
      }
      ctx.atKey = true;
      const keyStart = keyProps.end;
      const keyNode = key ? composeNode(ctx, key, keyProps, onError) : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);
      if (ctx.schema.compat)
        utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError);
      ctx.atKey = false;
      if (utilMapIncludes.mapIncludes(ctx, map4.items, keyNode))
        onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
      const valueProps = resolveProps.resolveProps(sep ?? [], {
        indicator: "map-value-ind",
        next: value,
        offset: keyNode.range[2],
        onError,
        parentIndent: bm.indent,
        startOnNewline: !key || key.type === "block-scalar"
      });
      offset = valueProps.end;
      if (valueProps.found) {
        if (implicitKey) {
          if (value?.type === "block-map" && !valueProps.hasNewline)
            onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings");
          if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
            onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
        }
        const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep, null, valueProps, onError);
        if (ctx.schema.compat)
          utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);
        offset = valueNode.range[2];
        const pair = new Pair2.Pair(keyNode, valueNode);
        if (ctx.options.keepSourceTokens)
          pair.srcToken = collItem;
        map4.items.push(pair);
      } else {
        if (implicitKey)
          onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values");
        if (valueProps.comment) {
          if (keyNode.comment)
            keyNode.comment += `
` + valueProps.comment;
          else
            keyNode.comment = valueProps.comment;
        }
        const pair = new Pair2.Pair(keyNode);
        if (ctx.options.keepSourceTokens)
          pair.srcToken = collItem;
        map4.items.push(pair);
      }
    }
    if (commentEnd && commentEnd < offset)
      onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content");
    map4.range = [bm.offset, offset, commentEnd ?? offset];
    return map4;
  }
  exports.resolveBlockMap = resolveBlockMap;
});

// node_modules/yaml/dist/compose/resolve-block-seq.js
var require_resolve_block_seq = __commonJS((exports) => {
  var YAMLSeq = require_YAMLSeq();
  var resolveProps = require_resolve_props();
  var utilFlowIndentCheck = require_util_flow_indent_check();
  function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {
    const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq;
    const seq = new NodeClass(ctx.schema);
    if (ctx.atRoot)
      ctx.atRoot = false;
    if (ctx.atKey)
      ctx.atKey = false;
    let offset = bs.offset;
    let commentEnd = null;
    for (const { start, value } of bs.items) {
      const props = resolveProps.resolveProps(start, {
        indicator: "seq-item-ind",
        next: value,
        offset,
        onError,
        parentIndent: bs.indent,
        startOnNewline: true
      });
      if (!props.found) {
        if (props.anchor || props.tag || value) {
          if (value?.type === "block-seq")
            onError(props.end, "BAD_INDENT", "All sequence items must start at the same column");
          else
            onError(offset, "MISSING_CHAR", "Sequence item without - indicator");
        } else {
          commentEnd = props.end;
          if (props.comment)
            seq.comment = props.comment;
          continue;
        }
      }
      const node = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError);
      if (ctx.schema.compat)
        utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError);
      offset = node.range[2];
      seq.items.push(node);
    }
    seq.range = [bs.offset, offset, commentEnd ?? offset];
    return seq;
  }
  exports.resolveBlockSeq = resolveBlockSeq;
});

// node_modules/yaml/dist/compose/resolve-end.js
var require_resolve_end = __commonJS((exports) => {
  function resolveEnd(end, offset, reqSpace, onError) {
    let comment = "";
    if (end) {
      let hasSpace = false;
      let sep = "";
      for (const token of end) {
        const { source, type } = token;
        switch (type) {
          case "space":
            hasSpace = true;
            break;
          case "comment": {
            if (reqSpace && !hasSpace)
              onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
            const cb = source.substring(1) || " ";
            if (!comment)
              comment = cb;
            else
              comment += sep + cb;
            sep = "";
            break;
          }
          case "newline":
            if (comment)
              sep += source;
            hasSpace = true;
            break;
          default:
            onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`);
        }
        offset += source.length;
      }
    }
    return { comment, offset };
  }
  exports.resolveEnd = resolveEnd;
});

// node_modules/yaml/dist/compose/resolve-flow-collection.js
var require_resolve_flow_collection = __commonJS((exports) => {
  var identity3 = require_identity();
  var Pair2 = require_Pair();
  var YAMLMap = require_YAMLMap();
  var YAMLSeq = require_YAMLSeq();
  var resolveEnd = require_resolve_end();
  var resolveProps = require_resolve_props();
  var utilContainsNewline = require_util_contains_newline();
  var utilMapIncludes = require_util_map_includes();
  var blockMsg = "Block collections are not allowed within flow collections";
  var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq");
  function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {
    const isMap = fc.start.source === "{";
    const fcName = isMap ? "flow map" : "flow sequence";
    const NodeClass = tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq);
    const coll = new NodeClass(ctx.schema);
    coll.flow = true;
    const atRoot = ctx.atRoot;
    if (atRoot)
      ctx.atRoot = false;
    if (ctx.atKey)
      ctx.atKey = false;
    let offset = fc.offset + fc.start.source.length;
    for (let i = 0;i < fc.items.length; ++i) {
      const collItem = fc.items[i];
      const { start, key, sep, value } = collItem;
      const props = resolveProps.resolveProps(start, {
        flow: fcName,
        indicator: "explicit-key-ind",
        next: key ?? sep?.[0],
        offset,
        onError,
        parentIndent: fc.indent,
        startOnNewline: false
      });
      if (!props.found) {
        if (!props.anchor && !props.tag && !sep && !value) {
          if (i === 0 && props.comma)
            onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
          else if (i < fc.items.length - 1)
            onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`);
          if (props.comment) {
            if (coll.comment)
              coll.comment += `
` + props.comment;
            else
              coll.comment = props.comment;
          }
          offset = props.end;
          continue;
        }
        if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key))
          onError(key, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line");
      }
      if (i === 0) {
        if (props.comma)
          onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
      } else {
        if (!props.comma)
          onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`);
        if (props.comment) {
          let prevItemComment = "";
          loop:
            for (const st of start) {
              switch (st.type) {
                case "comma":
                case "space":
                  break;
                case "comment":
                  prevItemComment = st.source.substring(1);
                  break loop;
                default:
                  break loop;
              }
            }
          if (prevItemComment) {
            let prev = coll.items[coll.items.length - 1];
            if (identity3.isPair(prev))
              prev = prev.value ?? prev.key;
            if (prev.comment)
              prev.comment += `
` + prevItemComment;
            else
              prev.comment = prevItemComment;
            props.comment = props.comment.substring(prevItemComment.length + 1);
          }
        }
      }
      if (!isMap && !sep && !props.found) {
        const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep, null, props, onError);
        coll.items.push(valueNode);
        offset = valueNode.range[2];
        if (isBlock(value))
          onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
      } else {
        ctx.atKey = true;
        const keyStart = props.end;
        const keyNode = key ? composeNode(ctx, key, props, onError) : composeEmptyNode(ctx, keyStart, start, null, props, onError);
        if (isBlock(key))
          onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
        ctx.atKey = false;
        const valueProps = resolveProps.resolveProps(sep ?? [], {
          flow: fcName,
          indicator: "map-value-ind",
          next: value,
          offset: keyNode.range[2],
          onError,
          parentIndent: fc.indent,
          startOnNewline: false
        });
        if (valueProps.found) {
          if (!isMap && !props.found && ctx.options.strict) {
            if (sep)
              for (const st of sep) {
                if (st === valueProps.found)
                  break;
                if (st.type === "newline") {
                  onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line");
                  break;
                }
              }
            if (props.start < valueProps.found.offset - 1024)
              onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key");
          }
        } else if (value) {
          if ("source" in value && value.source?.[0] === ":")
            onError(value, "MISSING_CHAR", `Missing space after : in ${fcName}`);
          else
            onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
        }
        const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError) : null;
        if (valueNode) {
          if (isBlock(value))
            onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
        } else if (valueProps.comment) {
          if (keyNode.comment)
            keyNode.comment += `
` + valueProps.comment;
          else
            keyNode.comment = valueProps.comment;
        }
        const pair = new Pair2.Pair(keyNode, valueNode);
        if (ctx.options.keepSourceTokens)
          pair.srcToken = collItem;
        if (isMap) {
          const map4 = coll;
          if (utilMapIncludes.mapIncludes(ctx, map4.items, keyNode))
            onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
          map4.items.push(pair);
        } else {
          const map4 = new YAMLMap.YAMLMap(ctx.schema);
          map4.flow = true;
          map4.items.push(pair);
          const endRange = (valueNode ?? keyNode).range;
          map4.range = [keyNode.range[0], endRange[1], endRange[2]];
          coll.items.push(map4);
        }
        offset = valueNode ? valueNode.range[2] : valueProps.end;
      }
    }
    const expectedEnd = isMap ? "}" : "]";
    const [ce, ...ee] = fc.end;
    let cePos = offset;
    if (ce?.source === expectedEnd)
      cePos = ce.offset + ce.source.length;
    else {
      const name = fcName[0].toUpperCase() + fcName.substring(1);
      const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
      onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg);
      if (ce && ce.source.length !== 1)
        ee.unshift(ce);
    }
    if (ee.length > 0) {
      const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError);
      if (end.comment) {
        if (coll.comment)
          coll.comment += `
` + end.comment;
        else
          coll.comment = end.comment;
      }
      coll.range = [fc.offset, cePos, end.offset];
    } else {
      coll.range = [fc.offset, cePos, cePos];
    }
    return coll;
  }
  exports.resolveFlowCollection = resolveFlowCollection;
});

// node_modules/yaml/dist/compose/compose-collection.js
var require_compose_collection = __commonJS((exports) => {
  var identity3 = require_identity();
  var Scalar = require_Scalar();
  var YAMLMap = require_YAMLMap();
  var YAMLSeq = require_YAMLSeq();
  var resolveBlockMap = require_resolve_block_map();
  var resolveBlockSeq = require_resolve_block_seq();
  var resolveFlowCollection = require_resolve_flow_collection();
  function resolveCollection(CN, ctx, token, onError, tagName, tag) {
    const coll = token.type === "block-map" ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag) : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag);
    const Coll = coll.constructor;
    if (tagName === "!" || tagName === Coll.tagName) {
      coll.tag = Coll.tagName;
      return coll;
    }
    if (tagName)
      coll.tag = tagName;
    return coll;
  }
  function composeCollection(CN, ctx, token, props, onError) {
    const tagToken = props.tag;
    const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg));
    if (token.type === "block-seq") {
      const { anchor, newlineAfterProp: nl } = props;
      const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken;
      if (lastProp && (!nl || nl.offset < lastProp.offset)) {
        const message = "Missing newline after block sequence props";
        onError(lastProp, "MISSING_CHAR", message);
      }
    }
    const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq";
    if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.YAMLSeq.tagName && expType === "seq") {
      return resolveCollection(CN, ctx, token, onError, tagName);
    }
    let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType);
    if (!tag) {
      const kt = ctx.schema.knownTags[tagName];
      if (kt?.collection === expType) {
        ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
        tag = kt;
      } else {
        if (kt) {
          onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true);
        } else {
          onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true);
        }
        return resolveCollection(CN, ctx, token, onError, tagName);
      }
    }
    const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);
    const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll;
    const node = identity3.isNode(res) ? res : new Scalar.Scalar(res);
    node.range = coll.range;
    node.tag = tagName;
    if (tag?.format)
      node.format = tag.format;
    return node;
  }
  exports.composeCollection = composeCollection;
});

// node_modules/yaml/dist/compose/resolve-block-scalar.js
var require_resolve_block_scalar = __commonJS((exports) => {
  var Scalar = require_Scalar();
  function resolveBlockScalar(ctx, scalar, onError) {
    const start = scalar.offset;
    const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);
    if (!header)
      return { value: "", type: null, comment: "", range: [start, start, start] };
    const type = header.mode === ">" ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL;
    const lines = scalar.source ? splitLines2(scalar.source) : [];
    let chompStart = lines.length;
    for (let i = lines.length - 1;i >= 0; --i) {
      const content = lines[i][1];
      if (content === "" || content === "\r")
        chompStart = i;
      else
        break;
    }
    if (chompStart === 0) {
      const value2 = header.chomp === "+" && lines.length > 0 ? `
`.repeat(Math.max(1, lines.length - 1)) : "";
      let end2 = start + header.length;
      if (scalar.source)
        end2 += scalar.source.length;
      return { value: value2, type, comment: header.comment, range: [start, end2, end2] };
    }
    let trimIndent = scalar.indent + header.indent;
    let offset = scalar.offset + header.length;
    let contentStart = 0;
    for (let i = 0;i < chompStart; ++i) {
      const [indent, content] = lines[i];
      if (content === "" || content === "\r") {
        if (header.indent === 0 && indent.length > trimIndent)
          trimIndent = indent.length;
      } else {
        if (indent.length < trimIndent) {
          const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator";
          onError(offset + indent.length, "MISSING_CHAR", message);
        }
        if (header.indent === 0)
          trimIndent = indent.length;
        contentStart = i;
        if (trimIndent === 0 && !ctx.atRoot) {
          const message = "Block scalar values in collections must be indented";
          onError(offset, "BAD_INDENT", message);
        }
        break;
      }
      offset += indent.length + content.length + 1;
    }
    for (let i = lines.length - 1;i >= chompStart; --i) {
      if (lines[i][0].length > trimIndent)
        chompStart = i + 1;
    }
    let value = "";
    let sep = "";
    let prevMoreIndented = false;
    for (let i = 0;i < contentStart; ++i)
      value += lines[i][0].slice(trimIndent) + `
`;
    for (let i = contentStart;i < chompStart; ++i) {
      let [indent, content] = lines[i];
      offset += indent.length + content.length + 1;
      const crlf = content[content.length - 1] === "\r";
      if (crlf)
        content = content.slice(0, -1);
      if (content && indent.length < trimIndent) {
        const src = header.indent ? "explicit indentation indicator" : "first line";
        const message = `Block scalar lines must not be less indented than their ${src}`;
        onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message);
        indent = "";
      }
      if (type === Scalar.Scalar.BLOCK_LITERAL) {
        value += sep + indent.slice(trimIndent) + content;
        sep = `
`;
      } else if (indent.length > trimIndent || content[0] === "\t") {
        if (sep === " ")
          sep = `
`;
        else if (!prevMoreIndented && sep === `
`)
          sep = `

`;
        value += sep + indent.slice(trimIndent) + content;
        sep = `
`;
        prevMoreIndented = true;
      } else if (content === "") {
        if (sep === `
`)
          value += `
`;
        else
          sep = `
`;
      } else {
        value += sep + content;
        sep = " ";
        prevMoreIndented = false;
      }
    }
    switch (header.chomp) {
      case "-":
        break;
      case "+":
        for (let i = chompStart;i < lines.length; ++i)
          value += `
` + lines[i][0].slice(trimIndent);
        if (value[value.length - 1] !== `
`)
          value += `
`;
        break;
      default:
        value += `
`;
    }
    const end = start + header.length + scalar.source.length;
    return { value, type, comment: header.comment, range: [start, end, end] };
  }
  function parseBlockScalarHeader({ offset, props }, strict, onError) {
    if (props[0].type !== "block-scalar-header") {
      onError(props[0], "IMPOSSIBLE", "Block scalar header not found");
      return null;
    }
    const { source } = props[0];
    const mode = source[0];
    let indent = 0;
    let chomp = "";
    let error48 = -1;
    for (let i = 1;i < source.length; ++i) {
      const ch = source[i];
      if (!chomp && (ch === "-" || ch === "+"))
        chomp = ch;
      else {
        const n = Number(ch);
        if (!indent && n)
          indent = n;
        else if (error48 === -1)
          error48 = offset + i;
      }
    }
    if (error48 !== -1)
      onError(error48, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`);
    let hasSpace = false;
    let comment = "";
    let length2 = source.length;
    for (let i = 1;i < props.length; ++i) {
      const token = props[i];
      switch (token.type) {
        case "space":
          hasSpace = true;
        case "newline":
          length2 += token.source.length;
          break;
        case "comment":
          if (strict && !hasSpace) {
            const message = "Comments must be separated from other tokens by white space characters";
            onError(token, "MISSING_CHAR", message);
          }
          length2 += token.source.length;
          comment = token.source.substring(1);
          break;
        case "error":
          onError(token, "UNEXPECTED_TOKEN", token.message);
          length2 += token.source.length;
          break;
        default: {
          const message = `Unexpected token in block scalar header: ${token.type}`;
          onError(token, "UNEXPECTED_TOKEN", message);
          const ts = token.source;
          if (ts && typeof ts === "string")
            length2 += ts.length;
        }
      }
    }
    return { mode, indent, chomp, comment, length: length2 };
  }
  function splitLines2(source) {
    const split = source.split(/\n( *)/);
    const first = split[0];
    const m = first.match(/^( *)/);
    const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first];
    const lines = [line0];
    for (let i = 1;i < split.length; i += 2)
      lines.push([split[i], split[i + 1]]);
    return lines;
  }
  exports.resolveBlockScalar = resolveBlockScalar;
});

// node_modules/yaml/dist/compose/resolve-flow-scalar.js
var require_resolve_flow_scalar = __commonJS((exports) => {
  var Scalar = require_Scalar();
  var resolveEnd = require_resolve_end();
  function resolveFlowScalar(scalar, strict, onError) {
    const { offset, type, source, end } = scalar;
    let _type;
    let value;
    const _onError = (rel, code, msg) => onError(offset + rel, code, msg);
    switch (type) {
      case "scalar":
        _type = Scalar.Scalar.PLAIN;
        value = plainValue(source, _onError);
        break;
      case "single-quoted-scalar":
        _type = Scalar.Scalar.QUOTE_SINGLE;
        value = singleQuotedValue(source, _onError);
        break;
      case "double-quoted-scalar":
        _type = Scalar.Scalar.QUOTE_DOUBLE;
        value = doubleQuotedValue(source, _onError);
        break;
      default:
        onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`);
        return {
          value: "",
          type: null,
          comment: "",
          range: [offset, offset + source.length, offset + source.length]
        };
    }
    const valueEnd = offset + source.length;
    const re2 = resolveEnd.resolveEnd(end, valueEnd, strict, onError);
    return {
      value,
      type: _type,
      comment: re2.comment,
      range: [offset, valueEnd, re2.offset]
    };
  }
  function plainValue(source, onError) {
    let badChar = "";
    switch (source[0]) {
      case "\t":
        badChar = "a tab character";
        break;
      case ",":
        badChar = "flow indicator character ,";
        break;
      case "%":
        badChar = "directive indicator character %";
        break;
      case "|":
      case ">": {
        badChar = `block scalar indicator ${source[0]}`;
        break;
      }
      case "@":
      case "`": {
        badChar = `reserved character ${source[0]}`;
        break;
      }
    }
    if (badChar)
      onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`);
    return foldLines(source);
  }
  function singleQuotedValue(source, onError) {
    if (source[source.length - 1] !== "'" || source.length === 1)
      onError(source.length, "MISSING_CHAR", "Missing closing 'quote");
    return foldLines(source.slice(1, -1)).replace(/''/g, "'");
  }
  function foldLines(source) {
    let first, line;
    try {
      first = new RegExp(`(.*?)(?<![ 	])[ 	]*\r?
`, "sy");
      line = new RegExp(`[ 	]*(.*?)(?:(?<![ 	])[ 	]*)?\r?
`, "sy");
    } catch {
      first = /(.*?)[ \t]*\r?\n/sy;
      line = /[ \t]*(.*?)[ \t]*\r?\n/sy;
    }
    let match = first.exec(source);
    if (!match)
      return source;
    let res = match[1];
    let sep = " ";
    let pos = first.lastIndex;
    line.lastIndex = pos;
    while (match = line.exec(source)) {
      if (match[1] === "") {
        if (sep === `
`)
          res += sep;
        else
          sep = `
`;
      } else {
        res += sep + match[1];
        sep = " ";
      }
      pos = line.lastIndex;
    }
    const last2 = /[ \t]*(.*)/sy;
    last2.lastIndex = pos;
    match = last2.exec(source);
    return res + sep + (match?.[1] ?? "");
  }
  function doubleQuotedValue(source, onError) {
    let res = "";
    for (let i = 1;i < source.length - 1; ++i) {
      const ch = source[i];
      if (ch === "\r" && source[i + 1] === `
`)
        continue;
      if (ch === `
`) {
        const { fold, offset } = foldNewline(source, i);
        res += fold;
        i = offset;
      } else if (ch === "\\") {
        let next = source[++i];
        const cc = escapeCodes[next];
        if (cc)
          res += cc;
        else if (next === `
`) {
          next = source[i + 1];
          while (next === " " || next === "\t")
            next = source[++i + 1];
        } else if (next === "\r" && source[i + 1] === `
`) {
          next = source[++i + 1];
          while (next === " " || next === "\t")
            next = source[++i + 1];
        } else if (next === "x" || next === "u" || next === "U") {
          const length2 = { x: 2, u: 4, U: 8 }[next];
          res += parseCharCode(source, i + 1, length2, onError);
          i += length2;
        } else {
          const raw = source.substr(i - 1, 2);
          onError(i - 1, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`);
          res += raw;
        }
      } else if (ch === " " || ch === "\t") {
        const wsStart = i;
        let next = source[i + 1];
        while (next === " " || next === "\t")
          next = source[++i + 1];
        if (next !== `
` && !(next === "\r" && source[i + 2] === `
`))
          res += i > wsStart ? source.slice(wsStart, i + 1) : ch;
      } else {
        res += ch;
      }
    }
    if (source[source.length - 1] !== '"' || source.length === 1)
      onError(source.length, "MISSING_CHAR", 'Missing closing "quote');
    return res;
  }
  function foldNewline(source, offset) {
    let fold = "";
    let ch = source[offset + 1];
    while (ch === " " || ch === "\t" || ch === `
` || ch === "\r") {
      if (ch === "\r" && source[offset + 2] !== `
`)
        break;
      if (ch === `
`)
        fold += `
`;
      offset += 1;
      ch = source[offset + 1];
    }
    if (!fold)
      fold = " ";
    return { fold, offset };
  }
  var escapeCodes = {
    "0": "\x00",
    a: "\x07",
    b: "\b",
    e: "\x1B",
    f: "\f",
    n: `
`,
    r: "\r",
    t: "\t",
    v: "\v",
    N: "",
    _: " ",
    L: "\u2028",
    P: "\u2029",
    " ": " ",
    '"': '"',
    "/": "/",
    "\\": "\\",
    "\t": "\t"
  };
  function parseCharCode(source, offset, length2, onError) {
    const cc = source.substr(offset, length2);
    const ok = cc.length === length2 && /^[0-9a-fA-F]+$/.test(cc);
    const code = ok ? parseInt(cc, 16) : NaN;
    if (isNaN(code)) {
      const raw = source.substr(offset - 2, length2 + 2);
      onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`);
      return raw;
    }
    return String.fromCodePoint(code);
  }
  exports.resolveFlowScalar = resolveFlowScalar;
});

// node_modules/yaml/dist/compose/compose-scalar.js
var require_compose_scalar = __commonJS((exports) => {
  var identity3 = require_identity();
  var Scalar = require_Scalar();
  var resolveBlockScalar = require_resolve_block_scalar();
  var resolveFlowScalar = require_resolve_flow_scalar();
  function composeScalar(ctx, token, tagToken, onError) {
    const { value, type, comment, range: range2 } = token.type === "block-scalar" ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError) : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError);
    const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null;
    let tag;
    if (ctx.options.stringKeys && ctx.atKey) {
      tag = ctx.schema[identity3.SCALAR];
    } else if (tagName)
      tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError);
    else if (token.type === "scalar")
      tag = findScalarTagByTest(ctx, value, token, onError);
    else
      tag = ctx.schema[identity3.SCALAR];
    let scalar;
    try {
      const res = tag.resolve(value, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options);
      scalar = identity3.isScalar(res) ? res : new Scalar.Scalar(res);
    } catch (error48) {
      const msg = error48 instanceof Error ? error48.message : String(error48);
      onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg);
      scalar = new Scalar.Scalar(value);
    }
    scalar.range = range2;
    scalar.source = value;
    if (type)
      scalar.type = type;
    if (tagName)
      scalar.tag = tagName;
    if (tag.format)
      scalar.format = tag.format;
    if (comment)
      scalar.comment = comment;
    return scalar;
  }
  function findScalarTagByName(schema, value, tagName, tagToken, onError) {
    if (tagName === "!")
      return schema[identity3.SCALAR];
    const matchWithTest = [];
    for (const tag of schema.tags) {
      if (!tag.collection && tag.tag === tagName) {
        if (tag.default && tag.test)
          matchWithTest.push(tag);
        else
          return tag;
      }
    }
    for (const tag of matchWithTest)
      if (tag.test?.test(value))
        return tag;
    const kt = schema.knownTags[tagName];
    if (kt && !kt.collection) {
      schema.tags.push(Object.assign({}, kt, { default: false, test: undefined }));
      return kt;
    }
    onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str");
    return schema[identity3.SCALAR];
  }
  function findScalarTagByTest({ atKey, directives, schema }, value, token, onError) {
    const tag = schema.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value)) || schema[identity3.SCALAR];
    if (schema.compat) {
      const compat2 = schema.compat.find((tag2) => tag2.default && tag2.test?.test(value)) ?? schema[identity3.SCALAR];
      if (tag.tag !== compat2.tag) {
        const ts = directives.tagString(tag.tag);
        const cs = directives.tagString(compat2.tag);
        const msg = `Value may be parsed as either ${ts} or ${cs}`;
        onError(token, "TAG_RESOLVE_FAILED", msg, true);
      }
    }
    return tag;
  }
  exports.composeScalar = composeScalar;
});

// node_modules/yaml/dist/compose/util-empty-scalar-position.js
var require_util_empty_scalar_position = __commonJS((exports) => {
  function emptyScalarPosition(offset, before, pos) {
    if (before) {
      pos ?? (pos = before.length);
      for (let i = pos - 1;i >= 0; --i) {
        let st = before[i];
        switch (st.type) {
          case "space":
          case "comment":
          case "newline":
            offset -= st.source.length;
            continue;
        }
        st = before[++i];
        while (st?.type === "space") {
          offset += st.source.length;
          st = before[++i];
        }
        break;
      }
    }
    return offset;
  }
  exports.emptyScalarPosition = emptyScalarPosition;
});

// node_modules/yaml/dist/compose/compose-node.js
var require_compose_node = __commonJS((exports) => {
  var Alias = require_Alias();
  var identity3 = require_identity();
  var composeCollection = require_compose_collection();
  var composeScalar = require_compose_scalar();
  var resolveEnd = require_resolve_end();
  var utilEmptyScalarPosition = require_util_empty_scalar_position();
  var CN = { composeNode, composeEmptyNode };
  function composeNode(ctx, token, props, onError) {
    const atKey = ctx.atKey;
    const { spaceBefore, comment, anchor, tag } = props;
    let node;
    let isSrcToken = true;
    switch (token.type) {
      case "alias":
        node = composeAlias(ctx, token, onError);
        if (anchor || tag)
          onError(token, "ALIAS_PROPS", "An alias node must not specify any properties");
        break;
      case "scalar":
      case "single-quoted-scalar":
      case "double-quoted-scalar":
      case "block-scalar":
        node = composeScalar.composeScalar(ctx, token, tag, onError);
        if (anchor)
          node.anchor = anchor.source.substring(1);
        break;
      case "block-map":
      case "block-seq":
      case "flow-collection":
        try {
          node = composeCollection.composeCollection(CN, ctx, token, props, onError);
          if (anchor)
            node.anchor = anchor.source.substring(1);
        } catch (error48) {
          const message = error48 instanceof Error ? error48.message : String(error48);
          onError(token, "RESOURCE_EXHAUSTION", message);
        }
        break;
      default: {
        const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`;
        onError(token, "UNEXPECTED_TOKEN", message);
        isSrcToken = false;
      }
    }
    node ?? (node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError));
    if (anchor && node.anchor === "")
      onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
    if (atKey && ctx.options.stringKeys && (!identity3.isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) {
      const msg = "With stringKeys, all keys must be strings";
      onError(tag ?? token, "NON_STRING_KEY", msg);
    }
    if (spaceBefore)
      node.spaceBefore = true;
    if (comment) {
      if (token.type === "scalar" && token.source === "")
        node.comment = comment;
      else
        node.commentBefore = comment;
    }
    if (ctx.options.keepSourceTokens && isSrcToken)
      node.srcToken = token;
    return node;
  }
  function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {
    const token = {
      type: "scalar",
      offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos),
      indent: -1,
      source: ""
    };
    const node = composeScalar.composeScalar(ctx, token, tag, onError);
    if (anchor) {
      node.anchor = anchor.source.substring(1);
      if (node.anchor === "")
        onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
    }
    if (spaceBefore)
      node.spaceBefore = true;
    if (comment) {
      node.comment = comment;
      node.range[2] = end;
    }
    return node;
  }
  function composeAlias({ options }, { offset, source, end }, onError) {
    const alias = new Alias.Alias(source.substring(1));
    if (alias.source === "")
      onError(offset, "BAD_ALIAS", "Alias cannot be an empty string");
    if (alias.source.endsWith(":"))
      onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true);
    const valueEnd = offset + source.length;
    const re2 = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError);
    alias.range = [offset, valueEnd, re2.offset];
    if (re2.comment)
      alias.comment = re2.comment;
    return alias;
  }
  exports.composeEmptyNode = composeEmptyNode;
  exports.composeNode = composeNode;
});

// node_modules/yaml/dist/compose/compose-doc.js
var require_compose_doc = __commonJS((exports) => {
  var Document = require_Document();
  var composeNode = require_compose_node();
  var resolveEnd = require_resolve_end();
  var resolveProps = require_resolve_props();
  function composeDoc(options, directives, { offset, start, value, end }, onError) {
    const opts = Object.assign({ _directives: directives }, options);
    const doc2 = new Document.Document(undefined, opts);
    const ctx = {
      atKey: false,
      atRoot: true,
      directives: doc2.directives,
      options: doc2.options,
      schema: doc2.schema
    };
    const props = resolveProps.resolveProps(start, {
      indicator: "doc-start",
      next: value ?? end?.[0],
      offset,
      onError,
      parentIndent: 0,
      startOnNewline: true
    });
    if (props.found) {
      doc2.directives.docStart = true;
      if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline)
        onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker");
    }
    doc2.contents = value ? composeNode.composeNode(ctx, value, props, onError) : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError);
    const contentEnd = doc2.contents.range[2];
    const re2 = resolveEnd.resolveEnd(end, contentEnd, false, onError);
    if (re2.comment)
      doc2.comment = re2.comment;
    doc2.range = [offset, contentEnd, re2.offset];
    return doc2;
  }
  exports.composeDoc = composeDoc;
});

// node_modules/yaml/dist/compose/composer.js
var require_composer = __commonJS((exports) => {
  var node_process = __require("process");
  var directives = require_directives();
  var Document = require_Document();
  var errors3 = require_errors();
  var identity3 = require_identity();
  var composeDoc = require_compose_doc();
  var resolveEnd = require_resolve_end();
  function getErrorPos(src) {
    if (typeof src === "number")
      return [src, src + 1];
    if (Array.isArray(src))
      return src.length === 2 ? src : [src[0], src[1]];
    const { offset, source } = src;
    return [offset, offset + (typeof source === "string" ? source.length : 1)];
  }
  function parsePrelude(prelude) {
    let comment = "";
    let atComment = false;
    let afterEmptyLine = false;
    for (let i = 0;i < prelude.length; ++i) {
      const source = prelude[i];
      switch (source[0]) {
        case "#":
          comment += (comment === "" ? "" : afterEmptyLine ? `

` : `
`) + (source.substring(1) || " ");
          atComment = true;
          afterEmptyLine = false;
          break;
        case "%":
          if (prelude[i + 1]?.[0] !== "#")
            i += 1;
          atComment = false;
          break;
        default:
          if (!atComment)
            afterEmptyLine = true;
          atComment = false;
      }
    }
    return { comment, afterEmptyLine };
  }

  class Composer {
    constructor(options = {}) {
      this.doc = null;
      this.atDirectives = false;
      this.prelude = [];
      this.errors = [];
      this.warnings = [];
      this.onError = (source, code, message, warning) => {
        const pos = getErrorPos(source);
        if (warning)
          this.warnings.push(new errors3.YAMLWarning(pos, code, message));
        else
          this.errors.push(new errors3.YAMLParseError(pos, code, message));
      };
      this.directives = new directives.Directives({ version: options.version || "1.2" });
      this.options = options;
    }
    decorate(doc2, afterDoc) {
      const { comment, afterEmptyLine } = parsePrelude(this.prelude);
      if (comment) {
        const dc = doc2.contents;
        if (afterDoc) {
          doc2.comment = doc2.comment ? `${doc2.comment}
${comment}` : comment;
        } else if (afterEmptyLine || doc2.directives.docStart || !dc) {
          doc2.commentBefore = comment;
        } else if (identity3.isCollection(dc) && !dc.flow && dc.items.length > 0) {
          let it = dc.items[0];
          if (identity3.isPair(it))
            it = it.key;
          const cb = it.commentBefore;
          it.commentBefore = cb ? `${comment}
${cb}` : comment;
        } else {
          const cb = dc.commentBefore;
          dc.commentBefore = cb ? `${comment}
${cb}` : comment;
        }
      }
      if (afterDoc) {
        Array.prototype.push.apply(doc2.errors, this.errors);
        Array.prototype.push.apply(doc2.warnings, this.warnings);
      } else {
        doc2.errors = this.errors;
        doc2.warnings = this.warnings;
      }
      this.prelude = [];
      this.errors = [];
      this.warnings = [];
    }
    streamInfo() {
      return {
        comment: parsePrelude(this.prelude).comment,
        directives: this.directives,
        errors: this.errors,
        warnings: this.warnings
      };
    }
    *compose(tokens, forceDoc = false, endOffset = -1) {
      for (const token of tokens)
        yield* this.next(token);
      yield* this.end(forceDoc, endOffset);
    }
    *next(token) {
      if (node_process.env.LOG_STREAM)
        console.dir(token, { depth: null });
      switch (token.type) {
        case "directive":
          this.directives.add(token.source, (offset, message, warning) => {
            const pos = getErrorPos(token);
            pos[0] += offset;
            this.onError(pos, "BAD_DIRECTIVE", message, warning);
          });
          this.prelude.push(token.source);
          this.atDirectives = true;
          break;
        case "document": {
          const doc2 = composeDoc.composeDoc(this.options, this.directives, token, this.onError);
          if (this.atDirectives && !doc2.directives.docStart)
            this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line");
          this.decorate(doc2, false);
          if (this.doc)
            yield this.doc;
          this.doc = doc2;
          this.atDirectives = false;
          break;
        }
        case "byte-order-mark":
        case "space":
          break;
        case "comment":
        case "newline":
          this.prelude.push(token.source);
          break;
        case "error": {
          const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message;
          const error48 = new errors3.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg);
          if (this.atDirectives || !this.doc)
            this.errors.push(error48);
          else
            this.doc.errors.push(error48);
          break;
        }
        case "doc-end": {
          if (!this.doc) {
            const msg = "Unexpected doc-end without preceding document";
            this.errors.push(new errors3.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg));
            break;
          }
          this.doc.directives.docEnd = true;
          const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);
          this.decorate(this.doc, true);
          if (end.comment) {
            const dc = this.doc.comment;
            this.doc.comment = dc ? `${dc}
${end.comment}` : end.comment;
          }
          this.doc.range[2] = end.offset;
          break;
        }
        default:
          this.errors.push(new errors3.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`));
      }
    }
    *end(forceDoc = false, endOffset = -1) {
      if (this.doc) {
        this.decorate(this.doc, true);
        yield this.doc;
        this.doc = null;
      } else if (forceDoc) {
        const opts = Object.assign({ _directives: this.directives }, this.options);
        const doc2 = new Document.Document(undefined, opts);
        if (this.atDirectives)
          this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line");
        doc2.range = [0, endOffset, endOffset];
        this.decorate(doc2, false);
        yield doc2;
      }
    }
  }
  exports.Composer = Composer;
});

// node_modules/yaml/dist/parse/cst-scalar.js
var require_cst_scalar = __commonJS((exports) => {
  var resolveBlockScalar = require_resolve_block_scalar();
  var resolveFlowScalar = require_resolve_flow_scalar();
  var errors3 = require_errors();
  var stringifyString = require_stringifyString();
  function resolveAsScalar(token, strict = true, onError) {
    if (token) {
      const _onError = (pos, code, message) => {
        const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
        if (onError)
          onError(offset, code, message);
        else
          throw new errors3.YAMLParseError([offset, offset + 1], code, message);
      };
      switch (token.type) {
        case "scalar":
        case "single-quoted-scalar":
        case "double-quoted-scalar":
          return resolveFlowScalar.resolveFlowScalar(token, strict, _onError);
        case "block-scalar":
          return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError);
      }
    }
    return null;
  }
  function createScalarToken(value, context) {
    const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context;
    const source = stringifyString.stringifyString({ type, value }, {
      implicitKey,
      indent: indent > 0 ? " ".repeat(indent) : "",
      inFlow,
      options: { blockQuote: true, lineWidth: -1 }
    });
    const end = context.end ?? [
      { type: "newline", offset: -1, indent, source: `
` }
    ];
    switch (source[0]) {
      case "|":
      case ">": {
        const he = source.indexOf(`
`);
        const head = source.substring(0, he);
        const body = source.substring(he + 1) + `
`;
        const props = [
          { type: "block-scalar-header", offset, indent, source: head }
        ];
        if (!addEndtoBlockProps(props, end))
          props.push({ type: "newline", offset: -1, indent, source: `
` });
        return { type: "block-scalar", offset, indent, props, source: body };
      }
      case '"':
        return { type: "double-quoted-scalar", offset, indent, source, end };
      case "'":
        return { type: "single-quoted-scalar", offset, indent, source, end };
      default:
        return { type: "scalar", offset, indent, source, end };
    }
  }
  function setScalarValue(token, value, context = {}) {
    let { afterKey = false, implicitKey = false, inFlow = false, type } = context;
    let indent = "indent" in token ? token.indent : null;
    if (afterKey && typeof indent === "number")
      indent += 2;
    if (!type)
      switch (token.type) {
        case "single-quoted-scalar":
          type = "QUOTE_SINGLE";
          break;
        case "double-quoted-scalar":
          type = "QUOTE_DOUBLE";
          break;
        case "block-scalar": {
          const header = token.props[0];
          if (header.type !== "block-scalar-header")
            throw new Error("Invalid block scalar header");
          type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL";
          break;
        }
        default:
          type = "PLAIN";
      }
    const source = stringifyString.stringifyString({ type, value }, {
      implicitKey: implicitKey || indent === null,
      indent: indent !== null && indent > 0 ? " ".repeat(indent) : "",
      inFlow,
      options: { blockQuote: true, lineWidth: -1 }
    });
    switch (source[0]) {
      case "|":
      case ">":
        setBlockScalarValue(token, source);
        break;
      case '"':
        setFlowScalarValue(token, source, "double-quoted-scalar");
        break;
      case "'":
        setFlowScalarValue(token, source, "single-quoted-scalar");
        break;
      default:
        setFlowScalarValue(token, source, "scalar");
    }
  }
  function setBlockScalarValue(token, source) {
    const he = source.indexOf(`
`);
    const head = source.substring(0, he);
    const body = source.substring(he + 1) + `
`;
    if (token.type === "block-scalar") {
      const header = token.props[0];
      if (header.type !== "block-scalar-header")
        throw new Error("Invalid block scalar header");
      header.source = head;
      token.source = body;
    } else {
      const { offset } = token;
      const indent = "indent" in token ? token.indent : -1;
      const props = [
        { type: "block-scalar-header", offset, indent, source: head }
      ];
      if (!addEndtoBlockProps(props, "end" in token ? token.end : undefined))
        props.push({ type: "newline", offset: -1, indent, source: `
` });
      for (const key of Object.keys(token))
        if (key !== "type" && key !== "offset")
          delete token[key];
      Object.assign(token, { type: "block-scalar", indent, props, source: body });
    }
  }
  function addEndtoBlockProps(props, end) {
    if (end)
      for (const st of end)
        switch (st.type) {
          case "space":
          case "comment":
            props.push(st);
            break;
          case "newline":
            props.push(st);
            return true;
        }
    return false;
  }
  function setFlowScalarValue(token, source, type) {
    switch (token.type) {
      case "scalar":
      case "double-quoted-scalar":
      case "single-quoted-scalar":
        token.type = type;
        token.source = source;
        break;
      case "block-scalar": {
        const end = token.props.slice(1);
        let oa = source.length;
        if (token.props[0].type === "block-scalar-header")
          oa -= token.props[0].source.length;
        for (const tok of end)
          tok.offset += oa;
        delete token.props;
        Object.assign(token, { type, source, end });
        break;
      }
      case "block-map":
      case "block-seq": {
        const offset = token.offset + source.length;
        const nl = { type: "newline", offset, indent: token.indent, source: `
` };
        delete token.items;
        Object.assign(token, { type, source, end: [nl] });
        break;
      }
      default: {
        const indent = "indent" in token ? token.indent : -1;
        const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : [];
        for (const key of Object.keys(token))
          if (key !== "type" && key !== "offset")
            delete token[key];
        Object.assign(token, { type, indent, source, end });
      }
    }
  }
  exports.createScalarToken = createScalarToken;
  exports.resolveAsScalar = resolveAsScalar;
  exports.setScalarValue = setScalarValue;
});

// node_modules/yaml/dist/parse/cst-stringify.js
var require_cst_stringify = __commonJS((exports) => {
  var stringify = (cst) => ("type" in cst) ? stringifyToken(cst) : stringifyItem(cst);
  function stringifyToken(token) {
    switch (token.type) {
      case "block-scalar": {
        let res = "";
        for (const tok of token.props)
          res += stringifyToken(tok);
        return res + token.source;
      }
      case "block-map":
      case "block-seq": {
        let res = "";
        for (const item of token.items)
          res += stringifyItem(item);
        return res;
      }
      case "flow-collection": {
        let res = token.start.source;
        for (const item of token.items)
          res += stringifyItem(item);
        for (const st of token.end)
          res += st.source;
        return res;
      }
      case "document": {
        let res = stringifyItem(token);
        if (token.end)
          for (const st of token.end)
            res += st.source;
        return res;
      }
      default: {
        let res = token.source;
        if ("end" in token && token.end)
          for (const st of token.end)
            res += st.source;
        return res;
      }
    }
  }
  function stringifyItem({ start, key, sep, value }) {
    let res = "";
    for (const st of start)
      res += st.source;
    if (key)
      res += stringifyToken(key);
    if (sep)
      for (const st of sep)
        res += st.source;
    if (value)
      res += stringifyToken(value);
    return res;
  }
  exports.stringify = stringify;
});

// node_modules/yaml/dist/parse/cst-visit.js
var require_cst_visit = __commonJS((exports) => {
  var BREAK = Symbol("break visit");
  var SKIP = Symbol("skip children");
  var REMOVE = Symbol("remove item");
  function visit(cst, visitor) {
    if ("type" in cst && cst.type === "document")
      cst = { start: cst.start, value: cst.value };
    _visit(Object.freeze([]), cst, visitor);
  }
  visit.BREAK = BREAK;
  visit.SKIP = SKIP;
  visit.REMOVE = REMOVE;
  visit.itemAtPath = (cst, path3) => {
    let item = cst;
    for (const [field, index] of path3) {
      const tok = item?.[field];
      if (tok && "items" in tok) {
        item = tok.items[index];
      } else
        return;
    }
    return item;
  };
  visit.parentCollection = (cst, path3) => {
    const parent = visit.itemAtPath(cst, path3.slice(0, -1));
    const field = path3[path3.length - 1][0];
    const coll = parent?.[field];
    if (coll && "items" in coll)
      return coll;
    throw new Error("Parent collection not found");
  };
  function _visit(path3, item, visitor) {
    let ctrl = visitor(item, path3);
    if (typeof ctrl === "symbol")
      return ctrl;
    for (const field of ["key", "value"]) {
      const token = item[field];
      if (token && "items" in token) {
        for (let i = 0;i < token.items.length; ++i) {
          const ci = _visit(Object.freeze(path3.concat([[field, i]])), token.items[i], visitor);
          if (typeof ci === "number")
            i = ci - 1;
          else if (ci === BREAK)
            return BREAK;
          else if (ci === REMOVE) {
            token.items.splice(i, 1);
            i -= 1;
          }
        }
        if (typeof ctrl === "function" && field === "key")
          ctrl = ctrl(item, path3);
      }
    }
    return typeof ctrl === "function" ? ctrl(item, path3) : ctrl;
  }
  exports.visit = visit;
});

// node_modules/yaml/dist/parse/cst.js
var require_cst = __commonJS((exports) => {
  var cstScalar = require_cst_scalar();
  var cstStringify = require_cst_stringify();
  var cstVisit = require_cst_visit();
  var BOM = "\uFEFF";
  var DOCUMENT = "\x02";
  var FLOW_END = "\x18";
  var SCALAR = "\x1F";
  var isCollection = (token) => !!token && ("items" in token);
  var isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar");
  function prettyToken(token) {
    switch (token) {
      case BOM:
        return "<BOM>";
      case DOCUMENT:
        return "<DOC>";
      case FLOW_END:
        return "<FLOW_END>";
      case SCALAR:
        return "<SCALAR>";
      default:
        return JSON.stringify(token);
    }
  }
  function tokenType(source) {
    switch (source) {
      case BOM:
        return "byte-order-mark";
      case DOCUMENT:
        return "doc-mode";
      case FLOW_END:
        return "flow-error-end";
      case SCALAR:
        return "scalar";
      case "---":
        return "doc-start";
      case "...":
        return "doc-end";
      case "":
      case `
`:
      case `\r
`:
        return "newline";
      case "-":
        return "seq-item-ind";
      case "?":
        return "explicit-key-ind";
      case ":":
        return "map-value-ind";
      case "{":
        return "flow-map-start";
      case "}":
        return "flow-map-end";
      case "[":
        return "flow-seq-start";
      case "]":
        return "flow-seq-end";
      case ",":
        return "comma";
    }
    switch (source[0]) {
      case " ":
      case "\t":
        return "space";
      case "#":
        return "comment";
      case "%":
        return "directive-line";
      case "*":
        return "alias";
      case "&":
        return "anchor";
      case "!":
        return "tag";
      case "'":
        return "single-quoted-scalar";
      case '"':
        return "double-quoted-scalar";
      case "|":
      case ">":
        return "block-scalar-header";
    }
    return null;
  }
  exports.createScalarToken = cstScalar.createScalarToken;
  exports.resolveAsScalar = cstScalar.resolveAsScalar;
  exports.setScalarValue = cstScalar.setScalarValue;
  exports.stringify = cstStringify.stringify;
  exports.visit = cstVisit.visit;
  exports.BOM = BOM;
  exports.DOCUMENT = DOCUMENT;
  exports.FLOW_END = FLOW_END;
  exports.SCALAR = SCALAR;
  exports.isCollection = isCollection;
  exports.isScalar = isScalar;
  exports.prettyToken = prettyToken;
  exports.tokenType = tokenType;
});

// node_modules/yaml/dist/parse/lexer.js
var require_lexer = __commonJS((exports) => {
  var cst = require_cst();
  function isEmpty2(ch) {
    switch (ch) {
      case undefined:
      case " ":
      case `
`:
      case "\r":
      case "\t":
        return true;
      default:
        return false;
    }
  }
  var hexDigits = new Set("0123456789ABCDEFabcdef");
  var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
  var flowIndicatorChars = new Set(",[]{}");
  var invalidAnchorChars = new Set(` ,[]{}
\r	`);
  var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);

  class Lexer {
    constructor() {
      this.atEnd = false;
      this.blockScalarIndent = -1;
      this.blockScalarKeep = false;
      this.buffer = "";
      this.flowKey = false;
      this.flowLevel = 0;
      this.indentNext = 0;
      this.indentValue = 0;
      this.lineEndPos = null;
      this.next = null;
      this.pos = 0;
    }
    *lex(source, incomplete = false) {
      if (source) {
        if (typeof source !== "string")
          throw TypeError("source is not a string");
        this.buffer = this.buffer ? this.buffer + source : source;
        this.lineEndPos = null;
      }
      this.atEnd = !incomplete;
      let next = this.next ?? "stream";
      while (next && (incomplete || this.hasChars(1)))
        next = yield* this.parseNext(next);
    }
    atLineEnd() {
      let i = this.pos;
      let ch = this.buffer[i];
      while (ch === " " || ch === "\t")
        ch = this.buffer[++i];
      if (!ch || ch === "#" || ch === `
`)
        return true;
      if (ch === "\r")
        return this.buffer[i + 1] === `
`;
      return false;
    }
    charAt(n) {
      return this.buffer[this.pos + n];
    }
    continueScalar(offset) {
      let ch = this.buffer[offset];
      if (this.indentNext > 0) {
        let indent = 0;
        while (ch === " ")
          ch = this.buffer[++indent + offset];
        if (ch === "\r") {
          const next = this.buffer[indent + offset + 1];
          if (next === `
` || !next && !this.atEnd)
            return offset + indent + 1;
        }
        return ch === `
` || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1;
      }
      if (ch === "-" || ch === ".") {
        const dt = this.buffer.substr(offset, 3);
        if ((dt === "---" || dt === "...") && isEmpty2(this.buffer[offset + 3]))
          return -1;
      }
      return offset;
    }
    getLine() {
      let end = this.lineEndPos;
      if (typeof end !== "number" || end !== -1 && end < this.pos) {
        end = this.buffer.indexOf(`
`, this.pos);
        this.lineEndPos = end;
      }
      if (end === -1)
        return this.atEnd ? this.buffer.substring(this.pos) : null;
      if (this.buffer[end - 1] === "\r")
        end -= 1;
      return this.buffer.substring(this.pos, end);
    }
    hasChars(n) {
      return this.pos + n <= this.buffer.length;
    }
    setNext(state) {
      this.buffer = this.buffer.substring(this.pos);
      this.pos = 0;
      this.lineEndPos = null;
      this.next = state;
      return null;
    }
    peek(n) {
      return this.buffer.substr(this.pos, n);
    }
    *parseNext(next) {
      switch (next) {
        case "stream":
          return yield* this.parseStream();
        case "line-start":
          return yield* this.parseLineStart();
        case "block-start":
          return yield* this.parseBlockStart();
        case "doc":
          return yield* this.parseDocument();
        case "flow":
          return yield* this.parseFlowCollection();
        case "quoted-scalar":
          return yield* this.parseQuotedScalar();
        case "block-scalar":
          return yield* this.parseBlockScalar();
        case "plain-scalar":
          return yield* this.parsePlainScalar();
      }
    }
    *parseStream() {
      let line = this.getLine();
      if (line === null)
        return this.setNext("stream");
      if (line[0] === cst.BOM) {
        yield* this.pushCount(1);
        line = line.substring(1);
      }
      if (line[0] === "%") {
        let dirEnd = line.length;
        let cs = line.indexOf("#");
        while (cs !== -1) {
          const ch = line[cs - 1];
          if (ch === " " || ch === "\t") {
            dirEnd = cs - 1;
            break;
          } else {
            cs = line.indexOf("#", cs + 1);
          }
        }
        while (true) {
          const ch = line[dirEnd - 1];
          if (ch === " " || ch === "\t")
            dirEnd -= 1;
          else
            break;
        }
        const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
        yield* this.pushCount(line.length - n);
        this.pushNewline();
        return "stream";
      }
      if (this.atLineEnd()) {
        const sp = yield* this.pushSpaces(true);
        yield* this.pushCount(line.length - sp);
        yield* this.pushNewline();
        return "stream";
      }
      yield cst.DOCUMENT;
      return yield* this.parseLineStart();
    }
    *parseLineStart() {
      const ch = this.charAt(0);
      if (!ch && !this.atEnd)
        return this.setNext("line-start");
      if (ch === "-" || ch === ".") {
        if (!this.atEnd && !this.hasChars(4))
          return this.setNext("line-start");
        const s = this.peek(3);
        if ((s === "---" || s === "...") && isEmpty2(this.charAt(3))) {
          yield* this.pushCount(3);
          this.indentValue = 0;
          this.indentNext = 0;
          return s === "---" ? "doc" : "stream";
        }
      }
      this.indentValue = yield* this.pushSpaces(false);
      if (this.indentNext > this.indentValue && !isEmpty2(this.charAt(1)))
        this.indentNext = this.indentValue;
      return yield* this.parseBlockStart();
    }
    *parseBlockStart() {
      const [ch0, ch1] = this.peek(2);
      if (!ch1 && !this.atEnd)
        return this.setNext("block-start");
      if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty2(ch1)) {
        const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
        this.indentNext = this.indentValue + 1;
        this.indentValue += n;
        return yield* this.parseBlockStart();
      }
      return "doc";
    }
    *parseDocument() {
      yield* this.pushSpaces(true);
      const line = this.getLine();
      if (line === null)
        return this.setNext("doc");
      let n = yield* this.pushIndicators();
      switch (line[n]) {
        case "#":
          yield* this.pushCount(line.length - n);
        case undefined:
          yield* this.pushNewline();
          return yield* this.parseLineStart();
        case "{":
        case "[":
          yield* this.pushCount(1);
          this.flowKey = false;
          this.flowLevel = 1;
          return "flow";
        case "}":
        case "]":
          yield* this.pushCount(1);
          return "doc";
        case "*":
          yield* this.pushUntil(isNotAnchorChar);
          return "doc";
        case '"':
        case "'":
          return yield* this.parseQuotedScalar();
        case "|":
        case ">":
          n += yield* this.parseBlockScalarHeader();
          n += yield* this.pushSpaces(true);
          yield* this.pushCount(line.length - n);
          yield* this.pushNewline();
          return yield* this.parseBlockScalar();
        default:
          return yield* this.parsePlainScalar();
      }
    }
    *parseFlowCollection() {
      let nl, sp;
      let indent = -1;
      do {
        nl = yield* this.pushNewline();
        if (nl > 0) {
          sp = yield* this.pushSpaces(false);
          this.indentValue = indent = sp;
        } else {
          sp = 0;
        }
        sp += yield* this.pushSpaces(true);
      } while (nl + sp > 0);
      const line = this.getLine();
      if (line === null)
        return this.setNext("flow");
      if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty2(line[3])) {
        const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}");
        if (!atFlowEndMarker) {
          this.flowLevel = 0;
          yield cst.FLOW_END;
          return yield* this.parseLineStart();
        }
      }
      let n = 0;
      while (line[n] === ",") {
        n += yield* this.pushCount(1);
        n += yield* this.pushSpaces(true);
        this.flowKey = false;
      }
      n += yield* this.pushIndicators();
      switch (line[n]) {
        case undefined:
          return "flow";
        case "#":
          yield* this.pushCount(line.length - n);
          return "flow";
        case "{":
        case "[":
          yield* this.pushCount(1);
          this.flowKey = false;
          this.flowLevel += 1;
          return "flow";
        case "}":
        case "]":
          yield* this.pushCount(1);
          this.flowKey = true;
          this.flowLevel -= 1;
          return this.flowLevel ? "flow" : "doc";
        case "*":
          yield* this.pushUntil(isNotAnchorChar);
          return "flow";
        case '"':
        case "'":
          this.flowKey = true;
          return yield* this.parseQuotedScalar();
        case ":": {
          const next = this.charAt(1);
          if (this.flowKey || isEmpty2(next) || next === ",") {
            this.flowKey = false;
            yield* this.pushCount(1);
            yield* this.pushSpaces(true);
            return "flow";
          }
        }
        default:
          this.flowKey = false;
          return yield* this.parsePlainScalar();
      }
    }
    *parseQuotedScalar() {
      const quote = this.charAt(0);
      let end = this.buffer.indexOf(quote, this.pos + 1);
      if (quote === "'") {
        while (end !== -1 && this.buffer[end + 1] === "'")
          end = this.buffer.indexOf("'", end + 2);
      } else {
        while (end !== -1) {
          let n = 0;
          while (this.buffer[end - 1 - n] === "\\")
            n += 1;
          if (n % 2 === 0)
            break;
          end = this.buffer.indexOf('"', end + 1);
        }
      }
      const qb = this.buffer.substring(0, end);
      let nl = qb.indexOf(`
`, this.pos);
      if (nl !== -1) {
        while (nl !== -1) {
          const cs = this.continueScalar(nl + 1);
          if (cs === -1)
            break;
          nl = qb.indexOf(`
`, cs);
        }
        if (nl !== -1) {
          end = nl - (qb[nl - 1] === "\r" ? 2 : 1);
        }
      }
      if (end === -1) {
        if (!this.atEnd)
          return this.setNext("quoted-scalar");
        end = this.buffer.length;
      }
      yield* this.pushToIndex(end + 1, false);
      return this.flowLevel ? "flow" : "doc";
    }
    *parseBlockScalarHeader() {
      this.blockScalarIndent = -1;
      this.blockScalarKeep = false;
      let i = this.pos;
      while (true) {
        const ch = this.buffer[++i];
        if (ch === "+")
          this.blockScalarKeep = true;
        else if (ch > "0" && ch <= "9")
          this.blockScalarIndent = Number(ch) - 1;
        else if (ch !== "-")
          break;
      }
      return yield* this.pushUntil((ch) => isEmpty2(ch) || ch === "#");
    }
    *parseBlockScalar() {
      let nl = this.pos - 1;
      let indent = 0;
      let ch;
      loop:
        for (let i2 = this.pos;ch = this.buffer[i2]; ++i2) {
          switch (ch) {
            case " ":
              indent += 1;
              break;
            case `
`:
              nl = i2;
              indent = 0;
              break;
            case "\r": {
              const next = this.buffer[i2 + 1];
              if (!next && !this.atEnd)
                return this.setNext("block-scalar");
              if (next === `
`)
                break;
            }
            default:
              break loop;
          }
        }
      if (!ch && !this.atEnd)
        return this.setNext("block-scalar");
      if (indent >= this.indentNext) {
        if (this.blockScalarIndent === -1)
          this.indentNext = indent;
        else {
          this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);
        }
        do {
          const cs = this.continueScalar(nl + 1);
          if (cs === -1)
            break;
          nl = this.buffer.indexOf(`
`, cs);
        } while (nl !== -1);
        if (nl === -1) {
          if (!this.atEnd)
            return this.setNext("block-scalar");
          nl = this.buffer.length;
        }
      }
      let i = nl + 1;
      ch = this.buffer[i];
      while (ch === " ")
        ch = this.buffer[++i];
      if (ch === "\t") {
        while (ch === "\t" || ch === " " || ch === "\r" || ch === `
`)
          ch = this.buffer[++i];
        nl = i - 1;
      } else if (!this.blockScalarKeep) {
        do {
          let i2 = nl - 1;
          let ch2 = this.buffer[i2];
          if (ch2 === "\r")
            ch2 = this.buffer[--i2];
          const lastChar = i2;
          while (ch2 === " ")
            ch2 = this.buffer[--i2];
          if (ch2 === `
` && i2 >= this.pos && i2 + 1 + indent > lastChar)
            nl = i2;
          else
            break;
        } while (true);
      }
      yield cst.SCALAR;
      yield* this.pushToIndex(nl + 1, true);
      return yield* this.parseLineStart();
    }
    *parsePlainScalar() {
      const inFlow = this.flowLevel > 0;
      let end = this.pos - 1;
      let i = this.pos - 1;
      let ch;
      while (ch = this.buffer[++i]) {
        if (ch === ":") {
          const next = this.buffer[i + 1];
          if (isEmpty2(next) || inFlow && flowIndicatorChars.has(next))
            break;
          end = i;
        } else if (isEmpty2(ch)) {
          let next = this.buffer[i + 1];
          if (ch === "\r") {
            if (next === `
`) {
              i += 1;
              ch = `
`;
              next = this.buffer[i + 1];
            } else
              end = i;
          }
          if (next === "#" || inFlow && flowIndicatorChars.has(next))
            break;
          if (ch === `
`) {
            const cs = this.continueScalar(i + 1);
            if (cs === -1)
              break;
            i = Math.max(i, cs - 2);
          }
        } else {
          if (inFlow && flowIndicatorChars.has(ch))
            break;
          end = i;
        }
      }
      if (!ch && !this.atEnd)
        return this.setNext("plain-scalar");
      yield cst.SCALAR;
      yield* this.pushToIndex(end + 1, true);
      return inFlow ? "flow" : "doc";
    }
    *pushCount(n) {
      if (n > 0) {
        yield this.buffer.substr(this.pos, n);
        this.pos += n;
        return n;
      }
      return 0;
    }
    *pushToIndex(i, allowEmpty) {
      const s = this.buffer.slice(this.pos, i);
      if (s) {
        yield s;
        this.pos += s.length;
        return s.length;
      } else if (allowEmpty)
        yield "";
      return 0;
    }
    *pushIndicators() {
      switch (this.charAt(0)) {
        case "!":
          return (yield* this.pushTag()) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
        case "&":
          return (yield* this.pushUntil(isNotAnchorChar)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
        case "-":
        case "?":
        case ":": {
          const inFlow = this.flowLevel > 0;
          const ch1 = this.charAt(1);
          if (isEmpty2(ch1) || inFlow && flowIndicatorChars.has(ch1)) {
            if (!inFlow)
              this.indentNext = this.indentValue + 1;
            else if (this.flowKey)
              this.flowKey = false;
            return (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
          }
        }
      }
      return 0;
    }
    *pushTag() {
      if (this.charAt(1) === "<") {
        let i = this.pos + 2;
        let ch = this.buffer[i];
        while (!isEmpty2(ch) && ch !== ">")
          ch = this.buffer[++i];
        return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false);
      } else {
        let i = this.pos + 1;
        let ch = this.buffer[i];
        while (ch) {
          if (tagChars.has(ch))
            ch = this.buffer[++i];
          else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) {
            ch = this.buffer[i += 3];
          } else
            break;
        }
        return yield* this.pushToIndex(i, false);
      }
    }
    *pushNewline() {
      const ch = this.buffer[this.pos];
      if (ch === `
`)
        return yield* this.pushCount(1);
      else if (ch === "\r" && this.charAt(1) === `
`)
        return yield* this.pushCount(2);
      else
        return 0;
    }
    *pushSpaces(allowTabs) {
      let i = this.pos - 1;
      let ch;
      do {
        ch = this.buffer[++i];
      } while (ch === " " || allowTabs && ch === "\t");
      const n = i - this.pos;
      if (n > 0) {
        yield this.buffer.substr(this.pos, n);
        this.pos = i;
      }
      return n;
    }
    *pushUntil(test) {
      let i = this.pos;
      let ch = this.buffer[i];
      while (!test(ch))
        ch = this.buffer[++i];
      return yield* this.pushToIndex(i, false);
    }
  }
  exports.Lexer = Lexer;
});

// node_modules/yaml/dist/parse/line-counter.js
var require_line_counter = __commonJS((exports) => {
  class LineCounter {
    constructor() {
      this.lineStarts = [];
      this.addNewLine = (offset) => this.lineStarts.push(offset);
      this.linePos = (offset) => {
        let low = 0;
        let high = this.lineStarts.length;
        while (low < high) {
          const mid = low + high >> 1;
          if (this.lineStarts[mid] < offset)
            low = mid + 1;
          else
            high = mid;
        }
        if (this.lineStarts[low] === offset)
          return { line: low + 1, col: 1 };
        if (low === 0)
          return { line: 0, col: offset };
        const start = this.lineStarts[low - 1];
        return { line: low, col: offset - start + 1 };
      };
    }
  }
  exports.LineCounter = LineCounter;
});

// node_modules/yaml/dist/parse/parser.js
var require_parser = __commonJS((exports) => {
  var node_process = __require("process");
  var cst = require_cst();
  var lexer = require_lexer();
  function includesToken(list, type) {
    for (let i = 0;i < list.length; ++i)
      if (list[i].type === type)
        return true;
    return false;
  }
  function findNonEmptyIndex(list) {
    for (let i = 0;i < list.length; ++i) {
      switch (list[i].type) {
        case "space":
        case "comment":
        case "newline":
          break;
        default:
          return i;
      }
    }
    return -1;
  }
  function isFlowToken(token) {
    switch (token?.type) {
      case "alias":
      case "scalar":
      case "single-quoted-scalar":
      case "double-quoted-scalar":
      case "flow-collection":
        return true;
      default:
        return false;
    }
  }
  function getPrevProps(parent) {
    switch (parent.type) {
      case "document":
        return parent.start;
      case "block-map": {
        const it = parent.items[parent.items.length - 1];
        return it.sep ?? it.start;
      }
      case "block-seq":
        return parent.items[parent.items.length - 1].start;
      default:
        return [];
    }
  }
  function getFirstKeyStartProps(prev) {
    if (prev.length === 0)
      return [];
    let i = prev.length;
    loop:
      while (--i >= 0) {
        switch (prev[i].type) {
          case "doc-start":
          case "explicit-key-ind":
          case "map-value-ind":
          case "seq-item-ind":
          case "newline":
            break loop;
        }
      }
    while (prev[++i]?.type === "space") {}
    return prev.splice(i, prev.length);
  }
  function fixFlowSeqItems(fc) {
    if (fc.start.type === "flow-seq-start") {
      for (const it of fc.items) {
        if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) {
          if (it.key)
            it.value = it.key;
          delete it.key;
          if (isFlowToken(it.value)) {
            if (it.value.end)
              Array.prototype.push.apply(it.value.end, it.sep);
            else
              it.value.end = it.sep;
          } else
            Array.prototype.push.apply(it.start, it.sep);
          delete it.sep;
        }
      }
    }
  }

  class Parser2 {
    constructor(onNewLine) {
      this.atNewLine = true;
      this.atScalar = false;
      this.indent = 0;
      this.offset = 0;
      this.onKeyLine = false;
      this.stack = [];
      this.source = "";
      this.type = "";
      this.lexer = new lexer.Lexer;
      this.onNewLine = onNewLine;
    }
    *parse(source, incomplete = false) {
      if (this.onNewLine && this.offset === 0)
        this.onNewLine(0);
      for (const lexeme of this.lexer.lex(source, incomplete))
        yield* this.next(lexeme);
      if (!incomplete)
        yield* this.end();
    }
    *next(source) {
      this.source = source;
      if (node_process.env.LOG_TOKENS)
        console.log("|", cst.prettyToken(source));
      if (this.atScalar) {
        this.atScalar = false;
        yield* this.step();
        this.offset += source.length;
        return;
      }
      const type = cst.tokenType(source);
      if (!type) {
        const message = `Not a YAML token: ${source}`;
        yield* this.pop({ type: "error", offset: this.offset, message, source });
        this.offset += source.length;
      } else if (type === "scalar") {
        this.atNewLine = false;
        this.atScalar = true;
        this.type = "scalar";
      } else {
        this.type = type;
        yield* this.step();
        switch (type) {
          case "newline":
            this.atNewLine = true;
            this.indent = 0;
            if (this.onNewLine)
              this.onNewLine(this.offset + source.length);
            break;
          case "space":
            if (this.atNewLine && source[0] === " ")
              this.indent += source.length;
            break;
          case "explicit-key-ind":
          case "map-value-ind":
          case "seq-item-ind":
            if (this.atNewLine)
              this.indent += source.length;
            break;
          case "doc-mode":
          case "flow-error-end":
            return;
          default:
            this.atNewLine = false;
        }
        this.offset += source.length;
      }
    }
    *end() {
      while (this.stack.length > 0)
        yield* this.pop();
    }
    get sourceToken() {
      const st = {
        type: this.type,
        offset: this.offset,
        indent: this.indent,
        source: this.source
      };
      return st;
    }
    *step() {
      const top = this.peek(1);
      if (this.type === "doc-end" && top?.type !== "doc-end") {
        while (this.stack.length > 0)
          yield* this.pop();
        this.stack.push({
          type: "doc-end",
          offset: this.offset,
          source: this.source
        });
        return;
      }
      if (!top)
        return yield* this.stream();
      switch (top.type) {
        case "document":
          return yield* this.document(top);
        case "alias":
        case "scalar":
        case "single-quoted-scalar":
        case "double-quoted-scalar":
          return yield* this.scalar(top);
        case "block-scalar":
          return yield* this.blockScalar(top);
        case "block-map":
          return yield* this.blockMap(top);
        case "block-seq":
          return yield* this.blockSequence(top);
        case "flow-collection":
          return yield* this.flowCollection(top);
        case "doc-end":
          return yield* this.documentEnd(top);
      }
      yield* this.pop();
    }
    peek(n) {
      return this.stack[this.stack.length - n];
    }
    *pop(error48) {
      const token = error48 ?? this.stack.pop();
      if (!token) {
        const message = "Tried to pop an empty stack";
        yield { type: "error", offset: this.offset, source: "", message };
      } else if (this.stack.length === 0) {
        yield token;
      } else {
        const top = this.peek(1);
        if (token.type === "block-scalar") {
          token.indent = "indent" in top ? top.indent : 0;
        } else if (token.type === "flow-collection" && top.type === "document") {
          token.indent = 0;
        }
        if (token.type === "flow-collection")
          fixFlowSeqItems(token);
        switch (top.type) {
          case "document":
            top.value = token;
            break;
          case "block-scalar":
            top.props.push(token);
            break;
          case "block-map": {
            const it = top.items[top.items.length - 1];
            if (it.value) {
              top.items.push({ start: [], key: token, sep: [] });
              this.onKeyLine = true;
              return;
            } else if (it.sep) {
              it.value = token;
            } else {
              Object.assign(it, { key: token, sep: [] });
              this.onKeyLine = !it.explicitKey;
              return;
            }
            break;
          }
          case "block-seq": {
            const it = top.items[top.items.length - 1];
            if (it.value)
              top.items.push({ start: [], value: token });
            else
              it.value = token;
            break;
          }
          case "flow-collection": {
            const it = top.items[top.items.length - 1];
            if (!it || it.value)
              top.items.push({ start: [], key: token, sep: [] });
            else if (it.sep)
              it.value = token;
            else
              Object.assign(it, { key: token, sep: [] });
            return;
          }
          default:
            yield* this.pop();
            yield* this.pop(token);
        }
        if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) {
          const last2 = token.items[token.items.length - 1];
          if (last2 && !last2.sep && !last2.value && last2.start.length > 0 && findNonEmptyIndex(last2.start) === -1 && (token.indent === 0 || last2.start.every((st) => st.type !== "comment" || st.indent < token.indent))) {
            if (top.type === "document")
              top.end = last2.start;
            else
              top.items.push({ start: last2.start });
            token.items.splice(-1, 1);
          }
        }
      }
    }
    *stream() {
      switch (this.type) {
        case "directive-line":
          yield { type: "directive", offset: this.offset, source: this.source };
          return;
        case "byte-order-mark":
        case "space":
        case "comment":
        case "newline":
          yield this.sourceToken;
          return;
        case "doc-mode":
        case "doc-start": {
          const doc2 = {
            type: "document",
            offset: this.offset,
            start: []
          };
          if (this.type === "doc-start")
            doc2.start.push(this.sourceToken);
          this.stack.push(doc2);
          return;
        }
      }
      yield {
        type: "error",
        offset: this.offset,
        message: `Unexpected ${this.type} token in YAML stream`,
        source: this.source
      };
    }
    *document(doc2) {
      if (doc2.value)
        return yield* this.lineEnd(doc2);
      switch (this.type) {
        case "doc-start": {
          if (findNonEmptyIndex(doc2.start) !== -1) {
            yield* this.pop();
            yield* this.step();
          } else
            doc2.start.push(this.sourceToken);
          return;
        }
        case "anchor":
        case "tag":
        case "space":
        case "comment":
        case "newline":
          doc2.start.push(this.sourceToken);
          return;
      }
      const bv = this.startBlockValue(doc2);
      if (bv)
        this.stack.push(bv);
      else {
        yield {
          type: "error",
          offset: this.offset,
          message: `Unexpected ${this.type} token in YAML document`,
          source: this.source
        };
      }
    }
    *scalar(scalar) {
      if (this.type === "map-value-ind") {
        const prev = getPrevProps(this.peek(2));
        const start = getFirstKeyStartProps(prev);
        let sep;
        if (scalar.end) {
          sep = scalar.end;
          sep.push(this.sourceToken);
          delete scalar.end;
        } else
          sep = [this.sourceToken];
        const map4 = {
          type: "block-map",
          offset: scalar.offset,
          indent: scalar.indent,
          items: [{ start, key: scalar, sep }]
        };
        this.onKeyLine = true;
        this.stack[this.stack.length - 1] = map4;
      } else
        yield* this.lineEnd(scalar);
    }
    *blockScalar(scalar) {
      switch (this.type) {
        case "space":
        case "comment":
        case "newline":
          scalar.props.push(this.sourceToken);
          return;
        case "scalar":
          scalar.source = this.source;
          this.atNewLine = true;
          this.indent = 0;
          if (this.onNewLine) {
            let nl = this.source.indexOf(`
`) + 1;
            while (nl !== 0) {
              this.onNewLine(this.offset + nl);
              nl = this.source.indexOf(`
`, nl) + 1;
            }
          }
          yield* this.pop();
          break;
        default:
          yield* this.pop();
          yield* this.step();
      }
    }
    *blockMap(map4) {
      const it = map4.items[map4.items.length - 1];
      switch (this.type) {
        case "newline":
          this.onKeyLine = false;
          if (it.value) {
            const end = "end" in it.value ? it.value.end : undefined;
            const last2 = Array.isArray(end) ? end[end.length - 1] : undefined;
            if (last2?.type === "comment")
              end?.push(this.sourceToken);
            else
              map4.items.push({ start: [this.sourceToken] });
          } else if (it.sep) {
            it.sep.push(this.sourceToken);
          } else {
            it.start.push(this.sourceToken);
          }
          return;
        case "space":
        case "comment":
          if (it.value) {
            map4.items.push({ start: [this.sourceToken] });
          } else if (it.sep) {
            it.sep.push(this.sourceToken);
          } else {
            if (this.atIndentedComment(it.start, map4.indent)) {
              const prev = map4.items[map4.items.length - 2];
              const end = prev?.value?.end;
              if (Array.isArray(end)) {
                Array.prototype.push.apply(end, it.start);
                end.push(this.sourceToken);
                map4.items.pop();
                return;
              }
            }
            it.start.push(this.sourceToken);
          }
          return;
      }
      if (this.indent >= map4.indent) {
        const atMapIndent = !this.onKeyLine && this.indent === map4.indent;
        const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind";
        let start = [];
        if (atNextItem && it.sep && !it.value) {
          const nl = [];
          for (let i = 0;i < it.sep.length; ++i) {
            const st = it.sep[i];
            switch (st.type) {
              case "newline":
                nl.push(i);
                break;
              case "space":
                break;
              case "comment":
                if (st.indent > map4.indent)
                  nl.length = 0;
                break;
              default:
                nl.length = 0;
            }
          }
          if (nl.length >= 2)
            start = it.sep.splice(nl[1]);
        }
        switch (this.type) {
          case "anchor":
          case "tag":
            if (atNextItem || it.value) {
              start.push(this.sourceToken);
              map4.items.push({ start });
              this.onKeyLine = true;
            } else if (it.sep) {
              it.sep.push(this.sourceToken);
            } else {
              it.start.push(this.sourceToken);
            }
            return;
          case "explicit-key-ind":
            if (!it.sep && !it.explicitKey) {
              it.start.push(this.sourceToken);
              it.explicitKey = true;
            } else if (atNextItem || it.value) {
              start.push(this.sourceToken);
              map4.items.push({ start, explicitKey: true });
            } else {
              this.stack.push({
                type: "block-map",
                offset: this.offset,
                indent: this.indent,
                items: [{ start: [this.sourceToken], explicitKey: true }]
              });
            }
            this.onKeyLine = true;
            return;
          case "map-value-ind":
            if (it.explicitKey) {
              if (!it.sep) {
                if (includesToken(it.start, "newline")) {
                  Object.assign(it, { key: null, sep: [this.sourceToken] });
                } else {
                  const start2 = getFirstKeyStartProps(it.start);
                  this.stack.push({
                    type: "block-map",
                    offset: this.offset,
                    indent: this.indent,
                    items: [{ start: start2, key: null, sep: [this.sourceToken] }]
                  });
                }
              } else if (it.value) {
                map4.items.push({ start: [], key: null, sep: [this.sourceToken] });
              } else if (includesToken(it.sep, "map-value-ind")) {
                this.stack.push({
                  type: "block-map",
                  offset: this.offset,
                  indent: this.indent,
                  items: [{ start, key: null, sep: [this.sourceToken] }]
                });
              } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) {
                const start2 = getFirstKeyStartProps(it.start);
                const key = it.key;
                const sep = it.sep;
                sep.push(this.sourceToken);
                delete it.key;
                delete it.sep;
                this.stack.push({
                  type: "block-map",
                  offset: this.offset,
                  indent: this.indent,
                  items: [{ start: start2, key, sep }]
                });
              } else if (start.length > 0) {
                it.sep = it.sep.concat(start, this.sourceToken);
              } else {
                it.sep.push(this.sourceToken);
              }
            } else {
              if (!it.sep) {
                Object.assign(it, { key: null, sep: [this.sourceToken] });
              } else if (it.value || atNextItem) {
                map4.items.push({ start, key: null, sep: [this.sourceToken] });
              } else if (includesToken(it.sep, "map-value-ind")) {
                this.stack.push({
                  type: "block-map",
                  offset: this.offset,
                  indent: this.indent,
                  items: [{ start: [], key: null, sep: [this.sourceToken] }]
                });
              } else {
                it.sep.push(this.sourceToken);
              }
            }
            this.onKeyLine = true;
            return;
          case "alias":
          case "scalar":
          case "single-quoted-scalar":
          case "double-quoted-scalar": {
            const fs2 = this.flowScalar(this.type);
            if (atNextItem || it.value) {
              map4.items.push({ start, key: fs2, sep: [] });
              this.onKeyLine = true;
            } else if (it.sep) {
              this.stack.push(fs2);
            } else {
              Object.assign(it, { key: fs2, sep: [] });
              this.onKeyLine = true;
            }
            return;
          }
          default: {
            const bv = this.startBlockValue(map4);
            if (bv) {
              if (bv.type === "block-seq") {
                if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) {
                  yield* this.pop({
                    type: "error",
                    offset: this.offset,
                    message: "Unexpected block-seq-ind on same line with key",
                    source: this.source
                  });
                  return;
                }
              } else if (atMapIndent) {
                map4.items.push({ start });
              }
              this.stack.push(bv);
              return;
            }
          }
        }
      }
      yield* this.pop();
      yield* this.step();
    }
    *blockSequence(seq) {
      const it = seq.items[seq.items.length - 1];
      switch (this.type) {
        case "newline":
          if (it.value) {
            const end = "end" in it.value ? it.value.end : undefined;
            const last2 = Array.isArray(end) ? end[end.length - 1] : undefined;
            if (last2?.type === "comment")
              end?.push(this.sourceToken);
            else
              seq.items.push({ start: [this.sourceToken] });
          } else
            it.start.push(this.sourceToken);
          return;
        case "space":
        case "comment":
          if (it.value)
            seq.items.push({ start: [this.sourceToken] });
          else {
            if (this.atIndentedComment(it.start, seq.indent)) {
              const prev = seq.items[seq.items.length - 2];
              const end = prev?.value?.end;
              if (Array.isArray(end)) {
                Array.prototype.push.apply(end, it.start);
                end.push(this.sourceToken);
                seq.items.pop();
                return;
              }
            }
            it.start.push(this.sourceToken);
          }
          return;
        case "anchor":
        case "tag":
          if (it.value || this.indent <= seq.indent)
            break;
          it.start.push(this.sourceToken);
          return;
        case "seq-item-ind":
          if (this.indent !== seq.indent)
            break;
          if (it.value || includesToken(it.start, "seq-item-ind"))
            seq.items.push({ start: [this.sourceToken] });
          else
            it.start.push(this.sourceToken);
          return;
      }
      if (this.indent > seq.indent) {
        const bv = this.startBlockValue(seq);
        if (bv) {
          this.stack.push(bv);
          return;
        }
      }
      yield* this.pop();
      yield* this.step();
    }
    *flowCollection(fc) {
      const it = fc.items[fc.items.length - 1];
      if (this.type === "flow-error-end") {
        let top;
        do {
          yield* this.pop();
          top = this.peek(1);
        } while (top?.type === "flow-collection");
      } else if (fc.end.length === 0) {
        switch (this.type) {
          case "comma":
          case "explicit-key-ind":
            if (!it || it.sep)
              fc.items.push({ start: [this.sourceToken] });
            else
              it.start.push(this.sourceToken);
            return;
          case "map-value-ind":
            if (!it || it.value)
              fc.items.push({ start: [], key: null, sep: [this.sourceToken] });
            else if (it.sep)
              it.sep.push(this.sourceToken);
            else
              Object.assign(it, { key: null, sep: [this.sourceToken] });
            return;
          case "space":
          case "comment":
          case "newline":
          case "anchor":
          case "tag":
            if (!it || it.value)
              fc.items.push({ start: [this.sourceToken] });
            else if (it.sep)
              it.sep.push(this.sourceToken);
            else
              it.start.push(this.sourceToken);
            return;
          case "alias":
          case "scalar":
          case "single-quoted-scalar":
          case "double-quoted-scalar": {
            const fs2 = this.flowScalar(this.type);
            if (!it || it.value)
              fc.items.push({ start: [], key: fs2, sep: [] });
            else if (it.sep)
              this.stack.push(fs2);
            else
              Object.assign(it, { key: fs2, sep: [] });
            return;
          }
          case "flow-map-end":
          case "flow-seq-end":
            fc.end.push(this.sourceToken);
            return;
        }
        const bv = this.startBlockValue(fc);
        if (bv)
          this.stack.push(bv);
        else {
          yield* this.pop();
          yield* this.step();
        }
      } else {
        const parent = this.peek(2);
        if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) {
          yield* this.pop();
          yield* this.step();
        } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") {
          const prev = getPrevProps(parent);
          const start = getFirstKeyStartProps(prev);
          fixFlowSeqItems(fc);
          const sep = fc.end.splice(1, fc.end.length);
          sep.push(this.sourceToken);
          const map4 = {
            type: "block-map",
            offset: fc.offset,
            indent: fc.indent,
            items: [{ start, key: fc, sep }]
          };
          this.onKeyLine = true;
          this.stack[this.stack.length - 1] = map4;
        } else {
          yield* this.lineEnd(fc);
        }
      }
    }
    flowScalar(type) {
      if (this.onNewLine) {
        let nl = this.source.indexOf(`
`) + 1;
        while (nl !== 0) {
          this.onNewLine(this.offset + nl);
          nl = this.source.indexOf(`
`, nl) + 1;
        }
      }
      return {
        type,
        offset: this.offset,
        indent: this.indent,
        source: this.source
      };
    }
    startBlockValue(parent) {
      switch (this.type) {
        case "alias":
        case "scalar":
        case "single-quoted-scalar":
        case "double-quoted-scalar":
          return this.flowScalar(this.type);
        case "block-scalar-header":
          return {
            type: "block-scalar",
            offset: this.offset,
            indent: this.indent,
            props: [this.sourceToken],
            source: ""
          };
        case "flow-map-start":
        case "flow-seq-start":
          return {
            type: "flow-collection",
            offset: this.offset,
            indent: this.indent,
            start: this.sourceToken,
            items: [],
            end: []
          };
        case "seq-item-ind":
          return {
            type: "block-seq",
            offset: this.offset,
            indent: this.indent,
            items: [{ start: [this.sourceToken] }]
          };
        case "explicit-key-ind": {
          this.onKeyLine = true;
          const prev = getPrevProps(parent);
          const start = getFirstKeyStartProps(prev);
          start.push(this.sourceToken);
          return {
            type: "block-map",
            offset: this.offset,
            indent: this.indent,
            items: [{ start, explicitKey: true }]
          };
        }
        case "map-value-ind": {
          this.onKeyLine = true;
          const prev = getPrevProps(parent);
          const start = getFirstKeyStartProps(prev);
          return {
            type: "block-map",
            offset: this.offset,
            indent: this.indent,
            items: [{ start, key: null, sep: [this.sourceToken] }]
          };
        }
      }
      return null;
    }
    atIndentedComment(start, indent) {
      if (this.type !== "comment")
        return false;
      if (this.indent <= indent)
        return false;
      return start.every((st) => st.type === "newline" || st.type === "space");
    }
    *documentEnd(docEnd) {
      if (this.type !== "doc-mode") {
        if (docEnd.end)
          docEnd.end.push(this.sourceToken);
        else
          docEnd.end = [this.sourceToken];
        if (this.type === "newline")
          yield* this.pop();
      }
    }
    *lineEnd(token) {
      switch (this.type) {
        case "comma":
        case "doc-start":
        case "doc-end":
        case "flow-seq-end":
        case "flow-map-end":
        case "map-value-ind":
          yield* this.pop();
          yield* this.step();
          break;
        case "newline":
          this.onKeyLine = false;
        case "space":
        case "comment":
        default:
          if (token.end)
            token.end.push(this.sourceToken);
          else
            token.end = [this.sourceToken];
          if (this.type === "newline")
            yield* this.pop();
      }
    }
  }
  exports.Parser = Parser2;
});

// node_modules/yaml/dist/public-api.js
var require_public_api = __commonJS((exports) => {
  var composer = require_composer();
  var Document = require_Document();
  var errors3 = require_errors();
  var log = require_log();
  var identity3 = require_identity();
  var lineCounter = require_line_counter();
  var parser = require_parser();
  function parseOptions(options) {
    const prettyErrors = options.prettyErrors !== false;
    const lineCounter$1 = options.lineCounter || prettyErrors && new lineCounter.LineCounter || null;
    return { lineCounter: lineCounter$1, prettyErrors };
  }
  function parseAllDocuments(source, options = {}) {
    const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
    const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
    const composer$1 = new composer.Composer(options);
    const docs = Array.from(composer$1.compose(parser$1.parse(source)));
    if (prettyErrors && lineCounter2)
      for (const doc2 of docs) {
        doc2.errors.forEach(errors3.prettifyError(source, lineCounter2));
        doc2.warnings.forEach(errors3.prettifyError(source, lineCounter2));
      }
    if (docs.length > 0)
      return docs;
    return Object.assign([], { empty: true }, composer$1.streamInfo());
  }
  function parseDocument(source, options = {}) {
    const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
    const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
    const composer$1 = new composer.Composer(options);
    let doc2 = null;
    for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) {
      if (!doc2)
        doc2 = _doc;
      else if (doc2.options.logLevel !== "silent") {
        doc2.errors.push(new errors3.YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()"));
        break;
      }
    }
    if (prettyErrors && lineCounter2) {
      doc2.errors.forEach(errors3.prettifyError(source, lineCounter2));
      doc2.warnings.forEach(errors3.prettifyError(source, lineCounter2));
    }
    return doc2;
  }
  function parse5(src, reviver, options) {
    let _reviver = undefined;
    if (typeof reviver === "function") {
      _reviver = reviver;
    } else if (options === undefined && reviver && typeof reviver === "object") {
      options = reviver;
    }
    const doc2 = parseDocument(src, options);
    if (!doc2)
      return null;
    doc2.warnings.forEach((warning) => log.warn(doc2.options.logLevel, warning));
    if (doc2.errors.length > 0) {
      if (doc2.options.logLevel !== "silent")
        throw doc2.errors[0];
      else
        doc2.errors = [];
    }
    return doc2.toJS(Object.assign({ reviver: _reviver }, options));
  }
  function stringify(value, replacer, options) {
    let _replacer = null;
    if (typeof replacer === "function" || Array.isArray(replacer)) {
      _replacer = replacer;
    } else if (options === undefined && replacer) {
      options = replacer;
    }
    if (typeof options === "string")
      options = options.length;
    if (typeof options === "number") {
      const indent = Math.round(options);
      options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };
    }
    if (value === undefined) {
      const { keepUndefined } = options ?? replacer ?? {};
      if (!keepUndefined)
        return;
    }
    if (identity3.isDocument(value) && !_replacer)
      return value.toString(options);
    return new Document.Document(value, _replacer, options).toString(options);
  }
  exports.parse = parse5;
  exports.parseAllDocuments = parseAllDocuments;
  exports.parseDocument = parseDocument;
  exports.stringify = stringify;
});

// node_modules/jstat/dist/jstat.js
var require_jstat = __commonJS((exports, module) => {
  (function(window2, factory) {
    if (typeof exports === "object") {
      module.exports = factory();
    } else if (typeof define === "function" && define.amd) {
      define(factory);
    } else {
      window2.jStat = factory();
    }
  })(exports, function() {
    var jStat = function(Math2, undefined2) {
      var concat = Array.prototype.concat;
      var slice3 = Array.prototype.slice;
      var toString = Object.prototype.toString;
      function calcRdx(n, m) {
        var val = n > m ? n : m;
        return Math2.pow(10, 17 - ~~(Math2.log(val > 0 ? val : -val) * Math2.LOG10E));
      }
      var isArray2 = Array.isArray || function isArray(arg) {
        return toString.call(arg) === "[object Array]";
      };
      function isFunction(arg) {
        return toString.call(arg) === "[object Function]";
      }
      function isNumber2(num) {
        return typeof num === "number" ? num - num === 0 : false;
      }
      function toVector(arr) {
        return concat.apply([], arr);
      }
      function jStat2() {
        return new jStat2._init(arguments);
      }
      jStat2.fn = jStat2.prototype;
      jStat2._init = function _init(args2) {
        if (isArray2(args2[0])) {
          if (isArray2(args2[0][0])) {
            if (isFunction(args2[1]))
              args2[0] = jStat2.map(args2[0], args2[1]);
            for (var i = 0;i < args2[0].length; i++)
              this[i] = args2[0][i];
            this.length = args2[0].length;
          } else {
            this[0] = isFunction(args2[1]) ? jStat2.map(args2[0], args2[1]) : args2[0];
            this.length = 1;
          }
        } else if (isNumber2(args2[0])) {
          this[0] = jStat2.seq.apply(null, args2);
          this.length = 1;
        } else if (args2[0] instanceof jStat2) {
          return jStat2(args2[0].toArray());
        } else {
          this[0] = [];
          this.length = 1;
        }
        return this;
      };
      jStat2._init.prototype = jStat2.prototype;
      jStat2._init.constructor = jStat2;
      jStat2.utils = {
        calcRdx,
        isArray: isArray2,
        isFunction,
        isNumber: isNumber2,
        toVector
      };
      jStat2._random_fn = Math2.random;
      jStat2.setRandom = function setRandom(fn) {
        if (typeof fn !== "function")
          throw new TypeError("fn is not a function");
        jStat2._random_fn = fn;
      };
      jStat2.extend = function extend(obj) {
        var i, j;
        if (arguments.length === 1) {
          for (j in obj)
            jStat2[j] = obj[j];
          return this;
        }
        for (i = 1;i < arguments.length; i++) {
          for (j in arguments[i])
            obj[j] = arguments[i][j];
        }
        return obj;
      };
      jStat2.rows = function rows(arr) {
        return arr.length || 1;
      };
      jStat2.cols = function cols(arr) {
        return arr[0].length || 1;
      };
      jStat2.dimensions = function dimensions(arr) {
        return {
          rows: jStat2.rows(arr),
          cols: jStat2.cols(arr)
        };
      };
      jStat2.row = function row(arr, index) {
        if (isArray2(index)) {
          return index.map(function(i) {
            return jStat2.row(arr, i);
          });
        }
        return arr[index];
      };
      jStat2.rowa = function rowa(arr, i) {
        return jStat2.row(arr, i);
      };
      jStat2.col = function col(arr, index) {
        if (isArray2(index)) {
          var submat = jStat2.arange(arr.length).map(function() {
            return new Array(index.length);
          });
          index.forEach(function(ind, i2) {
            jStat2.arange(arr.length).forEach(function(j) {
              submat[j][i2] = arr[j][ind];
            });
          });
          return submat;
        }
        var column2 = new Array(arr.length);
        for (var i = 0;i < arr.length; i++)
          column2[i] = [arr[i][index]];
        return column2;
      };
      jStat2.cola = function cola(arr, i) {
        return jStat2.col(arr, i).map(function(a) {
          return a[0];
        });
      };
      jStat2.diag = function diag(arr) {
        var nrow = jStat2.rows(arr);
        var res = new Array(nrow);
        for (var row2 = 0;row2 < nrow; row2++)
          res[row2] = [arr[row2][row2]];
        return res;
      };
      jStat2.antidiag = function antidiag(arr) {
        var nrow = jStat2.rows(arr) - 1;
        var res = new Array(nrow);
        for (var i = 0;nrow >= 0; nrow--, i++)
          res[i] = [arr[i][nrow]];
        return res;
      };
      jStat2.transpose = function transpose(arr) {
        var obj = [];
        var objArr, rows, cols, j, i;
        if (!isArray2(arr[0]))
          arr = [arr];
        rows = arr.length;
        cols = arr[0].length;
        for (i = 0;i < cols; i++) {
          objArr = new Array(rows);
          for (j = 0;j < rows; j++)
            objArr[j] = arr[j][i];
          obj.push(objArr);
        }
        return obj.length === 1 ? obj[0] : obj;
      };
      jStat2.map = function map(arr, func, toAlter) {
        var row2, nrow, ncol, res, col;
        if (!isArray2(arr[0]))
          arr = [arr];
        nrow = arr.length;
        ncol = arr[0].length;
        res = toAlter ? arr : new Array(nrow);
        for (row2 = 0;row2 < nrow; row2++) {
          if (!res[row2])
            res[row2] = new Array(ncol);
          for (col = 0;col < ncol; col++)
            res[row2][col] = func(arr[row2][col], row2, col);
        }
        return res.length === 1 ? res[0] : res;
      };
      jStat2.cumreduce = function cumreduce(arr, func, toAlter) {
        var row2, nrow, ncol, res, col;
        if (!isArray2(arr[0]))
          arr = [arr];
        nrow = arr.length;
        ncol = arr[0].length;
        res = toAlter ? arr : new Array(nrow);
        for (row2 = 0;row2 < nrow; row2++) {
          if (!res[row2])
            res[row2] = new Array(ncol);
          if (ncol > 0)
            res[row2][0] = arr[row2][0];
          for (col = 1;col < ncol; col++)
            res[row2][col] = func(res[row2][col - 1], arr[row2][col]);
        }
        return res.length === 1 ? res[0] : res;
      };
      jStat2.alter = function alter(arr, func) {
        return jStat2.map(arr, func, true);
      };
      jStat2.create = function create(rows, cols, func) {
        var res = new Array(rows);
        var i, j;
        if (isFunction(cols)) {
          func = cols;
          cols = rows;
        }
        for (i = 0;i < rows; i++) {
          res[i] = new Array(cols);
          for (j = 0;j < cols; j++)
            res[i][j] = func(i, j);
        }
        return res;
      };
      function retZero() {
        return 0;
      }
      jStat2.zeros = function zeros(rows, cols) {
        if (!isNumber2(cols))
          cols = rows;
        return jStat2.create(rows, cols, retZero);
      };
      function retOne() {
        return 1;
      }
      jStat2.ones = function ones(rows, cols) {
        if (!isNumber2(cols))
          cols = rows;
        return jStat2.create(rows, cols, retOne);
      };
      jStat2.rand = function rand(rows, cols) {
        if (!isNumber2(cols))
          cols = rows;
        return jStat2.create(rows, cols, jStat2._random_fn);
      };
      function retIdent(i, j) {
        return i === j ? 1 : 0;
      }
      jStat2.identity = function identity(rows, cols) {
        if (!isNumber2(cols))
          cols = rows;
        return jStat2.create(rows, cols, retIdent);
      };
      jStat2.symmetric = function symmetric(arr) {
        var size2 = arr.length;
        var row2, col;
        if (arr.length !== arr[0].length)
          return false;
        for (row2 = 0;row2 < size2; row2++) {
          for (col = 0;col < size2; col++)
            if (arr[col][row2] !== arr[row2][col])
              return false;
        }
        return true;
      };
      jStat2.clear = function clear(arr) {
        return jStat2.alter(arr, retZero);
      };
      jStat2.seq = function seq(min3, max4, length2, func) {
        if (!isFunction(func))
          func = false;
        var arr = [];
        var hival = calcRdx(min3, max4);
        var step = (max4 * hival - min3 * hival) / ((length2 - 1) * hival);
        var current = min3;
        var cnt;
        for (cnt = 0;current <= max4 && cnt < length2; cnt++, current = (min3 * hival + step * hival * cnt) / hival) {
          arr.push(func ? func(current, cnt) : current);
        }
        return arr;
      };
      jStat2.arange = function arange(start, end, step) {
        var rl = [];
        var i;
        step = step || 1;
        if (end === undefined2) {
          end = start;
          start = 0;
        }
        if (start === end || step === 0) {
          return [];
        }
        if (start < end && step < 0) {
          return [];
        }
        if (start > end && step > 0) {
          return [];
        }
        if (step > 0) {
          for (i = start;i < end; i += step) {
            rl.push(i);
          }
        } else {
          for (i = start;i > end; i += step) {
            rl.push(i);
          }
        }
        return rl;
      };
      jStat2.slice = function() {
        function _slice(list, start, end, step) {
          var i;
          var rl = [];
          var length2 = list.length;
          if (start === undefined2 && end === undefined2 && step === undefined2) {
            return jStat2.copy(list);
          }
          start = start || 0;
          end = end || list.length;
          start = start >= 0 ? start : length2 + start;
          end = end >= 0 ? end : length2 + end;
          step = step || 1;
          if (start === end || step === 0) {
            return [];
          }
          if (start < end && step < 0) {
            return [];
          }
          if (start > end && step > 0) {
            return [];
          }
          if (step > 0) {
            for (i = start;i < end; i += step) {
              rl.push(list[i]);
            }
          } else {
            for (i = start;i > end; i += step) {
              rl.push(list[i]);
            }
          }
          return rl;
        }
        function slice4(list, rcSlice) {
          var colSlice, rowSlice;
          rcSlice = rcSlice || {};
          if (isNumber2(rcSlice.row)) {
            if (isNumber2(rcSlice.col))
              return list[rcSlice.row][rcSlice.col];
            var row2 = jStat2.rowa(list, rcSlice.row);
            colSlice = rcSlice.col || {};
            return _slice(row2, colSlice.start, colSlice.end, colSlice.step);
          }
          if (isNumber2(rcSlice.col)) {
            var col = jStat2.cola(list, rcSlice.col);
            rowSlice = rcSlice.row || {};
            return _slice(col, rowSlice.start, rowSlice.end, rowSlice.step);
          }
          rowSlice = rcSlice.row || {};
          colSlice = rcSlice.col || {};
          var rows = _slice(list, rowSlice.start, rowSlice.end, rowSlice.step);
          return rows.map(function(row3) {
            return _slice(row3, colSlice.start, colSlice.end, colSlice.step);
          });
        }
        return slice4;
      }();
      jStat2.sliceAssign = function sliceAssign(A, rcSlice, B) {
        var nl, ml;
        if (isNumber2(rcSlice.row)) {
          if (isNumber2(rcSlice.col))
            return A[rcSlice.row][rcSlice.col] = B;
          rcSlice.col = rcSlice.col || {};
          rcSlice.col.start = rcSlice.col.start || 0;
          rcSlice.col.end = rcSlice.col.end || A[0].length;
          rcSlice.col.step = rcSlice.col.step || 1;
          nl = jStat2.arange(rcSlice.col.start, Math2.min(A.length, rcSlice.col.end), rcSlice.col.step);
          var m = rcSlice.row;
          nl.forEach(function(n2, i) {
            A[m][n2] = B[i];
          });
          return A;
        }
        if (isNumber2(rcSlice.col)) {
          rcSlice.row = rcSlice.row || {};
          rcSlice.row.start = rcSlice.row.start || 0;
          rcSlice.row.end = rcSlice.row.end || A.length;
          rcSlice.row.step = rcSlice.row.step || 1;
          ml = jStat2.arange(rcSlice.row.start, Math2.min(A[0].length, rcSlice.row.end), rcSlice.row.step);
          var n = rcSlice.col;
          ml.forEach(function(m2, j) {
            A[m2][n] = B[j];
          });
          return A;
        }
        if (B[0].length === undefined2) {
          B = [B];
        }
        rcSlice.row.start = rcSlice.row.start || 0;
        rcSlice.row.end = rcSlice.row.end || A.length;
        rcSlice.row.step = rcSlice.row.step || 1;
        rcSlice.col.start = rcSlice.col.start || 0;
        rcSlice.col.end = rcSlice.col.end || A[0].length;
        rcSlice.col.step = rcSlice.col.step || 1;
        ml = jStat2.arange(rcSlice.row.start, Math2.min(A.length, rcSlice.row.end), rcSlice.row.step);
        nl = jStat2.arange(rcSlice.col.start, Math2.min(A[0].length, rcSlice.col.end), rcSlice.col.step);
        ml.forEach(function(m2, i) {
          nl.forEach(function(n2, j) {
            A[m2][n2] = B[i][j];
          });
        });
        return A;
      };
      jStat2.diagonal = function diagonal(diagArray) {
        var mat = jStat2.zeros(diagArray.length, diagArray.length);
        diagArray.forEach(function(t, i) {
          mat[i][i] = t;
        });
        return mat;
      };
      jStat2.copy = function copy(A) {
        return A.map(function(row2) {
          if (isNumber2(row2))
            return row2;
          return row2.map(function(t) {
            return t;
          });
        });
      };
      var jProto = jStat2.prototype;
      jProto.length = 0;
      jProto.push = Array.prototype.push;
      jProto.sort = Array.prototype.sort;
      jProto.splice = Array.prototype.splice;
      jProto.slice = Array.prototype.slice;
      jProto.toArray = function toArray() {
        return this.length > 1 ? slice3.call(this) : slice3.call(this)[0];
      };
      jProto.map = function map(func, toAlter) {
        return jStat2(jStat2.map(this, func, toAlter));
      };
      jProto.cumreduce = function cumreduce(func, toAlter) {
        return jStat2(jStat2.cumreduce(this, func, toAlter));
      };
      jProto.alter = function alter(func) {
        jStat2.alter(this, func);
        return this;
      };
      (function(funcs) {
        for (var i = 0;i < funcs.length; i++)
          (function(passfunc) {
            jProto[passfunc] = function(func) {
              var self2 = this, results;
              if (func) {
                setTimeout(function() {
                  func.call(self2, jProto[passfunc].call(self2));
                });
                return this;
              }
              results = jStat2[passfunc](this);
              return isArray2(results) ? jStat2(results) : results;
            };
          })(funcs[i]);
      })("transpose clear symmetric rows cols dimensions diag antidiag".split(" "));
      (function(funcs) {
        for (var i = 0;i < funcs.length; i++)
          (function(passfunc) {
            jProto[passfunc] = function(index, func) {
              var self2 = this;
              if (func) {
                setTimeout(function() {
                  func.call(self2, jProto[passfunc].call(self2, index));
                });
                return this;
              }
              return jStat2(jStat2[passfunc](this, index));
            };
          })(funcs[i]);
      })("row col".split(" "));
      (function(funcs) {
        for (var i = 0;i < funcs.length; i++)
          (function(passfunc) {
            jProto[passfunc] = function() {
              return jStat2(jStat2[passfunc].apply(null, arguments));
            };
          })(funcs[i]);
      })("create zeros ones rand identity".split(" "));
      return jStat2;
    }(Math);
    (function(jStat2, Math2) {
      var isFunction = jStat2.utils.isFunction;
      function ascNum(a, b) {
        return a - b;
      }
      function clip(arg, min3, max4) {
        return Math2.max(min3, Math2.min(arg, max4));
      }
      jStat2.sum = function sum(arr) {
        var sum2 = 0;
        var i = arr.length;
        while (--i >= 0)
          sum2 += arr[i];
        return sum2;
      };
      jStat2.sumsqrd = function sumsqrd(arr) {
        var sum2 = 0;
        var i = arr.length;
        while (--i >= 0)
          sum2 += arr[i] * arr[i];
        return sum2;
      };
      jStat2.sumsqerr = function sumsqerr(arr) {
        var mean3 = jStat2.mean(arr);
        var sum2 = 0;
        var i = arr.length;
        var tmp;
        while (--i >= 0) {
          tmp = arr[i] - mean3;
          sum2 += tmp * tmp;
        }
        return sum2;
      };
      jStat2.sumrow = function sumrow(arr) {
        var sum2 = 0;
        var i = arr.length;
        while (--i >= 0)
          sum2 += arr[i];
        return sum2;
      };
      jStat2.product = function product(arr) {
        var prod = 1;
        var i = arr.length;
        while (--i >= 0)
          prod *= arr[i];
        return prod;
      };
      jStat2.min = function min(arr) {
        var low = arr[0];
        var i = 0;
        while (++i < arr.length)
          if (arr[i] < low)
            low = arr[i];
        return low;
      };
      jStat2.max = function max(arr) {
        var high = arr[0];
        var i = 0;
        while (++i < arr.length)
          if (arr[i] > high)
            high = arr[i];
        return high;
      };
      jStat2.unique = function unique(arr) {
        var hash2 = {}, _arr = [];
        for (var i = 0;i < arr.length; i++) {
          if (!hash2[arr[i]]) {
            hash2[arr[i]] = true;
            _arr.push(arr[i]);
          }
        }
        return _arr;
      };
      jStat2.mean = function mean(arr) {
        return jStat2.sum(arr) / arr.length;
      };
      jStat2.meansqerr = function meansqerr(arr) {
        return jStat2.sumsqerr(arr) / arr.length;
      };
      jStat2.geomean = function geomean(arr) {
        var logs = arr.map(Math2.log);
        var meanOfLogs = jStat2.mean(logs);
        return Math2.exp(meanOfLogs);
      };
      jStat2.median = function median(arr) {
        var arrlen = arr.length;
        var _arr = arr.slice().sort(ascNum);
        return !(arrlen & 1) ? (_arr[arrlen / 2 - 1] + _arr[arrlen / 2]) / 2 : _arr[arrlen / 2 | 0];
      };
      jStat2.cumsum = function cumsum(arr) {
        return jStat2.cumreduce(arr, function(a, b) {
          return a + b;
        });
      };
      jStat2.cumprod = function cumprod(arr) {
        return jStat2.cumreduce(arr, function(a, b) {
          return a * b;
        });
      };
      jStat2.diff = function diff(arr) {
        var diffs = [];
        var arrLen = arr.length;
        var i;
        for (i = 1;i < arrLen; i++)
          diffs.push(arr[i] - arr[i - 1]);
        return diffs;
      };
      jStat2.rank = function(arr) {
        var i;
        var distinctNumbers = [];
        var numberCounts = {};
        for (i = 0;i < arr.length; i++) {
          var number6 = arr[i];
          if (numberCounts[number6]) {
            numberCounts[number6]++;
          } else {
            numberCounts[number6] = 1;
            distinctNumbers.push(number6);
          }
        }
        var sortedDistinctNumbers = distinctNumbers.sort(ascNum);
        var numberRanks = {};
        var currentRank = 1;
        for (i = 0;i < sortedDistinctNumbers.length; i++) {
          var number6 = sortedDistinctNumbers[i];
          var count3 = numberCounts[number6];
          var first = currentRank;
          var last2 = currentRank + count3 - 1;
          var rank = (first + last2) / 2;
          numberRanks[number6] = rank;
          currentRank += count3;
        }
        return arr.map(function(number7) {
          return numberRanks[number7];
        });
      };
      jStat2.mode = function mode(arr) {
        var arrLen = arr.length;
        var _arr = arr.slice().sort(ascNum);
        var count3 = 1;
        var maxCount = 0;
        var numMaxCount = 0;
        var mode_arr = [];
        var i;
        for (i = 0;i < arrLen; i++) {
          if (_arr[i] === _arr[i + 1]) {
            count3++;
          } else {
            if (count3 > maxCount) {
              mode_arr = [_arr[i]];
              maxCount = count3;
              numMaxCount = 0;
            } else if (count3 === maxCount) {
              mode_arr.push(_arr[i]);
              numMaxCount++;
            }
            count3 = 1;
          }
        }
        return numMaxCount === 0 ? mode_arr[0] : mode_arr;
      };
      jStat2.range = function range(arr) {
        return jStat2.max(arr) - jStat2.min(arr);
      };
      jStat2.variance = function variance(arr, flag) {
        return jStat2.sumsqerr(arr) / (arr.length - (flag ? 1 : 0));
      };
      jStat2.pooledvariance = function pooledvariance(arr) {
        var sumsqerr = arr.reduce(function(a, samples) {
          return a + jStat2.sumsqerr(samples);
        }, 0);
        var count3 = arr.reduce(function(a, samples) {
          return a + samples.length;
        }, 0);
        return sumsqerr / (count3 - arr.length);
      };
      jStat2.deviation = function(arr) {
        var mean3 = jStat2.mean(arr);
        var arrlen = arr.length;
        var dev = new Array(arrlen);
        for (var i = 0;i < arrlen; i++) {
          dev[i] = arr[i] - mean3;
        }
        return dev;
      };
      jStat2.stdev = function stdev(arr, flag) {
        return Math2.sqrt(jStat2.variance(arr, flag));
      };
      jStat2.pooledstdev = function pooledstdev(arr) {
        return Math2.sqrt(jStat2.pooledvariance(arr));
      };
      jStat2.meandev = function meandev(arr) {
        var mean3 = jStat2.mean(arr);
        var a = [];
        for (var i = arr.length - 1;i >= 0; i--) {
          a.push(Math2.abs(arr[i] - mean3));
        }
        return jStat2.mean(a);
      };
      jStat2.meddev = function meddev(arr) {
        var median = jStat2.median(arr);
        var a = [];
        for (var i = arr.length - 1;i >= 0; i--) {
          a.push(Math2.abs(arr[i] - median));
        }
        return jStat2.median(a);
      };
      jStat2.coeffvar = function coeffvar(arr) {
        return jStat2.stdev(arr) / jStat2.mean(arr);
      };
      jStat2.quartiles = function quartiles(arr) {
        var arrlen = arr.length;
        var _arr = arr.slice().sort(ascNum);
        return [
          _arr[Math2.round(arrlen / 4) - 1],
          _arr[Math2.round(arrlen / 2) - 1],
          _arr[Math2.round(arrlen * 3 / 4) - 1]
        ];
      };
      jStat2.quantiles = function quantiles(arr, quantilesArray, alphap, betap) {
        var sortedArray = arr.slice().sort(ascNum);
        var quantileVals = [quantilesArray.length];
        var n = arr.length;
        var i, p, m, aleph, k, gamma2;
        if (typeof alphap === "undefined")
          alphap = 3 / 8;
        if (typeof betap === "undefined")
          betap = 3 / 8;
        for (i = 0;i < quantilesArray.length; i++) {
          p = quantilesArray[i];
          m = alphap + p * (1 - alphap - betap);
          aleph = n * p + m;
          k = Math2.floor(clip(aleph, 1, n - 1));
          gamma2 = clip(aleph - k, 0, 1);
          quantileVals[i] = (1 - gamma2) * sortedArray[k - 1] + gamma2 * sortedArray[k];
        }
        return quantileVals;
      };
      jStat2.percentile = function percentile(arr, k, exclusive) {
        var _arr = arr.slice().sort(ascNum);
        var realIndex = k * (_arr.length + (exclusive ? 1 : -1)) + (exclusive ? 0 : 1);
        var index = parseInt(realIndex);
        var frac = realIndex - index;
        if (index + 1 < _arr.length) {
          return _arr[index - 1] + frac * (_arr[index] - _arr[index - 1]);
        } else {
          return _arr[index - 1];
        }
      };
      jStat2.percentileOfScore = function percentileOfScore(arr, score, kind) {
        var counter = 0;
        var len = arr.length;
        var strict = false;
        var value, i;
        if (kind === "strict")
          strict = true;
        for (i = 0;i < len; i++) {
          value = arr[i];
          if (strict && value < score || !strict && value <= score) {
            counter++;
          }
        }
        return counter / len;
      };
      jStat2.histogram = function histogram(arr, binCnt) {
        binCnt = binCnt || 4;
        var first = jStat2.min(arr);
        var binWidth = (jStat2.max(arr) - first) / binCnt;
        var len = arr.length;
        var bins = [];
        var i;
        for (i = 0;i < binCnt; i++)
          bins[i] = 0;
        for (i = 0;i < len; i++)
          bins[Math2.min(Math2.floor((arr[i] - first) / binWidth), binCnt - 1)] += 1;
        return bins;
      };
      jStat2.covariance = function covariance(arr1, arr2) {
        var u = jStat2.mean(arr1);
        var v = jStat2.mean(arr2);
        var arr1Len = arr1.length;
        var sq_dev = new Array(arr1Len);
        var i;
        for (i = 0;i < arr1Len; i++)
          sq_dev[i] = (arr1[i] - u) * (arr2[i] - v);
        return jStat2.sum(sq_dev) / (arr1Len - 1);
      };
      jStat2.corrcoeff = function corrcoeff(arr1, arr2) {
        return jStat2.covariance(arr1, arr2) / jStat2.stdev(arr1, 1) / jStat2.stdev(arr2, 1);
      };
      jStat2.spearmancoeff = function(arr1, arr2) {
        arr1 = jStat2.rank(arr1);
        arr2 = jStat2.rank(arr2);
        return jStat2.corrcoeff(arr1, arr2);
      };
      jStat2.stanMoment = function stanMoment(arr, n) {
        var mu = jStat2.mean(arr);
        var sigma = jStat2.stdev(arr);
        var len = arr.length;
        var skewSum = 0;
        for (var i = 0;i < len; i++)
          skewSum += Math2.pow((arr[i] - mu) / sigma, n);
        return skewSum / arr.length;
      };
      jStat2.skewness = function skewness(arr) {
        return jStat2.stanMoment(arr, 3);
      };
      jStat2.kurtosis = function kurtosis(arr) {
        return jStat2.stanMoment(arr, 4) - 3;
      };
      var jProto = jStat2.prototype;
      (function(funcs) {
        for (var i = 0;i < funcs.length; i++)
          (function(passfunc) {
            jProto[passfunc] = function(fullbool, func) {
              var arr = [];
              var i2 = 0;
              var tmpthis = this;
              if (isFunction(fullbool)) {
                func = fullbool;
                fullbool = false;
              }
              if (func) {
                setTimeout(function() {
                  func.call(tmpthis, jProto[passfunc].call(tmpthis, fullbool));
                });
                return this;
              }
              if (this.length > 1) {
                tmpthis = fullbool === true ? this : this.transpose();
                for (;i2 < tmpthis.length; i2++)
                  arr[i2] = jStat2[passfunc](tmpthis[i2]);
                return arr;
              }
              return jStat2[passfunc](this[0], fullbool);
            };
          })(funcs[i]);
      })("cumsum cumprod".split(" "));
      (function(funcs) {
        for (var i = 0;i < funcs.length; i++)
          (function(passfunc) {
            jProto[passfunc] = function(fullbool, func) {
              var arr = [];
              var i2 = 0;
              var tmpthis = this;
              if (isFunction(fullbool)) {
                func = fullbool;
                fullbool = false;
              }
              if (func) {
                setTimeout(function() {
                  func.call(tmpthis, jProto[passfunc].call(tmpthis, fullbool));
                });
                return this;
              }
              if (this.length > 1) {
                if (passfunc !== "sumrow")
                  tmpthis = fullbool === true ? this : this.transpose();
                for (;i2 < tmpthis.length; i2++)
                  arr[i2] = jStat2[passfunc](tmpthis[i2]);
                return fullbool === true ? jStat2[passfunc](jStat2.utils.toVector(arr)) : arr;
              }
              return jStat2[passfunc](this[0], fullbool);
            };
          })(funcs[i]);
      })(("sum sumsqrd sumsqerr sumrow product min max unique mean meansqerr " + "geomean median diff rank mode range variance deviation stdev meandev " + "meddev coeffvar quartiles histogram skewness kurtosis").split(" "));
      (function(funcs) {
        for (var i = 0;i < funcs.length; i++)
          (function(passfunc) {
            jProto[passfunc] = function() {
              var arr = [];
              var i2 = 0;
              var tmpthis = this;
              var args2 = Array.prototype.slice.call(arguments);
              var callbackFunction;
              if (isFunction(args2[args2.length - 1])) {
                callbackFunction = args2[args2.length - 1];
                var argsToPass = args2.slice(0, args2.length - 1);
                setTimeout(function() {
                  callbackFunction.call(tmpthis, jProto[passfunc].apply(tmpthis, argsToPass));
                });
                return this;
              } else {
                callbackFunction = undefined;
                var curriedFunction = function curriedFunction(vector) {
                  return jStat2[passfunc].apply(tmpthis, [vector].concat(args2));
                };
              }
              if (this.length > 1) {
                tmpthis = tmpthis.transpose();
                for (;i2 < tmpthis.length; i2++)
                  arr[i2] = curriedFunction(tmpthis[i2]);
                return arr;
              }
              return curriedFunction(this[0]);
            };
          })(funcs[i]);
      })("quantiles percentileOfScore".split(" "));
    })(jStat, Math);
    (function(jStat2, Math2) {
      jStat2.gammaln = function gammaln(x2) {
        var j = 0;
        var cof = [
          76.18009172947146,
          -86.50532032941678,
          24.01409824083091,
          -1.231739572450155,
          0.001208650973866179,
          -0.000005395239384953
        ];
        var ser = 1.000000000190015;
        var xx, y2, tmp;
        tmp = (y2 = xx = x2) + 5.5;
        tmp -= (xx + 0.5) * Math2.log(tmp);
        for (;j < 6; j++)
          ser += cof[j] / ++y2;
        return Math2.log(2.5066282746310007 * ser / xx) - tmp;
      };
      jStat2.loggam = function loggam(x2) {
        var x0, x22, xp, gl, gl0;
        var k, n;
        var a = [
          0.08333333333333333,
          -0.002777777777777778,
          0.0007936507936507937,
          -0.0005952380952380952,
          0.0008417508417508418,
          -0.001917526917526918,
          0.00641025641025641,
          -0.02955065359477124,
          0.1796443723688307,
          -1.3924322169059
        ];
        x0 = x2;
        n = 0;
        if (x2 == 1 || x2 == 2) {
          return 0;
        }
        if (x2 <= 7) {
          n = Math2.floor(7 - x2);
          x0 = x2 + n;
        }
        x22 = 1 / (x0 * x0);
        xp = 2 * Math2.PI;
        gl0 = a[9];
        for (k = 8;k >= 0; k--) {
          gl0 *= x22;
          gl0 += a[k];
        }
        gl = gl0 / x0 + 0.5 * Math2.log(xp) + (x0 - 0.5) * Math2.log(x0) - x0;
        if (x2 <= 7) {
          for (k = 1;k <= n; k++) {
            gl -= Math2.log(x0 - 1);
            x0 -= 1;
          }
        }
        return gl;
      };
      jStat2.gammafn = function gammafn(x2) {
        var p = [
          -1.716185138865495,
          24.76565080557592,
          -379.80425647094563,
          629.3311553128184,
          866.9662027904133,
          -31451.272968848367,
          -36144.413418691176,
          66456.14382024054
        ];
        var q = [
          -30.8402300119739,
          315.35062697960416,
          -1015.1563674902192,
          -3107.771671572311,
          22538.11842098015,
          4755.846277527881,
          -134659.9598649693,
          -115132.2596755535
        ];
        var fact = false;
        var n = 0;
        var xden = 0;
        var xnum = 0;
        var y2 = x2;
        var i, z2, yi, res;
        if (x2 > 171.6243769536076) {
          return Infinity;
        }
        if (y2 <= 0) {
          res = y2 % 1 + 0.00000000000000036;
          if (res) {
            fact = (!(y2 & 1) ? 1 : -1) * Math2.PI / Math2.sin(Math2.PI * res);
            y2 = 1 - y2;
          } else {
            return Infinity;
          }
        }
        yi = y2;
        if (y2 < 1) {
          z2 = y2++;
        } else {
          z2 = (y2 -= n = (y2 | 0) - 1) - 1;
        }
        for (i = 0;i < 8; ++i) {
          xnum = (xnum + p[i]) * z2;
          xden = xden * z2 + q[i];
        }
        res = xnum / xden + 1;
        if (yi < y2) {
          res /= yi;
        } else if (yi > y2) {
          for (i = 0;i < n; ++i) {
            res *= y2;
            y2++;
          }
        }
        if (fact) {
          res = fact / res;
        }
        return res;
      };
      jStat2.gammap = function gammap(a, x2) {
        return jStat2.lowRegGamma(a, x2) * jStat2.gammafn(a);
      };
      jStat2.lowRegGamma = function lowRegGamma(a, x2) {
        var aln = jStat2.gammaln(a);
        var ap = a;
        var sum2 = 1 / a;
        var del = sum2;
        var b = x2 + 1 - a;
        var c = 1 / 0.000000000000000000000000000001;
        var d = 1 / b;
        var h = d;
        var i = 1;
        var ITMAX = -~(Math2.log(a >= 1 ? a : 1 / a) * 8.5 + a * 0.4 + 17);
        var an;
        if (x2 < 0 || a <= 0) {
          return NaN;
        } else if (x2 < a + 1) {
          for (;i <= ITMAX; i++) {
            sum2 += del *= x2 / ++ap;
          }
          return sum2 * Math2.exp(-x2 + a * Math2.log(x2) - aln);
        }
        for (;i <= ITMAX; i++) {
          an = -i * (i - a);
          b += 2;
          d = an * d + b;
          c = b + an / c;
          d = 1 / d;
          h *= d * c;
        }
        return 1 - h * Math2.exp(-x2 + a * Math2.log(x2) - aln);
      };
      jStat2.factorialln = function factorialln(n) {
        return n < 0 ? NaN : jStat2.gammaln(n + 1);
      };
      jStat2.factorial = function factorial(n) {
        return n < 0 ? NaN : jStat2.gammafn(n + 1);
      };
      jStat2.combination = function combination(n, m) {
        return n > 170 || m > 170 ? Math2.exp(jStat2.combinationln(n, m)) : jStat2.factorial(n) / jStat2.factorial(m) / jStat2.factorial(n - m);
      };
      jStat2.combinationln = function combinationln(n, m) {
        return jStat2.factorialln(n) - jStat2.factorialln(m) - jStat2.factorialln(n - m);
      };
      jStat2.permutation = function permutation(n, m) {
        return jStat2.factorial(n) / jStat2.factorial(n - m);
      };
      jStat2.betafn = function betafn(x2, y2) {
        if (x2 <= 0 || y2 <= 0)
          return;
        return x2 + y2 > 170 ? Math2.exp(jStat2.betaln(x2, y2)) : jStat2.gammafn(x2) * jStat2.gammafn(y2) / jStat2.gammafn(x2 + y2);
      };
      jStat2.betaln = function betaln(x2, y2) {
        return jStat2.gammaln(x2) + jStat2.gammaln(y2) - jStat2.gammaln(x2 + y2);
      };
      jStat2.betacf = function betacf(x2, a, b) {
        var fpmin = 0.000000000000000000000000000001;
        var m = 1;
        var qab = a + b;
        var qap = a + 1;
        var qam = a - 1;
        var c = 1;
        var d = 1 - qab * x2 / qap;
        var m2, aa, del, h;
        if (Math2.abs(d) < fpmin)
          d = fpmin;
        d = 1 / d;
        h = d;
        for (;m <= 100; m++) {
          m2 = 2 * m;
          aa = m * (b - m) * x2 / ((qam + m2) * (a + m2));
          d = 1 + aa * d;
          if (Math2.abs(d) < fpmin)
            d = fpmin;
          c = 1 + aa / c;
          if (Math2.abs(c) < fpmin)
            c = fpmin;
          d = 1 / d;
          h *= d * c;
          aa = -(a + m) * (qab + m) * x2 / ((a + m2) * (qap + m2));
          d = 1 + aa * d;
          if (Math2.abs(d) < fpmin)
            d = fpmin;
          c = 1 + aa / c;
          if (Math2.abs(c) < fpmin)
            c = fpmin;
          d = 1 / d;
          del = d * c;
          h *= del;
          if (Math2.abs(del - 1) < 0.0000003)
            break;
        }
        return h;
      };
      jStat2.gammapinv = function gammapinv(p, a) {
        var j = 0;
        var a1 = a - 1;
        var EPS = 0.00000001;
        var gln = jStat2.gammaln(a);
        var x2, err, t, u, pp, lna1, afac;
        if (p >= 1)
          return Math2.max(100, a + 100 * Math2.sqrt(a));
        if (p <= 0)
          return 0;
        if (a > 1) {
          lna1 = Math2.log(a1);
          afac = Math2.exp(a1 * (lna1 - 1) - gln);
          pp = p < 0.5 ? p : 1 - p;
          t = Math2.sqrt(-2 * Math2.log(pp));
          x2 = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t;
          if (p < 0.5)
            x2 = -x2;
          x2 = Math2.max(0.001, a * Math2.pow(1 - 1 / (9 * a) - x2 / (3 * Math2.sqrt(a)), 3));
        } else {
          t = 1 - a * (0.253 + a * 0.12);
          if (p < t)
            x2 = Math2.pow(p / t, 1 / a);
          else
            x2 = 1 - Math2.log(1 - (p - t) / (1 - t));
        }
        for (;j < 12; j++) {
          if (x2 <= 0)
            return 0;
          err = jStat2.lowRegGamma(a, x2) - p;
          if (a > 1)
            t = afac * Math2.exp(-(x2 - a1) + a1 * (Math2.log(x2) - lna1));
          else
            t = Math2.exp(-x2 + a1 * Math2.log(x2) - gln);
          u = err / t;
          x2 -= t = u / (1 - 0.5 * Math2.min(1, u * ((a - 1) / x2 - 1)));
          if (x2 <= 0)
            x2 = 0.5 * (x2 + t);
          if (Math2.abs(t) < EPS * x2)
            break;
        }
        return x2;
      };
      jStat2.erf = function erf(x2) {
        var cof = [
          -1.3026537197817094,
          0.6419697923564902,
          0.019476473204185836,
          -0.00956151478680863,
          -0.000946595344482036,
          0.000366839497852761,
          0.000042523324806907,
          -0.000020278578112534,
          -0.000001624290004647,
          0.00000130365583558,
          0.000000015626441722,
          -0.000000085238095915,
          0.000000006529054439,
          0.000000005059343495,
          -0.000000000991364156,
          -0.000000000227365122,
          0.000000000096467911,
          0.000000000002394038,
          -0.000000000006886027,
          0.000000000000894487,
          0.000000000000313092,
          -0.000000000000112708,
          0.000000000000000381,
          0.000000000000007106,
          -0.000000000000001523,
          -0.000000000000000094,
          0.000000000000000121,
          -0.000000000000000028
        ];
        var j = cof.length - 1;
        var isneg = false;
        var d = 0;
        var dd = 0;
        var t, ty, tmp, res;
        if (x2 < 0) {
          x2 = -x2;
          isneg = true;
        }
        t = 2 / (2 + x2);
        ty = 4 * t - 2;
        for (;j > 0; j--) {
          tmp = d;
          d = ty * d - dd + cof[j];
          dd = tmp;
        }
        res = t * Math2.exp(-x2 * x2 + 0.5 * (cof[0] + ty * d) - dd);
        return isneg ? res - 1 : 1 - res;
      };
      jStat2.erfc = function erfc(x2) {
        return 1 - jStat2.erf(x2);
      };
      jStat2.erfcinv = function erfcinv(p) {
        var j = 0;
        var x2, err, t, pp;
        if (p >= 2)
          return -100;
        if (p <= 0)
          return 100;
        pp = p < 1 ? p : 2 - p;
        t = Math2.sqrt(-2 * Math2.log(pp / 2));
        x2 = -0.70711 * ((2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t);
        for (;j < 2; j++) {
          err = jStat2.erfc(x2) - pp;
          x2 += err / (1.1283791670955126 * Math2.exp(-x2 * x2) - x2 * err);
        }
        return p < 1 ? x2 : -x2;
      };
      jStat2.ibetainv = function ibetainv(p, a, b) {
        var EPS = 0.00000001;
        var a1 = a - 1;
        var b1 = b - 1;
        var j = 0;
        var lna, lnb, pp, t, u, err, x2, al, h, w, afac;
        if (p <= 0)
          return 0;
        if (p >= 1)
          return 1;
        if (a >= 1 && b >= 1) {
          pp = p < 0.5 ? p : 1 - p;
          t = Math2.sqrt(-2 * Math2.log(pp));
          x2 = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t;
          if (p < 0.5)
            x2 = -x2;
          al = (x2 * x2 - 3) / 6;
          h = 2 / (1 / (2 * a - 1) + 1 / (2 * b - 1));
          w = x2 * Math2.sqrt(al + h) / h - (1 / (2 * b - 1) - 1 / (2 * a - 1)) * (al + 5 / 6 - 2 / (3 * h));
          x2 = a / (a + b * Math2.exp(2 * w));
        } else {
          lna = Math2.log(a / (a + b));
          lnb = Math2.log(b / (a + b));
          t = Math2.exp(a * lna) / a;
          u = Math2.exp(b * lnb) / b;
          w = t + u;
          if (p < t / w)
            x2 = Math2.pow(a * w * p, 1 / a);
          else
            x2 = 1 - Math2.pow(b * w * (1 - p), 1 / b);
        }
        afac = -jStat2.gammaln(a) - jStat2.gammaln(b) + jStat2.gammaln(a + b);
        for (;j < 10; j++) {
          if (x2 === 0 || x2 === 1)
            return x2;
          err = jStat2.ibeta(x2, a, b) - p;
          t = Math2.exp(a1 * Math2.log(x2) + b1 * Math2.log(1 - x2) + afac);
          u = err / t;
          x2 -= t = u / (1 - 0.5 * Math2.min(1, u * (a1 / x2 - b1 / (1 - x2))));
          if (x2 <= 0)
            x2 = 0.5 * (x2 + t);
          if (x2 >= 1)
            x2 = 0.5 * (x2 + t + 1);
          if (Math2.abs(t) < EPS * x2 && j > 0)
            break;
        }
        return x2;
      };
      jStat2.ibeta = function ibeta(x2, a, b) {
        var bt = x2 === 0 || x2 === 1 ? 0 : Math2.exp(jStat2.gammaln(a + b) - jStat2.gammaln(a) - jStat2.gammaln(b) + a * Math2.log(x2) + b * Math2.log(1 - x2));
        if (x2 < 0 || x2 > 1)
          return false;
        if (x2 < (a + 1) / (a + b + 2))
          return bt * jStat2.betacf(x2, a, b) / a;
        return 1 - bt * jStat2.betacf(1 - x2, b, a) / b;
      };
      jStat2.randn = function randn(n, m) {
        var u, v, x2, y2, q;
        if (!m)
          m = n;
        if (n)
          return jStat2.create(n, m, function() {
            return jStat2.randn();
          });
        do {
          u = jStat2._random_fn();
          v = 1.7156 * (jStat2._random_fn() - 0.5);
          x2 = u - 0.449871;
          y2 = Math2.abs(v) + 0.386595;
          q = x2 * x2 + y2 * (0.196 * y2 - 0.25472 * x2);
        } while (q > 0.27597 && (q > 0.27846 || v * v > -4 * Math2.log(u) * u * u));
        return v / u;
      };
      jStat2.randg = function randg(shape2, n, m) {
        var oalph = shape2;
        var a1, a2, u, v, x2, mat;
        if (!m)
          m = n;
        if (!shape2)
          shape2 = 1;
        if (n) {
          mat = jStat2.zeros(n, m);
          mat.alter(function() {
            return jStat2.randg(shape2);
          });
          return mat;
        }
        if (shape2 < 1)
          shape2 += 1;
        a1 = shape2 - 1 / 3;
        a2 = 1 / Math2.sqrt(9 * a1);
        do {
          do {
            x2 = jStat2.randn();
            v = 1 + a2 * x2;
          } while (v <= 0);
          v = v * v * v;
          u = jStat2._random_fn();
        } while (u > 1 - 0.331 * Math2.pow(x2, 4) && Math2.log(u) > 0.5 * x2 * x2 + a1 * (1 - v + Math2.log(v)));
        if (shape2 == oalph)
          return a1 * v;
        do {
          u = jStat2._random_fn();
        } while (u === 0);
        return Math2.pow(u, 1 / oalph) * a1 * v;
      };
      (function(funcs) {
        for (var i = 0;i < funcs.length; i++)
          (function(passfunc) {
            jStat2.fn[passfunc] = function() {
              return jStat2(jStat2.map(this, function(value) {
                return jStat2[passfunc](value);
              }));
            };
          })(funcs[i]);
      })("gammaln gammafn factorial factorialln".split(" "));
      (function(funcs) {
        for (var i = 0;i < funcs.length; i++)
          (function(passfunc) {
            jStat2.fn[passfunc] = function() {
              return jStat2(jStat2[passfunc].apply(null, arguments));
            };
          })(funcs[i]);
      })("randn".split(" "));
    })(jStat, Math);
    (function(jStat2, Math2) {
      (function(list) {
        for (var i = 0;i < list.length; i++)
          (function(func) {
            jStat2[func] = function f(a, b, c) {
              if (!(this instanceof f))
                return new f(a, b, c);
              this._a = a;
              this._b = b;
              this._c = c;
              return this;
            };
            jStat2.fn[func] = function(a, b, c) {
              var newthis = jStat2[func](a, b, c);
              newthis.data = this;
              return newthis;
            };
            jStat2[func].prototype.sample = function(arr) {
              var a = this._a;
              var b = this._b;
              var c = this._c;
              if (arr)
                return jStat2.alter(arr, function() {
                  return jStat2[func].sample(a, b, c);
                });
              else
                return jStat2[func].sample(a, b, c);
            };
            (function(vals) {
              for (var i2 = 0;i2 < vals.length; i2++)
                (function(fnfunc) {
                  jStat2[func].prototype[fnfunc] = function(x2) {
                    var a = this._a;
                    var b = this._b;
                    var c = this._c;
                    if (!x2 && x2 !== 0)
                      x2 = this.data;
                    if (typeof x2 !== "number") {
                      return jStat2.fn.map.call(x2, function(x3) {
                        return jStat2[func][fnfunc](x3, a, b, c);
                      });
                    }
                    return jStat2[func][fnfunc](x2, a, b, c);
                  };
                })(vals[i2]);
            })("pdf cdf inv".split(" "));
            (function(vals) {
              for (var i2 = 0;i2 < vals.length; i2++)
                (function(fnfunc) {
                  jStat2[func].prototype[fnfunc] = function() {
                    return jStat2[func][fnfunc](this._a, this._b, this._c);
                  };
                })(vals[i2]);
            })("mean median mode variance".split(" "));
          })(list[i]);
      })(("beta centralF cauchy chisquare exponential gamma invgamma kumaraswamy " + "laplace lognormal noncentralt normal pareto studentt weibull uniform " + "binomial negbin hypgeom poisson triangular tukey arcsine").split(" "));
      jStat2.extend(jStat2.beta, {
        pdf: function pdf(x2, alpha, beta) {
          if (x2 > 1 || x2 < 0)
            return 0;
          if (alpha == 1 && beta == 1)
            return 1;
          if (alpha < 512 && beta < 512) {
            return Math2.pow(x2, alpha - 1) * Math2.pow(1 - x2, beta - 1) / jStat2.betafn(alpha, beta);
          } else {
            return Math2.exp((alpha - 1) * Math2.log(x2) + (beta - 1) * Math2.log(1 - x2) - jStat2.betaln(alpha, beta));
          }
        },
        cdf: function cdf(x2, alpha, beta) {
          return x2 > 1 || x2 < 0 ? (x2 > 1) * 1 : jStat2.ibeta(x2, alpha, beta);
        },
        inv: function inv(x2, alpha, beta) {
          return jStat2.ibetainv(x2, alpha, beta);
        },
        mean: function mean(alpha, beta) {
          return alpha / (alpha + beta);
        },
        median: function median(alpha, beta) {
          return jStat2.ibetainv(0.5, alpha, beta);
        },
        mode: function mode(alpha, beta) {
          return (alpha - 1) / (alpha + beta - 2);
        },
        sample: function sample(alpha, beta) {
          var u = jStat2.randg(alpha);
          return u / (u + jStat2.randg(beta));
        },
        variance: function variance(alpha, beta) {
          return alpha * beta / (Math2.pow(alpha + beta, 2) * (alpha + beta + 1));
        }
      });
      jStat2.extend(jStat2.centralF, {
        pdf: function pdf(x2, df1, df2) {
          var p, q, f;
          if (x2 < 0)
            return 0;
          if (df1 <= 2) {
            if (x2 === 0 && df1 < 2) {
              return Infinity;
            }
            if (x2 === 0 && df1 === 2) {
              return 1;
            }
            return 1 / jStat2.betafn(df1 / 2, df2 / 2) * Math2.pow(df1 / df2, df1 / 2) * Math2.pow(x2, df1 / 2 - 1) * Math2.pow(1 + df1 / df2 * x2, -(df1 + df2) / 2);
          }
          p = df1 * x2 / (df2 + x2 * df1);
          q = df2 / (df2 + x2 * df1);
          f = df1 * q / 2;
          return f * jStat2.binomial.pdf((df1 - 2) / 2, (df1 + df2 - 2) / 2, p);
        },
        cdf: function cdf(x2, df1, df2) {
          if (x2 < 0)
            return 0;
          return jStat2.ibeta(df1 * x2 / (df1 * x2 + df2), df1 / 2, df2 / 2);
        },
        inv: function inv(x2, df1, df2) {
          return df2 / (df1 * (1 / jStat2.ibetainv(x2, df1 / 2, df2 / 2) - 1));
        },
        mean: function mean(df1, df2) {
          return df2 > 2 ? df2 / (df2 - 2) : undefined;
        },
        mode: function mode(df1, df2) {
          return df1 > 2 ? df2 * (df1 - 2) / (df1 * (df2 + 2)) : undefined;
        },
        sample: function sample(df1, df2) {
          var x1 = jStat2.randg(df1 / 2) * 2;
          var x2 = jStat2.randg(df2 / 2) * 2;
          return x1 / df1 / (x2 / df2);
        },
        variance: function variance(df1, df2) {
          if (df2 <= 4)
            return;
          return 2 * df2 * df2 * (df1 + df2 - 2) / (df1 * (df2 - 2) * (df2 - 2) * (df2 - 4));
        }
      });
      jStat2.extend(jStat2.cauchy, {
        pdf: function pdf(x2, local, scale) {
          if (scale < 0) {
            return 0;
          }
          return scale / (Math2.pow(x2 - local, 2) + Math2.pow(scale, 2)) / Math2.PI;
        },
        cdf: function cdf(x2, local, scale) {
          return Math2.atan((x2 - local) / scale) / Math2.PI + 0.5;
        },
        inv: function(p, local, scale) {
          return local + scale * Math2.tan(Math2.PI * (p - 0.5));
        },
        median: function median(local) {
          return local;
        },
        mode: function mode(local) {
          return local;
        },
        sample: function sample(local, scale) {
          return jStat2.randn() * Math2.sqrt(1 / (2 * jStat2.randg(0.5))) * scale + local;
        }
      });
      jStat2.extend(jStat2.chisquare, {
        pdf: function pdf(x2, dof) {
          if (x2 < 0)
            return 0;
          return x2 === 0 && dof === 2 ? 0.5 : Math2.exp((dof / 2 - 1) * Math2.log(x2) - x2 / 2 - dof / 2 * Math2.log(2) - jStat2.gammaln(dof / 2));
        },
        cdf: function cdf(x2, dof) {
          if (x2 < 0)
            return 0;
          return jStat2.lowRegGamma(dof / 2, x2 / 2);
        },
        inv: function(p, dof) {
          return 2 * jStat2.gammapinv(p, 0.5 * dof);
        },
        mean: function(dof) {
          return dof;
        },
        median: function median(dof) {
          return dof * Math2.pow(1 - 2 / (9 * dof), 3);
        },
        mode: function mode(dof) {
          return dof - 2 > 0 ? dof - 2 : 0;
        },
        sample: function sample(dof) {
          return jStat2.randg(dof / 2) * 2;
        },
        variance: function variance(dof) {
          return 2 * dof;
        }
      });
      jStat2.extend(jStat2.exponential, {
        pdf: function pdf(x2, rate) {
          return x2 < 0 ? 0 : rate * Math2.exp(-rate * x2);
        },
        cdf: function cdf(x2, rate) {
          return x2 < 0 ? 0 : 1 - Math2.exp(-rate * x2);
        },
        inv: function(p, rate) {
          return -Math2.log(1 - p) / rate;
        },
        mean: function(rate) {
          return 1 / rate;
        },
        median: function(rate) {
          return 1 / rate * Math2.log(2);
        },
        mode: function mode() {
          return 0;
        },
        sample: function sample(rate) {
          return -1 / rate * Math2.log(jStat2._random_fn());
        },
        variance: function(rate) {
          return Math2.pow(rate, -2);
        }
      });
      jStat2.extend(jStat2.gamma, {
        pdf: function pdf(x2, shape2, scale) {
          if (x2 < 0)
            return 0;
          return x2 === 0 && shape2 === 1 ? 1 / scale : Math2.exp((shape2 - 1) * Math2.log(x2) - x2 / scale - jStat2.gammaln(shape2) - shape2 * Math2.log(scale));
        },
        cdf: function cdf(x2, shape2, scale) {
          if (x2 < 0)
            return 0;
          return jStat2.lowRegGamma(shape2, x2 / scale);
        },
        inv: function(p, shape2, scale) {
          return jStat2.gammapinv(p, shape2) * scale;
        },
        mean: function(shape2, scale) {
          return shape2 * scale;
        },
        mode: function mode(shape2, scale) {
          if (shape2 > 1)
            return (shape2 - 1) * scale;
          return;
        },
        sample: function sample(shape2, scale) {
          return jStat2.randg(shape2) * scale;
        },
        variance: function variance(shape2, scale) {
          return shape2 * scale * scale;
        }
      });
      jStat2.extend(jStat2.invgamma, {
        pdf: function pdf(x2, shape2, scale) {
          if (x2 <= 0)
            return 0;
          return Math2.exp(-(shape2 + 1) * Math2.log(x2) - scale / x2 - jStat2.gammaln(shape2) + shape2 * Math2.log(scale));
        },
        cdf: function cdf(x2, shape2, scale) {
          if (x2 <= 0)
            return 0;
          return 1 - jStat2.lowRegGamma(shape2, scale / x2);
        },
        inv: function(p, shape2, scale) {
          return scale / jStat2.gammapinv(1 - p, shape2);
        },
        mean: function(shape2, scale) {
          return shape2 > 1 ? scale / (shape2 - 1) : undefined;
        },
        mode: function mode(shape2, scale) {
          return scale / (shape2 + 1);
        },
        sample: function sample(shape2, scale) {
          return scale / jStat2.randg(shape2);
        },
        variance: function variance(shape2, scale) {
          if (shape2 <= 2)
            return;
          return scale * scale / ((shape2 - 1) * (shape2 - 1) * (shape2 - 2));
        }
      });
      jStat2.extend(jStat2.kumaraswamy, {
        pdf: function pdf(x2, alpha, beta) {
          if (x2 === 0 && alpha === 1)
            return beta;
          else if (x2 === 1 && beta === 1)
            return alpha;
          return Math2.exp(Math2.log(alpha) + Math2.log(beta) + (alpha - 1) * Math2.log(x2) + (beta - 1) * Math2.log(1 - Math2.pow(x2, alpha)));
        },
        cdf: function cdf(x2, alpha, beta) {
          if (x2 < 0)
            return 0;
          else if (x2 > 1)
            return 1;
          return 1 - Math2.pow(1 - Math2.pow(x2, alpha), beta);
        },
        inv: function inv(p, alpha, beta) {
          return Math2.pow(1 - Math2.pow(1 - p, 1 / beta), 1 / alpha);
        },
        mean: function(alpha, beta) {
          return beta * jStat2.gammafn(1 + 1 / alpha) * jStat2.gammafn(beta) / jStat2.gammafn(1 + 1 / alpha + beta);
        },
        median: function median(alpha, beta) {
          return Math2.pow(1 - Math2.pow(2, -1 / beta), 1 / alpha);
        },
        mode: function mode(alpha, beta) {
          if (!(alpha >= 1 && beta >= 1 && (alpha !== 1 && beta !== 1)))
            return;
          return Math2.pow((alpha - 1) / (alpha * beta - 1), 1 / alpha);
        },
        variance: function variance() {
          throw new Error("variance not yet implemented");
        }
      });
      jStat2.extend(jStat2.lognormal, {
        pdf: function pdf(x2, mu, sigma) {
          if (x2 <= 0)
            return 0;
          return Math2.exp(-Math2.log(x2) - 0.5 * Math2.log(2 * Math2.PI) - Math2.log(sigma) - Math2.pow(Math2.log(x2) - mu, 2) / (2 * sigma * sigma));
        },
        cdf: function cdf(x2, mu, sigma) {
          if (x2 < 0)
            return 0;
          return 0.5 + 0.5 * jStat2.erf((Math2.log(x2) - mu) / Math2.sqrt(2 * sigma * sigma));
        },
        inv: function(p, mu, sigma) {
          return Math2.exp(-1.4142135623730951 * sigma * jStat2.erfcinv(2 * p) + mu);
        },
        mean: function mean(mu, sigma) {
          return Math2.exp(mu + sigma * sigma / 2);
        },
        median: function median(mu) {
          return Math2.exp(mu);
        },
        mode: function mode(mu, sigma) {
          return Math2.exp(mu - sigma * sigma);
        },
        sample: function sample(mu, sigma) {
          return Math2.exp(jStat2.randn() * sigma + mu);
        },
        variance: function variance(mu, sigma) {
          return (Math2.exp(sigma * sigma) - 1) * Math2.exp(2 * mu + sigma * sigma);
        }
      });
      jStat2.extend(jStat2.noncentralt, {
        pdf: function pdf(x2, dof, ncp) {
          var tol = 0.00000000000001;
          if (Math2.abs(ncp) < tol)
            return jStat2.studentt.pdf(x2, dof);
          if (Math2.abs(x2) < tol) {
            return Math2.exp(jStat2.gammaln((dof + 1) / 2) - ncp * ncp / 2 - 0.5 * Math2.log(Math2.PI * dof) - jStat2.gammaln(dof / 2));
          }
          return dof / x2 * (jStat2.noncentralt.cdf(x2 * Math2.sqrt(1 + 2 / dof), dof + 2, ncp) - jStat2.noncentralt.cdf(x2, dof, ncp));
        },
        cdf: function cdf(x2, dof, ncp) {
          var tol = 0.00000000000001;
          var min_iterations = 200;
          if (Math2.abs(ncp) < tol)
            return jStat2.studentt.cdf(x2, dof);
          var flip = false;
          if (x2 < 0) {
            flip = true;
            ncp = -ncp;
          }
          var prob = jStat2.normal.cdf(-ncp, 0, 1);
          var value = tol + 1;
          var lastvalue = value;
          var y2 = x2 * x2 / (x2 * x2 + dof);
          var j = 0;
          var p = Math2.exp(-ncp * ncp / 2);
          var q = Math2.exp(-ncp * ncp / 2 - 0.5 * Math2.log(2) - jStat2.gammaln(3 / 2)) * ncp;
          while (j < min_iterations || lastvalue > tol || value > tol) {
            lastvalue = value;
            if (j > 0) {
              p *= ncp * ncp / (2 * j);
              q *= ncp * ncp / (2 * (j + 1 / 2));
            }
            value = p * jStat2.beta.cdf(y2, j + 0.5, dof / 2) + q * jStat2.beta.cdf(y2, j + 1, dof / 2);
            prob += 0.5 * value;
            j++;
          }
          return flip ? 1 - prob : prob;
        }
      });
      jStat2.extend(jStat2.normal, {
        pdf: function pdf(x2, mean3, std) {
          return Math2.exp(-0.5 * Math2.log(2 * Math2.PI) - Math2.log(std) - Math2.pow(x2 - mean3, 2) / (2 * std * std));
        },
        cdf: function cdf(x2, mean3, std) {
          return 0.5 * (1 + jStat2.erf((x2 - mean3) / Math2.sqrt(2 * std * std)));
        },
        inv: function(p, mean3, std) {
          return -1.4142135623730951 * std * jStat2.erfcinv(2 * p) + mean3;
        },
        mean: function(mean3) {
          return mean3;
        },
        median: function median(mean3) {
          return mean3;
        },
        mode: function(mean3) {
          return mean3;
        },
        sample: function sample(mean3, std) {
          return jStat2.randn() * std + mean3;
        },
        variance: function(mean3, std) {
          return std * std;
        }
      });
      jStat2.extend(jStat2.pareto, {
        pdf: function pdf(x2, scale, shape2) {
          if (x2 < scale)
            return 0;
          return shape2 * Math2.pow(scale, shape2) / Math2.pow(x2, shape2 + 1);
        },
        cdf: function cdf(x2, scale, shape2) {
          if (x2 < scale)
            return 0;
          return 1 - Math2.pow(scale / x2, shape2);
        },
        inv: function inv(p, scale, shape2) {
          return scale / Math2.pow(1 - p, 1 / shape2);
        },
        mean: function mean(scale, shape2) {
          if (shape2 <= 1)
            return;
          return shape2 * Math2.pow(scale, shape2) / (shape2 - 1);
        },
        median: function median(scale, shape2) {
          return scale * (shape2 * Math2.SQRT2);
        },
        mode: function mode(scale) {
          return scale;
        },
        variance: function(scale, shape2) {
          if (shape2 <= 2)
            return;
          return scale * scale * shape2 / (Math2.pow(shape2 - 1, 2) * (shape2 - 2));
        }
      });
      jStat2.extend(jStat2.studentt, {
        pdf: function pdf(x2, dof) {
          dof = dof > 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ? 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 : dof;
          return 1 / (Math2.sqrt(dof) * jStat2.betafn(0.5, dof / 2)) * Math2.pow(1 + x2 * x2 / dof, -((dof + 1) / 2));
        },
        cdf: function cdf(x2, dof) {
          var dof2 = dof / 2;
          return jStat2.ibeta((x2 + Math2.sqrt(x2 * x2 + dof)) / (2 * Math2.sqrt(x2 * x2 + dof)), dof2, dof2);
        },
        inv: function(p, dof) {
          var x2 = jStat2.ibetainv(2 * Math2.min(p, 1 - p), 0.5 * dof, 0.5);
          x2 = Math2.sqrt(dof * (1 - x2) / x2);
          return p > 0.5 ? x2 : -x2;
        },
        mean: function mean(dof) {
          return dof > 1 ? 0 : undefined;
        },
        median: function median() {
          return 0;
        },
        mode: function mode() {
          return 0;
        },
        sample: function sample(dof) {
          return jStat2.randn() * Math2.sqrt(dof / (2 * jStat2.randg(dof / 2)));
        },
        variance: function variance(dof) {
          return dof > 2 ? dof / (dof - 2) : dof > 1 ? Infinity : undefined;
        }
      });
      jStat2.extend(jStat2.weibull, {
        pdf: function pdf(x2, scale, shape2) {
          if (x2 < 0 || scale < 0 || shape2 < 0)
            return 0;
          return shape2 / scale * Math2.pow(x2 / scale, shape2 - 1) * Math2.exp(-Math2.pow(x2 / scale, shape2));
        },
        cdf: function cdf(x2, scale, shape2) {
          return x2 < 0 ? 0 : 1 - Math2.exp(-Math2.pow(x2 / scale, shape2));
        },
        inv: function(p, scale, shape2) {
          return scale * Math2.pow(-Math2.log(1 - p), 1 / shape2);
        },
        mean: function(scale, shape2) {
          return scale * jStat2.gammafn(1 + 1 / shape2);
        },
        median: function median(scale, shape2) {
          return scale * Math2.pow(Math2.log(2), 1 / shape2);
        },
        mode: function mode(scale, shape2) {
          if (shape2 <= 1)
            return 0;
          return scale * Math2.pow((shape2 - 1) / shape2, 1 / shape2);
        },
        sample: function sample(scale, shape2) {
          return scale * Math2.pow(-Math2.log(jStat2._random_fn()), 1 / shape2);
        },
        variance: function variance(scale, shape2) {
          return scale * scale * jStat2.gammafn(1 + 2 / shape2) - Math2.pow(jStat2.weibull.mean(scale, shape2), 2);
        }
      });
      jStat2.extend(jStat2.uniform, {
        pdf: function pdf(x2, a, b) {
          return x2 < a || x2 > b ? 0 : 1 / (b - a);
        },
        cdf: function cdf(x2, a, b) {
          if (x2 < a)
            return 0;
          else if (x2 < b)
            return (x2 - a) / (b - a);
          return 1;
        },
        inv: function(p, a, b) {
          return a + p * (b - a);
        },
        mean: function mean(a, b) {
          return 0.5 * (a + b);
        },
        median: function median(a, b) {
          return jStat2.mean(a, b);
        },
        mode: function mode() {
          throw new Error("mode is not yet implemented");
        },
        sample: function sample(a, b) {
          return a / 2 + b / 2 + (b / 2 - a / 2) * (2 * jStat2._random_fn() - 1);
        },
        variance: function variance(a, b) {
          return Math2.pow(b - a, 2) / 12;
        }
      });
      function betinc(x2, a, b, eps) {
        var a0 = 0;
        var b0 = 1;
        var a1 = 1;
        var b1 = 1;
        var m9 = 0;
        var a2 = 0;
        var c9;
        while (Math2.abs((a1 - a2) / a1) > eps) {
          a2 = a1;
          c9 = -(a + m9) * (a + b + m9) * x2 / (a + 2 * m9) / (a + 2 * m9 + 1);
          a0 = a1 + c9 * a0;
          b0 = b1 + c9 * b0;
          m9 = m9 + 1;
          c9 = m9 * (b - m9) * x2 / (a + 2 * m9 - 1) / (a + 2 * m9);
          a1 = a0 + c9 * a1;
          b1 = b0 + c9 * b1;
          a0 = a0 / b1;
          b0 = b0 / b1;
          a1 = a1 / b1;
          b1 = 1;
        }
        return a1 / a;
      }
      jStat2.extend(jStat2.binomial, {
        pdf: function pdf(k, n, p) {
          return p === 0 || p === 1 ? n * p === k ? 1 : 0 : jStat2.combination(n, k) * Math2.pow(p, k) * Math2.pow(1 - p, n - k);
        },
        cdf: function cdf(x2, n, p) {
          var betacdf;
          var eps = 0.0000000001;
          if (x2 < 0)
            return 0;
          if (x2 >= n)
            return 1;
          if (p < 0 || p > 1 || n <= 0)
            return NaN;
          x2 = Math2.floor(x2);
          var z2 = p;
          var a = x2 + 1;
          var b = n - x2;
          var s = a + b;
          var bt = Math2.exp(jStat2.gammaln(s) - jStat2.gammaln(b) - jStat2.gammaln(a) + a * Math2.log(z2) + b * Math2.log(1 - z2));
          if (z2 < (a + 1) / (s + 2))
            betacdf = bt * betinc(z2, a, b, eps);
          else
            betacdf = 1 - bt * betinc(1 - z2, b, a, eps);
          return Math2.round((1 - betacdf) * (1 / eps)) / (1 / eps);
        }
      });
      jStat2.extend(jStat2.negbin, {
        pdf: function pdf(k, r, p) {
          if (k !== k >>> 0)
            return false;
          if (k < 0)
            return 0;
          return jStat2.combination(k + r - 1, r - 1) * Math2.pow(1 - p, k) * Math2.pow(p, r);
        },
        cdf: function cdf(x2, r, p) {
          var sum2 = 0, k = 0;
          if (x2 < 0)
            return 0;
          for (;k <= x2; k++) {
            sum2 += jStat2.negbin.pdf(k, r, p);
          }
          return sum2;
        }
      });
      jStat2.extend(jStat2.hypgeom, {
        pdf: function pdf(k, N, m, n) {
          if (k !== k | 0) {
            return false;
          } else if (k < 0 || k < m - (N - n)) {
            return 0;
          } else if (k > n || k > m) {
            return 0;
          } else if (m * 2 > N) {
            if (n * 2 > N) {
              return jStat2.hypgeom.pdf(N - m - n + k, N, N - m, N - n);
            } else {
              return jStat2.hypgeom.pdf(n - k, N, N - m, n);
            }
          } else if (n * 2 > N) {
            return jStat2.hypgeom.pdf(m - k, N, m, N - n);
          } else if (m < n) {
            return jStat2.hypgeom.pdf(k, N, n, m);
          } else {
            var scaledPDF = 1;
            var samplesDone = 0;
            for (var i = 0;i < k; i++) {
              while (scaledPDF > 1 && samplesDone < n) {
                scaledPDF *= 1 - m / (N - samplesDone);
                samplesDone++;
              }
              scaledPDF *= (n - i) * (m - i) / ((i + 1) * (N - m - n + i + 1));
            }
            for (;samplesDone < n; samplesDone++) {
              scaledPDF *= 1 - m / (N - samplesDone);
            }
            return Math2.min(1, Math2.max(0, scaledPDF));
          }
        },
        cdf: function cdf(x2, N, m, n) {
          if (x2 < 0 || x2 < m - (N - n)) {
            return 0;
          } else if (x2 >= n || x2 >= m) {
            return 1;
          } else if (m * 2 > N) {
            if (n * 2 > N) {
              return jStat2.hypgeom.cdf(N - m - n + x2, N, N - m, N - n);
            } else {
              return 1 - jStat2.hypgeom.cdf(n - x2 - 1, N, N - m, n);
            }
          } else if (n * 2 > N) {
            return 1 - jStat2.hypgeom.cdf(m - x2 - 1, N, m, N - n);
          } else if (m < n) {
            return jStat2.hypgeom.cdf(x2, N, n, m);
          } else {
            var scaledCDF = 1;
            var scaledPDF = 1;
            var samplesDone = 0;
            for (var i = 0;i < x2; i++) {
              while (scaledCDF > 1 && samplesDone < n) {
                var factor = 1 - m / (N - samplesDone);
                scaledPDF *= factor;
                scaledCDF *= factor;
                samplesDone++;
              }
              scaledPDF *= (n - i) * (m - i) / ((i + 1) * (N - m - n + i + 1));
              scaledCDF += scaledPDF;
            }
            for (;samplesDone < n; samplesDone++) {
              scaledCDF *= 1 - m / (N - samplesDone);
            }
            return Math2.min(1, Math2.max(0, scaledCDF));
          }
        }
      });
      jStat2.extend(jStat2.poisson, {
        pdf: function pdf(k, l) {
          if (l < 0 || k % 1 !== 0 || k < 0) {
            return 0;
          }
          return Math2.pow(l, k) * Math2.exp(-l) / jStat2.factorial(k);
        },
        cdf: function cdf(x2, l) {
          var sumarr = [], k = 0;
          if (x2 < 0)
            return 0;
          for (;k <= x2; k++) {
            sumarr.push(jStat2.poisson.pdf(k, l));
          }
          return jStat2.sum(sumarr);
        },
        mean: function(l) {
          return l;
        },
        variance: function(l) {
          return l;
        },
        sampleSmall: function sampleSmall(l) {
          var p = 1, k = 0, L = Math2.exp(-l);
          do {
            k++;
            p *= jStat2._random_fn();
          } while (p > L);
          return k - 1;
        },
        sampleLarge: function sampleLarge(l) {
          var lam = l;
          var k;
          var U, V, slam, loglam, a, b, invalpha, vr, us;
          slam = Math2.sqrt(lam);
          loglam = Math2.log(lam);
          b = 0.931 + 2.53 * slam;
          a = -0.059 + 0.02483 * b;
          invalpha = 1.1239 + 1.1328 / (b - 3.4);
          vr = 0.9277 - 3.6224 / (b - 2);
          while (true) {
            U = Math2.random() - 0.5;
            V = Math2.random();
            us = 0.5 - Math2.abs(U);
            k = Math2.floor((2 * a / us + b) * U + lam + 0.43);
            if (us >= 0.07 && V <= vr) {
              return k;
            }
            if (k < 0 || us < 0.013 && V > us) {
              continue;
            }
            if (Math2.log(V) + Math2.log(invalpha) - Math2.log(a / (us * us) + b) <= -lam + k * loglam - jStat2.loggam(k + 1)) {
              return k;
            }
          }
        },
        sample: function sample(l) {
          if (l < 10)
            return this.sampleSmall(l);
          else
            return this.sampleLarge(l);
        }
      });
      jStat2.extend(jStat2.triangular, {
        pdf: function pdf(x2, a, b, c) {
          if (b <= a || c < a || c > b) {
            return NaN;
          } else {
            if (x2 < a || x2 > b) {
              return 0;
            } else if (x2 < c) {
              return 2 * (x2 - a) / ((b - a) * (c - a));
            } else if (x2 === c) {
              return 2 / (b - a);
            } else {
              return 2 * (b - x2) / ((b - a) * (b - c));
            }
          }
        },
        cdf: function cdf(x2, a, b, c) {
          if (b <= a || c < a || c > b)
            return NaN;
          if (x2 <= a)
            return 0;
          else if (x2 >= b)
            return 1;
          if (x2 <= c)
            return Math2.pow(x2 - a, 2) / ((b - a) * (c - a));
          else
            return 1 - Math2.pow(b - x2, 2) / ((b - a) * (b - c));
        },
        inv: function inv(p, a, b, c) {
          if (b <= a || c < a || c > b) {
            return NaN;
          } else {
            if (p <= (c - a) / (b - a)) {
              return a + (b - a) * Math2.sqrt(p * ((c - a) / (b - a)));
            } else {
              return a + (b - a) * (1 - Math2.sqrt((1 - p) * (1 - (c - a) / (b - a))));
            }
          }
        },
        mean: function mean(a, b, c) {
          return (a + b + c) / 3;
        },
        median: function median(a, b, c) {
          if (c <= (a + b) / 2) {
            return b - Math2.sqrt((b - a) * (b - c)) / Math2.sqrt(2);
          } else if (c > (a + b) / 2) {
            return a + Math2.sqrt((b - a) * (c - a)) / Math2.sqrt(2);
          }
        },
        mode: function mode(a, b, c) {
          return c;
        },
        sample: function sample(a, b, c) {
          var u = jStat2._random_fn();
          if (u < (c - a) / (b - a))
            return a + Math2.sqrt(u * (b - a) * (c - a));
          return b - Math2.sqrt((1 - u) * (b - a) * (b - c));
        },
        variance: function variance(a, b, c) {
          return (a * a + b * b + c * c - a * b - a * c - b * c) / 18;
        }
      });
      jStat2.extend(jStat2.arcsine, {
        pdf: function pdf(x2, a, b) {
          if (b <= a)
            return NaN;
          return x2 <= a || x2 >= b ? 0 : 2 / Math2.PI * Math2.pow(Math2.pow(b - a, 2) - Math2.pow(2 * x2 - a - b, 2), -0.5);
        },
        cdf: function cdf(x2, a, b) {
          if (x2 < a)
            return 0;
          else if (x2 < b)
            return 2 / Math2.PI * Math2.asin(Math2.sqrt((x2 - a) / (b - a)));
          return 1;
        },
        inv: function(p, a, b) {
          return a + (0.5 - 0.5 * Math2.cos(Math2.PI * p)) * (b - a);
        },
        mean: function mean(a, b) {
          if (b <= a)
            return NaN;
          return (a + b) / 2;
        },
        median: function median(a, b) {
          if (b <= a)
            return NaN;
          return (a + b) / 2;
        },
        mode: function mode() {
          throw new Error("mode is not yet implemented");
        },
        sample: function sample(a, b) {
          return (a + b) / 2 + (b - a) / 2 * Math2.sin(2 * Math2.PI * jStat2.uniform.sample(0, 1));
        },
        variance: function variance(a, b) {
          if (b <= a)
            return NaN;
          return Math2.pow(b - a, 2) / 8;
        }
      });
      function laplaceSign(x2) {
        return x2 / Math2.abs(x2);
      }
      jStat2.extend(jStat2.laplace, {
        pdf: function pdf(x2, mu, b) {
          return b <= 0 ? 0 : Math2.exp(-Math2.abs(x2 - mu) / b) / (2 * b);
        },
        cdf: function cdf(x2, mu, b) {
          if (b <= 0) {
            return 0;
          }
          if (x2 < mu) {
            return 0.5 * Math2.exp((x2 - mu) / b);
          } else {
            return 1 - 0.5 * Math2.exp(-(x2 - mu) / b);
          }
        },
        mean: function(mu) {
          return mu;
        },
        median: function(mu) {
          return mu;
        },
        mode: function(mu) {
          return mu;
        },
        variance: function(mu, b) {
          return 2 * b * b;
        },
        sample: function sample(mu, b) {
          var u = jStat2._random_fn() - 0.5;
          return mu - b * laplaceSign(u) * Math2.log(1 - 2 * Math2.abs(u));
        }
      });
      function tukeyWprob(w, rr, cc) {
        var nleg = 12;
        var ihalf = 6;
        var C1 = -30;
        var C2 = -50;
        var C3 = 60;
        var bb = 8;
        var wlar = 3;
        var wincr1 = 2;
        var wincr2 = 3;
        var xleg = [
          0.9815606342467192,
          0.9041172563704749,
          0.7699026741943047,
          0.5873179542866175,
          0.3678314989981802,
          0.1252334085114689
        ];
        var aleg = [
          0.04717533638651183,
          0.10693932599531843,
          0.16007832854334622,
          0.20316742672306592,
          0.2334925365383548,
          0.24914704581340277
        ];
        var qsqz = w * 0.5;
        if (qsqz >= bb)
          return 1;
        var pr_w = 2 * jStat2.normal.cdf(qsqz, 0, 1, 1, 0) - 1;
        if (pr_w >= Math2.exp(C2 / cc))
          pr_w = Math2.pow(pr_w, cc);
        else
          pr_w = 0;
        var wincr;
        if (w > wlar)
          wincr = wincr1;
        else
          wincr = wincr2;
        var blb = qsqz;
        var binc = (bb - qsqz) / wincr;
        var bub = blb + binc;
        var einsum = 0;
        var cc1 = cc - 1;
        for (var wi = 1;wi <= wincr; wi++) {
          var elsum = 0;
          var a = 0.5 * (bub + blb);
          var b = 0.5 * (bub - blb);
          for (var jj = 1;jj <= nleg; jj++) {
            var j, xx;
            if (ihalf < jj) {
              j = nleg - jj + 1;
              xx = xleg[j - 1];
            } else {
              j = jj;
              xx = -xleg[j - 1];
            }
            var c = b * xx;
            var ac = a + c;
            var qexpo = ac * ac;
            if (qexpo > C3)
              break;
            var pplus = 2 * jStat2.normal.cdf(ac, 0, 1, 1, 0);
            var pminus = 2 * jStat2.normal.cdf(ac, w, 1, 1, 0);
            var rinsum = pplus * 0.5 - pminus * 0.5;
            if (rinsum >= Math2.exp(C1 / cc1)) {
              rinsum = aleg[j - 1] * Math2.exp(-(0.5 * qexpo)) * Math2.pow(rinsum, cc1);
              elsum += rinsum;
            }
          }
          elsum *= 2 * b * cc / Math2.sqrt(2 * Math2.PI);
          einsum += elsum;
          blb = bub;
          bub += binc;
        }
        pr_w += einsum;
        if (pr_w <= Math2.exp(C1 / rr))
          return 0;
        pr_w = Math2.pow(pr_w, rr);
        if (pr_w >= 1)
          return 1;
        return pr_w;
      }
      function tukeyQinv(p, c, v) {
        var p0 = 0.322232421088;
        var q0 = 0.099348462606;
        var p1 = -1;
        var q1 = 0.588581570495;
        var p2 = -0.342242088547;
        var q2 = 0.531103462366;
        var p3 = -0.204231210125;
        var q3 = 0.10353775285;
        var p4 = -0.0000453642210148;
        var q4 = 0.0038560700634;
        var c1 = 0.8832;
        var c2 = 0.2368;
        var c3 = 1.214;
        var c4 = 1.208;
        var c5 = 1.4142;
        var vmax = 120;
        var ps = 0.5 - 0.5 * p;
        var yi = Math2.sqrt(Math2.log(1 / (ps * ps)));
        var t = yi + ((((yi * p4 + p3) * yi + p2) * yi + p1) * yi + p0) / ((((yi * q4 + q3) * yi + q2) * yi + q1) * yi + q0);
        if (v < vmax)
          t += (t * t * t + t) / v / 4;
        var q = c1 - c2 * t;
        if (v < vmax)
          q += -c3 / v + c4 * t / v;
        return t * (q * Math2.log(c - 1) + c5);
      }
      jStat2.extend(jStat2.tukey, {
        cdf: function cdf(q, nmeans, df) {
          var rr = 1;
          var cc = nmeans;
          var nlegq = 16;
          var ihalfq = 8;
          var eps1 = -30;
          var eps2 = 0.00000000000001;
          var dhaf = 100;
          var dquar = 800;
          var deigh = 5000;
          var dlarg = 25000;
          var ulen1 = 1;
          var ulen2 = 0.5;
          var ulen3 = 0.25;
          var ulen4 = 0.125;
          var xlegq = [
            0.9894009349916499,
            0.9445750230732326,
            0.8656312023878318,
            0.755404408355003,
            0.6178762444026438,
            0.45801677765722737,
            0.2816035507792589,
            0.09501250983763744
          ];
          var alegq = [
            0.027152459411754096,
            0.062253523938647894,
            0.09515851168249279,
            0.12462897125553388,
            0.14959598881657674,
            0.16915651939500254,
            0.18260341504492358,
            0.1894506104550685
          ];
          if (q <= 0)
            return 0;
          if (df < 2 || rr < 1 || cc < 2)
            return NaN;
          if (!Number.isFinite(q))
            return 1;
          if (df > dlarg)
            return tukeyWprob(q, rr, cc);
          var f2 = df * 0.5;
          var f2lf = f2 * Math2.log(df) - df * Math2.log(2) - jStat2.gammaln(f2);
          var f21 = f2 - 1;
          var ff4 = df * 0.25;
          var ulen;
          if (df <= dhaf)
            ulen = ulen1;
          else if (df <= dquar)
            ulen = ulen2;
          else if (df <= deigh)
            ulen = ulen3;
          else
            ulen = ulen4;
          f2lf += Math2.log(ulen);
          var ans = 0;
          for (var i = 1;i <= 50; i++) {
            var otsum = 0;
            var twa1 = (2 * i - 1) * ulen;
            for (var jj = 1;jj <= nlegq; jj++) {
              var j, t1;
              if (ihalfq < jj) {
                j = jj - ihalfq - 1;
                t1 = f2lf + f21 * Math2.log(twa1 + xlegq[j] * ulen) - (xlegq[j] * ulen + twa1) * ff4;
              } else {
                j = jj - 1;
                t1 = f2lf + f21 * Math2.log(twa1 - xlegq[j] * ulen) + (xlegq[j] * ulen - twa1) * ff4;
              }
              var qsqz;
              if (t1 >= eps1) {
                if (ihalfq < jj) {
                  qsqz = q * Math2.sqrt((xlegq[j] * ulen + twa1) * 0.5);
                } else {
                  qsqz = q * Math2.sqrt((-(xlegq[j] * ulen) + twa1) * 0.5);
                }
                var wprb = tukeyWprob(qsqz, rr, cc);
                var rotsum = wprb * alegq[j] * Math2.exp(t1);
                otsum += rotsum;
              }
            }
            if (i * ulen >= 1 && otsum <= eps2)
              break;
            ans += otsum;
          }
          if (otsum > eps2) {
            throw new Error("tukey.cdf failed to converge");
          }
          if (ans > 1)
            ans = 1;
          return ans;
        },
        inv: function(p, nmeans, df) {
          var rr = 1;
          var cc = nmeans;
          var eps = 0.0001;
          var maxiter = 50;
          if (df < 2 || rr < 1 || cc < 2)
            return NaN;
          if (p < 0 || p > 1)
            return NaN;
          if (p === 0)
            return 0;
          if (p === 1)
            return Infinity;
          var x0 = tukeyQinv(p, cc, df);
          var valx0 = jStat2.tukey.cdf(x0, nmeans, df) - p;
          var x1;
          if (valx0 > 0)
            x1 = Math2.max(0, x0 - 1);
          else
            x1 = x0 + 1;
          var valx1 = jStat2.tukey.cdf(x1, nmeans, df) - p;
          var ans;
          for (var iter = 1;iter < maxiter; iter++) {
            ans = x1 - valx1 * (x1 - x0) / (valx1 - valx0);
            valx0 = valx1;
            x0 = x1;
            if (ans < 0) {
              ans = 0;
              valx1 = -p;
            }
            valx1 = jStat2.tukey.cdf(ans, nmeans, df) - p;
            x1 = ans;
            var xabs = Math2.abs(x1 - x0);
            if (xabs < eps)
              return ans;
          }
          throw new Error("tukey.inv failed to converge");
        }
      });
    })(jStat, Math);
    (function(jStat2, Math2) {
      var push = Array.prototype.push;
      var isArray2 = jStat2.utils.isArray;
      function isUsable(arg) {
        return isArray2(arg) || arg instanceof jStat2;
      }
      jStat2.extend({
        add: function add(arr, arg) {
          if (isUsable(arg)) {
            if (!isUsable(arg[0]))
              arg = [arg];
            return jStat2.map(arr, function(value, row2, col) {
              return value + arg[row2][col];
            });
          }
          return jStat2.map(arr, function(value) {
            return value + arg;
          });
        },
        subtract: function subtract(arr, arg) {
          if (isUsable(arg)) {
            if (!isUsable(arg[0]))
              arg = [arg];
            return jStat2.map(arr, function(value, row2, col) {
              return value - arg[row2][col] || 0;
            });
          }
          return jStat2.map(arr, function(value) {
            return value - arg;
          });
        },
        divide: function divide(arr, arg) {
          if (isUsable(arg)) {
            if (!isUsable(arg[0]))
              arg = [arg];
            return jStat2.multiply(arr, jStat2.inv(arg));
          }
          return jStat2.map(arr, function(value) {
            return value / arg;
          });
        },
        multiply: function multiply(arr, arg) {
          var row2, col, nrescols, sum2, nrow, ncol, res, rescols;
          if (arr.length === undefined && arg.length === undefined) {
            return arr * arg;
          }
          nrow = arr.length, ncol = arr[0].length, res = jStat2.zeros(nrow, nrescols = isUsable(arg) ? arg[0].length : ncol), rescols = 0;
          if (isUsable(arg)) {
            for (;rescols < nrescols; rescols++) {
              for (row2 = 0;row2 < nrow; row2++) {
                sum2 = 0;
                for (col = 0;col < ncol; col++)
                  sum2 += arr[row2][col] * arg[col][rescols];
                res[row2][rescols] = sum2;
              }
            }
            return nrow === 1 && rescols === 1 ? res[0][0] : res;
          }
          return jStat2.map(arr, function(value) {
            return value * arg;
          });
        },
        outer: function outer(A, B) {
          return jStat2.multiply(A.map(function(t) {
            return [t];
          }), [B]);
        },
        dot: function dot(arr, arg) {
          if (!isUsable(arr[0]))
            arr = [arr];
          if (!isUsable(arg[0]))
            arg = [arg];
          var left = arr[0].length === 1 && arr.length !== 1 ? jStat2.transpose(arr) : arr, right = arg[0].length === 1 && arg.length !== 1 ? jStat2.transpose(arg) : arg, res = [], row2 = 0, nrow = left.length, ncol = left[0].length, sum2, col;
          for (;row2 < nrow; row2++) {
            res[row2] = [];
            sum2 = 0;
            for (col = 0;col < ncol; col++)
              sum2 += left[row2][col] * right[row2][col];
            res[row2] = sum2;
          }
          return res.length === 1 ? res[0] : res;
        },
        pow: function pow(arr, arg) {
          return jStat2.map(arr, function(value) {
            return Math2.pow(value, arg);
          });
        },
        exp: function exp(arr) {
          return jStat2.map(arr, function(value) {
            return Math2.exp(value);
          });
        },
        log: function exp(arr) {
          return jStat2.map(arr, function(value) {
            return Math2.log(value);
          });
        },
        abs: function abs(arr) {
          return jStat2.map(arr, function(value) {
            return Math2.abs(value);
          });
        },
        norm: function norm(arr, p) {
          var nnorm = 0, i = 0;
          if (isNaN(p))
            p = 2;
          if (isUsable(arr[0]))
            arr = arr[0];
          for (;i < arr.length; i++) {
            nnorm += Math2.pow(Math2.abs(arr[i]), p);
          }
          return Math2.pow(nnorm, 1 / p);
        },
        angle: function angle(arr, arg) {
          return Math2.acos(jStat2.dot(arr, arg) / (jStat2.norm(arr) * jStat2.norm(arg)));
        },
        aug: function aug(a, b) {
          var newarr = [];
          var i;
          for (i = 0;i < a.length; i++) {
            newarr.push(a[i].slice());
          }
          for (i = 0;i < newarr.length; i++) {
            push.apply(newarr[i], b[i]);
          }
          return newarr;
        },
        inv: function inv(a) {
          var rows = a.length;
          var cols = a[0].length;
          var b = jStat2.identity(rows, cols);
          var c = jStat2.gauss_jordan(a, b);
          var result = [];
          var i = 0;
          var j;
          for (;i < rows; i++) {
            result[i] = [];
            for (j = cols;j < c[0].length; j++)
              result[i][j - cols] = c[i][j];
          }
          return result;
        },
        det: function det(a) {
          if (a.length === 2) {
            return a[0][0] * a[1][1] - a[0][1] * a[1][0];
          }
          var determinant = 0;
          for (var i = 0;i < a.length; i++) {
            var submatrix = [];
            for (var row2 = 1;row2 < a.length; row2++) {
              submatrix[row2 - 1] = [];
              for (var col = 0;col < a.length; col++) {
                if (col < i) {
                  submatrix[row2 - 1][col] = a[row2][col];
                } else if (col > i) {
                  submatrix[row2 - 1][col - 1] = a[row2][col];
                }
              }
            }
            var sign2 = i % 2 ? -1 : 1;
            determinant += det(submatrix) * a[0][i] * sign2;
          }
          return determinant;
        },
        gauss_elimination: function gauss_elimination(a, b) {
          var i = 0, j = 0, n = a.length, m = a[0].length, factor = 1, sum2 = 0, x2 = [], maug, pivot, temp, k;
          a = jStat2.aug(a, b);
          maug = a[0].length;
          for (i = 0;i < n; i++) {
            pivot = a[i][i];
            j = i;
            for (k = i + 1;k < m; k++) {
              if (pivot < Math2.abs(a[k][i])) {
                pivot = a[k][i];
                j = k;
              }
            }
            if (j != i) {
              for (k = 0;k < maug; k++) {
                temp = a[i][k];
                a[i][k] = a[j][k];
                a[j][k] = temp;
              }
            }
            for (j = i + 1;j < n; j++) {
              factor = a[j][i] / a[i][i];
              for (k = i;k < maug; k++) {
                a[j][k] = a[j][k] - factor * a[i][k];
              }
            }
          }
          for (i = n - 1;i >= 0; i--) {
            sum2 = 0;
            for (j = i + 1;j <= n - 1; j++) {
              sum2 = sum2 + x2[j] * a[i][j];
            }
            x2[i] = (a[i][maug - 1] - sum2) / a[i][i];
          }
          return x2;
        },
        gauss_jordan: function gauss_jordan(a, b) {
          var m = jStat2.aug(a, b);
          var h = m.length;
          var w = m[0].length;
          var c = 0;
          var x2, y2, y22;
          for (y2 = 0;y2 < h; y2++) {
            var maxrow = y2;
            for (y22 = y2 + 1;y22 < h; y22++) {
              if (Math2.abs(m[y22][y2]) > Math2.abs(m[maxrow][y2]))
                maxrow = y22;
            }
            var tmp = m[y2];
            m[y2] = m[maxrow];
            m[maxrow] = tmp;
            for (y22 = y2 + 1;y22 < h; y22++) {
              c = m[y22][y2] / m[y2][y2];
              for (x2 = y2;x2 < w; x2++) {
                m[y22][x2] -= m[y2][x2] * c;
              }
            }
          }
          for (y2 = h - 1;y2 >= 0; y2--) {
            c = m[y2][y2];
            for (y22 = 0;y22 < y2; y22++) {
              for (x2 = w - 1;x2 > y2 - 1; x2--) {
                m[y22][x2] -= m[y2][x2] * m[y22][y2] / c;
              }
            }
            m[y2][y2] /= c;
            for (x2 = h;x2 < w; x2++) {
              m[y2][x2] /= c;
            }
          }
          return m;
        },
        triaUpSolve: function triaUpSolve(A, b) {
          var size2 = A[0].length;
          var x2 = jStat2.zeros(1, size2)[0];
          var parts;
          var matrix_mode = false;
          if (b[0].length != null) {
            b = b.map(function(i) {
              return i[0];
            });
            matrix_mode = true;
          }
          jStat2.arange(size2 - 1, -1, -1).forEach(function(i) {
            parts = jStat2.arange(i + 1, size2).map(function(j) {
              return x2[j] * A[i][j];
            });
            x2[i] = (b[i] - jStat2.sum(parts)) / A[i][i];
          });
          if (matrix_mode)
            return x2.map(function(i) {
              return [i];
            });
          return x2;
        },
        triaLowSolve: function triaLowSolve(A, b) {
          var size2 = A[0].length;
          var x2 = jStat2.zeros(1, size2)[0];
          var parts;
          var matrix_mode = false;
          if (b[0].length != null) {
            b = b.map(function(i) {
              return i[0];
            });
            matrix_mode = true;
          }
          jStat2.arange(size2).forEach(function(i) {
            parts = jStat2.arange(i).map(function(j) {
              return A[i][j] * x2[j];
            });
            x2[i] = (b[i] - jStat2.sum(parts)) / A[i][i];
          });
          if (matrix_mode)
            return x2.map(function(i) {
              return [i];
            });
          return x2;
        },
        lu: function lu(A) {
          var size2 = A.length;
          var L = jStat2.identity(size2);
          var R = jStat2.zeros(A.length, A[0].length);
          var parts;
          jStat2.arange(size2).forEach(function(t) {
            R[0][t] = A[0][t];
          });
          jStat2.arange(1, size2).forEach(function(l) {
            jStat2.arange(l).forEach(function(i) {
              parts = jStat2.arange(i).map(function(jj) {
                return L[l][jj] * R[jj][i];
              });
              L[l][i] = (A[l][i] - jStat2.sum(parts)) / R[i][i];
            });
            jStat2.arange(l, size2).forEach(function(j) {
              parts = jStat2.arange(l).map(function(jj) {
                return L[l][jj] * R[jj][j];
              });
              R[l][j] = A[parts.length][j] - jStat2.sum(parts);
            });
          });
          return [L, R];
        },
        cholesky: function cholesky(A) {
          var size2 = A.length;
          var T = jStat2.zeros(A.length, A[0].length);
          var parts;
          jStat2.arange(size2).forEach(function(i) {
            parts = jStat2.arange(i).map(function(t) {
              return Math2.pow(T[i][t], 2);
            });
            T[i][i] = Math2.sqrt(A[i][i] - jStat2.sum(parts));
            jStat2.arange(i + 1, size2).forEach(function(j) {
              parts = jStat2.arange(i).map(function(t) {
                return T[i][t] * T[j][t];
              });
              T[j][i] = (A[i][j] - jStat2.sum(parts)) / T[i][i];
            });
          });
          return T;
        },
        gauss_jacobi: function gauss_jacobi(a, b, x2, r) {
          var i = 0;
          var j = 0;
          var n = a.length;
          var l = [];
          var u = [];
          var d = [];
          var xv, c, h, xk;
          for (;i < n; i++) {
            l[i] = [];
            u[i] = [];
            d[i] = [];
            for (j = 0;j < n; j++) {
              if (i > j) {
                l[i][j] = a[i][j];
                u[i][j] = d[i][j] = 0;
              } else if (i < j) {
                u[i][j] = a[i][j];
                l[i][j] = d[i][j] = 0;
              } else {
                d[i][j] = a[i][j];
                l[i][j] = u[i][j] = 0;
              }
            }
          }
          h = jStat2.multiply(jStat2.multiply(jStat2.inv(d), jStat2.add(l, u)), -1);
          c = jStat2.multiply(jStat2.inv(d), b);
          xv = x2;
          xk = jStat2.add(jStat2.multiply(h, x2), c);
          i = 2;
          while (Math2.abs(jStat2.norm(jStat2.subtract(xk, xv))) > r) {
            xv = xk;
            xk = jStat2.add(jStat2.multiply(h, xv), c);
            i++;
          }
          return xk;
        },
        gauss_seidel: function gauss_seidel(a, b, x2, r) {
          var i = 0;
          var n = a.length;
          var l = [];
          var u = [];
          var d = [];
          var j, xv, c, h, xk;
          for (;i < n; i++) {
            l[i] = [];
            u[i] = [];
            d[i] = [];
            for (j = 0;j < n; j++) {
              if (i > j) {
                l[i][j] = a[i][j];
                u[i][j] = d[i][j] = 0;
              } else if (i < j) {
                u[i][j] = a[i][j];
                l[i][j] = d[i][j] = 0;
              } else {
                d[i][j] = a[i][j];
                l[i][j] = u[i][j] = 0;
              }
            }
          }
          h = jStat2.multiply(jStat2.multiply(jStat2.inv(jStat2.add(d, l)), u), -1);
          c = jStat2.multiply(jStat2.inv(jStat2.add(d, l)), b);
          xv = x2;
          xk = jStat2.add(jStat2.multiply(h, x2), c);
          i = 2;
          while (Math2.abs(jStat2.norm(jStat2.subtract(xk, xv))) > r) {
            xv = xk;
            xk = jStat2.add(jStat2.multiply(h, xv), c);
            i = i + 1;
          }
          return xk;
        },
        SOR: function SOR(a, b, x2, r, w) {
          var i = 0;
          var n = a.length;
          var l = [];
          var u = [];
          var d = [];
          var j, xv, c, h, xk;
          for (;i < n; i++) {
            l[i] = [];
            u[i] = [];
            d[i] = [];
            for (j = 0;j < n; j++) {
              if (i > j) {
                l[i][j] = a[i][j];
                u[i][j] = d[i][j] = 0;
              } else if (i < j) {
                u[i][j] = a[i][j];
                l[i][j] = d[i][j] = 0;
              } else {
                d[i][j] = a[i][j];
                l[i][j] = u[i][j] = 0;
              }
            }
          }
          h = jStat2.multiply(jStat2.inv(jStat2.add(d, jStat2.multiply(l, w))), jStat2.subtract(jStat2.multiply(d, 1 - w), jStat2.multiply(u, w)));
          c = jStat2.multiply(jStat2.multiply(jStat2.inv(jStat2.add(d, jStat2.multiply(l, w))), b), w);
          xv = x2;
          xk = jStat2.add(jStat2.multiply(h, x2), c);
          i = 2;
          while (Math2.abs(jStat2.norm(jStat2.subtract(xk, xv))) > r) {
            xv = xk;
            xk = jStat2.add(jStat2.multiply(h, xv), c);
            i++;
          }
          return xk;
        },
        householder: function householder(a) {
          var m = a.length;
          var n = a[0].length;
          var i = 0;
          var w = [];
          var p = [];
          var alpha, r, k, j, factor;
          for (;i < m - 1; i++) {
            alpha = 0;
            for (j = i + 1;j < n; j++)
              alpha += a[j][i] * a[j][i];
            factor = a[i + 1][i] > 0 ? -1 : 1;
            alpha = factor * Math2.sqrt(alpha);
            r = Math2.sqrt((alpha * alpha - a[i + 1][i] * alpha) / 2);
            w = jStat2.zeros(m, 1);
            w[i + 1][0] = (a[i + 1][i] - alpha) / (2 * r);
            for (k = i + 2;k < m; k++)
              w[k][0] = a[k][i] / (2 * r);
            p = jStat2.subtract(jStat2.identity(m, n), jStat2.multiply(jStat2.multiply(w, jStat2.transpose(w)), 2));
            a = jStat2.multiply(p, jStat2.multiply(a, p));
          }
          return a;
        },
        QR: function() {
          var sum2 = jStat2.sum;
          var range2 = jStat2.arange;
          function qr2(x2) {
            var n = x2.length;
            var p = x2[0].length;
            var r = jStat2.zeros(p, p);
            x2 = jStat2.copy(x2);
            var i, j, k;
            for (j = 0;j < p; j++) {
              r[j][j] = Math2.sqrt(sum2(range2(n).map(function(i2) {
                return x2[i2][j] * x2[i2][j];
              })));
              for (i = 0;i < n; i++) {
                x2[i][j] = x2[i][j] / r[j][j];
              }
              for (k = j + 1;k < p; k++) {
                r[j][k] = sum2(range2(n).map(function(i2) {
                  return x2[i2][j] * x2[i2][k];
                }));
                for (i = 0;i < n; i++) {
                  x2[i][k] = x2[i][k] - x2[i][j] * r[j][k];
                }
              }
            }
            return [x2, r];
          }
          return qr2;
        }(),
        lstsq: function() {
          function R_I(A) {
            A = jStat2.copy(A);
            var size2 = A.length;
            var I = jStat2.identity(size2);
            jStat2.arange(size2 - 1, -1, -1).forEach(function(i) {
              jStat2.sliceAssign(I, { row: i }, jStat2.divide(jStat2.slice(I, { row: i }), A[i][i]));
              jStat2.sliceAssign(A, { row: i }, jStat2.divide(jStat2.slice(A, { row: i }), A[i][i]));
              jStat2.arange(i).forEach(function(j) {
                var c = jStat2.multiply(A[j][i], -1);
                var Aj = jStat2.slice(A, { row: j });
                var cAi = jStat2.multiply(jStat2.slice(A, { row: i }), c);
                jStat2.sliceAssign(A, { row: j }, jStat2.add(Aj, cAi));
                var Ij = jStat2.slice(I, { row: j });
                var cIi = jStat2.multiply(jStat2.slice(I, { row: i }), c);
                jStat2.sliceAssign(I, { row: j }, jStat2.add(Ij, cIi));
              });
            });
            return I;
          }
          function qr_solve(A, b) {
            var array_mode = false;
            if (b[0].length === undefined) {
              b = b.map(function(x3) {
                return [x3];
              });
              array_mode = true;
            }
            var QR = jStat2.QR(A);
            var Q = QR[0];
            var R = QR[1];
            var attrs = A[0].length;
            var Q1 = jStat2.slice(Q, { col: { end: attrs } });
            var R1 = jStat2.slice(R, { row: { end: attrs } });
            var RI = R_I(R1);
            var Q2 = jStat2.transpose(Q1);
            if (Q2[0].length === undefined) {
              Q2 = [Q2];
            }
            var x2 = jStat2.multiply(jStat2.multiply(RI, Q2), b);
            if (x2.length === undefined) {
              x2 = [[x2]];
            }
            if (array_mode)
              return x2.map(function(i) {
                return i[0];
              });
            return x2;
          }
          return qr_solve;
        }(),
        jacobi: function jacobi(a) {
          var condition = 1;
          var n = a.length;
          var e = jStat2.identity(n, n);
          var ev = [];
          var b, i, j, p, q, maxim, theta, s;
          while (condition === 1) {
            maxim = a[0][1];
            p = 0;
            q = 1;
            for (i = 0;i < n; i++) {
              for (j = 0;j < n; j++) {
                if (i != j) {
                  if (maxim < Math2.abs(a[i][j])) {
                    maxim = Math2.abs(a[i][j]);
                    p = i;
                    q = j;
                  }
                }
              }
            }
            if (a[p][p] === a[q][q])
              theta = a[p][q] > 0 ? Math2.PI / 4 : -Math2.PI / 4;
            else
              theta = Math2.atan(2 * a[p][q] / (a[p][p] - a[q][q])) / 2;
            s = jStat2.identity(n, n);
            s[p][p] = Math2.cos(theta);
            s[p][q] = -Math2.sin(theta);
            s[q][p] = Math2.sin(theta);
            s[q][q] = Math2.cos(theta);
            e = jStat2.multiply(e, s);
            b = jStat2.multiply(jStat2.multiply(jStat2.inv(s), a), s);
            a = b;
            condition = 0;
            for (i = 1;i < n; i++) {
              for (j = 1;j < n; j++) {
                if (i != j && Math2.abs(a[i][j]) > 0.001) {
                  condition = 1;
                }
              }
            }
          }
          for (i = 0;i < n; i++)
            ev.push(a[i][i]);
          return [e, ev];
        },
        rungekutta: function rungekutta(f, h, p, t_j, u_j, order) {
          var k1, k2, u_j1, k3, k4;
          if (order === 2) {
            while (t_j <= p) {
              k1 = h * f(t_j, u_j);
              k2 = h * f(t_j + h, u_j + k1);
              u_j1 = u_j + (k1 + k2) / 2;
              u_j = u_j1;
              t_j = t_j + h;
            }
          }
          if (order === 4) {
            while (t_j <= p) {
              k1 = h * f(t_j, u_j);
              k2 = h * f(t_j + h / 2, u_j + k1 / 2);
              k3 = h * f(t_j + h / 2, u_j + k2 / 2);
              k4 = h * f(t_j + h, u_j + k3);
              u_j1 = u_j + (k1 + 2 * k2 + 2 * k3 + k4) / 6;
              u_j = u_j1;
              t_j = t_j + h;
            }
          }
          return u_j;
        },
        romberg: function romberg(f, a, b, order) {
          var i = 0;
          var h = (b - a) / 2;
          var x2 = [];
          var h1 = [];
          var g = [];
          var m, a1, j, k, I;
          while (i < order / 2) {
            I = f(a);
            for (j = a, k = 0;j <= b; j = j + h, k++)
              x2[k] = j;
            m = x2.length;
            for (j = 1;j < m - 1; j++) {
              I += (j % 2 !== 0 ? 4 : 2) * f(x2[j]);
            }
            I = h / 3 * (I + f(b));
            g[i] = I;
            h /= 2;
            i++;
          }
          a1 = g.length;
          m = 1;
          while (a1 !== 1) {
            for (j = 0;j < a1 - 1; j++)
              h1[j] = (Math2.pow(4, m) * g[j + 1] - g[j]) / (Math2.pow(4, m) - 1);
            a1 = h1.length;
            g = h1;
            h1 = [];
            m++;
          }
          return g;
        },
        richardson: function richardson(X, f, x2, h) {
          function pos(X2, x3) {
            var i2 = 0;
            var n = X2.length;
            var p;
            for (;i2 < n; i2++)
              if (X2[i2] === x3)
                p = i2;
            return p;
          }
          var h_min = Math2.abs(x2 - X[pos(X, x2) + 1]);
          var i = 0;
          var g = [];
          var h1 = [];
          var y1, y2, m, a, j;
          while (h >= h_min) {
            y1 = pos(X, x2 + h);
            y2 = pos(X, x2);
            g[i] = (f[y1] - 2 * f[y2] + f[2 * y2 - y1]) / (h * h);
            h /= 2;
            i++;
          }
          a = g.length;
          m = 1;
          while (a != 1) {
            for (j = 0;j < a - 1; j++)
              h1[j] = (Math2.pow(4, m) * g[j + 1] - g[j]) / (Math2.pow(4, m) - 1);
            a = h1.length;
            g = h1;
            h1 = [];
            m++;
          }
          return g;
        },
        simpson: function simpson(f, a, b, n) {
          var h = (b - a) / n;
          var I = f(a);
          var x2 = [];
          var j = a;
          var k = 0;
          var i = 1;
          var m;
          for (;j <= b; j = j + h, k++)
            x2[k] = j;
          m = x2.length;
          for (;i < m - 1; i++) {
            I += (i % 2 !== 0 ? 4 : 2) * f(x2[i]);
          }
          return h / 3 * (I + f(b));
        },
        hermite: function hermite(X, F, dF, value) {
          var n = X.length;
          var p = 0;
          var i = 0;
          var l = [];
          var dl = [];
          var A = [];
          var B = [];
          var j;
          for (;i < n; i++) {
            l[i] = 1;
            for (j = 0;j < n; j++) {
              if (i != j)
                l[i] *= (value - X[j]) / (X[i] - X[j]);
            }
            dl[i] = 0;
            for (j = 0;j < n; j++) {
              if (i != j)
                dl[i] += 1 / (X[i] - X[j]);
            }
            A[i] = (1 - 2 * (value - X[i]) * dl[i]) * (l[i] * l[i]);
            B[i] = (value - X[i]) * (l[i] * l[i]);
            p += A[i] * F[i] + B[i] * dF[i];
          }
          return p;
        },
        lagrange: function lagrange(X, F, value) {
          var p = 0;
          var i = 0;
          var j, l;
          var n = X.length;
          for (;i < n; i++) {
            l = F[i];
            for (j = 0;j < n; j++) {
              if (i != j)
                l *= (value - X[j]) / (X[i] - X[j]);
            }
            p += l;
          }
          return p;
        },
        cubic_spline: function cubic_spline(X, F, value) {
          var n = X.length;
          var i = 0, j;
          var A = [];
          var B = [];
          var alpha = [];
          var c = [];
          var h = [];
          var b = [];
          var d = [];
          for (;i < n - 1; i++)
            h[i] = X[i + 1] - X[i];
          alpha[0] = 0;
          for (i = 1;i < n - 1; i++) {
            alpha[i] = 3 / h[i] * (F[i + 1] - F[i]) - 3 / h[i - 1] * (F[i] - F[i - 1]);
          }
          for (i = 1;i < n - 1; i++) {
            A[i] = [];
            B[i] = [];
            A[i][i - 1] = h[i - 1];
            A[i][i] = 2 * (h[i - 1] + h[i]);
            A[i][i + 1] = h[i];
            B[i][0] = alpha[i];
          }
          c = jStat2.multiply(jStat2.inv(A), B);
          for (j = 0;j < n - 1; j++) {
            b[j] = (F[j + 1] - F[j]) / h[j] - h[j] * (c[j + 1][0] + 2 * c[j][0]) / 3;
            d[j] = (c[j + 1][0] - c[j][0]) / (3 * h[j]);
          }
          for (j = 0;j < n; j++) {
            if (X[j] > value)
              break;
          }
          j -= 1;
          return F[j] + (value - X[j]) * b[j] + jStat2.sq(value - X[j]) * c[j] + (value - X[j]) * jStat2.sq(value - X[j]) * d[j];
        },
        gauss_quadrature: function gauss_quadrature() {
          throw new Error("gauss_quadrature not yet implemented");
        },
        PCA: function PCA(X) {
          var m = X.length;
          var n = X[0].length;
          var i = 0;
          var j, temp1;
          var u = [];
          var D = [];
          var result = [];
          var temp2 = [];
          var Y = [];
          var Bt = [];
          var B = [];
          var C = [];
          var V = [];
          var Vt = [];
          for (i = 0;i < m; i++) {
            u[i] = jStat2.sum(X[i]) / n;
          }
          for (i = 0;i < n; i++) {
            B[i] = [];
            for (j = 0;j < m; j++) {
              B[i][j] = X[j][i] - u[j];
            }
          }
          B = jStat2.transpose(B);
          for (i = 0;i < m; i++) {
            C[i] = [];
            for (j = 0;j < m; j++) {
              C[i][j] = jStat2.dot([B[i]], [B[j]]) / (n - 1);
            }
          }
          result = jStat2.jacobi(C);
          V = result[0];
          D = result[1];
          Vt = jStat2.transpose(V);
          for (i = 0;i < D.length; i++) {
            for (j = i;j < D.length; j++) {
              if (D[i] < D[j]) {
                temp1 = D[i];
                D[i] = D[j];
                D[j] = temp1;
                temp2 = Vt[i];
                Vt[i] = Vt[j];
                Vt[j] = temp2;
              }
            }
          }
          Bt = jStat2.transpose(B);
          for (i = 0;i < m; i++) {
            Y[i] = [];
            for (j = 0;j < Bt.length; j++) {
              Y[i][j] = jStat2.dot([Vt[i]], [Bt[j]]);
            }
          }
          return [X, D, Vt, Y];
        }
      });
      (function(funcs) {
        for (var i = 0;i < funcs.length; i++)
          (function(passfunc) {
            jStat2.fn[passfunc] = function(arg, func) {
              var tmpthis = this;
              if (func) {
                setTimeout(function() {
                  func.call(tmpthis, jStat2.fn[passfunc].call(tmpthis, arg));
                }, 15);
                return this;
              }
              if (typeof jStat2[passfunc](this, arg) === "number")
                return jStat2[passfunc](this, arg);
              else
                return jStat2(jStat2[passfunc](this, arg));
            };
          })(funcs[i]);
      })("add divide multiply subtract dot pow exp log abs norm angle".split(" "));
    })(jStat, Math);
    (function(jStat2, Math2) {
      var slice3 = [].slice;
      var isNumber2 = jStat2.utils.isNumber;
      var isArray2 = jStat2.utils.isArray;
      jStat2.extend({
        zscore: function zscore() {
          var args2 = slice3.call(arguments);
          if (isNumber2(args2[1])) {
            return (args2[0] - args2[1]) / args2[2];
          }
          return (args2[0] - jStat2.mean(args2[1])) / jStat2.stdev(args2[1], args2[2]);
        },
        ztest: function ztest() {
          var args2 = slice3.call(arguments);
          var z2;
          if (isArray2(args2[1])) {
            z2 = jStat2.zscore(args2[0], args2[1], args2[3]);
            return args2[2] === 1 ? jStat2.normal.cdf(-Math2.abs(z2), 0, 1) : jStat2.normal.cdf(-Math2.abs(z2), 0, 1) * 2;
          } else {
            if (args2.length > 2) {
              z2 = jStat2.zscore(args2[0], args2[1], args2[2]);
              return args2[3] === 1 ? jStat2.normal.cdf(-Math2.abs(z2), 0, 1) : jStat2.normal.cdf(-Math2.abs(z2), 0, 1) * 2;
            } else {
              z2 = args2[0];
              return args2[1] === 1 ? jStat2.normal.cdf(-Math2.abs(z2), 0, 1) : jStat2.normal.cdf(-Math2.abs(z2), 0, 1) * 2;
            }
          }
        }
      });
      jStat2.extend(jStat2.fn, {
        zscore: function zscore(value, flag) {
          return (value - this.mean()) / this.stdev(flag);
        },
        ztest: function ztest(value, sides, flag) {
          var zscore = Math2.abs(this.zscore(value, flag));
          return sides === 1 ? jStat2.normal.cdf(-zscore, 0, 1) : jStat2.normal.cdf(-zscore, 0, 1) * 2;
        }
      });
      jStat2.extend({
        tscore: function tscore() {
          var args2 = slice3.call(arguments);
          return args2.length === 4 ? (args2[0] - args2[1]) / (args2[2] / Math2.sqrt(args2[3])) : (args2[0] - jStat2.mean(args2[1])) / (jStat2.stdev(args2[1], true) / Math2.sqrt(args2[1].length));
        },
        ttest: function ttest() {
          var args2 = slice3.call(arguments);
          var tscore;
          if (args2.length === 5) {
            tscore = Math2.abs(jStat2.tscore(args2[0], args2[1], args2[2], args2[3]));
            return args2[4] === 1 ? jStat2.studentt.cdf(-tscore, args2[3] - 1) : jStat2.studentt.cdf(-tscore, args2[3] - 1) * 2;
          }
          if (isNumber2(args2[1])) {
            tscore = Math2.abs(args2[0]);
            return args2[2] == 1 ? jStat2.studentt.cdf(-tscore, args2[1] - 1) : jStat2.studentt.cdf(-tscore, args2[1] - 1) * 2;
          }
          tscore = Math2.abs(jStat2.tscore(args2[0], args2[1]));
          return args2[2] == 1 ? jStat2.studentt.cdf(-tscore, args2[1].length - 1) : jStat2.studentt.cdf(-tscore, args2[1].length - 1) * 2;
        }
      });
      jStat2.extend(jStat2.fn, {
        tscore: function tscore(value) {
          return (value - this.mean()) / (this.stdev(true) / Math2.sqrt(this.cols()));
        },
        ttest: function ttest(value, sides) {
          return sides === 1 ? 1 - jStat2.studentt.cdf(Math2.abs(this.tscore(value)), this.cols() - 1) : jStat2.studentt.cdf(-Math2.abs(this.tscore(value)), this.cols() - 1) * 2;
        }
      });
      jStat2.extend({
        anovafscore: function anovafscore() {
          var args2 = slice3.call(arguments), expVar, sample, sampMean, sampSampMean, tmpargs, unexpVar, i, j;
          if (args2.length === 1) {
            tmpargs = new Array(args2[0].length);
            for (i = 0;i < args2[0].length; i++) {
              tmpargs[i] = args2[0][i];
            }
            args2 = tmpargs;
          }
          sample = new Array;
          for (i = 0;i < args2.length; i++) {
            sample = sample.concat(args2[i]);
          }
          sampMean = jStat2.mean(sample);
          expVar = 0;
          for (i = 0;i < args2.length; i++) {
            expVar = expVar + args2[i].length * Math2.pow(jStat2.mean(args2[i]) - sampMean, 2);
          }
          expVar /= args2.length - 1;
          unexpVar = 0;
          for (i = 0;i < args2.length; i++) {
            sampSampMean = jStat2.mean(args2[i]);
            for (j = 0;j < args2[i].length; j++) {
              unexpVar += Math2.pow(args2[i][j] - sampSampMean, 2);
            }
          }
          unexpVar /= sample.length - args2.length;
          return expVar / unexpVar;
        },
        anovaftest: function anovaftest() {
          var args2 = slice3.call(arguments), df1, df2, n, i;
          if (isNumber2(args2[0])) {
            return 1 - jStat2.centralF.cdf(args2[0], args2[1], args2[2]);
          }
          var anovafscore = jStat2.anovafscore(args2);
          df1 = args2.length - 1;
          n = 0;
          for (i = 0;i < args2.length; i++) {
            n = n + args2[i].length;
          }
          df2 = n - df1 - 1;
          return 1 - jStat2.centralF.cdf(anovafscore, df1, df2);
        },
        ftest: function ftest(fscore, df1, df2) {
          return 1 - jStat2.centralF.cdf(fscore, df1, df2);
        }
      });
      jStat2.extend(jStat2.fn, {
        anovafscore: function anovafscore() {
          return jStat2.anovafscore(this.toArray());
        },
        anovaftes: function anovaftes() {
          var n = 0;
          var i;
          for (i = 0;i < this.length; i++) {
            n = n + this[i].length;
          }
          return jStat2.ftest(this.anovafscore(), this.length - 1, n - this.length);
        }
      });
      jStat2.extend({
        qscore: function qscore() {
          var args2 = slice3.call(arguments);
          var mean1, mean22, n1, n2, sd;
          if (isNumber2(args2[0])) {
            mean1 = args2[0];
            mean22 = args2[1];
            n1 = args2[2];
            n2 = args2[3];
            sd = args2[4];
          } else {
            mean1 = jStat2.mean(args2[0]);
            mean22 = jStat2.mean(args2[1]);
            n1 = args2[0].length;
            n2 = args2[1].length;
            sd = args2[2];
          }
          return Math2.abs(mean1 - mean22) / (sd * Math2.sqrt((1 / n1 + 1 / n2) / 2));
        },
        qtest: function qtest() {
          var args2 = slice3.call(arguments);
          var qscore;
          if (args2.length === 3) {
            qscore = args2[0];
            args2 = args2.slice(1);
          } else if (args2.length === 7) {
            qscore = jStat2.qscore(args2[0], args2[1], args2[2], args2[3], args2[4]);
            args2 = args2.slice(5);
          } else {
            qscore = jStat2.qscore(args2[0], args2[1], args2[2]);
            args2 = args2.slice(3);
          }
          var n = args2[0];
          var k = args2[1];
          return 1 - jStat2.tukey.cdf(qscore, k, n - k);
        },
        tukeyhsd: function tukeyhsd(arrays) {
          var sd = jStat2.pooledstdev(arrays);
          var means = arrays.map(function(arr) {
            return jStat2.mean(arr);
          });
          var n = arrays.reduce(function(n2, arr) {
            return n2 + arr.length;
          }, 0);
          var results = [];
          for (var i = 0;i < arrays.length; ++i) {
            for (var j = i + 1;j < arrays.length; ++j) {
              var p = jStat2.qtest(means[i], means[j], arrays[i].length, arrays[j].length, sd, n, arrays.length);
              results.push([[i, j], p]);
            }
          }
          return results;
        }
      });
      jStat2.extend({
        normalci: function normalci() {
          var args2 = slice3.call(arguments), ans = new Array(2), change;
          if (args2.length === 4) {
            change = Math2.abs(jStat2.normal.inv(args2[1] / 2, 0, 1) * args2[2] / Math2.sqrt(args2[3]));
          } else {
            change = Math2.abs(jStat2.normal.inv(args2[1] / 2, 0, 1) * jStat2.stdev(args2[2]) / Math2.sqrt(args2[2].length));
          }
          ans[0] = args2[0] - change;
          ans[1] = args2[0] + change;
          return ans;
        },
        tci: function tci() {
          var args2 = slice3.call(arguments), ans = new Array(2), change;
          if (args2.length === 4) {
            change = Math2.abs(jStat2.studentt.inv(args2[1] / 2, args2[3] - 1) * args2[2] / Math2.sqrt(args2[3]));
          } else {
            change = Math2.abs(jStat2.studentt.inv(args2[1] / 2, args2[2].length - 1) * jStat2.stdev(args2[2], true) / Math2.sqrt(args2[2].length));
          }
          ans[0] = args2[0] - change;
          ans[1] = args2[0] + change;
          return ans;
        },
        significant: function significant(pvalue, alpha) {
          return pvalue < alpha;
        }
      });
      jStat2.extend(jStat2.fn, {
        normalci: function normalci(value, alpha) {
          return jStat2.normalci(value, alpha, this.toArray());
        },
        tci: function tci(value, alpha) {
          return jStat2.tci(value, alpha, this.toArray());
        }
      });
      function differenceOfProportions(p1, n1, p2, n2) {
        if (p1 > 1 || p2 > 1 || p1 <= 0 || p2 <= 0) {
          throw new Error("Proportions should be greater than 0 and less than 1");
        }
        var pooled = (p1 * n1 + p2 * n2) / (n1 + n2);
        var se = Math2.sqrt(pooled * (1 - pooled) * (1 / n1 + 1 / n2));
        return (p1 - p2) / se;
      }
      jStat2.extend(jStat2.fn, {
        oneSidedDifferenceOfProportions: function oneSidedDifferenceOfProportions(p1, n1, p2, n2) {
          var z2 = differenceOfProportions(p1, n1, p2, n2);
          return jStat2.ztest(z2, 1);
        },
        twoSidedDifferenceOfProportions: function twoSidedDifferenceOfProportions(p1, n1, p2, n2) {
          var z2 = differenceOfProportions(p1, n1, p2, n2);
          return jStat2.ztest(z2, 2);
        }
      });
    })(jStat, Math);
    jStat.models = function() {
      function sub_regress(exog) {
        var var_count = exog[0].length;
        var modelList = jStat.arange(var_count).map(function(endog_index) {
          var exog_index = jStat.arange(var_count).filter(function(i) {
            return i !== endog_index;
          });
          return ols(jStat.col(exog, endog_index).map(function(x2) {
            return x2[0];
          }), jStat.col(exog, exog_index));
        });
        return modelList;
      }
      function ols(endog, exog) {
        var nobs = endog.length;
        var df_model = exog[0].length - 1;
        var df_resid = nobs - df_model - 1;
        var coef = jStat.lstsq(exog, endog);
        var predict = jStat.multiply(exog, coef.map(function(x2) {
          return [x2];
        })).map(function(p) {
          return p[0];
        });
        var resid = jStat.subtract(endog, predict);
        var ybar = jStat.mean(endog);
        var SSE = jStat.sum(predict.map(function(f) {
          return Math.pow(f - ybar, 2);
        }));
        var SSR = jStat.sum(endog.map(function(y2, i) {
          return Math.pow(y2 - predict[i], 2);
        }));
        var SST = SSE + SSR;
        var R2 = SSE / SST;
        return {
          exog,
          endog,
          nobs,
          df_model,
          df_resid,
          coef,
          predict,
          resid,
          ybar,
          SST,
          SSE,
          SSR,
          R2
        };
      }
      function t_test(model) {
        var subModelList = sub_regress(model.exog);
        var sigmaHat = Math.sqrt(model.SSR / model.df_resid);
        var seBetaHat = subModelList.map(function(mod) {
          var SST = mod.SST;
          var R2 = mod.R2;
          return sigmaHat / Math.sqrt(SST * (1 - R2));
        });
        var tStatistic = model.coef.map(function(coef, i) {
          return (coef - 0) / seBetaHat[i];
        });
        var pValue = tStatistic.map(function(t) {
          var leftppf = jStat.studentt.cdf(t, model.df_resid);
          return (leftppf > 0.5 ? 1 - leftppf : leftppf) * 2;
        });
        var c = jStat.studentt.inv(0.975, model.df_resid);
        var interval95 = model.coef.map(function(coef, i) {
          var d = c * seBetaHat[i];
          return [coef - d, coef + d];
        });
        return {
          se: seBetaHat,
          t: tStatistic,
          p: pValue,
          sigmaHat,
          interval95
        };
      }
      function F_test(model) {
        var F_statistic = model.R2 / model.df_model / ((1 - model.R2) / model.df_resid);
        var fcdf = function(x2, n1, n2) {
          return jStat.beta.cdf(x2 / (n2 / n1 + x2), n1 / 2, n2 / 2);
        };
        var pvalue = 1 - fcdf(F_statistic, model.df_model, model.df_resid);
        return { F_statistic, pvalue };
      }
      function ols_wrap(endog, exog) {
        var model = ols(endog, exog);
        var ttest = t_test(model);
        var ftest = F_test(model);
        var adjust_R2 = 1 - (1 - model.R2) * ((model.nobs - 1) / model.df_resid);
        model.t = ttest;
        model.f = ftest;
        model.adjust_R2 = adjust_R2;
        return model;
      }
      return { ols: ols_wrap };
    }();
    jStat.extend({
      buildxmatrix: function buildxmatrix() {
        var matrixRows = new Array(arguments.length);
        for (var i = 0;i < arguments.length; i++) {
          var array3 = [1];
          matrixRows[i] = array3.concat(arguments[i]);
        }
        return jStat(matrixRows);
      },
      builddxmatrix: function builddxmatrix() {
        var matrixRows = new Array(arguments[0].length);
        for (var i = 0;i < arguments[0].length; i++) {
          var array3 = [1];
          matrixRows[i] = array3.concat(arguments[0][i]);
        }
        return jStat(matrixRows);
      },
      buildjxmatrix: function buildjxmatrix(jMat) {
        var pass = new Array(jMat.length);
        for (var i = 0;i < jMat.length; i++) {
          pass[i] = jMat[i];
        }
        return jStat.builddxmatrix(pass);
      },
      buildymatrix: function buildymatrix(array3) {
        return jStat(array3).transpose();
      },
      buildjymatrix: function buildjymatrix(jMat) {
        return jMat.transpose();
      },
      matrixmult: function matrixmult(A, B) {
        var i, j, k, result, sum2;
        if (A.cols() == B.rows()) {
          if (B.rows() > 1) {
            result = [];
            for (i = 0;i < A.rows(); i++) {
              result[i] = [];
              for (j = 0;j < B.cols(); j++) {
                sum2 = 0;
                for (k = 0;k < A.cols(); k++) {
                  sum2 += A.toArray()[i][k] * B.toArray()[k][j];
                }
                result[i][j] = sum2;
              }
            }
            return jStat(result);
          }
          result = [];
          for (i = 0;i < A.rows(); i++) {
            result[i] = [];
            for (j = 0;j < B.cols(); j++) {
              sum2 = 0;
              for (k = 0;k < A.cols(); k++) {
                sum2 += A.toArray()[i][k] * B.toArray()[j];
              }
              result[i][j] = sum2;
            }
          }
          return jStat(result);
        }
      },
      regress: function regress(jMatX, jMatY) {
        var innerinv = jStat.xtranspxinv(jMatX);
        var xtransp = jMatX.transpose();
        var next = jStat.matrixmult(jStat(innerinv), xtransp);
        return jStat.matrixmult(next, jMatY);
      },
      regresst: function regresst(jMatX, jMatY, sides) {
        var beta = jStat.regress(jMatX, jMatY);
        var compile = {};
        compile.anova = {};
        var jMatYBar = jStat.jMatYBar(jMatX, beta);
        compile.yBar = jMatYBar;
        var yAverage = jMatY.mean();
        compile.anova.residuals = jStat.residuals(jMatY, jMatYBar);
        compile.anova.ssr = jStat.ssr(jMatYBar, yAverage);
        compile.anova.msr = compile.anova.ssr / (jMatX[0].length - 1);
        compile.anova.sse = jStat.sse(jMatY, jMatYBar);
        compile.anova.mse = compile.anova.sse / (jMatY.length - (jMatX[0].length - 1) - 1);
        compile.anova.sst = jStat.sst(jMatY, yAverage);
        compile.anova.mst = compile.anova.sst / (jMatY.length - 1);
        compile.anova.r2 = 1 - compile.anova.sse / compile.anova.sst;
        if (compile.anova.r2 < 0)
          compile.anova.r2 = 0;
        compile.anova.fratio = compile.anova.msr / compile.anova.mse;
        compile.anova.pvalue = jStat.anovaftest(compile.anova.fratio, jMatX[0].length - 1, jMatY.length - (jMatX[0].length - 1) - 1);
        compile.anova.rmse = Math.sqrt(compile.anova.mse);
        compile.anova.r2adj = 1 - compile.anova.mse / compile.anova.mst;
        if (compile.anova.r2adj < 0)
          compile.anova.r2adj = 0;
        compile.stats = new Array(jMatX[0].length);
        var covar = jStat.xtranspxinv(jMatX);
        var sds, ts, ps;
        for (var i = 0;i < beta.length; i++) {
          sds = Math.sqrt(compile.anova.mse * Math.abs(covar[i][i]));
          ts = Math.abs(beta[i] / sds);
          ps = jStat.ttest(ts, jMatY.length - jMatX[0].length - 1, sides);
          compile.stats[i] = [beta[i], sds, ts, ps];
        }
        compile.regress = beta;
        return compile;
      },
      xtranspx: function xtranspx(jMatX) {
        return jStat.matrixmult(jMatX.transpose(), jMatX);
      },
      xtranspxinv: function xtranspxinv(jMatX) {
        var inner = jStat.matrixmult(jMatX.transpose(), jMatX);
        var innerinv = jStat.inv(inner);
        return innerinv;
      },
      jMatYBar: function jMatYBar(jMatX, beta) {
        var yBar = jStat.matrixmult(jMatX, beta);
        return new jStat(yBar);
      },
      residuals: function residuals(jMatY, jMatYBar) {
        return jStat.matrixsubtract(jMatY, jMatYBar);
      },
      ssr: function ssr(jMatYBar, yAverage) {
        var ssr = 0;
        for (var i = 0;i < jMatYBar.length; i++) {
          ssr += Math.pow(jMatYBar[i] - yAverage, 2);
        }
        return ssr;
      },
      sse: function sse(jMatY, jMatYBar) {
        var sse = 0;
        for (var i = 0;i < jMatY.length; i++) {
          sse += Math.pow(jMatY[i] - jMatYBar[i], 2);
        }
        return sse;
      },
      sst: function sst(jMatY, yAverage) {
        var sst = 0;
        for (var i = 0;i < jMatY.length; i++) {
          sst += Math.pow(jMatY[i] - yAverage, 2);
        }
        return sst;
      },
      matrixsubtract: function matrixsubtract(A, B) {
        var ans = new Array(A.length);
        for (var i = 0;i < A.length; i++) {
          ans[i] = new Array(A[i].length);
          for (var j = 0;j < A[i].length; j++) {
            ans[i][j] = A[i][j] - B[i][j];
          }
        }
        return jStat(ans);
      }
    });
    jStat.jStat = jStat;
    return jStat;
  });
});

// node_modules/bessel/bessel.js
var require_bessel = __commonJS((exports) => {
  var BESSEL;
  (function(factory) {
    if (typeof DO_NOT_EXPORT_BESSEL === "undefined") {
      if (typeof exports === "object") {
        factory(exports);
      } else if (typeof define === "function" && define.amd) {
        define(function() {
          var module2 = {};
          factory(module2);
          return module2;
        });
      } else {
        factory(BESSEL = {});
      }
    } else {
      factory(BESSEL = {});
    }
  })(function(BESSEL2) {
    BESSEL2.version = "1.0.2";
    var M = Math;
    function _horner(arr, v) {
      for (var i = 0, z2 = 0;i < arr.length; ++i)
        z2 = v * z2 + arr[i];
      return z2;
    }
    function _bessel_iter(x2, n, f0, f1, sign2) {
      if (n === 0)
        return f0;
      if (n === 1)
        return f1;
      var tdx = 2 / x2, f2 = f1;
      for (var o = 1;o < n; ++o) {
        f2 = f1 * o * tdx + sign2 * f0;
        f0 = f1;
        f1 = f2;
      }
      return f2;
    }
    function _bessel_wrap(bessel0, bessel1, name, nonzero, sign2) {
      return function bessel(x2, n) {
        if (nonzero) {
          if (x2 === 0)
            return nonzero == 1 ? -Infinity : Infinity;
          else if (x2 < 0)
            return NaN;
        }
        if (n === 0)
          return bessel0(x2);
        if (n === 1)
          return bessel1(x2);
        if (n < 0)
          return NaN;
        n |= 0;
        var b0 = bessel0(x2), b1 = bessel1(x2);
        return _bessel_iter(x2, n, b0, b1, sign2);
      };
    }
    var besselj = function() {
      var W = 0.636619772;
      var b0_a1a = [57568490574, -13362590354, 651619640.7, -11214424.18, 77392.33017, -184.9052456].reverse();
      var b0_a2a = [57568490411, 1029532985, 9494680.718, 59272.64853, 267.8532712, 1].reverse();
      var b0_a1b = [1, -0.001098628627, 0.00002734510407, -0.000002073370639, 0.0000002093887211].reverse();
      var b0_a2b = [-0.01562499995, 0.0001430488765, -0.000006911147651, 0.0000007621095161, -0.0000000934935152].reverse();
      function bessel0(x2) {
        var a = 0, a1 = 0, a2 = 0, y2 = x2 * x2;
        if (x2 < 8) {
          a1 = _horner(b0_a1a, y2);
          a2 = _horner(b0_a2a, y2);
          a = a1 / a2;
        } else {
          var xx = x2 - 0.785398164;
          y2 = 64 / y2;
          a1 = _horner(b0_a1b, y2);
          a2 = _horner(b0_a2b, y2);
          a = M.sqrt(W / x2) * (M.cos(xx) * a1 - M.sin(xx) * a2 * 8 / x2);
        }
        return a;
      }
      var b1_a1a = [72362614232, -7895059235, 242396853.1, -2972611.439, 15704.4826, -30.16036606].reverse();
      var b1_a2a = [144725228442, 2300535178, 18583304.74, 99447.43394, 376.9991397, 1].reverse();
      var b1_a1b = [1, 0.00183105, -0.00003516396496, 0.000002457520174, -0.000000240337019].reverse();
      var b1_a2b = [0.04687499995, -0.0002002690873, 0.000008449199096, -0.00000088228987, 0.000000105787412].reverse();
      function bessel1(x2) {
        var a = 0, a1 = 0, a2 = 0, y2 = x2 * x2, xx = M.abs(x2) - 2.356194491;
        if (Math.abs(x2) < 8) {
          a1 = x2 * _horner(b1_a1a, y2);
          a2 = _horner(b1_a2a, y2);
          a = a1 / a2;
        } else {
          y2 = 64 / y2;
          a1 = _horner(b1_a1b, y2);
          a2 = _horner(b1_a2b, y2);
          a = M.sqrt(W / M.abs(x2)) * (M.cos(xx) * a1 - M.sin(xx) * a2 * 8 / M.abs(x2));
          if (x2 < 0)
            a = -a;
        }
        return a;
      }
      return function besselj(x2, n) {
        n = Math.round(n);
        if (!isFinite(x2))
          return isNaN(x2) ? x2 : 0;
        if (n < 0)
          return (n % 2 ? -1 : 1) * besselj(x2, -n);
        if (x2 < 0)
          return (n % 2 ? -1 : 1) * besselj(-x2, n);
        if (n === 0)
          return bessel0(x2);
        if (n === 1)
          return bessel1(x2);
        if (x2 === 0)
          return 0;
        var ret = 0;
        if (x2 > n) {
          ret = _bessel_iter(x2, n, bessel0(x2), bessel1(x2), -1);
        } else {
          var m = 2 * M.floor((n + M.floor(M.sqrt(40 * n))) / 2);
          var jsum = false;
          var bjp = 0, sum2 = 0;
          var bj = 1, bjm = 0;
          var tox = 2 / x2;
          for (var j = m;j > 0; j--) {
            bjm = j * tox * bj - bjp;
            bjp = bj;
            bj = bjm;
            if (M.abs(bj) > 10000000000) {
              bj *= 0.0000000001;
              bjp *= 0.0000000001;
              ret *= 0.0000000001;
              sum2 *= 0.0000000001;
            }
            if (jsum)
              sum2 += bj;
            jsum = !jsum;
            if (j == n)
              ret = bjp;
          }
          sum2 = 2 * sum2 - bj;
          ret /= sum2;
        }
        return ret;
      };
    }();
    var bessely = function() {
      var W = 0.636619772;
      var b0_a1a = [-2957821389, 7062834065, -512359803.6, 10879881.29, -86327.92757, 228.4622733].reverse();
      var b0_a2a = [40076544269, 745249964.8, 7189466.438, 47447.2647, 226.1030244, 1].reverse();
      var b0_a1b = [1, -0.001098628627, 0.00002734510407, -0.000002073370639, 0.0000002093887211].reverse();
      var b0_a2b = [-0.01562499995, 0.0001430488765, -0.000006911147651, 0.0000007621095161, -0.0000000934945152].reverse();
      function bessel0(x2) {
        var a = 0, a1 = 0, a2 = 0, y2 = x2 * x2, xx = x2 - 0.785398164;
        if (x2 < 8) {
          a1 = _horner(b0_a1a, y2);
          a2 = _horner(b0_a2a, y2);
          a = a1 / a2 + W * besselj(x2, 0) * M.log(x2);
        } else {
          y2 = 64 / y2;
          a1 = _horner(b0_a1b, y2);
          a2 = _horner(b0_a2b, y2);
          a = M.sqrt(W / x2) * (M.sin(xx) * a1 + M.cos(xx) * a2 * 8 / x2);
        }
        return a;
      }
      var b1_a1a = [-4900604943000, 1275274390000, -51534381390, 734926455.1, -4237922.726, 8511.937935].reverse();
      var b1_a2a = [24995805700000, 424441966400, 3733650367, 22459040.02, 102042.605, 354.9632885, 1].reverse();
      var b1_a1b = [1, 0.00183105, -0.00003516396496, 0.000002457520174, -0.000000240337019].reverse();
      var b1_a2b = [0.04687499995, -0.0002002690873, 0.000008449199096, -0.00000088228987, 0.000000105787412].reverse();
      function bessel1(x2) {
        var a = 0, a1 = 0, a2 = 0, y2 = x2 * x2, xx = x2 - 2.356194491;
        if (x2 < 8) {
          a1 = x2 * _horner(b1_a1a, y2);
          a2 = _horner(b1_a2a, y2);
          a = a1 / a2 + W * (besselj(x2, 1) * M.log(x2) - 1 / x2);
        } else {
          y2 = 64 / y2;
          a1 = _horner(b1_a1b, y2);
          a2 = _horner(b1_a2b, y2);
          a = M.sqrt(W / x2) * (M.sin(xx) * a1 + M.cos(xx) * a2 * 8 / x2);
        }
        return a;
      }
      return _bessel_wrap(bessel0, bessel1, "BESSELY", 1, -1);
    }();
    var besseli = function() {
      var b0_a = [1, 3.5156229, 3.0899424, 1.2067492, 0.2659732, 0.0360768, 0.0045813].reverse();
      var b0_b = [0.39894228, 0.01328592, 0.00225319, -0.00157565, 0.00916281, -0.02057706, 0.02635537, -0.01647633, 0.00392377].reverse();
      function bessel0(x2) {
        if (x2 <= 3.75)
          return _horner(b0_a, x2 * x2 / (3.75 * 3.75));
        return M.exp(M.abs(x2)) / M.sqrt(M.abs(x2)) * _horner(b0_b, 3.75 / M.abs(x2));
      }
      var b1_a = [0.5, 0.87890594, 0.51498869, 0.15084934, 0.02658733, 0.00301532, 0.00032411].reverse();
      var b1_b = [0.39894228, -0.03988024, -0.00362018, 0.00163801, -0.01031555, 0.02282967, -0.02895312, 0.01787654, -0.00420059].reverse();
      function bessel1(x2) {
        if (x2 < 3.75)
          return x2 * _horner(b1_a, x2 * x2 / (3.75 * 3.75));
        return (x2 < 0 ? -1 : 1) * M.exp(M.abs(x2)) / M.sqrt(M.abs(x2)) * _horner(b1_b, 3.75 / M.abs(x2));
      }
      return function besseli(x2, n) {
        n = Math.round(n);
        if (n === 0)
          return bessel0(x2);
        if (n === 1)
          return bessel1(x2);
        if (n < 0)
          return NaN;
        if (M.abs(x2) === 0)
          return 0;
        if (x2 == Infinity)
          return Infinity;
        var ret = 0, j, tox = 2 / M.abs(x2), bip = 0, bi = 1, bim = 0;
        var m = 2 * M.round((n + M.round(M.sqrt(40 * n))) / 2);
        for (j = m;j > 0; j--) {
          bim = j * tox * bi + bip;
          bip = bi;
          bi = bim;
          if (M.abs(bi) > 10000000000) {
            bi *= 0.0000000001;
            bip *= 0.0000000001;
            ret *= 0.0000000001;
          }
          if (j == n)
            ret = bip;
        }
        ret *= besseli(x2, 0) / bi;
        return x2 < 0 && n % 2 ? -ret : ret;
      };
    }();
    var besselk = function() {
      var b0_a = [-0.57721566, 0.4227842, 0.23069756, 0.0348859, 0.00262698, 0.0001075, 0.0000074].reverse();
      var b0_b = [1.25331414, -0.07832358, 0.02189568, -0.01062446, 0.00587872, -0.0025154, 0.00053208].reverse();
      function bessel0(x2) {
        if (x2 <= 2)
          return -M.log(x2 / 2) * besseli(x2, 0) + _horner(b0_a, x2 * x2 / 4);
        return M.exp(-x2) / M.sqrt(x2) * _horner(b0_b, 2 / x2);
      }
      var b1_a = [1, 0.15443144, -0.67278579, -0.18156897, -0.01919402, -0.00110404, -0.00004686].reverse();
      var b1_b = [1.25331414, 0.23498619, -0.0365562, 0.01504268, -0.00780353, 0.00325614, -0.00068245].reverse();
      function bessel1(x2) {
        if (x2 <= 2)
          return M.log(x2 / 2) * besseli(x2, 1) + 1 / x2 * _horner(b1_a, x2 * x2 / 4);
        return M.exp(-x2) / M.sqrt(x2) * _horner(b1_b, 2 / x2);
      }
      return _bessel_wrap(bessel0, bessel1, "BESSELK", 2, 1);
    }();
    BESSEL2.besselj = besselj;
    BESSEL2.bessely = bessely;
    BESSEL2.besseli = besseli;
    BESSEL2.besselk = besselk;
  });
});

// node_modules/he/he.js
var require_he = __commonJS((exports, module) => {
  /*! https://mths.be/he v1.2.0 by @mathias | MIT license */
  (function(root) {
    var freeExports = typeof exports == "object" && exports;
    var freeModule = typeof module == "object" && module && exports == freeExports && module;
    var freeGlobal = typeof global == "object" && global;
    if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
      root = freeGlobal;
    }
    var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
    var regexAsciiWhitelist = /[\x01-\x7F]/g;
    var regexBmpWhitelist = /[\x01-\t\x0B\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g;
    var regexEncodeNonAscii = /<\u20D2|=\u20E5|>\u20D2|\u205F\u200A|\u219D\u0338|\u2202\u0338|\u2220\u20D2|\u2229\uFE00|\u222A\uFE00|\u223C\u20D2|\u223D\u0331|\u223E\u0333|\u2242\u0338|\u224B\u0338|\u224D\u20D2|\u224E\u0338|\u224F\u0338|\u2250\u0338|\u2261\u20E5|\u2264\u20D2|\u2265\u20D2|\u2266\u0338|\u2267\u0338|\u2268\uFE00|\u2269\uFE00|\u226A\u0338|\u226A\u20D2|\u226B\u0338|\u226B\u20D2|\u227F\u0338|\u2282\u20D2|\u2283\u20D2|\u228A\uFE00|\u228B\uFE00|\u228F\u0338|\u2290\u0338|\u2293\uFE00|\u2294\uFE00|\u22B4\u20D2|\u22B5\u20D2|\u22D8\u0338|\u22D9\u0338|\u22DA\uFE00|\u22DB\uFE00|\u22F5\u0338|\u22F9\u0338|\u2933\u0338|\u29CF\u0338|\u29D0\u0338|\u2A6D\u0338|\u2A70\u0338|\u2A7D\u0338|\u2A7E\u0338|\u2AA1\u0338|\u2AA2\u0338|\u2AAC\uFE00|\u2AAD\uFE00|\u2AAF\u0338|\u2AB0\u0338|\u2AC5\u0338|\u2AC6\u0338|\u2ACB\uFE00|\u2ACC\uFE00|\u2AFD\u20E5|[\xA0-\u0113\u0116-\u0122\u0124-\u012B\u012E-\u014D\u0150-\u017E\u0192\u01B5\u01F5\u0237\u02C6\u02C7\u02D8-\u02DD\u0311\u0391-\u03A1\u03A3-\u03A9\u03B1-\u03C9\u03D1\u03D2\u03D5\u03D6\u03DC\u03DD\u03F0\u03F1\u03F5\u03F6\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E\u045F\u2002-\u2005\u2007-\u2010\u2013-\u2016\u2018-\u201A\u201C-\u201E\u2020-\u2022\u2025\u2026\u2030-\u2035\u2039\u203A\u203E\u2041\u2043\u2044\u204F\u2057\u205F-\u2063\u20AC\u20DB\u20DC\u2102\u2105\u210A-\u2113\u2115-\u211E\u2122\u2124\u2127-\u2129\u212C\u212D\u212F-\u2131\u2133-\u2138\u2145-\u2148\u2153-\u215E\u2190-\u219B\u219D-\u21A7\u21A9-\u21AE\u21B0-\u21B3\u21B5-\u21B7\u21BA-\u21DB\u21DD\u21E4\u21E5\u21F5\u21FD-\u2205\u2207-\u2209\u220B\u220C\u220F-\u2214\u2216-\u2218\u221A\u221D-\u2238\u223A-\u2257\u2259\u225A\u225C\u225F-\u2262\u2264-\u228B\u228D-\u229B\u229D-\u22A5\u22A7-\u22B0\u22B2-\u22BB\u22BD-\u22DB\u22DE-\u22E3\u22E6-\u22F7\u22F9-\u22FE\u2305\u2306\u2308-\u2310\u2312\u2313\u2315\u2316\u231C-\u231F\u2322\u2323\u232D\u232E\u2336\u233D\u233F\u237C\u23B0\u23B1\u23B4-\u23B6\u23DC-\u23DF\u23E2\u23E7\u2423\u24C8\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2550-\u256C\u2580\u2584\u2588\u2591-\u2593\u25A1\u25AA\u25AB\u25AD\u25AE\u25B1\u25B3-\u25B5\u25B8\u25B9\u25BD-\u25BF\u25C2\u25C3\u25CA\u25CB\u25EC\u25EF\u25F8-\u25FC\u2605\u2606\u260E\u2640\u2642\u2660\u2663\u2665\u2666\u266A\u266D-\u266F\u2713\u2717\u2720\u2736\u2758\u2772\u2773\u27C8\u27C9\u27E6-\u27ED\u27F5-\u27FA\u27FC\u27FF\u2902-\u2905\u290C-\u2913\u2916\u2919-\u2920\u2923-\u292A\u2933\u2935-\u2939\u293C\u293D\u2945\u2948-\u294B\u294E-\u2976\u2978\u2979\u297B-\u297F\u2985\u2986\u298B-\u2996\u299A\u299C\u299D\u29A4-\u29B7\u29B9\u29BB\u29BC\u29BE-\u29C5\u29C9\u29CD-\u29D0\u29DC-\u29DE\u29E3-\u29E5\u29EB\u29F4\u29F6\u2A00-\u2A02\u2A04\u2A06\u2A0C\u2A0D\u2A10-\u2A17\u2A22-\u2A27\u2A29\u2A2A\u2A2D-\u2A31\u2A33-\u2A3C\u2A3F\u2A40\u2A42-\u2A4D\u2A50\u2A53-\u2A58\u2A5A-\u2A5D\u2A5F\u2A66\u2A6A\u2A6D-\u2A75\u2A77-\u2A9A\u2A9D-\u2AA2\u2AA4-\u2AB0\u2AB3-\u2AC8\u2ACB\u2ACC\u2ACF-\u2ADB\u2AE4\u2AE6-\u2AE9\u2AEB-\u2AF3\u2AFD\uFB00-\uFB04]|\uD835[\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDCCF\uDD04\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDD6B]/g;
    var encodeMap = { "­": "shy", "‌": "zwnj", "‍": "zwj", "‎": "lrm", "⁣": "ic", "⁢": "it", "⁡": "af", "‏": "rlm", "​": "ZeroWidthSpace", "⁠": "NoBreak", "̑": "DownBreve", "⃛": "tdot", "⃜": "DotDot", "\t": "Tab", "\n": "NewLine", " ": "puncsp", " ": "MediumSpace", " ": "thinsp", " ": "hairsp", " ": "emsp13", " ": "ensp", " ": "emsp14", " ": "emsp", " ": "numsp", " ": "nbsp", "  ": "ThickSpace", "‾": "oline", _: "lowbar", "‐": "dash", "–": "ndash", "—": "mdash", "―": "horbar", ",": "comma", ";": "semi", "⁏": "bsemi", ":": "colon", "⩴": "Colone", "!": "excl", "¡": "iexcl", "?": "quest", "¿": "iquest", ".": "period", "‥": "nldr", "…": "mldr", "·": "middot", "'": "apos", "‘": "lsquo", "’": "rsquo", "‚": "sbquo", "‹": "lsaquo", "›": "rsaquo", '"': "quot", "“": "ldquo", "”": "rdquo", "„": "bdquo", "«": "laquo", "»": "raquo", "(": "lpar", ")": "rpar", "[": "lsqb", "]": "rsqb", "{": "lcub", "}": "rcub", "⌈": "lceil", "⌉": "rceil", "⌊": "lfloor", "⌋": "rfloor", "⦅": "lopar", "⦆": "ropar", "⦋": "lbrke", "⦌": "rbrke", "⦍": "lbrkslu", "⦎": "rbrksld", "⦏": "lbrksld", "⦐": "rbrkslu", "⦑": "langd", "⦒": "rangd", "⦓": "lparlt", "⦔": "rpargt", "⦕": "gtlPar", "⦖": "ltrPar", "⟦": "lobrk", "⟧": "robrk", "⟨": "lang", "⟩": "rang", "⟪": "Lang", "⟫": "Rang", "⟬": "loang", "⟭": "roang", "❲": "lbbrk", "❳": "rbbrk", "‖": "Vert", "§": "sect", "¶": "para", "@": "commat", "*": "ast", "/": "sol", undefined: null, "&": "amp", "#": "num", "%": "percnt", "‰": "permil", "‱": "pertenk", "†": "dagger", "‡": "Dagger", "•": "bull", "⁃": "hybull", "′": "prime", "″": "Prime", "‴": "tprime", "⁗": "qprime", "‵": "bprime", "⁁": "caret", "`": "grave", "´": "acute", "˜": "tilde", "^": "Hat", "¯": "macr", "˘": "breve", "˙": "dot", "¨": "die", "˚": "ring", "˝": "dblac", "¸": "cedil", "˛": "ogon", "ˆ": "circ", "ˇ": "caron", "°": "deg", "©": "copy", "®": "reg", "℗": "copysr", "℘": "wp", "℞": "rx", "℧": "mho", "℩": "iiota", "←": "larr", "↚": "nlarr", "→": "rarr", "↛": "nrarr", "↑": "uarr", "↓": "darr", "↔": "harr", "↮": "nharr", "↕": "varr", "↖": "nwarr", "↗": "nearr", "↘": "searr", "↙": "swarr", "↝": "rarrw", "↝̸": "nrarrw", "↞": "Larr", "↟": "Uarr", "↠": "Rarr", "↡": "Darr", "↢": "larrtl", "↣": "rarrtl", "↤": "mapstoleft", "↥": "mapstoup", "↦": "map", "↧": "mapstodown", "↩": "larrhk", "↪": "rarrhk", "↫": "larrlp", "↬": "rarrlp", "↭": "harrw", "↰": "lsh", "↱": "rsh", "↲": "ldsh", "↳": "rdsh", "↵": "crarr", "↶": "cularr", "↷": "curarr", "↺": "olarr", "↻": "orarr", "↼": "lharu", "↽": "lhard", "↾": "uharr", "↿": "uharl", "⇀": "rharu", "⇁": "rhard", "⇂": "dharr", "⇃": "dharl", "⇄": "rlarr", "⇅": "udarr", "⇆": "lrarr", "⇇": "llarr", "⇈": "uuarr", "⇉": "rrarr", "⇊": "ddarr", "⇋": "lrhar", "⇌": "rlhar", "⇐": "lArr", "⇍": "nlArr", "⇑": "uArr", "⇒": "rArr", "⇏": "nrArr", "⇓": "dArr", "⇔": "iff", "⇎": "nhArr", "⇕": "vArr", "⇖": "nwArr", "⇗": "neArr", "⇘": "seArr", "⇙": "swArr", "⇚": "lAarr", "⇛": "rAarr", "⇝": "zigrarr", "⇤": "larrb", "⇥": "rarrb", "⇵": "duarr", "⇽": "loarr", "⇾": "roarr", "⇿": "hoarr", "∀": "forall", "∁": "comp", "∂": "part", "∂̸": "npart", "∃": "exist", "∄": "nexist", "∅": "empty", "∇": "Del", "∈": "in", "∉": "notin", "∋": "ni", "∌": "notni", "϶": "bepsi", "∏": "prod", "∐": "coprod", "∑": "sum", "+": "plus", "±": "pm", "÷": "div", "×": "times", "<": "lt", "≮": "nlt", "<⃒": "nvlt", "=": "equals", "≠": "ne", "=⃥": "bne", "⩵": "Equal", ">": "gt", "≯": "ngt", ">⃒": "nvgt", "¬": "not", "|": "vert", "¦": "brvbar", "−": "minus", "∓": "mp", "∔": "plusdo", "⁄": "frasl", "∖": "setmn", "∗": "lowast", "∘": "compfn", "√": "Sqrt", "∝": "prop", "∞": "infin", "∟": "angrt", "∠": "ang", "∠⃒": "nang", "∡": "angmsd", "∢": "angsph", "∣": "mid", "∤": "nmid", "∥": "par", "∦": "npar", "∧": "and", "∨": "or", "∩": "cap", "∩︀": "caps", "∪": "cup", "∪︀": "cups", "∫": "int", "∬": "Int", "∭": "tint", "⨌": "qint", "∮": "oint", "∯": "Conint", "∰": "Cconint", "∱": "cwint", "∲": "cwconint", "∳": "awconint", "∴": "there4", "∵": "becaus", "∶": "ratio", "∷": "Colon", "∸": "minusd", "∺": "mDDot", "∻": "homtht", "∼": "sim", "≁": "nsim", "∼⃒": "nvsim", "∽": "bsim", "∽̱": "race", "∾": "ac", "∾̳": "acE", "∿": "acd", "≀": "wr", "≂": "esim", "≂̸": "nesim", "≃": "sime", "≄": "nsime", "≅": "cong", "≇": "ncong", "≆": "simne", "≈": "ap", "≉": "nap", "≊": "ape", "≋": "apid", "≋̸": "napid", "≌": "bcong", "≍": "CupCap", "≭": "NotCupCap", "≍⃒": "nvap", "≎": "bump", "≎̸": "nbump", "≏": "bumpe", "≏̸": "nbumpe", "≐": "doteq", "≐̸": "nedot", "≑": "eDot", "≒": "efDot", "≓": "erDot", "≔": "colone", "≕": "ecolon", "≖": "ecir", "≗": "cire", "≙": "wedgeq", "≚": "veeeq", "≜": "trie", "≟": "equest", "≡": "equiv", "≢": "nequiv", "≡⃥": "bnequiv", "≤": "le", "≰": "nle", "≤⃒": "nvle", "≥": "ge", "≱": "nge", "≥⃒": "nvge", "≦": "lE", "≦̸": "nlE", "≧": "gE", "≧̸": "ngE", "≨︀": "lvnE", "≨": "lnE", "≩": "gnE", "≩︀": "gvnE", "≪": "ll", "≪̸": "nLtv", "≪⃒": "nLt", "≫": "gg", "≫̸": "nGtv", "≫⃒": "nGt", "≬": "twixt", "≲": "lsim", "≴": "nlsim", "≳": "gsim", "≵": "ngsim", "≶": "lg", "≸": "ntlg", "≷": "gl", "≹": "ntgl", "≺": "pr", "⊀": "npr", "≻": "sc", "⊁": "nsc", "≼": "prcue", "⋠": "nprcue", "≽": "sccue", "⋡": "nsccue", "≾": "prsim", "≿": "scsim", "≿̸": "NotSucceedsTilde", "⊂": "sub", "⊄": "nsub", "⊂⃒": "vnsub", "⊃": "sup", "⊅": "nsup", "⊃⃒": "vnsup", "⊆": "sube", "⊈": "nsube", "⊇": "supe", "⊉": "nsupe", "⊊︀": "vsubne", "⊊": "subne", "⊋︀": "vsupne", "⊋": "supne", "⊍": "cupdot", "⊎": "uplus", "⊏": "sqsub", "⊏̸": "NotSquareSubset", "⊐": "sqsup", "⊐̸": "NotSquareSuperset", "⊑": "sqsube", "⋢": "nsqsube", "⊒": "sqsupe", "⋣": "nsqsupe", "⊓": "sqcap", "⊓︀": "sqcaps", "⊔": "sqcup", "⊔︀": "sqcups", "⊕": "oplus", "⊖": "ominus", "⊗": "otimes", "⊘": "osol", "⊙": "odot", "⊚": "ocir", "⊛": "oast", "⊝": "odash", "⊞": "plusb", "⊟": "minusb", "⊠": "timesb", "⊡": "sdotb", "⊢": "vdash", "⊬": "nvdash", "⊣": "dashv", "⊤": "top", "⊥": "bot", "⊧": "models", "⊨": "vDash", "⊭": "nvDash", "⊩": "Vdash", "⊮": "nVdash", "⊪": "Vvdash", "⊫": "VDash", "⊯": "nVDash", "⊰": "prurel", "⊲": "vltri", "⋪": "nltri", "⊳": "vrtri", "⋫": "nrtri", "⊴": "ltrie", "⋬": "nltrie", "⊴⃒": "nvltrie", "⊵": "rtrie", "⋭": "nrtrie", "⊵⃒": "nvrtrie", "⊶": "origof", "⊷": "imof", "⊸": "mumap", "⊹": "hercon", "⊺": "intcal", "⊻": "veebar", "⊽": "barvee", "⊾": "angrtvb", "⊿": "lrtri", "⋀": "Wedge", "⋁": "Vee", "⋂": "xcap", "⋃": "xcup", "⋄": "diam", "⋅": "sdot", "⋆": "Star", "⋇": "divonx", "⋈": "bowtie", "⋉": "ltimes", "⋊": "rtimes", "⋋": "lthree", "⋌": "rthree", "⋍": "bsime", "⋎": "cuvee", "⋏": "cuwed", "⋐": "Sub", "⋑": "Sup", "⋒": "Cap", "⋓": "Cup", "⋔": "fork", "⋕": "epar", "⋖": "ltdot", "⋗": "gtdot", "⋘": "Ll", "⋘̸": "nLl", "⋙": "Gg", "⋙̸": "nGg", "⋚︀": "lesg", "⋚": "leg", "⋛": "gel", "⋛︀": "gesl", "⋞": "cuepr", "⋟": "cuesc", "⋦": "lnsim", "⋧": "gnsim", "⋨": "prnsim", "⋩": "scnsim", "⋮": "vellip", "⋯": "ctdot", "⋰": "utdot", "⋱": "dtdot", "⋲": "disin", "⋳": "isinsv", "⋴": "isins", "⋵": "isindot", "⋵̸": "notindot", "⋶": "notinvc", "⋷": "notinvb", "⋹": "isinE", "⋹̸": "notinE", "⋺": "nisd", "⋻": "xnis", "⋼": "nis", "⋽": "notnivc", "⋾": "notnivb", "⌅": "barwed", "⌆": "Barwed", "⌌": "drcrop", "⌍": "dlcrop", "⌎": "urcrop", "⌏": "ulcrop", "⌐": "bnot", "⌒": "profline", "⌓": "profsurf", "⌕": "telrec", "⌖": "target", "⌜": "ulcorn", "⌝": "urcorn", "⌞": "dlcorn", "⌟": "drcorn", "⌢": "frown", "⌣": "smile", "⌭": "cylcty", "⌮": "profalar", "⌶": "topbot", "⌽": "ovbar", "⌿": "solbar", "⍼": "angzarr", "⎰": "lmoust", "⎱": "rmoust", "⎴": "tbrk", "⎵": "bbrk", "⎶": "bbrktbrk", "⏜": "OverParenthesis", "⏝": "UnderParenthesis", "⏞": "OverBrace", "⏟": "UnderBrace", "⏢": "trpezium", "⏧": "elinters", "␣": "blank", "─": "boxh", "│": "boxv", "┌": "boxdr", "┐": "boxdl", "└": "boxur", "┘": "boxul", "├": "boxvr", "┤": "boxvl", "┬": "boxhd", "┴": "boxhu", "┼": "boxvh", "═": "boxH", "║": "boxV", "╒": "boxdR", "╓": "boxDr", "╔": "boxDR", "╕": "boxdL", "╖": "boxDl", "╗": "boxDL", "╘": "boxuR", "╙": "boxUr", "╚": "boxUR", "╛": "boxuL", "╜": "boxUl", "╝": "boxUL", "╞": "boxvR", "╟": "boxVr", "╠": "boxVR", "╡": "boxvL", "╢": "boxVl", "╣": "boxVL", "╤": "boxHd", "╥": "boxhD", "╦": "boxHD", "╧": "boxHu", "╨": "boxhU", "╩": "boxHU", "╪": "boxvH", "╫": "boxVh", "╬": "boxVH", "▀": "uhblk", "▄": "lhblk", "█": "block", "░": "blk14", "▒": "blk12", "▓": "blk34", "□": "squ", "▪": "squf", "▫": "EmptyVerySmallSquare", "▭": "rect", "▮": "marker", "▱": "fltns", "△": "xutri", "▴": "utrif", "▵": "utri", "▸": "rtrif", "▹": "rtri", "▽": "xdtri", "▾": "dtrif", "▿": "dtri", "◂": "ltrif", "◃": "ltri", "◊": "loz", "○": "cir", "◬": "tridot", "◯": "xcirc", "◸": "ultri", "◹": "urtri", "◺": "lltri", "◻": "EmptySmallSquare", "◼": "FilledSmallSquare", "★": "starf", "☆": "star", "☎": "phone", "♀": "female", "♂": "male", "♠": "spades", "♣": "clubs", "♥": "hearts", "♦": "diams", "♪": "sung", "✓": "check", "✗": "cross", "✠": "malt", "✶": "sext", "❘": "VerticalSeparator", "⟈": "bsolhsub", "⟉": "suphsol", "⟵": "xlarr", "⟶": "xrarr", "⟷": "xharr", "⟸": "xlArr", "⟹": "xrArr", "⟺": "xhArr", "⟼": "xmap", "⟿": "dzigrarr", "⤂": "nvlArr", "⤃": "nvrArr", "⤄": "nvHarr", "⤅": "Map", "⤌": "lbarr", "⤍": "rbarr", "⤎": "lBarr", "⤏": "rBarr", "⤐": "RBarr", "⤑": "DDotrahd", "⤒": "UpArrowBar", "⤓": "DownArrowBar", "⤖": "Rarrtl", "⤙": "latail", "⤚": "ratail", "⤛": "lAtail", "⤜": "rAtail", "⤝": "larrfs", "⤞": "rarrfs", "⤟": "larrbfs", "⤠": "rarrbfs", "⤣": "nwarhk", "⤤": "nearhk", "⤥": "searhk", "⤦": "swarhk", "⤧": "nwnear", "⤨": "toea", "⤩": "tosa", "⤪": "swnwar", "⤳": "rarrc", "⤳̸": "nrarrc", "⤵": "cudarrr", "⤶": "ldca", "⤷": "rdca", "⤸": "cudarrl", "⤹": "larrpl", "⤼": "curarrm", "⤽": "cularrp", "⥅": "rarrpl", "⥈": "harrcir", "⥉": "Uarrocir", "⥊": "lurdshar", "⥋": "ldrushar", "⥎": "LeftRightVector", "⥏": "RightUpDownVector", "⥐": "DownLeftRightVector", "⥑": "LeftUpDownVector", "⥒": "LeftVectorBar", "⥓": "RightVectorBar", "⥔": "RightUpVectorBar", "⥕": "RightDownVectorBar", "⥖": "DownLeftVectorBar", "⥗": "DownRightVectorBar", "⥘": "LeftUpVectorBar", "⥙": "LeftDownVectorBar", "⥚": "LeftTeeVector", "⥛": "RightTeeVector", "⥜": "RightUpTeeVector", "⥝": "RightDownTeeVector", "⥞": "DownLeftTeeVector", "⥟": "DownRightTeeVector", "⥠": "LeftUpTeeVector", "⥡": "LeftDownTeeVector", "⥢": "lHar", "⥣": "uHar", "⥤": "rHar", "⥥": "dHar", "⥦": "luruhar", "⥧": "ldrdhar", "⥨": "ruluhar", "⥩": "rdldhar", "⥪": "lharul", "⥫": "llhard", "⥬": "rharul", "⥭": "lrhard", "⥮": "udhar", "⥯": "duhar", "⥰": "RoundImplies", "⥱": "erarr", "⥲": "simrarr", "⥳": "larrsim", "⥴": "rarrsim", "⥵": "rarrap", "⥶": "ltlarr", "⥸": "gtrarr", "⥹": "subrarr", "⥻": "suplarr", "⥼": "lfisht", "⥽": "rfisht", "⥾": "ufisht", "⥿": "dfisht", "⦚": "vzigzag", "⦜": "vangrt", "⦝": "angrtvbd", "⦤": "ange", "⦥": "range", "⦦": "dwangle", "⦧": "uwangle", "⦨": "angmsdaa", "⦩": "angmsdab", "⦪": "angmsdac", "⦫": "angmsdad", "⦬": "angmsdae", "⦭": "angmsdaf", "⦮": "angmsdag", "⦯": "angmsdah", "⦰": "bemptyv", "⦱": "demptyv", "⦲": "cemptyv", "⦳": "raemptyv", "⦴": "laemptyv", "⦵": "ohbar", "⦶": "omid", "⦷": "opar", "⦹": "operp", "⦻": "olcross", "⦼": "odsold", "⦾": "olcir", "⦿": "ofcir", "⧀": "olt", "⧁": "ogt", "⧂": "cirscir", "⧃": "cirE", "⧄": "solb", "⧅": "bsolb", "⧉": "boxbox", "⧍": "trisb", "⧎": "rtriltri", "⧏": "LeftTriangleBar", "⧏̸": "NotLeftTriangleBar", "⧐": "RightTriangleBar", "⧐̸": "NotRightTriangleBar", "⧜": "iinfin", "⧝": "infintie", "⧞": "nvinfin", "⧣": "eparsl", "⧤": "smeparsl", "⧥": "eqvparsl", "⧫": "lozf", "⧴": "RuleDelayed", "⧶": "dsol", "⨀": "xodot", "⨁": "xoplus", "⨂": "xotime", "⨄": "xuplus", "⨆": "xsqcup", "⨍": "fpartint", "⨐": "cirfnint", "⨑": "awint", "⨒": "rppolint", "⨓": "scpolint", "⨔": "npolint", "⨕": "pointint", "⨖": "quatint", "⨗": "intlarhk", "⨢": "pluscir", "⨣": "plusacir", "⨤": "simplus", "⨥": "plusdu", "⨦": "plussim", "⨧": "plustwo", "⨩": "mcomma", "⨪": "minusdu", "⨭": "loplus", "⨮": "roplus", "⨯": "Cross", "⨰": "timesd", "⨱": "timesbar", "⨳": "smashp", "⨴": "lotimes", "⨵": "rotimes", "⨶": "otimesas", "⨷": "Otimes", "⨸": "odiv", "⨹": "triplus", "⨺": "triminus", "⨻": "tritime", "⨼": "iprod", "⨿": "amalg", "⩀": "capdot", "⩂": "ncup", "⩃": "ncap", "⩄": "capand", "⩅": "cupor", "⩆": "cupcap", "⩇": "capcup", "⩈": "cupbrcap", "⩉": "capbrcup", "⩊": "cupcup", "⩋": "capcap", "⩌": "ccups", "⩍": "ccaps", "⩐": "ccupssm", "⩓": "And", "⩔": "Or", "⩕": "andand", "⩖": "oror", "⩗": "orslope", "⩘": "andslope", "⩚": "andv", "⩛": "orv", "⩜": "andd", "⩝": "ord", "⩟": "wedbar", "⩦": "sdote", "⩪": "simdot", "⩭": "congdot", "⩭̸": "ncongdot", "⩮": "easter", "⩯": "apacir", "⩰": "apE", "⩰̸": "napE", "⩱": "eplus", "⩲": "pluse", "⩳": "Esim", "⩷": "eDDot", "⩸": "equivDD", "⩹": "ltcir", "⩺": "gtcir", "⩻": "ltquest", "⩼": "gtquest", "⩽": "les", "⩽̸": "nles", "⩾": "ges", "⩾̸": "nges", "⩿": "lesdot", "⪀": "gesdot", "⪁": "lesdoto", "⪂": "gesdoto", "⪃": "lesdotor", "⪄": "gesdotol", "⪅": "lap", "⪆": "gap", "⪇": "lne", "⪈": "gne", "⪉": "lnap", "⪊": "gnap", "⪋": "lEg", "⪌": "gEl", "⪍": "lsime", "⪎": "gsime", "⪏": "lsimg", "⪐": "gsiml", "⪑": "lgE", "⪒": "glE", "⪓": "lesges", "⪔": "gesles", "⪕": "els", "⪖": "egs", "⪗": "elsdot", "⪘": "egsdot", "⪙": "el", "⪚": "eg", "⪝": "siml", "⪞": "simg", "⪟": "simlE", "⪠": "simgE", "⪡": "LessLess", "⪡̸": "NotNestedLessLess", "⪢": "GreaterGreater", "⪢̸": "NotNestedGreaterGreater", "⪤": "glj", "⪥": "gla", "⪦": "ltcc", "⪧": "gtcc", "⪨": "lescc", "⪩": "gescc", "⪪": "smt", "⪫": "lat", "⪬": "smte", "⪬︀": "smtes", "⪭": "late", "⪭︀": "lates", "⪮": "bumpE", "⪯": "pre", "⪯̸": "npre", "⪰": "sce", "⪰̸": "nsce", "⪳": "prE", "⪴": "scE", "⪵": "prnE", "⪶": "scnE", "⪷": "prap", "⪸": "scap", "⪹": "prnap", "⪺": "scnap", "⪻": "Pr", "⪼": "Sc", "⪽": "subdot", "⪾": "supdot", "⪿": "subplus", "⫀": "supplus", "⫁": "submult", "⫂": "supmult", "⫃": "subedot", "⫄": "supedot", "⫅": "subE", "⫅̸": "nsubE", "⫆": "supE", "⫆̸": "nsupE", "⫇": "subsim", "⫈": "supsim", "⫋︀": "vsubnE", "⫋": "subnE", "⫌︀": "vsupnE", "⫌": "supnE", "⫏": "csub", "⫐": "csup", "⫑": "csube", "⫒": "csupe", "⫓": "subsup", "⫔": "supsub", "⫕": "subsub", "⫖": "supsup", "⫗": "suphsub", "⫘": "supdsub", "⫙": "forkv", "⫚": "topfork", "⫛": "mlcp", "⫤": "Dashv", "⫦": "Vdashl", "⫧": "Barv", "⫨": "vBar", "⫩": "vBarv", "⫫": "Vbar", "⫬": "Not", "⫭": "bNot", "⫮": "rnmid", "⫯": "cirmid", "⫰": "midcir", "⫱": "topcir", "⫲": "nhpar", "⫳": "parsim", "⫽": "parsl", "⫽⃥": "nparsl", "♭": "flat", "♮": "natur", "♯": "sharp", "¤": "curren", "¢": "cent", $: "dollar", "£": "pound", "¥": "yen", "€": "euro", "¹": "sup1", "½": "half", "⅓": "frac13", "¼": "frac14", "⅕": "frac15", "⅙": "frac16", "⅛": "frac18", "²": "sup2", "⅔": "frac23", "⅖": "frac25", "³": "sup3", "¾": "frac34", "⅗": "frac35", "⅜": "frac38", "⅘": "frac45", "⅚": "frac56", "⅝": "frac58", "⅞": "frac78", "\uD835\uDCB6": "ascr", "\uD835\uDD52": "aopf", "\uD835\uDD1E": "afr", "\uD835\uDD38": "Aopf", "\uD835\uDD04": "Afr", "\uD835\uDC9C": "Ascr", "ª": "ordf", "á": "aacute", "Á": "Aacute", "à": "agrave", "À": "Agrave", "ă": "abreve", "Ă": "Abreve", "â": "acirc", "Â": "Acirc", "å": "aring", "Å": "angst", "ä": "auml", "Ä": "Auml", "ã": "atilde", "Ã": "Atilde", "ą": "aogon", "Ą": "Aogon", "ā": "amacr", "Ā": "Amacr", "æ": "aelig", "Æ": "AElig", "\uD835\uDCB7": "bscr", "\uD835\uDD53": "bopf", "\uD835\uDD1F": "bfr", "\uD835\uDD39": "Bopf", "ℬ": "Bscr", "\uD835\uDD05": "Bfr", "\uD835\uDD20": "cfr", "\uD835\uDCB8": "cscr", "\uD835\uDD54": "copf", "ℭ": "Cfr", "\uD835\uDC9E": "Cscr", "ℂ": "Copf", "ć": "cacute", "Ć": "Cacute", "ĉ": "ccirc", "Ĉ": "Ccirc", "č": "ccaron", "Č": "Ccaron", "ċ": "cdot", "Ċ": "Cdot", "ç": "ccedil", "Ç": "Ccedil", "℅": "incare", "\uD835\uDD21": "dfr", "ⅆ": "dd", "\uD835\uDD55": "dopf", "\uD835\uDCB9": "dscr", "\uD835\uDC9F": "Dscr", "\uD835\uDD07": "Dfr", "ⅅ": "DD", "\uD835\uDD3B": "Dopf", "ď": "dcaron", "Ď": "Dcaron", "đ": "dstrok", "Đ": "Dstrok", "ð": "eth", "Ð": "ETH", "ⅇ": "ee", "ℯ": "escr", "\uD835\uDD22": "efr", "\uD835\uDD56": "eopf", "ℰ": "Escr", "\uD835\uDD08": "Efr", "\uD835\uDD3C": "Eopf", "é": "eacute", "É": "Eacute", "è": "egrave", "È": "Egrave", "ê": "ecirc", "Ê": "Ecirc", "ě": "ecaron", "Ě": "Ecaron", "ë": "euml", "Ë": "Euml", "ė": "edot", "Ė": "Edot", "ę": "eogon", "Ę": "Eogon", "ē": "emacr", "Ē": "Emacr", "\uD835\uDD23": "ffr", "\uD835\uDD57": "fopf", "\uD835\uDCBB": "fscr", "\uD835\uDD09": "Ffr", "\uD835\uDD3D": "Fopf", "ℱ": "Fscr", "ﬀ": "fflig", "ﬃ": "ffilig", "ﬄ": "ffllig", "ﬁ": "filig", fj: "fjlig", "ﬂ": "fllig", "ƒ": "fnof", "ℊ": "gscr", "\uD835\uDD58": "gopf", "\uD835\uDD24": "gfr", "\uD835\uDCA2": "Gscr", "\uD835\uDD3E": "Gopf", "\uD835\uDD0A": "Gfr", "ǵ": "gacute", "ğ": "gbreve", "Ğ": "Gbreve", "ĝ": "gcirc", "Ĝ": "Gcirc", "ġ": "gdot", "Ġ": "Gdot", "Ģ": "Gcedil", "\uD835\uDD25": "hfr", "ℎ": "planckh", "\uD835\uDCBD": "hscr", "\uD835\uDD59": "hopf", "ℋ": "Hscr", "ℌ": "Hfr", "ℍ": "Hopf", "ĥ": "hcirc", "Ĥ": "Hcirc", "ℏ": "hbar", "ħ": "hstrok", "Ħ": "Hstrok", "\uD835\uDD5A": "iopf", "\uD835\uDD26": "ifr", "\uD835\uDCBE": "iscr", "ⅈ": "ii", "\uD835\uDD40": "Iopf", "ℐ": "Iscr", "ℑ": "Im", "í": "iacute", "Í": "Iacute", "ì": "igrave", "Ì": "Igrave", "î": "icirc", "Î": "Icirc", "ï": "iuml", "Ï": "Iuml", "ĩ": "itilde", "Ĩ": "Itilde", "İ": "Idot", "į": "iogon", "Į": "Iogon", "ī": "imacr", "Ī": "Imacr", "ĳ": "ijlig", "Ĳ": "IJlig", "ı": "imath", "\uD835\uDCBF": "jscr", "\uD835\uDD5B": "jopf", "\uD835\uDD27": "jfr", "\uD835\uDCA5": "Jscr", "\uD835\uDD0D": "Jfr", "\uD835\uDD41": "Jopf", "ĵ": "jcirc", "Ĵ": "Jcirc", "ȷ": "jmath", "\uD835\uDD5C": "kopf", "\uD835\uDCC0": "kscr", "\uD835\uDD28": "kfr", "\uD835\uDCA6": "Kscr", "\uD835\uDD42": "Kopf", "\uD835\uDD0E": "Kfr", "ķ": "kcedil", "Ķ": "Kcedil", "\uD835\uDD29": "lfr", "\uD835\uDCC1": "lscr", "ℓ": "ell", "\uD835\uDD5D": "lopf", "ℒ": "Lscr", "\uD835\uDD0F": "Lfr", "\uD835\uDD43": "Lopf", "ĺ": "lacute", "Ĺ": "Lacute", "ľ": "lcaron", "Ľ": "Lcaron", "ļ": "lcedil", "Ļ": "Lcedil", "ł": "lstrok", "Ł": "Lstrok", "ŀ": "lmidot", "Ŀ": "Lmidot", "\uD835\uDD2A": "mfr", "\uD835\uDD5E": "mopf", "\uD835\uDCC2": "mscr", "\uD835\uDD10": "Mfr", "\uD835\uDD44": "Mopf", "ℳ": "Mscr", "\uD835\uDD2B": "nfr", "\uD835\uDD5F": "nopf", "\uD835\uDCC3": "nscr", "ℕ": "Nopf", "\uD835\uDCA9": "Nscr", "\uD835\uDD11": "Nfr", "ń": "nacute", "Ń": "Nacute", "ň": "ncaron", "Ň": "Ncaron", "ñ": "ntilde", "Ñ": "Ntilde", "ņ": "ncedil", "Ņ": "Ncedil", "№": "numero", "ŋ": "eng", "Ŋ": "ENG", "\uD835\uDD60": "oopf", "\uD835\uDD2C": "ofr", "ℴ": "oscr", "\uD835\uDCAA": "Oscr", "\uD835\uDD12": "Ofr", "\uD835\uDD46": "Oopf", "º": "ordm", "ó": "oacute", "Ó": "Oacute", "ò": "ograve", "Ò": "Ograve", "ô": "ocirc", "Ô": "Ocirc", "ö": "ouml", "Ö": "Ouml", "ő": "odblac", "Ő": "Odblac", "õ": "otilde", "Õ": "Otilde", "ø": "oslash", "Ø": "Oslash", "ō": "omacr", "Ō": "Omacr", "œ": "oelig", "Œ": "OElig", "\uD835\uDD2D": "pfr", "\uD835\uDCC5": "pscr", "\uD835\uDD61": "popf", "ℙ": "Popf", "\uD835\uDD13": "Pfr", "\uD835\uDCAB": "Pscr", "\uD835\uDD62": "qopf", "\uD835\uDD2E": "qfr", "\uD835\uDCC6": "qscr", "\uD835\uDCAC": "Qscr", "\uD835\uDD14": "Qfr", "ℚ": "Qopf", "ĸ": "kgreen", "\uD835\uDD2F": "rfr", "\uD835\uDD63": "ropf", "\uD835\uDCC7": "rscr", "ℛ": "Rscr", "ℜ": "Re", "ℝ": "Ropf", "ŕ": "racute", "Ŕ": "Racute", "ř": "rcaron", "Ř": "Rcaron", "ŗ": "rcedil", "Ŗ": "Rcedil", "\uD835\uDD64": "sopf", "\uD835\uDCC8": "sscr", "\uD835\uDD30": "sfr", "\uD835\uDD4A": "Sopf", "\uD835\uDD16": "Sfr", "\uD835\uDCAE": "Sscr", "Ⓢ": "oS", "ś": "sacute", "Ś": "Sacute", "ŝ": "scirc", "Ŝ": "Scirc", "š": "scaron", "Š": "Scaron", "ş": "scedil", "Ş": "Scedil", "ß": "szlig", "\uD835\uDD31": "tfr", "\uD835\uDCC9": "tscr", "\uD835\uDD65": "topf", "\uD835\uDCAF": "Tscr", "\uD835\uDD17": "Tfr", "\uD835\uDD4B": "Topf", "ť": "tcaron", "Ť": "Tcaron", "ţ": "tcedil", "Ţ": "Tcedil", "™": "trade", "ŧ": "tstrok", "Ŧ": "Tstrok", "\uD835\uDCCA": "uscr", "\uD835\uDD66": "uopf", "\uD835\uDD32": "ufr", "\uD835\uDD4C": "Uopf", "\uD835\uDD18": "Ufr", "\uD835\uDCB0": "Uscr", "ú": "uacute", "Ú": "Uacute", "ù": "ugrave", "Ù": "Ugrave", "ŭ": "ubreve", "Ŭ": "Ubreve", "û": "ucirc", "Û": "Ucirc", "ů": "uring", "Ů": "Uring", "ü": "uuml", "Ü": "Uuml", "ű": "udblac", "Ű": "Udblac", "ũ": "utilde", "Ũ": "Utilde", "ų": "uogon", "Ų": "Uogon", "ū": "umacr", "Ū": "Umacr", "\uD835\uDD33": "vfr", "\uD835\uDD67": "vopf", "\uD835\uDCCB": "vscr", "\uD835\uDD19": "Vfr", "\uD835\uDD4D": "Vopf", "\uD835\uDCB1": "Vscr", "\uD835\uDD68": "wopf", "\uD835\uDCCC": "wscr", "\uD835\uDD34": "wfr", "\uD835\uDCB2": "Wscr", "\uD835\uDD4E": "Wopf", "\uD835\uDD1A": "Wfr", "ŵ": "wcirc", "Ŵ": "Wcirc", "\uD835\uDD35": "xfr", "\uD835\uDCCD": "xscr", "\uD835\uDD69": "xopf", "\uD835\uDD4F": "Xopf", "\uD835\uDD1B": "Xfr", "\uD835\uDCB3": "Xscr", "\uD835\uDD36": "yfr", "\uD835\uDCCE": "yscr", "\uD835\uDD6A": "yopf", "\uD835\uDCB4": "Yscr", "\uD835\uDD1C": "Yfr", "\uD835\uDD50": "Yopf", "ý": "yacute", "Ý": "Yacute", "ŷ": "ycirc", "Ŷ": "Ycirc", "ÿ": "yuml", "Ÿ": "Yuml", "\uD835\uDCCF": "zscr", "\uD835\uDD37": "zfr", "\uD835\uDD6B": "zopf", "ℨ": "Zfr", "ℤ": "Zopf", "\uD835\uDCB5": "Zscr", "ź": "zacute", "Ź": "Zacute", "ž": "zcaron", "Ž": "Zcaron", "ż": "zdot", "Ż": "Zdot", "Ƶ": "imped", "þ": "thorn", "Þ": "THORN", "ŉ": "napos", "α": "alpha", "Α": "Alpha", "β": "beta", "Β": "Beta", "γ": "gamma", "Γ": "Gamma", "δ": "delta", "Δ": "Delta", "ε": "epsi", "ϵ": "epsiv", "Ε": "Epsilon", "ϝ": "gammad", "Ϝ": "Gammad", "ζ": "zeta", "Ζ": "Zeta", "η": "eta", "Η": "Eta", "θ": "theta", "ϑ": "thetav", "Θ": "Theta", "ι": "iota", "Ι": "Iota", "κ": "kappa", "ϰ": "kappav", "Κ": "Kappa", "λ": "lambda", "Λ": "Lambda", "μ": "mu", "µ": "micro", "Μ": "Mu", "ν": "nu", "Ν": "Nu", "ξ": "xi", "Ξ": "Xi", "ο": "omicron", "Ο": "Omicron", "π": "pi", "ϖ": "piv", "Π": "Pi", "ρ": "rho", "ϱ": "rhov", "Ρ": "Rho", "σ": "sigma", "Σ": "Sigma", "ς": "sigmaf", "τ": "tau", "Τ": "Tau", "υ": "upsi", "Υ": "Upsilon", "ϒ": "Upsi", "φ": "phi", "ϕ": "phiv", "Φ": "Phi", "χ": "chi", "Χ": "Chi", "ψ": "psi", "Ψ": "Psi", "ω": "omega", "Ω": "ohm", "а": "acy", "А": "Acy", "б": "bcy", "Б": "Bcy", "в": "vcy", "В": "Vcy", "г": "gcy", "Г": "Gcy", "ѓ": "gjcy", "Ѓ": "GJcy", "д": "dcy", "Д": "Dcy", "ђ": "djcy", "Ђ": "DJcy", "е": "iecy", "Е": "IEcy", "ё": "iocy", "Ё": "IOcy", "є": "jukcy", "Є": "Jukcy", "ж": "zhcy", "Ж": "ZHcy", "з": "zcy", "З": "Zcy", "ѕ": "dscy", "Ѕ": "DScy", "и": "icy", "И": "Icy", "і": "iukcy", "І": "Iukcy", "ї": "yicy", "Ї": "YIcy", "й": "jcy", "Й": "Jcy", "ј": "jsercy", "Ј": "Jsercy", "к": "kcy", "К": "Kcy", "ќ": "kjcy", "Ќ": "KJcy", "л": "lcy", "Л": "Lcy", "љ": "ljcy", "Љ": "LJcy", "м": "mcy", "М": "Mcy", "н": "ncy", "Н": "Ncy", "њ": "njcy", "Њ": "NJcy", "о": "ocy", "О": "Ocy", "п": "pcy", "П": "Pcy", "р": "rcy", "Р": "Rcy", "с": "scy", "С": "Scy", "т": "tcy", "Т": "Tcy", "ћ": "tshcy", "Ћ": "TSHcy", "у": "ucy", "У": "Ucy", "ў": "ubrcy", "Ў": "Ubrcy", "ф": "fcy", "Ф": "Fcy", "х": "khcy", "Х": "KHcy", "ц": "tscy", "Ц": "TScy", "ч": "chcy", "Ч": "CHcy", "џ": "dzcy", "Џ": "DZcy", "ш": "shcy", "Ш": "SHcy", "щ": "shchcy", "Щ": "SHCHcy", "ъ": "hardcy", "Ъ": "HARDcy", "ы": "ycy", "Ы": "Ycy", "ь": "softcy", "Ь": "SOFTcy", "э": "ecy", "Э": "Ecy", "ю": "yucy", "Ю": "YUcy", "я": "yacy", "Я": "YAcy", "ℵ": "aleph", "ℶ": "beth", "ℷ": "gimel", "ℸ": "daleth" };
    var regexEscape = /["&'<>`]/g;
    var escapeMap = {
      '"': "&quot;",
      "&": "&amp;",
      "'": "&#x27;",
      "<": "&lt;",
      ">": "&gt;",
      "`": "&#x60;"
    };
    var regexInvalidEntity = /&#(?:[xX][^a-fA-F0-9]|[^0-9xX])/;
    var regexInvalidRawCodePoint = /[\0-\x08\x0B\x0E-\x1F\x7F-\x9F\uFDD0-\uFDEF\uFFFE\uFFFF]|[\uD83F\uD87F\uD8BF\uD8FF\uD93F\uD97F\uD9BF\uD9FF\uDA3F\uDA7F\uDABF\uDAFF\uDB3F\uDB7F\uDBBF\uDBFF][\uDFFE\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
    var regexDecode = /&(CounterClockwiseContourIntegral|DoubleLongLeftRightArrow|ClockwiseContourIntegral|NotNestedGreaterGreater|NotSquareSupersetEqual|DiacriticalDoubleAcute|NotRightTriangleEqual|NotSucceedsSlantEqual|NotPrecedesSlantEqual|CloseCurlyDoubleQuote|NegativeVeryThinSpace|DoubleContourIntegral|FilledVerySmallSquare|CapitalDifferentialD|OpenCurlyDoubleQuote|EmptyVerySmallSquare|NestedGreaterGreater|DoubleLongRightArrow|NotLeftTriangleEqual|NotGreaterSlantEqual|ReverseUpEquilibrium|DoubleLeftRightArrow|NotSquareSubsetEqual|NotDoubleVerticalBar|RightArrowLeftArrow|NotGreaterFullEqual|NotRightTriangleBar|SquareSupersetEqual|DownLeftRightVector|DoubleLongLeftArrow|leftrightsquigarrow|LeftArrowRightArrow|NegativeMediumSpace|blacktriangleright|RightDownVectorBar|PrecedesSlantEqual|RightDoubleBracket|SucceedsSlantEqual|NotLeftTriangleBar|RightTriangleEqual|SquareIntersection|RightDownTeeVector|ReverseEquilibrium|NegativeThickSpace|longleftrightarrow|Longleftrightarrow|LongLeftRightArrow|DownRightTeeVector|DownRightVectorBar|GreaterSlantEqual|SquareSubsetEqual|LeftDownVectorBar|LeftDoubleBracket|VerticalSeparator|rightleftharpoons|NotGreaterGreater|NotSquareSuperset|blacktriangleleft|blacktriangledown|NegativeThinSpace|LeftDownTeeVector|NotLessSlantEqual|leftrightharpoons|DoubleUpDownArrow|DoubleVerticalBar|LeftTriangleEqual|FilledSmallSquare|twoheadrightarrow|NotNestedLessLess|DownLeftTeeVector|DownLeftVectorBar|RightAngleBracket|NotTildeFullEqual|NotReverseElement|RightUpDownVector|DiacriticalTilde|NotSucceedsTilde|circlearrowright|NotPrecedesEqual|rightharpoondown|DoubleRightArrow|NotSucceedsEqual|NonBreakingSpace|NotRightTriangle|LessEqualGreater|RightUpTeeVector|LeftAngleBracket|GreaterFullEqual|DownArrowUpArrow|RightUpVectorBar|twoheadleftarrow|GreaterEqualLess|downharpoonright|RightTriangleBar|ntrianglerighteq|NotSupersetEqual|LeftUpDownVector|DiacriticalAcute|rightrightarrows|vartriangleright|UpArrowDownArrow|DiacriticalGrave|UnderParenthesis|EmptySmallSquare|LeftUpVectorBar|leftrightarrows|DownRightVector|downharpoonleft|trianglerighteq|ShortRightArrow|OverParenthesis|DoubleLeftArrow|DoubleDownArrow|NotSquareSubset|bigtriangledown|ntrianglelefteq|UpperRightArrow|curvearrowright|vartriangleleft|NotLeftTriangle|nleftrightarrow|LowerRightArrow|NotHumpDownHump|NotGreaterTilde|rightthreetimes|LeftUpTeeVector|NotGreaterEqual|straightepsilon|LeftTriangleBar|rightsquigarrow|ContourIntegral|rightleftarrows|CloseCurlyQuote|RightDownVector|LeftRightVector|nLeftrightarrow|leftharpoondown|circlearrowleft|SquareSuperset|OpenCurlyQuote|hookrightarrow|HorizontalLine|DiacriticalDot|NotLessGreater|ntriangleright|DoubleRightTee|InvisibleComma|InvisibleTimes|LowerLeftArrow|DownLeftVector|NotSubsetEqual|curvearrowleft|trianglelefteq|NotVerticalBar|TildeFullEqual|downdownarrows|NotGreaterLess|RightTeeVector|ZeroWidthSpace|looparrowright|LongRightArrow|doublebarwedge|ShortLeftArrow|ShortDownArrow|RightVectorBar|GreaterGreater|ReverseElement|rightharpoonup|LessSlantEqual|leftthreetimes|upharpoonright|rightarrowtail|LeftDownVector|Longrightarrow|NestedLessLess|UpperLeftArrow|nshortparallel|leftleftarrows|leftrightarrow|Leftrightarrow|LeftRightArrow|longrightarrow|upharpoonleft|RightArrowBar|ApplyFunction|LeftTeeVector|leftarrowtail|NotEqualTilde|varsubsetneqq|varsupsetneqq|RightTeeArrow|SucceedsEqual|SucceedsTilde|LeftVectorBar|SupersetEqual|hookleftarrow|DifferentialD|VerticalTilde|VeryThinSpace|blacktriangle|bigtriangleup|LessFullEqual|divideontimes|leftharpoonup|UpEquilibrium|ntriangleleft|RightTriangle|measuredangle|shortparallel|longleftarrow|Longleftarrow|LongLeftArrow|DoubleLeftTee|Poincareplane|PrecedesEqual|triangleright|DoubleUpArrow|RightUpVector|fallingdotseq|looparrowleft|PrecedesTilde|NotTildeEqual|NotTildeTilde|smallsetminus|Proportional|triangleleft|triangledown|UnderBracket|NotHumpEqual|exponentiale|ExponentialE|NotLessTilde|HilbertSpace|RightCeiling|blacklozenge|varsupsetneq|HumpDownHump|GreaterEqual|VerticalLine|LeftTeeArrow|NotLessEqual|DownTeeArrow|LeftTriangle|varsubsetneq|Intersection|NotCongruent|DownArrowBar|LeftUpVector|LeftArrowBar|risingdotseq|GreaterTilde|RoundImplies|SquareSubset|ShortUpArrow|NotSuperset|quaternions|precnapprox|backepsilon|preccurlyeq|OverBracket|blacksquare|MediumSpace|VerticalBar|circledcirc|circleddash|CircleMinus|CircleTimes|LessGreater|curlyeqprec|curlyeqsucc|diamondsuit|UpDownArrow|Updownarrow|RuleDelayed|Rrightarrow|updownarrow|RightVector|nRightarrow|nrightarrow|eqslantless|LeftCeiling|Equilibrium|SmallCircle|expectation|NotSucceeds|thickapprox|GreaterLess|SquareUnion|NotPrecedes|NotLessLess|straightphi|succnapprox|succcurlyeq|SubsetEqual|sqsupseteq|Proportion|Laplacetrf|ImaginaryI|supsetneqq|NotGreater|gtreqqless|NotElement|ThickSpace|TildeEqual|TildeTilde|Fouriertrf|rmoustache|EqualTilde|eqslantgtr|UnderBrace|LeftVector|UpArrowBar|nLeftarrow|nsubseteqq|subsetneqq|nsupseteqq|nleftarrow|succapprox|lessapprox|UpTeeArrow|upuparrows|curlywedge|lesseqqgtr|varepsilon|varnothing|RightFloor|complement|CirclePlus|sqsubseteq|Lleftarrow|circledast|RightArrow|Rightarrow|rightarrow|lmoustache|Bernoullis|precapprox|mapstoleft|mapstodown|longmapsto|dotsquare|downarrow|DoubleDot|nsubseteq|supsetneq|leftarrow|nsupseteq|subsetneq|ThinSpace|ngeqslant|subseteqq|HumpEqual|NotSubset|triangleq|NotCupCap|lesseqgtr|heartsuit|TripleDot|Leftarrow|Coproduct|Congruent|varpropto|complexes|gvertneqq|LeftArrow|LessTilde|supseteqq|MinusPlus|CircleDot|nleqslant|NotExists|gtreqless|nparallel|UnionPlus|LeftFloor|checkmark|CenterDot|centerdot|Mellintrf|gtrapprox|bigotimes|OverBrace|spadesuit|therefore|pitchfork|rationals|PlusMinus|Backslash|Therefore|DownBreve|backsimeq|backprime|DownArrow|nshortmid|Downarrow|lvertneqq|eqvparsl|imagline|imagpart|infintie|integers|Integral|intercal|LessLess|Uarrocir|intlarhk|sqsupset|angmsdaf|sqsubset|llcorner|vartheta|cupbrcap|lnapprox|Superset|SuchThat|succnsim|succneqq|angmsdag|biguplus|curlyvee|trpezium|Succeeds|NotTilde|bigwedge|angmsdah|angrtvbd|triminus|cwconint|fpartint|lrcorner|smeparsl|subseteq|urcorner|lurdshar|laemptyv|DDotrahd|approxeq|ldrushar|awconint|mapstoup|backcong|shortmid|triangle|geqslant|gesdotol|timesbar|circledR|circledS|setminus|multimap|naturals|scpolint|ncongdot|RightTee|boxminus|gnapprox|boxtimes|andslope|thicksim|angmsdaa|varsigma|cirfnint|rtriltri|angmsdab|rppolint|angmsdac|barwedge|drbkarow|clubsuit|thetasym|bsolhsub|capbrcup|dzigrarr|doteqdot|DotEqual|dotminus|UnderBar|NotEqual|realpart|otimesas|ulcorner|hksearow|hkswarow|parallel|PartialD|elinters|emptyset|plusacir|bbrktbrk|angmsdad|pointint|bigoplus|angmsdae|Precedes|bigsqcup|varkappa|notindot|supseteq|precneqq|precnsim|profalar|profline|profsurf|leqslant|lesdotor|raemptyv|subplus|notnivb|notnivc|subrarr|zigrarr|vzigzag|submult|subedot|Element|between|cirscir|larrbfs|larrsim|lotimes|lbrksld|lbrkslu|lozenge|ldrdhar|dbkarow|bigcirc|epsilon|simrarr|simplus|ltquest|Epsilon|luruhar|gtquest|maltese|npolint|eqcolon|npreceq|bigodot|ddagger|gtrless|bnequiv|harrcir|ddotseq|equivDD|backsim|demptyv|nsqsube|nsqsupe|Upsilon|nsubset|upsilon|minusdu|nsucceq|swarrow|nsupset|coloneq|searrow|boxplus|napprox|natural|asympeq|alefsym|congdot|nearrow|bigstar|diamond|supplus|tritime|LeftTee|nvinfin|triplus|NewLine|nvltrie|nvrtrie|nwarrow|nexists|Diamond|ruluhar|Implies|supmult|angzarr|suplarr|suphsub|questeq|because|digamma|Because|olcross|bemptyv|omicron|Omicron|rotimes|NoBreak|intprod|angrtvb|orderof|uwangle|suphsol|lesdoto|orslope|DownTee|realine|cudarrl|rdldhar|OverBar|supedot|lessdot|supdsub|topfork|succsim|rbrkslu|rbrksld|pertenk|cudarrr|isindot|planckh|lessgtr|pluscir|gesdoto|plussim|plustwo|lesssim|cularrp|rarrsim|Cayleys|notinva|notinvb|notinvc|UpArrow|Uparrow|uparrow|NotLess|dwangle|precsim|Product|curarrm|Cconint|dotplus|rarrbfs|ccupssm|Cedilla|cemptyv|notniva|quatint|frac35|frac38|frac45|frac56|frac58|frac78|tridot|xoplus|gacute|gammad|Gammad|lfisht|lfloor|bigcup|sqsupe|gbreve|Gbreve|lharul|sqsube|sqcups|Gcedil|apacir|llhard|lmidot|Lmidot|lmoust|andand|sqcaps|approx|Abreve|spades|circeq|tprime|divide|topcir|Assign|topbot|gesdot|divonx|xuplus|timesd|gesles|atilde|solbar|SOFTcy|loplus|timesb|lowast|lowbar|dlcorn|dlcrop|softcy|dollar|lparlt|thksim|lrhard|Atilde|lsaquo|smashp|bigvee|thinsp|wreath|bkarow|lsquor|lstrok|Lstrok|lthree|ltimes|ltlarr|DotDot|simdot|ltrPar|weierp|xsqcup|angmsd|sigmav|sigmaf|zeetrf|Zcaron|zcaron|mapsto|vsupne|thetav|cirmid|marker|mcomma|Zacute|vsubnE|there4|gtlPar|vsubne|bottom|gtrarr|SHCHcy|shchcy|midast|midcir|middot|minusb|minusd|gtrdot|bowtie|sfrown|mnplus|models|colone|seswar|Colone|mstpos|searhk|gtrsim|nacute|Nacute|boxbox|telrec|hairsp|Tcedil|nbumpe|scnsim|ncaron|Ncaron|ncedil|Ncedil|hamilt|Scedil|nearhk|hardcy|HARDcy|tcedil|Tcaron|commat|nequiv|nesear|tcaron|target|hearts|nexist|varrho|scedil|Scaron|scaron|hellip|Sacute|sacute|hercon|swnwar|compfn|rtimes|rthree|rsquor|rsaquo|zacute|wedgeq|homtht|barvee|barwed|Barwed|rpargt|horbar|conint|swarhk|roplus|nltrie|hslash|hstrok|Hstrok|rmoust|Conint|bprime|hybull|hyphen|iacute|Iacute|supsup|supsub|supsim|varphi|coprod|brvbar|agrave|Supset|supset|igrave|Igrave|notinE|Agrave|iiiint|iinfin|copysr|wedbar|Verbar|vangrt|becaus|incare|verbar|inodot|bullet|drcorn|intcal|drcrop|cularr|vellip|Utilde|bumpeq|cupcap|dstrok|Dstrok|CupCap|cupcup|cupdot|eacute|Eacute|supdot|iquest|easter|ecaron|Ecaron|ecolon|isinsv|utilde|itilde|Itilde|curarr|succeq|Bumpeq|cacute|ulcrop|nparsl|Cacute|nprcue|egrave|Egrave|nrarrc|nrarrw|subsup|subsub|nrtrie|jsercy|nsccue|Jsercy|kappav|kcedil|Kcedil|subsim|ulcorn|nsimeq|egsdot|veebar|kgreen|capand|elsdot|Subset|subset|curren|aacute|lacute|Lacute|emptyv|ntilde|Ntilde|lagran|lambda|Lambda|capcap|Ugrave|langle|subdot|emsp13|numero|emsp14|nvdash|nvDash|nVdash|nVDash|ugrave|ufisht|nvHarr|larrfs|nvlArr|larrhk|larrlp|larrpl|nvrArr|Udblac|nwarhk|larrtl|nwnear|oacute|Oacute|latail|lAtail|sstarf|lbrace|odblac|Odblac|lbrack|udblac|odsold|eparsl|lcaron|Lcaron|ograve|Ograve|lcedil|Lcedil|Aacute|ssmile|ssetmn|squarf|ldquor|capcup|ominus|cylcty|rharul|eqcirc|dagger|rfloor|rfisht|Dagger|daleth|equals|origof|capdot|equest|dcaron|Dcaron|rdquor|oslash|Oslash|otilde|Otilde|otimes|Otimes|urcrop|Ubreve|ubreve|Yacute|Uacute|uacute|Rcedil|rcedil|urcorn|parsim|Rcaron|Vdashl|rcaron|Tstrok|percnt|period|permil|Exists|yacute|rbrack|rbrace|phmmat|ccaron|Ccaron|planck|ccedil|plankv|tstrok|female|plusdo|plusdu|ffilig|plusmn|ffllig|Ccedil|rAtail|dfisht|bernou|ratail|Rarrtl|rarrtl|angsph|rarrpl|rarrlp|rarrhk|xwedge|xotime|forall|ForAll|Vvdash|vsupnE|preceq|bigcap|frac12|frac13|frac14|primes|rarrfs|prnsim|frac15|Square|frac16|square|lesdot|frac18|frac23|propto|prurel|rarrap|rangle|puncsp|frac25|Racute|qprime|racute|lesges|frac34|abreve|AElig|eqsim|utdot|setmn|urtri|Equal|Uring|seArr|uring|searr|dashv|Dashv|mumap|nabla|iogon|Iogon|sdote|sdotb|scsim|napid|napos|equiv|natur|Acirc|dblac|erarr|nbump|iprod|erDot|ucirc|awint|esdot|angrt|ncong|isinE|scnap|Scirc|scirc|ndash|isins|Ubrcy|nearr|neArr|isinv|nedot|ubrcy|acute|Ycirc|iukcy|Iukcy|xutri|nesim|caret|jcirc|Jcirc|caron|twixt|ddarr|sccue|exist|jmath|sbquo|ngeqq|angst|ccaps|lceil|ngsim|UpTee|delta|Delta|rtrif|nharr|nhArr|nhpar|rtrie|jukcy|Jukcy|kappa|rsquo|Kappa|nlarr|nlArr|TSHcy|rrarr|aogon|Aogon|fflig|xrarr|tshcy|ccirc|nleqq|filig|upsih|nless|dharl|nlsim|fjlig|ropar|nltri|dharr|robrk|roarr|fllig|fltns|roang|rnmid|subnE|subne|lAarr|trisb|Ccirc|acirc|ccups|blank|VDash|forkv|Vdash|langd|cedil|blk12|blk14|laquo|strns|diams|notin|vDash|larrb|blk34|block|disin|uplus|vdash|vBarv|aelig|starf|Wedge|check|xrArr|lates|lbarr|lBarr|notni|lbbrk|bcong|frasl|lbrke|frown|vrtri|vprop|vnsup|gamma|Gamma|wedge|xodot|bdquo|srarr|doteq|ldquo|boxdl|boxdL|gcirc|Gcirc|boxDl|boxDL|boxdr|boxdR|boxDr|TRADE|trade|rlhar|boxDR|vnsub|npart|vltri|rlarr|boxhd|boxhD|nprec|gescc|nrarr|nrArr|boxHd|boxHD|boxhu|boxhU|nrtri|boxHu|clubs|boxHU|times|colon|Colon|gimel|xlArr|Tilde|nsime|tilde|nsmid|nspar|THORN|thorn|xlarr|nsube|nsubE|thkap|xhArr|comma|nsucc|boxul|boxuL|nsupe|nsupE|gneqq|gnsim|boxUl|boxUL|grave|boxur|boxuR|boxUr|boxUR|lescc|angle|bepsi|boxvh|varpi|boxvH|numsp|Theta|gsime|gsiml|theta|boxVh|boxVH|boxvl|gtcir|gtdot|boxvL|boxVl|boxVL|crarr|cross|Cross|nvsim|boxvr|nwarr|nwArr|sqsup|dtdot|Uogon|lhard|lharu|dtrif|ocirc|Ocirc|lhblk|duarr|odash|sqsub|Hacek|sqcup|llarr|duhar|oelig|OElig|ofcir|boxvR|uogon|lltri|boxVr|csube|uuarr|ohbar|csupe|ctdot|olarr|olcir|harrw|oline|sqcap|omacr|Omacr|omega|Omega|boxVR|aleph|lneqq|lnsim|loang|loarr|rharu|lobrk|hcirc|operp|oplus|rhard|Hcirc|orarr|Union|order|ecirc|Ecirc|cuepr|szlig|cuesc|breve|reals|eDDot|Breve|hoarr|lopar|utrif|rdquo|Umacr|umacr|efDot|swArr|ultri|alpha|rceil|ovbar|swarr|Wcirc|wcirc|smtes|smile|bsemi|lrarr|aring|parsl|lrhar|bsime|uhblk|lrtri|cupor|Aring|uharr|uharl|slarr|rbrke|bsolb|lsime|rbbrk|RBarr|lsimg|phone|rBarr|rbarr|icirc|lsquo|Icirc|emacr|Emacr|ratio|simne|plusb|simlE|simgE|simeq|pluse|ltcir|ltdot|empty|xharr|xdtri|iexcl|Alpha|ltrie|rarrw|pound|ltrif|xcirc|bumpe|prcue|bumpE|asymp|amacr|cuvee|Sigma|sigma|iiint|udhar|iiota|ijlig|IJlig|supnE|imacr|Imacr|prime|Prime|image|prnap|eogon|Eogon|rarrc|mdash|mDDot|cuwed|imath|supne|imped|Amacr|udarr|prsim|micro|rarrb|cwint|raquo|infin|eplus|range|rangd|Ucirc|radic|minus|amalg|veeeq|rAarr|epsiv|ycirc|quest|sharp|quot|zwnj|Qscr|race|qscr|Qopf|qopf|qint|rang|Rang|Zscr|zscr|Zopf|zopf|rarr|rArr|Rarr|Pscr|pscr|prop|prod|prnE|prec|ZHcy|zhcy|prap|Zeta|zeta|Popf|popf|Zdot|plus|zdot|Yuml|yuml|phiv|YUcy|yucy|Yscr|yscr|perp|Yopf|yopf|part|para|YIcy|Ouml|rcub|yicy|YAcy|rdca|ouml|osol|Oscr|rdsh|yacy|real|oscr|xvee|andd|rect|andv|Xscr|oror|ordm|ordf|xscr|ange|aopf|Aopf|rHar|Xopf|opar|Oopf|xopf|xnis|rhov|oopf|omid|xmap|oint|apid|apos|ogon|ascr|Ascr|odot|odiv|xcup|xcap|ocir|oast|nvlt|nvle|nvgt|nvge|nvap|Wscr|wscr|auml|ntlg|ntgl|nsup|nsub|nsim|Nscr|nscr|nsce|Wopf|ring|npre|wopf|npar|Auml|Barv|bbrk|Nopf|nopf|nmid|nLtv|beta|ropf|Ropf|Beta|beth|nles|rpar|nleq|bnot|bNot|nldr|NJcy|rscr|Rscr|Vscr|vscr|rsqb|njcy|bopf|nisd|Bopf|rtri|Vopf|nGtv|ngtr|vopf|boxh|boxH|boxv|nges|ngeq|boxV|bscr|scap|Bscr|bsim|Vert|vert|bsol|bull|bump|caps|cdot|ncup|scnE|ncap|nbsp|napE|Cdot|cent|sdot|Vbar|nang|vBar|chcy|Mscr|mscr|sect|semi|CHcy|Mopf|mopf|sext|circ|cire|mldr|mlcp|cirE|comp|shcy|SHcy|vArr|varr|cong|copf|Copf|copy|COPY|malt|male|macr|lvnE|cscr|ltri|sime|ltcc|simg|Cscr|siml|csub|Uuml|lsqb|lsim|uuml|csup|Lscr|lscr|utri|smid|lpar|cups|smte|lozf|darr|Lopf|Uscr|solb|lopf|sopf|Sopf|lneq|uscr|spar|dArr|lnap|Darr|dash|Sqrt|LJcy|ljcy|lHar|dHar|Upsi|upsi|diam|lesg|djcy|DJcy|leqq|dopf|Dopf|dscr|Dscr|dscy|ldsh|ldca|squf|DScy|sscr|Sscr|dsol|lcub|late|star|Star|Uopf|Larr|lArr|larr|uopf|dtri|dzcy|sube|subE|Lang|lang|Kscr|kscr|Kopf|kopf|KJcy|kjcy|KHcy|khcy|DZcy|ecir|edot|eDot|Jscr|jscr|succ|Jopf|jopf|Edot|uHar|emsp|ensp|Iuml|iuml|eopf|isin|Iscr|iscr|Eopf|epar|sung|epsi|escr|sup1|sup2|sup3|Iota|iota|supe|supE|Iopf|iopf|IOcy|iocy|Escr|esim|Esim|imof|Uarr|QUOT|uArr|uarr|euml|IEcy|iecy|Idot|Euml|euro|excl|Hscr|hscr|Hopf|hopf|TScy|tscy|Tscr|hbar|tscr|flat|tbrk|fnof|hArr|harr|half|fopf|Fopf|tdot|gvnE|fork|trie|gtcc|fscr|Fscr|gdot|gsim|Gscr|gscr|Gopf|gopf|gneq|Gdot|tosa|gnap|Topf|topf|geqq|toea|GJcy|gjcy|tint|gesl|mid|Sfr|ggg|top|ges|gla|glE|glj|geq|gne|gEl|gel|gnE|Gcy|gcy|gap|Tfr|tfr|Tcy|tcy|Hat|Tau|Ffr|tau|Tab|hfr|Hfr|ffr|Fcy|fcy|icy|Icy|iff|ETH|eth|ifr|Ifr|Eta|eta|int|Int|Sup|sup|ucy|Ucy|Sum|sum|jcy|ENG|ufr|Ufr|eng|Jcy|jfr|els|ell|egs|Efr|efr|Jfr|uml|kcy|Kcy|Ecy|ecy|kfr|Kfr|lap|Sub|sub|lat|lcy|Lcy|leg|Dot|dot|lEg|leq|les|squ|div|die|lfr|Lfr|lgE|Dfr|dfr|Del|deg|Dcy|dcy|lne|lnE|sol|loz|smt|Cup|lrm|cup|lsh|Lsh|sim|shy|map|Map|mcy|Mcy|mfr|Mfr|mho|gfr|Gfr|sfr|cir|Chi|chi|nap|Cfr|vcy|Vcy|cfr|Scy|scy|ncy|Ncy|vee|Vee|Cap|cap|nfr|scE|sce|Nfr|nge|ngE|nGg|vfr|Vfr|ngt|bot|nGt|nis|niv|Rsh|rsh|nle|nlE|bne|Bfr|bfr|nLl|nlt|nLt|Bcy|bcy|not|Not|rlm|wfr|Wfr|npr|nsc|num|ocy|ast|Ocy|ofr|xfr|Xfr|Ofr|ogt|ohm|apE|olt|Rho|ape|rho|Rfr|rfr|ord|REG|ang|reg|orv|And|and|AMP|Rcy|amp|Afr|ycy|Ycy|yen|yfr|Yfr|rcy|par|pcy|Pcy|pfr|Pfr|phi|Phi|afr|Acy|acy|zcy|Zcy|piv|acE|acd|zfr|Zfr|pre|prE|psi|Psi|qfr|Qfr|zwj|Or|ge|Gg|gt|gg|el|oS|lt|Lt|LT|Re|lg|gl|eg|ne|Im|it|le|DD|wp|wr|nu|Nu|dd|lE|Sc|sc|pi|Pi|ee|af|ll|Ll|rx|gE|xi|pm|Xi|ic|pr|Pr|in|ni|mp|mu|ac|Mu|or|ap|Gt|GT|ii);|&(Aacute|Agrave|Atilde|Ccedil|Eacute|Egrave|Iacute|Igrave|Ntilde|Oacute|Ograve|Oslash|Otilde|Uacute|Ugrave|Yacute|aacute|agrave|atilde|brvbar|ccedil|curren|divide|eacute|egrave|frac12|frac14|frac34|iacute|igrave|iquest|middot|ntilde|oacute|ograve|oslash|otilde|plusmn|uacute|ugrave|yacute|AElig|Acirc|Aring|Ecirc|Icirc|Ocirc|THORN|Ucirc|acirc|acute|aelig|aring|cedil|ecirc|icirc|iexcl|laquo|micro|ocirc|pound|raquo|szlig|thorn|times|ucirc|Auml|COPY|Euml|Iuml|Ouml|QUOT|Uuml|auml|cent|copy|euml|iuml|macr|nbsp|ordf|ordm|ouml|para|quot|sect|sup1|sup2|sup3|uuml|yuml|AMP|ETH|REG|amp|deg|eth|not|reg|shy|uml|yen|GT|LT|gt|lt)(?!;)([=a-zA-Z0-9]?)|&#([0-9]+)(;?)|&#[xX]([a-fA-F0-9]+)(;?)|&([0-9a-zA-Z]+)/g;
    var decodeMap = { aacute: "á", Aacute: "Á", abreve: "ă", Abreve: "Ă", ac: "∾", acd: "∿", acE: "∾̳", acirc: "â", Acirc: "Â", acute: "´", acy: "а", Acy: "А", aelig: "æ", AElig: "Æ", af: "⁡", afr: "\uD835\uDD1E", Afr: "\uD835\uDD04", agrave: "à", Agrave: "À", alefsym: "ℵ", aleph: "ℵ", alpha: "α", Alpha: "Α", amacr: "ā", Amacr: "Ā", amalg: "⨿", amp: "&", AMP: "&", and: "∧", And: "⩓", andand: "⩕", andd: "⩜", andslope: "⩘", andv: "⩚", ang: "∠", ange: "⦤", angle: "∠", angmsd: "∡", angmsdaa: "⦨", angmsdab: "⦩", angmsdac: "⦪", angmsdad: "⦫", angmsdae: "⦬", angmsdaf: "⦭", angmsdag: "⦮", angmsdah: "⦯", angrt: "∟", angrtvb: "⊾", angrtvbd: "⦝", angsph: "∢", angst: "Å", angzarr: "⍼", aogon: "ą", Aogon: "Ą", aopf: "\uD835\uDD52", Aopf: "\uD835\uDD38", ap: "≈", apacir: "⩯", ape: "≊", apE: "⩰", apid: "≋", apos: "'", ApplyFunction: "⁡", approx: "≈", approxeq: "≊", aring: "å", Aring: "Å", ascr: "\uD835\uDCB6", Ascr: "\uD835\uDC9C", Assign: "≔", ast: "*", asymp: "≈", asympeq: "≍", atilde: "ã", Atilde: "Ã", auml: "ä", Auml: "Ä", awconint: "∳", awint: "⨑", backcong: "≌", backepsilon: "϶", backprime: "‵", backsim: "∽", backsimeq: "⋍", Backslash: "∖", Barv: "⫧", barvee: "⊽", barwed: "⌅", Barwed: "⌆", barwedge: "⌅", bbrk: "⎵", bbrktbrk: "⎶", bcong: "≌", bcy: "б", Bcy: "Б", bdquo: "„", becaus: "∵", because: "∵", Because: "∵", bemptyv: "⦰", bepsi: "϶", bernou: "ℬ", Bernoullis: "ℬ", beta: "β", Beta: "Β", beth: "ℶ", between: "≬", bfr: "\uD835\uDD1F", Bfr: "\uD835\uDD05", bigcap: "⋂", bigcirc: "◯", bigcup: "⋃", bigodot: "⨀", bigoplus: "⨁", bigotimes: "⨂", bigsqcup: "⨆", bigstar: "★", bigtriangledown: "▽", bigtriangleup: "△", biguplus: "⨄", bigvee: "⋁", bigwedge: "⋀", bkarow: "⤍", blacklozenge: "⧫", blacksquare: "▪", blacktriangle: "▴", blacktriangledown: "▾", blacktriangleleft: "◂", blacktriangleright: "▸", blank: "␣", blk12: "▒", blk14: "░", blk34: "▓", block: "█", bne: "=⃥", bnequiv: "≡⃥", bnot: "⌐", bNot: "⫭", bopf: "\uD835\uDD53", Bopf: "\uD835\uDD39", bot: "⊥", bottom: "⊥", bowtie: "⋈", boxbox: "⧉", boxdl: "┐", boxdL: "╕", boxDl: "╖", boxDL: "╗", boxdr: "┌", boxdR: "╒", boxDr: "╓", boxDR: "╔", boxh: "─", boxH: "═", boxhd: "┬", boxhD: "╥", boxHd: "╤", boxHD: "╦", boxhu: "┴", boxhU: "╨", boxHu: "╧", boxHU: "╩", boxminus: "⊟", boxplus: "⊞", boxtimes: "⊠", boxul: "┘", boxuL: "╛", boxUl: "╜", boxUL: "╝", boxur: "└", boxuR: "╘", boxUr: "╙", boxUR: "╚", boxv: "│", boxV: "║", boxvh: "┼", boxvH: "╪", boxVh: "╫", boxVH: "╬", boxvl: "┤", boxvL: "╡", boxVl: "╢", boxVL: "╣", boxvr: "├", boxvR: "╞", boxVr: "╟", boxVR: "╠", bprime: "‵", breve: "˘", Breve: "˘", brvbar: "¦", bscr: "\uD835\uDCB7", Bscr: "ℬ", bsemi: "⁏", bsim: "∽", bsime: "⋍", bsol: "\\", bsolb: "⧅", bsolhsub: "⟈", bull: "•", bullet: "•", bump: "≎", bumpe: "≏", bumpE: "⪮", bumpeq: "≏", Bumpeq: "≎", cacute: "ć", Cacute: "Ć", cap: "∩", Cap: "⋒", capand: "⩄", capbrcup: "⩉", capcap: "⩋", capcup: "⩇", capdot: "⩀", CapitalDifferentialD: "ⅅ", caps: "∩︀", caret: "⁁", caron: "ˇ", Cayleys: "ℭ", ccaps: "⩍", ccaron: "č", Ccaron: "Č", ccedil: "ç", Ccedil: "Ç", ccirc: "ĉ", Ccirc: "Ĉ", Cconint: "∰", ccups: "⩌", ccupssm: "⩐", cdot: "ċ", Cdot: "Ċ", cedil: "¸", Cedilla: "¸", cemptyv: "⦲", cent: "¢", centerdot: "·", CenterDot: "·", cfr: "\uD835\uDD20", Cfr: "ℭ", chcy: "ч", CHcy: "Ч", check: "✓", checkmark: "✓", chi: "χ", Chi: "Χ", cir: "○", circ: "ˆ", circeq: "≗", circlearrowleft: "↺", circlearrowright: "↻", circledast: "⊛", circledcirc: "⊚", circleddash: "⊝", CircleDot: "⊙", circledR: "®", circledS: "Ⓢ", CircleMinus: "⊖", CirclePlus: "⊕", CircleTimes: "⊗", cire: "≗", cirE: "⧃", cirfnint: "⨐", cirmid: "⫯", cirscir: "⧂", ClockwiseContourIntegral: "∲", CloseCurlyDoubleQuote: "”", CloseCurlyQuote: "’", clubs: "♣", clubsuit: "♣", colon: ":", Colon: "∷", colone: "≔", Colone: "⩴", coloneq: "≔", comma: ",", commat: "@", comp: "∁", compfn: "∘", complement: "∁", complexes: "ℂ", cong: "≅", congdot: "⩭", Congruent: "≡", conint: "∮", Conint: "∯", ContourIntegral: "∮", copf: "\uD835\uDD54", Copf: "ℂ", coprod: "∐", Coproduct: "∐", copy: "©", COPY: "©", copysr: "℗", CounterClockwiseContourIntegral: "∳", crarr: "↵", cross: "✗", Cross: "⨯", cscr: "\uD835\uDCB8", Cscr: "\uD835\uDC9E", csub: "⫏", csube: "⫑", csup: "⫐", csupe: "⫒", ctdot: "⋯", cudarrl: "⤸", cudarrr: "⤵", cuepr: "⋞", cuesc: "⋟", cularr: "↶", cularrp: "⤽", cup: "∪", Cup: "⋓", cupbrcap: "⩈", cupcap: "⩆", CupCap: "≍", cupcup: "⩊", cupdot: "⊍", cupor: "⩅", cups: "∪︀", curarr: "↷", curarrm: "⤼", curlyeqprec: "⋞", curlyeqsucc: "⋟", curlyvee: "⋎", curlywedge: "⋏", curren: "¤", curvearrowleft: "↶", curvearrowright: "↷", cuvee: "⋎", cuwed: "⋏", cwconint: "∲", cwint: "∱", cylcty: "⌭", dagger: "†", Dagger: "‡", daleth: "ℸ", darr: "↓", dArr: "⇓", Darr: "↡", dash: "‐", dashv: "⊣", Dashv: "⫤", dbkarow: "⤏", dblac: "˝", dcaron: "ď", Dcaron: "Ď", dcy: "д", Dcy: "Д", dd: "ⅆ", DD: "ⅅ", ddagger: "‡", ddarr: "⇊", DDotrahd: "⤑", ddotseq: "⩷", deg: "°", Del: "∇", delta: "δ", Delta: "Δ", demptyv: "⦱", dfisht: "⥿", dfr: "\uD835\uDD21", Dfr: "\uD835\uDD07", dHar: "⥥", dharl: "⇃", dharr: "⇂", DiacriticalAcute: "´", DiacriticalDot: "˙", DiacriticalDoubleAcute: "˝", DiacriticalGrave: "`", DiacriticalTilde: "˜", diam: "⋄", diamond: "⋄", Diamond: "⋄", diamondsuit: "♦", diams: "♦", die: "¨", DifferentialD: "ⅆ", digamma: "ϝ", disin: "⋲", div: "÷", divide: "÷", divideontimes: "⋇", divonx: "⋇", djcy: "ђ", DJcy: "Ђ", dlcorn: "⌞", dlcrop: "⌍", dollar: "$", dopf: "\uD835\uDD55", Dopf: "\uD835\uDD3B", dot: "˙", Dot: "¨", DotDot: "⃜", doteq: "≐", doteqdot: "≑", DotEqual: "≐", dotminus: "∸", dotplus: "∔", dotsquare: "⊡", doublebarwedge: "⌆", DoubleContourIntegral: "∯", DoubleDot: "¨", DoubleDownArrow: "⇓", DoubleLeftArrow: "⇐", DoubleLeftRightArrow: "⇔", DoubleLeftTee: "⫤", DoubleLongLeftArrow: "⟸", DoubleLongLeftRightArrow: "⟺", DoubleLongRightArrow: "⟹", DoubleRightArrow: "⇒", DoubleRightTee: "⊨", DoubleUpArrow: "⇑", DoubleUpDownArrow: "⇕", DoubleVerticalBar: "∥", downarrow: "↓", Downarrow: "⇓", DownArrow: "↓", DownArrowBar: "⤓", DownArrowUpArrow: "⇵", DownBreve: "̑", downdownarrows: "⇊", downharpoonleft: "⇃", downharpoonright: "⇂", DownLeftRightVector: "⥐", DownLeftTeeVector: "⥞", DownLeftVector: "↽", DownLeftVectorBar: "⥖", DownRightTeeVector: "⥟", DownRightVector: "⇁", DownRightVectorBar: "⥗", DownTee: "⊤", DownTeeArrow: "↧", drbkarow: "⤐", drcorn: "⌟", drcrop: "⌌", dscr: "\uD835\uDCB9", Dscr: "\uD835\uDC9F", dscy: "ѕ", DScy: "Ѕ", dsol: "⧶", dstrok: "đ", Dstrok: "Đ", dtdot: "⋱", dtri: "▿", dtrif: "▾", duarr: "⇵", duhar: "⥯", dwangle: "⦦", dzcy: "џ", DZcy: "Џ", dzigrarr: "⟿", eacute: "é", Eacute: "É", easter: "⩮", ecaron: "ě", Ecaron: "Ě", ecir: "≖", ecirc: "ê", Ecirc: "Ê", ecolon: "≕", ecy: "э", Ecy: "Э", eDDot: "⩷", edot: "ė", eDot: "≑", Edot: "Ė", ee: "ⅇ", efDot: "≒", efr: "\uD835\uDD22", Efr: "\uD835\uDD08", eg: "⪚", egrave: "è", Egrave: "È", egs: "⪖", egsdot: "⪘", el: "⪙", Element: "∈", elinters: "⏧", ell: "ℓ", els: "⪕", elsdot: "⪗", emacr: "ē", Emacr: "Ē", empty: "∅", emptyset: "∅", EmptySmallSquare: "◻", emptyv: "∅", EmptyVerySmallSquare: "▫", emsp: " ", emsp13: " ", emsp14: " ", eng: "ŋ", ENG: "Ŋ", ensp: " ", eogon: "ę", Eogon: "Ę", eopf: "\uD835\uDD56", Eopf: "\uD835\uDD3C", epar: "⋕", eparsl: "⧣", eplus: "⩱", epsi: "ε", epsilon: "ε", Epsilon: "Ε", epsiv: "ϵ", eqcirc: "≖", eqcolon: "≕", eqsim: "≂", eqslantgtr: "⪖", eqslantless: "⪕", Equal: "⩵", equals: "=", EqualTilde: "≂", equest: "≟", Equilibrium: "⇌", equiv: "≡", equivDD: "⩸", eqvparsl: "⧥", erarr: "⥱", erDot: "≓", escr: "ℯ", Escr: "ℰ", esdot: "≐", esim: "≂", Esim: "⩳", eta: "η", Eta: "Η", eth: "ð", ETH: "Ð", euml: "ë", Euml: "Ë", euro: "€", excl: "!", exist: "∃", Exists: "∃", expectation: "ℰ", exponentiale: "ⅇ", ExponentialE: "ⅇ", fallingdotseq: "≒", fcy: "ф", Fcy: "Ф", female: "♀", ffilig: "ﬃ", fflig: "ﬀ", ffllig: "ﬄ", ffr: "\uD835\uDD23", Ffr: "\uD835\uDD09", filig: "ﬁ", FilledSmallSquare: "◼", FilledVerySmallSquare: "▪", fjlig: "fj", flat: "♭", fllig: "ﬂ", fltns: "▱", fnof: "ƒ", fopf: "\uD835\uDD57", Fopf: "\uD835\uDD3D", forall: "∀", ForAll: "∀", fork: "⋔", forkv: "⫙", Fouriertrf: "ℱ", fpartint: "⨍", frac12: "½", frac13: "⅓", frac14: "¼", frac15: "⅕", frac16: "⅙", frac18: "⅛", frac23: "⅔", frac25: "⅖", frac34: "¾", frac35: "⅗", frac38: "⅜", frac45: "⅘", frac56: "⅚", frac58: "⅝", frac78: "⅞", frasl: "⁄", frown: "⌢", fscr: "\uD835\uDCBB", Fscr: "ℱ", gacute: "ǵ", gamma: "γ", Gamma: "Γ", gammad: "ϝ", Gammad: "Ϝ", gap: "⪆", gbreve: "ğ", Gbreve: "Ğ", Gcedil: "Ģ", gcirc: "ĝ", Gcirc: "Ĝ", gcy: "г", Gcy: "Г", gdot: "ġ", Gdot: "Ġ", ge: "≥", gE: "≧", gel: "⋛", gEl: "⪌", geq: "≥", geqq: "≧", geqslant: "⩾", ges: "⩾", gescc: "⪩", gesdot: "⪀", gesdoto: "⪂", gesdotol: "⪄", gesl: "⋛︀", gesles: "⪔", gfr: "\uD835\uDD24", Gfr: "\uD835\uDD0A", gg: "≫", Gg: "⋙", ggg: "⋙", gimel: "ℷ", gjcy: "ѓ", GJcy: "Ѓ", gl: "≷", gla: "⪥", glE: "⪒", glj: "⪤", gnap: "⪊", gnapprox: "⪊", gne: "⪈", gnE: "≩", gneq: "⪈", gneqq: "≩", gnsim: "⋧", gopf: "\uD835\uDD58", Gopf: "\uD835\uDD3E", grave: "`", GreaterEqual: "≥", GreaterEqualLess: "⋛", GreaterFullEqual: "≧", GreaterGreater: "⪢", GreaterLess: "≷", GreaterSlantEqual: "⩾", GreaterTilde: "≳", gscr: "ℊ", Gscr: "\uD835\uDCA2", gsim: "≳", gsime: "⪎", gsiml: "⪐", gt: ">", Gt: "≫", GT: ">", gtcc: "⪧", gtcir: "⩺", gtdot: "⋗", gtlPar: "⦕", gtquest: "⩼", gtrapprox: "⪆", gtrarr: "⥸", gtrdot: "⋗", gtreqless: "⋛", gtreqqless: "⪌", gtrless: "≷", gtrsim: "≳", gvertneqq: "≩︀", gvnE: "≩︀", Hacek: "ˇ", hairsp: " ", half: "½", hamilt: "ℋ", hardcy: "ъ", HARDcy: "Ъ", harr: "↔", hArr: "⇔", harrcir: "⥈", harrw: "↭", Hat: "^", hbar: "ℏ", hcirc: "ĥ", Hcirc: "Ĥ", hearts: "♥", heartsuit: "♥", hellip: "…", hercon: "⊹", hfr: "\uD835\uDD25", Hfr: "ℌ", HilbertSpace: "ℋ", hksearow: "⤥", hkswarow: "⤦", hoarr: "⇿", homtht: "∻", hookleftarrow: "↩", hookrightarrow: "↪", hopf: "\uD835\uDD59", Hopf: "ℍ", horbar: "―", HorizontalLine: "─", hscr: "\uD835\uDCBD", Hscr: "ℋ", hslash: "ℏ", hstrok: "ħ", Hstrok: "Ħ", HumpDownHump: "≎", HumpEqual: "≏", hybull: "⁃", hyphen: "‐", iacute: "í", Iacute: "Í", ic: "⁣", icirc: "î", Icirc: "Î", icy: "и", Icy: "И", Idot: "İ", iecy: "е", IEcy: "Е", iexcl: "¡", iff: "⇔", ifr: "\uD835\uDD26", Ifr: "ℑ", igrave: "ì", Igrave: "Ì", ii: "ⅈ", iiiint: "⨌", iiint: "∭", iinfin: "⧜", iiota: "℩", ijlig: "ĳ", IJlig: "Ĳ", Im: "ℑ", imacr: "ī", Imacr: "Ī", image: "ℑ", ImaginaryI: "ⅈ", imagline: "ℐ", imagpart: "ℑ", imath: "ı", imof: "⊷", imped: "Ƶ", Implies: "⇒", in: "∈", incare: "℅", infin: "∞", infintie: "⧝", inodot: "ı", int: "∫", Int: "∬", intcal: "⊺", integers: "ℤ", Integral: "∫", intercal: "⊺", Intersection: "⋂", intlarhk: "⨗", intprod: "⨼", InvisibleComma: "⁣", InvisibleTimes: "⁢", iocy: "ё", IOcy: "Ё", iogon: "į", Iogon: "Į", iopf: "\uD835\uDD5A", Iopf: "\uD835\uDD40", iota: "ι", Iota: "Ι", iprod: "⨼", iquest: "¿", iscr: "\uD835\uDCBE", Iscr: "ℐ", isin: "∈", isindot: "⋵", isinE: "⋹", isins: "⋴", isinsv: "⋳", isinv: "∈", it: "⁢", itilde: "ĩ", Itilde: "Ĩ", iukcy: "і", Iukcy: "І", iuml: "ï", Iuml: "Ï", jcirc: "ĵ", Jcirc: "Ĵ", jcy: "й", Jcy: "Й", jfr: "\uD835\uDD27", Jfr: "\uD835\uDD0D", jmath: "ȷ", jopf: "\uD835\uDD5B", Jopf: "\uD835\uDD41", jscr: "\uD835\uDCBF", Jscr: "\uD835\uDCA5", jsercy: "ј", Jsercy: "Ј", jukcy: "є", Jukcy: "Є", kappa: "κ", Kappa: "Κ", kappav: "ϰ", kcedil: "ķ", Kcedil: "Ķ", kcy: "к", Kcy: "К", kfr: "\uD835\uDD28", Kfr: "\uD835\uDD0E", kgreen: "ĸ", khcy: "х", KHcy: "Х", kjcy: "ќ", KJcy: "Ќ", kopf: "\uD835\uDD5C", Kopf: "\uD835\uDD42", kscr: "\uD835\uDCC0", Kscr: "\uD835\uDCA6", lAarr: "⇚", lacute: "ĺ", Lacute: "Ĺ", laemptyv: "⦴", lagran: "ℒ", lambda: "λ", Lambda: "Λ", lang: "⟨", Lang: "⟪", langd: "⦑", langle: "⟨", lap: "⪅", Laplacetrf: "ℒ", laquo: "«", larr: "←", lArr: "⇐", Larr: "↞", larrb: "⇤", larrbfs: "⤟", larrfs: "⤝", larrhk: "↩", larrlp: "↫", larrpl: "⤹", larrsim: "⥳", larrtl: "↢", lat: "⪫", latail: "⤙", lAtail: "⤛", late: "⪭", lates: "⪭︀", lbarr: "⤌", lBarr: "⤎", lbbrk: "❲", lbrace: "{", lbrack: "[", lbrke: "⦋", lbrksld: "⦏", lbrkslu: "⦍", lcaron: "ľ", Lcaron: "Ľ", lcedil: "ļ", Lcedil: "Ļ", lceil: "⌈", lcub: "{", lcy: "л", Lcy: "Л", ldca: "⤶", ldquo: "“", ldquor: "„", ldrdhar: "⥧", ldrushar: "⥋", ldsh: "↲", le: "≤", lE: "≦", LeftAngleBracket: "⟨", leftarrow: "←", Leftarrow: "⇐", LeftArrow: "←", LeftArrowBar: "⇤", LeftArrowRightArrow: "⇆", leftarrowtail: "↢", LeftCeiling: "⌈", LeftDoubleBracket: "⟦", LeftDownTeeVector: "⥡", LeftDownVector: "⇃", LeftDownVectorBar: "⥙", LeftFloor: "⌊", leftharpoondown: "↽", leftharpoonup: "↼", leftleftarrows: "⇇", leftrightarrow: "↔", Leftrightarrow: "⇔", LeftRightArrow: "↔", leftrightarrows: "⇆", leftrightharpoons: "⇋", leftrightsquigarrow: "↭", LeftRightVector: "⥎", LeftTee: "⊣", LeftTeeArrow: "↤", LeftTeeVector: "⥚", leftthreetimes: "⋋", LeftTriangle: "⊲", LeftTriangleBar: "⧏", LeftTriangleEqual: "⊴", LeftUpDownVector: "⥑", LeftUpTeeVector: "⥠", LeftUpVector: "↿", LeftUpVectorBar: "⥘", LeftVector: "↼", LeftVectorBar: "⥒", leg: "⋚", lEg: "⪋", leq: "≤", leqq: "≦", leqslant: "⩽", les: "⩽", lescc: "⪨", lesdot: "⩿", lesdoto: "⪁", lesdotor: "⪃", lesg: "⋚︀", lesges: "⪓", lessapprox: "⪅", lessdot: "⋖", lesseqgtr: "⋚", lesseqqgtr: "⪋", LessEqualGreater: "⋚", LessFullEqual: "≦", LessGreater: "≶", lessgtr: "≶", LessLess: "⪡", lesssim: "≲", LessSlantEqual: "⩽", LessTilde: "≲", lfisht: "⥼", lfloor: "⌊", lfr: "\uD835\uDD29", Lfr: "\uD835\uDD0F", lg: "≶", lgE: "⪑", lHar: "⥢", lhard: "↽", lharu: "↼", lharul: "⥪", lhblk: "▄", ljcy: "љ", LJcy: "Љ", ll: "≪", Ll: "⋘", llarr: "⇇", llcorner: "⌞", Lleftarrow: "⇚", llhard: "⥫", lltri: "◺", lmidot: "ŀ", Lmidot: "Ŀ", lmoust: "⎰", lmoustache: "⎰", lnap: "⪉", lnapprox: "⪉", lne: "⪇", lnE: "≨", lneq: "⪇", lneqq: "≨", lnsim: "⋦", loang: "⟬", loarr: "⇽", lobrk: "⟦", longleftarrow: "⟵", Longleftarrow: "⟸", LongLeftArrow: "⟵", longleftrightarrow: "⟷", Longleftrightarrow: "⟺", LongLeftRightArrow: "⟷", longmapsto: "⟼", longrightarrow: "⟶", Longrightarrow: "⟹", LongRightArrow: "⟶", looparrowleft: "↫", looparrowright: "↬", lopar: "⦅", lopf: "\uD835\uDD5D", Lopf: "\uD835\uDD43", loplus: "⨭", lotimes: "⨴", lowast: "∗", lowbar: "_", LowerLeftArrow: "↙", LowerRightArrow: "↘", loz: "◊", lozenge: "◊", lozf: "⧫", lpar: "(", lparlt: "⦓", lrarr: "⇆", lrcorner: "⌟", lrhar: "⇋", lrhard: "⥭", lrm: "‎", lrtri: "⊿", lsaquo: "‹", lscr: "\uD835\uDCC1", Lscr: "ℒ", lsh: "↰", Lsh: "↰", lsim: "≲", lsime: "⪍", lsimg: "⪏", lsqb: "[", lsquo: "‘", lsquor: "‚", lstrok: "ł", Lstrok: "Ł", lt: "<", Lt: "≪", LT: "<", ltcc: "⪦", ltcir: "⩹", ltdot: "⋖", lthree: "⋋", ltimes: "⋉", ltlarr: "⥶", ltquest: "⩻", ltri: "◃", ltrie: "⊴", ltrif: "◂", ltrPar: "⦖", lurdshar: "⥊", luruhar: "⥦", lvertneqq: "≨︀", lvnE: "≨︀", macr: "¯", male: "♂", malt: "✠", maltese: "✠", map: "↦", Map: "⤅", mapsto: "↦", mapstodown: "↧", mapstoleft: "↤", mapstoup: "↥", marker: "▮", mcomma: "⨩", mcy: "м", Mcy: "М", mdash: "—", mDDot: "∺", measuredangle: "∡", MediumSpace: " ", Mellintrf: "ℳ", mfr: "\uD835\uDD2A", Mfr: "\uD835\uDD10", mho: "℧", micro: "µ", mid: "∣", midast: "*", midcir: "⫰", middot: "·", minus: "−", minusb: "⊟", minusd: "∸", minusdu: "⨪", MinusPlus: "∓", mlcp: "⫛", mldr: "…", mnplus: "∓", models: "⊧", mopf: "\uD835\uDD5E", Mopf: "\uD835\uDD44", mp: "∓", mscr: "\uD835\uDCC2", Mscr: "ℳ", mstpos: "∾", mu: "μ", Mu: "Μ", multimap: "⊸", mumap: "⊸", nabla: "∇", nacute: "ń", Nacute: "Ń", nang: "∠⃒", nap: "≉", napE: "⩰̸", napid: "≋̸", napos: "ŉ", napprox: "≉", natur: "♮", natural: "♮", naturals: "ℕ", nbsp: " ", nbump: "≎̸", nbumpe: "≏̸", ncap: "⩃", ncaron: "ň", Ncaron: "Ň", ncedil: "ņ", Ncedil: "Ņ", ncong: "≇", ncongdot: "⩭̸", ncup: "⩂", ncy: "н", Ncy: "Н", ndash: "–", ne: "≠", nearhk: "⤤", nearr: "↗", neArr: "⇗", nearrow: "↗", nedot: "≐̸", NegativeMediumSpace: "​", NegativeThickSpace: "​", NegativeThinSpace: "​", NegativeVeryThinSpace: "​", nequiv: "≢", nesear: "⤨", nesim: "≂̸", NestedGreaterGreater: "≫", NestedLessLess: "≪", NewLine: `
`, nexist: "∄", nexists: "∄", nfr: "\uD835\uDD2B", Nfr: "\uD835\uDD11", nge: "≱", ngE: "≧̸", ngeq: "≱", ngeqq: "≧̸", ngeqslant: "⩾̸", nges: "⩾̸", nGg: "⋙̸", ngsim: "≵", ngt: "≯", nGt: "≫⃒", ngtr: "≯", nGtv: "≫̸", nharr: "↮", nhArr: "⇎", nhpar: "⫲", ni: "∋", nis: "⋼", nisd: "⋺", niv: "∋", njcy: "њ", NJcy: "Њ", nlarr: "↚", nlArr: "⇍", nldr: "‥", nle: "≰", nlE: "≦̸", nleftarrow: "↚", nLeftarrow: "⇍", nleftrightarrow: "↮", nLeftrightarrow: "⇎", nleq: "≰", nleqq: "≦̸", nleqslant: "⩽̸", nles: "⩽̸", nless: "≮", nLl: "⋘̸", nlsim: "≴", nlt: "≮", nLt: "≪⃒", nltri: "⋪", nltrie: "⋬", nLtv: "≪̸", nmid: "∤", NoBreak: "⁠", NonBreakingSpace: " ", nopf: "\uD835\uDD5F", Nopf: "ℕ", not: "¬", Not: "⫬", NotCongruent: "≢", NotCupCap: "≭", NotDoubleVerticalBar: "∦", NotElement: "∉", NotEqual: "≠", NotEqualTilde: "≂̸", NotExists: "∄", NotGreater: "≯", NotGreaterEqual: "≱", NotGreaterFullEqual: "≧̸", NotGreaterGreater: "≫̸", NotGreaterLess: "≹", NotGreaterSlantEqual: "⩾̸", NotGreaterTilde: "≵", NotHumpDownHump: "≎̸", NotHumpEqual: "≏̸", notin: "∉", notindot: "⋵̸", notinE: "⋹̸", notinva: "∉", notinvb: "⋷", notinvc: "⋶", NotLeftTriangle: "⋪", NotLeftTriangleBar: "⧏̸", NotLeftTriangleEqual: "⋬", NotLess: "≮", NotLessEqual: "≰", NotLessGreater: "≸", NotLessLess: "≪̸", NotLessSlantEqual: "⩽̸", NotLessTilde: "≴", NotNestedGreaterGreater: "⪢̸", NotNestedLessLess: "⪡̸", notni: "∌", notniva: "∌", notnivb: "⋾", notnivc: "⋽", NotPrecedes: "⊀", NotPrecedesEqual: "⪯̸", NotPrecedesSlantEqual: "⋠", NotReverseElement: "∌", NotRightTriangle: "⋫", NotRightTriangleBar: "⧐̸", NotRightTriangleEqual: "⋭", NotSquareSubset: "⊏̸", NotSquareSubsetEqual: "⋢", NotSquareSuperset: "⊐̸", NotSquareSupersetEqual: "⋣", NotSubset: "⊂⃒", NotSubsetEqual: "⊈", NotSucceeds: "⊁", NotSucceedsEqual: "⪰̸", NotSucceedsSlantEqual: "⋡", NotSucceedsTilde: "≿̸", NotSuperset: "⊃⃒", NotSupersetEqual: "⊉", NotTilde: "≁", NotTildeEqual: "≄", NotTildeFullEqual: "≇", NotTildeTilde: "≉", NotVerticalBar: "∤", npar: "∦", nparallel: "∦", nparsl: "⫽⃥", npart: "∂̸", npolint: "⨔", npr: "⊀", nprcue: "⋠", npre: "⪯̸", nprec: "⊀", npreceq: "⪯̸", nrarr: "↛", nrArr: "⇏", nrarrc: "⤳̸", nrarrw: "↝̸", nrightarrow: "↛", nRightarrow: "⇏", nrtri: "⋫", nrtrie: "⋭", nsc: "⊁", nsccue: "⋡", nsce: "⪰̸", nscr: "\uD835\uDCC3", Nscr: "\uD835\uDCA9", nshortmid: "∤", nshortparallel: "∦", nsim: "≁", nsime: "≄", nsimeq: "≄", nsmid: "∤", nspar: "∦", nsqsube: "⋢", nsqsupe: "⋣", nsub: "⊄", nsube: "⊈", nsubE: "⫅̸", nsubset: "⊂⃒", nsubseteq: "⊈", nsubseteqq: "⫅̸", nsucc: "⊁", nsucceq: "⪰̸", nsup: "⊅", nsupe: "⊉", nsupE: "⫆̸", nsupset: "⊃⃒", nsupseteq: "⊉", nsupseteqq: "⫆̸", ntgl: "≹", ntilde: "ñ", Ntilde: "Ñ", ntlg: "≸", ntriangleleft: "⋪", ntrianglelefteq: "⋬", ntriangleright: "⋫", ntrianglerighteq: "⋭", nu: "ν", Nu: "Ν", num: "#", numero: "№", numsp: " ", nvap: "≍⃒", nvdash: "⊬", nvDash: "⊭", nVdash: "⊮", nVDash: "⊯", nvge: "≥⃒", nvgt: ">⃒", nvHarr: "⤄", nvinfin: "⧞", nvlArr: "⤂", nvle: "≤⃒", nvlt: "<⃒", nvltrie: "⊴⃒", nvrArr: "⤃", nvrtrie: "⊵⃒", nvsim: "∼⃒", nwarhk: "⤣", nwarr: "↖", nwArr: "⇖", nwarrow: "↖", nwnear: "⤧", oacute: "ó", Oacute: "Ó", oast: "⊛", ocir: "⊚", ocirc: "ô", Ocirc: "Ô", ocy: "о", Ocy: "О", odash: "⊝", odblac: "ő", Odblac: "Ő", odiv: "⨸", odot: "⊙", odsold: "⦼", oelig: "œ", OElig: "Œ", ofcir: "⦿", ofr: "\uD835\uDD2C", Ofr: "\uD835\uDD12", ogon: "˛", ograve: "ò", Ograve: "Ò", ogt: "⧁", ohbar: "⦵", ohm: "Ω", oint: "∮", olarr: "↺", olcir: "⦾", olcross: "⦻", oline: "‾", olt: "⧀", omacr: "ō", Omacr: "Ō", omega: "ω", Omega: "Ω", omicron: "ο", Omicron: "Ο", omid: "⦶", ominus: "⊖", oopf: "\uD835\uDD60", Oopf: "\uD835\uDD46", opar: "⦷", OpenCurlyDoubleQuote: "“", OpenCurlyQuote: "‘", operp: "⦹", oplus: "⊕", or: "∨", Or: "⩔", orarr: "↻", ord: "⩝", order: "ℴ", orderof: "ℴ", ordf: "ª", ordm: "º", origof: "⊶", oror: "⩖", orslope: "⩗", orv: "⩛", oS: "Ⓢ", oscr: "ℴ", Oscr: "\uD835\uDCAA", oslash: "ø", Oslash: "Ø", osol: "⊘", otilde: "õ", Otilde: "Õ", otimes: "⊗", Otimes: "⨷", otimesas: "⨶", ouml: "ö", Ouml: "Ö", ovbar: "⌽", OverBar: "‾", OverBrace: "⏞", OverBracket: "⎴", OverParenthesis: "⏜", par: "∥", para: "¶", parallel: "∥", parsim: "⫳", parsl: "⫽", part: "∂", PartialD: "∂", pcy: "п", Pcy: "П", percnt: "%", period: ".", permil: "‰", perp: "⊥", pertenk: "‱", pfr: "\uD835\uDD2D", Pfr: "\uD835\uDD13", phi: "φ", Phi: "Φ", phiv: "ϕ", phmmat: "ℳ", phone: "☎", pi: "π", Pi: "Π", pitchfork: "⋔", piv: "ϖ", planck: "ℏ", planckh: "ℎ", plankv: "ℏ", plus: "+", plusacir: "⨣", plusb: "⊞", pluscir: "⨢", plusdo: "∔", plusdu: "⨥", pluse: "⩲", PlusMinus: "±", plusmn: "±", plussim: "⨦", plustwo: "⨧", pm: "±", Poincareplane: "ℌ", pointint: "⨕", popf: "\uD835\uDD61", Popf: "ℙ", pound: "£", pr: "≺", Pr: "⪻", prap: "⪷", prcue: "≼", pre: "⪯", prE: "⪳", prec: "≺", precapprox: "⪷", preccurlyeq: "≼", Precedes: "≺", PrecedesEqual: "⪯", PrecedesSlantEqual: "≼", PrecedesTilde: "≾", preceq: "⪯", precnapprox: "⪹", precneqq: "⪵", precnsim: "⋨", precsim: "≾", prime: "′", Prime: "″", primes: "ℙ", prnap: "⪹", prnE: "⪵", prnsim: "⋨", prod: "∏", Product: "∏", profalar: "⌮", profline: "⌒", profsurf: "⌓", prop: "∝", Proportion: "∷", Proportional: "∝", propto: "∝", prsim: "≾", prurel: "⊰", pscr: "\uD835\uDCC5", Pscr: "\uD835\uDCAB", psi: "ψ", Psi: "Ψ", puncsp: " ", qfr: "\uD835\uDD2E", Qfr: "\uD835\uDD14", qint: "⨌", qopf: "\uD835\uDD62", Qopf: "ℚ", qprime: "⁗", qscr: "\uD835\uDCC6", Qscr: "\uD835\uDCAC", quaternions: "ℍ", quatint: "⨖", quest: "?", questeq: "≟", quot: '"', QUOT: '"', rAarr: "⇛", race: "∽̱", racute: "ŕ", Racute: "Ŕ", radic: "√", raemptyv: "⦳", rang: "⟩", Rang: "⟫", rangd: "⦒", range: "⦥", rangle: "⟩", raquo: "»", rarr: "→", rArr: "⇒", Rarr: "↠", rarrap: "⥵", rarrb: "⇥", rarrbfs: "⤠", rarrc: "⤳", rarrfs: "⤞", rarrhk: "↪", rarrlp: "↬", rarrpl: "⥅", rarrsim: "⥴", rarrtl: "↣", Rarrtl: "⤖", rarrw: "↝", ratail: "⤚", rAtail: "⤜", ratio: "∶", rationals: "ℚ", rbarr: "⤍", rBarr: "⤏", RBarr: "⤐", rbbrk: "❳", rbrace: "}", rbrack: "]", rbrke: "⦌", rbrksld: "⦎", rbrkslu: "⦐", rcaron: "ř", Rcaron: "Ř", rcedil: "ŗ", Rcedil: "Ŗ", rceil: "⌉", rcub: "}", rcy: "р", Rcy: "Р", rdca: "⤷", rdldhar: "⥩", rdquo: "”", rdquor: "”", rdsh: "↳", Re: "ℜ", real: "ℜ", realine: "ℛ", realpart: "ℜ", reals: "ℝ", rect: "▭", reg: "®", REG: "®", ReverseElement: "∋", ReverseEquilibrium: "⇋", ReverseUpEquilibrium: "⥯", rfisht: "⥽", rfloor: "⌋", rfr: "\uD835\uDD2F", Rfr: "ℜ", rHar: "⥤", rhard: "⇁", rharu: "⇀", rharul: "⥬", rho: "ρ", Rho: "Ρ", rhov: "ϱ", RightAngleBracket: "⟩", rightarrow: "→", Rightarrow: "⇒", RightArrow: "→", RightArrowBar: "⇥", RightArrowLeftArrow: "⇄", rightarrowtail: "↣", RightCeiling: "⌉", RightDoubleBracket: "⟧", RightDownTeeVector: "⥝", RightDownVector: "⇂", RightDownVectorBar: "⥕", RightFloor: "⌋", rightharpoondown: "⇁", rightharpoonup: "⇀", rightleftarrows: "⇄", rightleftharpoons: "⇌", rightrightarrows: "⇉", rightsquigarrow: "↝", RightTee: "⊢", RightTeeArrow: "↦", RightTeeVector: "⥛", rightthreetimes: "⋌", RightTriangle: "⊳", RightTriangleBar: "⧐", RightTriangleEqual: "⊵", RightUpDownVector: "⥏", RightUpTeeVector: "⥜", RightUpVector: "↾", RightUpVectorBar: "⥔", RightVector: "⇀", RightVectorBar: "⥓", ring: "˚", risingdotseq: "≓", rlarr: "⇄", rlhar: "⇌", rlm: "‏", rmoust: "⎱", rmoustache: "⎱", rnmid: "⫮", roang: "⟭", roarr: "⇾", robrk: "⟧", ropar: "⦆", ropf: "\uD835\uDD63", Ropf: "ℝ", roplus: "⨮", rotimes: "⨵", RoundImplies: "⥰", rpar: ")", rpargt: "⦔", rppolint: "⨒", rrarr: "⇉", Rrightarrow: "⇛", rsaquo: "›", rscr: "\uD835\uDCC7", Rscr: "ℛ", rsh: "↱", Rsh: "↱", rsqb: "]", rsquo: "’", rsquor: "’", rthree: "⋌", rtimes: "⋊", rtri: "▹", rtrie: "⊵", rtrif: "▸", rtriltri: "⧎", RuleDelayed: "⧴", ruluhar: "⥨", rx: "℞", sacute: "ś", Sacute: "Ś", sbquo: "‚", sc: "≻", Sc: "⪼", scap: "⪸", scaron: "š", Scaron: "Š", sccue: "≽", sce: "⪰", scE: "⪴", scedil: "ş", Scedil: "Ş", scirc: "ŝ", Scirc: "Ŝ", scnap: "⪺", scnE: "⪶", scnsim: "⋩", scpolint: "⨓", scsim: "≿", scy: "с", Scy: "С", sdot: "⋅", sdotb: "⊡", sdote: "⩦", searhk: "⤥", searr: "↘", seArr: "⇘", searrow: "↘", sect: "§", semi: ";", seswar: "⤩", setminus: "∖", setmn: "∖", sext: "✶", sfr: "\uD835\uDD30", Sfr: "\uD835\uDD16", sfrown: "⌢", sharp: "♯", shchcy: "щ", SHCHcy: "Щ", shcy: "ш", SHcy: "Ш", ShortDownArrow: "↓", ShortLeftArrow: "←", shortmid: "∣", shortparallel: "∥", ShortRightArrow: "→", ShortUpArrow: "↑", shy: "­", sigma: "σ", Sigma: "Σ", sigmaf: "ς", sigmav: "ς", sim: "∼", simdot: "⩪", sime: "≃", simeq: "≃", simg: "⪞", simgE: "⪠", siml: "⪝", simlE: "⪟", simne: "≆", simplus: "⨤", simrarr: "⥲", slarr: "←", SmallCircle: "∘", smallsetminus: "∖", smashp: "⨳", smeparsl: "⧤", smid: "∣", smile: "⌣", smt: "⪪", smte: "⪬", smtes: "⪬︀", softcy: "ь", SOFTcy: "Ь", sol: "/", solb: "⧄", solbar: "⌿", sopf: "\uD835\uDD64", Sopf: "\uD835\uDD4A", spades: "♠", spadesuit: "♠", spar: "∥", sqcap: "⊓", sqcaps: "⊓︀", sqcup: "⊔", sqcups: "⊔︀", Sqrt: "√", sqsub: "⊏", sqsube: "⊑", sqsubset: "⊏", sqsubseteq: "⊑", sqsup: "⊐", sqsupe: "⊒", sqsupset: "⊐", sqsupseteq: "⊒", squ: "□", square: "□", Square: "□", SquareIntersection: "⊓", SquareSubset: "⊏", SquareSubsetEqual: "⊑", SquareSuperset: "⊐", SquareSupersetEqual: "⊒", SquareUnion: "⊔", squarf: "▪", squf: "▪", srarr: "→", sscr: "\uD835\uDCC8", Sscr: "\uD835\uDCAE", ssetmn: "∖", ssmile: "⌣", sstarf: "⋆", star: "☆", Star: "⋆", starf: "★", straightepsilon: "ϵ", straightphi: "ϕ", strns: "¯", sub: "⊂", Sub: "⋐", subdot: "⪽", sube: "⊆", subE: "⫅", subedot: "⫃", submult: "⫁", subne: "⊊", subnE: "⫋", subplus: "⪿", subrarr: "⥹", subset: "⊂", Subset: "⋐", subseteq: "⊆", subseteqq: "⫅", SubsetEqual: "⊆", subsetneq: "⊊", subsetneqq: "⫋", subsim: "⫇", subsub: "⫕", subsup: "⫓", succ: "≻", succapprox: "⪸", succcurlyeq: "≽", Succeeds: "≻", SucceedsEqual: "⪰", SucceedsSlantEqual: "≽", SucceedsTilde: "≿", succeq: "⪰", succnapprox: "⪺", succneqq: "⪶", succnsim: "⋩", succsim: "≿", SuchThat: "∋", sum: "∑", Sum: "∑", sung: "♪", sup: "⊃", Sup: "⋑", sup1: "¹", sup2: "²", sup3: "³", supdot: "⪾", supdsub: "⫘", supe: "⊇", supE: "⫆", supedot: "⫄", Superset: "⊃", SupersetEqual: "⊇", suphsol: "⟉", suphsub: "⫗", suplarr: "⥻", supmult: "⫂", supne: "⊋", supnE: "⫌", supplus: "⫀", supset: "⊃", Supset: "⋑", supseteq: "⊇", supseteqq: "⫆", supsetneq: "⊋", supsetneqq: "⫌", supsim: "⫈", supsub: "⫔", supsup: "⫖", swarhk: "⤦", swarr: "↙", swArr: "⇙", swarrow: "↙", swnwar: "⤪", szlig: "ß", Tab: "\t", target: "⌖", tau: "τ", Tau: "Τ", tbrk: "⎴", tcaron: "ť", Tcaron: "Ť", tcedil: "ţ", Tcedil: "Ţ", tcy: "т", Tcy: "Т", tdot: "⃛", telrec: "⌕", tfr: "\uD835\uDD31", Tfr: "\uD835\uDD17", there4: "∴", therefore: "∴", Therefore: "∴", theta: "θ", Theta: "Θ", thetasym: "ϑ", thetav: "ϑ", thickapprox: "≈", thicksim: "∼", ThickSpace: "  ", thinsp: " ", ThinSpace: " ", thkap: "≈", thksim: "∼", thorn: "þ", THORN: "Þ", tilde: "˜", Tilde: "∼", TildeEqual: "≃", TildeFullEqual: "≅", TildeTilde: "≈", times: "×", timesb: "⊠", timesbar: "⨱", timesd: "⨰", tint: "∭", toea: "⤨", top: "⊤", topbot: "⌶", topcir: "⫱", topf: "\uD835\uDD65", Topf: "\uD835\uDD4B", topfork: "⫚", tosa: "⤩", tprime: "‴", trade: "™", TRADE: "™", triangle: "▵", triangledown: "▿", triangleleft: "◃", trianglelefteq: "⊴", triangleq: "≜", triangleright: "▹", trianglerighteq: "⊵", tridot: "◬", trie: "≜", triminus: "⨺", TripleDot: "⃛", triplus: "⨹", trisb: "⧍", tritime: "⨻", trpezium: "⏢", tscr: "\uD835\uDCC9", Tscr: "\uD835\uDCAF", tscy: "ц", TScy: "Ц", tshcy: "ћ", TSHcy: "Ћ", tstrok: "ŧ", Tstrok: "Ŧ", twixt: "≬", twoheadleftarrow: "↞", twoheadrightarrow: "↠", uacute: "ú", Uacute: "Ú", uarr: "↑", uArr: "⇑", Uarr: "↟", Uarrocir: "⥉", ubrcy: "ў", Ubrcy: "Ў", ubreve: "ŭ", Ubreve: "Ŭ", ucirc: "û", Ucirc: "Û", ucy: "у", Ucy: "У", udarr: "⇅", udblac: "ű", Udblac: "Ű", udhar: "⥮", ufisht: "⥾", ufr: "\uD835\uDD32", Ufr: "\uD835\uDD18", ugrave: "ù", Ugrave: "Ù", uHar: "⥣", uharl: "↿", uharr: "↾", uhblk: "▀", ulcorn: "⌜", ulcorner: "⌜", ulcrop: "⌏", ultri: "◸", umacr: "ū", Umacr: "Ū", uml: "¨", UnderBar: "_", UnderBrace: "⏟", UnderBracket: "⎵", UnderParenthesis: "⏝", Union: "⋃", UnionPlus: "⊎", uogon: "ų", Uogon: "Ų", uopf: "\uD835\uDD66", Uopf: "\uD835\uDD4C", uparrow: "↑", Uparrow: "⇑", UpArrow: "↑", UpArrowBar: "⤒", UpArrowDownArrow: "⇅", updownarrow: "↕", Updownarrow: "⇕", UpDownArrow: "↕", UpEquilibrium: "⥮", upharpoonleft: "↿", upharpoonright: "↾", uplus: "⊎", UpperLeftArrow: "↖", UpperRightArrow: "↗", upsi: "υ", Upsi: "ϒ", upsih: "ϒ", upsilon: "υ", Upsilon: "Υ", UpTee: "⊥", UpTeeArrow: "↥", upuparrows: "⇈", urcorn: "⌝", urcorner: "⌝", urcrop: "⌎", uring: "ů", Uring: "Ů", urtri: "◹", uscr: "\uD835\uDCCA", Uscr: "\uD835\uDCB0", utdot: "⋰", utilde: "ũ", Utilde: "Ũ", utri: "▵", utrif: "▴", uuarr: "⇈", uuml: "ü", Uuml: "Ü", uwangle: "⦧", vangrt: "⦜", varepsilon: "ϵ", varkappa: "ϰ", varnothing: "∅", varphi: "ϕ", varpi: "ϖ", varpropto: "∝", varr: "↕", vArr: "⇕", varrho: "ϱ", varsigma: "ς", varsubsetneq: "⊊︀", varsubsetneqq: "⫋︀", varsupsetneq: "⊋︀", varsupsetneqq: "⫌︀", vartheta: "ϑ", vartriangleleft: "⊲", vartriangleright: "⊳", vBar: "⫨", Vbar: "⫫", vBarv: "⫩", vcy: "в", Vcy: "В", vdash: "⊢", vDash: "⊨", Vdash: "⊩", VDash: "⊫", Vdashl: "⫦", vee: "∨", Vee: "⋁", veebar: "⊻", veeeq: "≚", vellip: "⋮", verbar: "|", Verbar: "‖", vert: "|", Vert: "‖", VerticalBar: "∣", VerticalLine: "|", VerticalSeparator: "❘", VerticalTilde: "≀", VeryThinSpace: " ", vfr: "\uD835\uDD33", Vfr: "\uD835\uDD19", vltri: "⊲", vnsub: "⊂⃒", vnsup: "⊃⃒", vopf: "\uD835\uDD67", Vopf: "\uD835\uDD4D", vprop: "∝", vrtri: "⊳", vscr: "\uD835\uDCCB", Vscr: "\uD835\uDCB1", vsubne: "⊊︀", vsubnE: "⫋︀", vsupne: "⊋︀", vsupnE: "⫌︀", Vvdash: "⊪", vzigzag: "⦚", wcirc: "ŵ", Wcirc: "Ŵ", wedbar: "⩟", wedge: "∧", Wedge: "⋀", wedgeq: "≙", weierp: "℘", wfr: "\uD835\uDD34", Wfr: "\uD835\uDD1A", wopf: "\uD835\uDD68", Wopf: "\uD835\uDD4E", wp: "℘", wr: "≀", wreath: "≀", wscr: "\uD835\uDCCC", Wscr: "\uD835\uDCB2", xcap: "⋂", xcirc: "◯", xcup: "⋃", xdtri: "▽", xfr: "\uD835\uDD35", Xfr: "\uD835\uDD1B", xharr: "⟷", xhArr: "⟺", xi: "ξ", Xi: "Ξ", xlarr: "⟵", xlArr: "⟸", xmap: "⟼", xnis: "⋻", xodot: "⨀", xopf: "\uD835\uDD69", Xopf: "\uD835\uDD4F", xoplus: "⨁", xotime: "⨂", xrarr: "⟶", xrArr: "⟹", xscr: "\uD835\uDCCD", Xscr: "\uD835\uDCB3", xsqcup: "⨆", xuplus: "⨄", xutri: "△", xvee: "⋁", xwedge: "⋀", yacute: "ý", Yacute: "Ý", yacy: "я", YAcy: "Я", ycirc: "ŷ", Ycirc: "Ŷ", ycy: "ы", Ycy: "Ы", yen: "¥", yfr: "\uD835\uDD36", Yfr: "\uD835\uDD1C", yicy: "ї", YIcy: "Ї", yopf: "\uD835\uDD6A", Yopf: "\uD835\uDD50", yscr: "\uD835\uDCCE", Yscr: "\uD835\uDCB4", yucy: "ю", YUcy: "Ю", yuml: "ÿ", Yuml: "Ÿ", zacute: "ź", Zacute: "Ź", zcaron: "ž", Zcaron: "Ž", zcy: "з", Zcy: "З", zdot: "ż", Zdot: "Ż", zeetrf: "ℨ", ZeroWidthSpace: "​", zeta: "ζ", Zeta: "Ζ", zfr: "\uD835\uDD37", Zfr: "ℨ", zhcy: "ж", ZHcy: "Ж", zigrarr: "⇝", zopf: "\uD835\uDD6B", Zopf: "ℤ", zscr: "\uD835\uDCCF", Zscr: "\uD835\uDCB5", zwj: "‍", zwnj: "‌" };
    var decodeMapLegacy = { aacute: "á", Aacute: "Á", acirc: "â", Acirc: "Â", acute: "´", aelig: "æ", AElig: "Æ", agrave: "à", Agrave: "À", amp: "&", AMP: "&", aring: "å", Aring: "Å", atilde: "ã", Atilde: "Ã", auml: "ä", Auml: "Ä", brvbar: "¦", ccedil: "ç", Ccedil: "Ç", cedil: "¸", cent: "¢", copy: "©", COPY: "©", curren: "¤", deg: "°", divide: "÷", eacute: "é", Eacute: "É", ecirc: "ê", Ecirc: "Ê", egrave: "è", Egrave: "È", eth: "ð", ETH: "Ð", euml: "ë", Euml: "Ë", frac12: "½", frac14: "¼", frac34: "¾", gt: ">", GT: ">", iacute: "í", Iacute: "Í", icirc: "î", Icirc: "Î", iexcl: "¡", igrave: "ì", Igrave: "Ì", iquest: "¿", iuml: "ï", Iuml: "Ï", laquo: "«", lt: "<", LT: "<", macr: "¯", micro: "µ", middot: "·", nbsp: " ", not: "¬", ntilde: "ñ", Ntilde: "Ñ", oacute: "ó", Oacute: "Ó", ocirc: "ô", Ocirc: "Ô", ograve: "ò", Ograve: "Ò", ordf: "ª", ordm: "º", oslash: "ø", Oslash: "Ø", otilde: "õ", Otilde: "Õ", ouml: "ö", Ouml: "Ö", para: "¶", plusmn: "±", pound: "£", quot: '"', QUOT: '"', raquo: "»", reg: "®", REG: "®", sect: "§", shy: "­", sup1: "¹", sup2: "²", sup3: "³", szlig: "ß", thorn: "þ", THORN: "Þ", times: "×", uacute: "ú", Uacute: "Ú", ucirc: "û", Ucirc: "Û", ugrave: "ù", Ugrave: "Ù", uml: "¨", uuml: "ü", Uuml: "Ü", yacute: "ý", Yacute: "Ý", yen: "¥", yuml: "ÿ" };
    var decodeMapNumeric = { "0": "�", "128": "€", "130": "‚", "131": "ƒ", "132": "„", "133": "…", "134": "†", "135": "‡", "136": "ˆ", "137": "‰", "138": "Š", "139": "‹", "140": "Œ", "142": "Ž", "145": "‘", "146": "’", "147": "“", "148": "”", "149": "•", "150": "–", "151": "—", "152": "˜", "153": "™", "154": "š", "155": "›", "156": "œ", "158": "ž", "159": "Ÿ" };
    var invalidReferenceCodePoints = [1, 2, 3, 4, 5, 6, 7, 8, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 64976, 64977, 64978, 64979, 64980, 64981, 64982, 64983, 64984, 64985, 64986, 64987, 64988, 64989, 64990, 64991, 64992, 64993, 64994, 64995, 64996, 64997, 64998, 64999, 65000, 65001, 65002, 65003, 65004, 65005, 65006, 65007, 65534, 65535, 131070, 131071, 196606, 196607, 262142, 262143, 327678, 327679, 393214, 393215, 458750, 458751, 524286, 524287, 589822, 589823, 655358, 655359, 720894, 720895, 786430, 786431, 851966, 851967, 917502, 917503, 983038, 983039, 1048574, 1048575, 1114110, 1114111];
    var stringFromCharCode = String.fromCharCode;
    var object2 = {};
    var hasOwnProperty = object2.hasOwnProperty;
    var has = function(object3, propertyName) {
      return hasOwnProperty.call(object3, propertyName);
    };
    var contains = function(array3, value2) {
      var index = -1;
      var length2 = array3.length;
      while (++index < length2) {
        if (array3[index] == value2) {
          return true;
        }
      }
      return false;
    };
    var merge2 = function(options, defaults) {
      if (!options) {
        return defaults;
      }
      var result = {};
      var key2;
      for (key2 in defaults) {
        result[key2] = has(options, key2) ? options[key2] : defaults[key2];
      }
      return result;
    };
    var codePointToSymbol = function(codePoint, strict) {
      var output = "";
      if (codePoint >= 55296 && codePoint <= 57343 || codePoint > 1114111) {
        if (strict) {
          parseError("character reference outside the permissible Unicode range");
        }
        return "�";
      }
      if (has(decodeMapNumeric, codePoint)) {
        if (strict) {
          parseError("disallowed character reference");
        }
        return decodeMapNumeric[codePoint];
      }
      if (strict && contains(invalidReferenceCodePoints, codePoint)) {
        parseError("disallowed character reference");
      }
      if (codePoint > 65535) {
        codePoint -= 65536;
        output += stringFromCharCode(codePoint >>> 10 & 1023 | 55296);
        codePoint = 56320 | codePoint & 1023;
      }
      output += stringFromCharCode(codePoint);
      return output;
    };
    var hexEscape = function(codePoint) {
      return "&#x" + codePoint.toString(16).toUpperCase() + ";";
    };
    var decEscape = function(codePoint) {
      return "&#" + codePoint + ";";
    };
    var parseError = function(message) {
      throw Error("Parse error: " + message);
    };
    var encode3 = function(string4, options) {
      options = merge2(options, encode3.options);
      var strict = options.strict;
      if (strict && regexInvalidRawCodePoint.test(string4)) {
        parseError("forbidden code point");
      }
      var encodeEverything = options.encodeEverything;
      var useNamedReferences = options.useNamedReferences;
      var allowUnsafeSymbols = options.allowUnsafeSymbols;
      var escapeCodePoint = options.decimal ? decEscape : hexEscape;
      var escapeBmpSymbol = function(symbol3) {
        return escapeCodePoint(symbol3.charCodeAt(0));
      };
      if (encodeEverything) {
        string4 = string4.replace(regexAsciiWhitelist, function(symbol3) {
          if (useNamedReferences && has(encodeMap, symbol3)) {
            return "&" + encodeMap[symbol3] + ";";
          }
          return escapeBmpSymbol(symbol3);
        });
        if (useNamedReferences) {
          string4 = string4.replace(/&gt;\u20D2/g, "&nvgt;").replace(/&lt;\u20D2/g, "&nvlt;").replace(/&#x66;&#x6A;/g, "&fjlig;");
        }
        if (useNamedReferences) {
          string4 = string4.replace(regexEncodeNonAscii, function(string5) {
            return "&" + encodeMap[string5] + ";";
          });
        }
      } else if (useNamedReferences) {
        if (!allowUnsafeSymbols) {
          string4 = string4.replace(regexEscape, function(string5) {
            return "&" + encodeMap[string5] + ";";
          });
        }
        string4 = string4.replace(/&gt;\u20D2/g, "&nvgt;").replace(/&lt;\u20D2/g, "&nvlt;");
        string4 = string4.replace(regexEncodeNonAscii, function(string5) {
          return "&" + encodeMap[string5] + ";";
        });
      } else if (!allowUnsafeSymbols) {
        string4 = string4.replace(regexEscape, escapeBmpSymbol);
      }
      return string4.replace(regexAstralSymbols, function($0) {
        var high = $0.charCodeAt(0);
        var low = $0.charCodeAt(1);
        var codePoint = (high - 55296) * 1024 + low - 56320 + 65536;
        return escapeCodePoint(codePoint);
      }).replace(regexBmpWhitelist, escapeBmpSymbol);
    };
    encode3.options = {
      allowUnsafeSymbols: false,
      encodeEverything: false,
      strict: false,
      useNamedReferences: false,
      decimal: false
    };
    var decode3 = function(html, options) {
      options = merge2(options, decode3.options);
      var strict = options.strict;
      if (strict && regexInvalidEntity.test(html)) {
        parseError("malformed character reference");
      }
      return html.replace(regexDecode, function($0, $1, $2, $3, $4, $5, $6, $7, $8) {
        var codePoint;
        var semicolon;
        var decDigits;
        var hexDigits;
        var reference;
        var next2;
        if ($1) {
          reference = $1;
          return decodeMap[reference];
        }
        if ($2) {
          reference = $2;
          next2 = $3;
          if (next2 && options.isAttributeValue) {
            if (strict && next2 == "=") {
              parseError("`&` did not start a character reference");
            }
            return $0;
          } else {
            if (strict) {
              parseError("named character reference was not terminated by a semicolon");
            }
            return decodeMapLegacy[reference] + (next2 || "");
          }
        }
        if ($4) {
          decDigits = $4;
          semicolon = $5;
          if (strict && !semicolon) {
            parseError("character reference was not terminated by a semicolon");
          }
          codePoint = parseInt(decDigits, 10);
          return codePointToSymbol(codePoint, strict);
        }
        if ($6) {
          hexDigits = $6;
          semicolon = $7;
          if (strict && !semicolon) {
            parseError("character reference was not terminated by a semicolon");
          }
          codePoint = parseInt(hexDigits, 16);
          return codePointToSymbol(codePoint, strict);
        }
        if (strict) {
          parseError("named character reference was not terminated by a semicolon");
        }
        return $0;
      });
    };
    decode3.options = {
      isAttributeValue: false,
      strict: false
    };
    var escape2 = function(string4) {
      return string4.replace(regexEscape, function($0) {
        return escapeMap[$0];
      });
    };
    var he = {
      version: "1.2.0",
      encode: encode3,
      decode: decode3,
      escape: escape2,
      unescape: decode3
    };
    if (typeof define == "function" && typeof define.amd == "object" && define.amd) {
      define(function() {
        return he;
      });
    } else if (freeExports && !freeExports.nodeType) {
      if (freeModule) {
        freeModule.exports = he;
      } else {
        for (var key in he) {
          has(he, key) && (freeExports[key] = he[key]);
        }
      }
    } else {
      root.he = he;
    }
  })(exports);
});

// node_modules/node-html-parser/dist/nodes/node.js
var require_node = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  var he_1 = require_he();

  class Node2 {
    constructor(parentNode = null, range2) {
      this.parentNode = parentNode;
      this.childNodes = [];
      Object.defineProperty(this, "range", {
        enumerable: false,
        writable: true,
        configurable: true,
        value: range2 !== null && range2 !== undefined ? range2 : [-1, -1]
      });
    }
    remove() {
      if (this.parentNode) {
        const children = this.parentNode.childNodes;
        this.parentNode.childNodes = children.filter((child) => {
          return this !== child;
        });
        this.parentNode = null;
      }
      return this;
    }
    get innerText() {
      return this.rawText;
    }
    get textContent() {
      return (0, he_1.decode)(this.rawText);
    }
    set textContent(val) {
      this.rawText = (0, he_1.encode)(val);
    }
  }
  exports.default = Node2;
});

// node_modules/node-html-parser/dist/nodes/type.js
var require_type = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  var NodeType;
  (function(NodeType2) {
    NodeType2[NodeType2["ELEMENT_NODE"] = 1] = "ELEMENT_NODE";
    NodeType2[NodeType2["TEXT_NODE"] = 3] = "TEXT_NODE";
    NodeType2[NodeType2["COMMENT_NODE"] = 8] = "COMMENT_NODE";
  })(NodeType || (NodeType = {}));
  exports.default = NodeType;
});

// node_modules/node-html-parser/dist/nodes/comment.js
var require_comment = __commonJS((exports) => {
  var __importDefault = exports && exports.__importDefault || function(mod2) {
    return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  var node_1 = __importDefault(require_node());
  var type_1 = __importDefault(require_type());

  class CommentNode extends node_1.default {
    clone() {
      return new CommentNode(this.rawText, null, undefined, this.rawTagName);
    }
    constructor(rawText, parentNode = null, range2, rawTagName = "!--") {
      super(parentNode, range2);
      this.rawText = rawText;
      this.rawTagName = rawTagName;
      this.nodeType = type_1.default.COMMENT_NODE;
    }
    get text() {
      return this.rawText;
    }
    toString() {
      return `<!--${this.rawText}-->`;
    }
  }
  exports.default = CommentNode;
});

// node_modules/domelementtype/lib/index.js
var require_lib = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.Doctype = exports.CDATA = exports.Tag = exports.Style = exports.Script = exports.Comment = exports.Directive = exports.Text = exports.Root = exports.isTag = exports.ElementType = undefined;
  var ElementType2;
  (function(ElementType3) {
    ElementType3["Root"] = "root";
    ElementType3["Text"] = "text";
    ElementType3["Directive"] = "directive";
    ElementType3["Comment"] = "comment";
    ElementType3["Script"] = "script";
    ElementType3["Style"] = "style";
    ElementType3["Tag"] = "tag";
    ElementType3["CDATA"] = "cdata";
    ElementType3["Doctype"] = "doctype";
  })(ElementType2 = exports.ElementType || (exports.ElementType = {}));
  function isTag(elem) {
    return elem.type === ElementType2.Tag || elem.type === ElementType2.Script || elem.type === ElementType2.Style;
  }
  exports.isTag = isTag;
  exports.Root = ElementType2.Root;
  exports.Text = ElementType2.Text;
  exports.Directive = ElementType2.Directive;
  exports.Comment = ElementType2.Comment;
  exports.Script = ElementType2.Script;
  exports.Style = ElementType2.Style;
  exports.Tag = ElementType2.Tag;
  exports.CDATA = ElementType2.CDATA;
  exports.Doctype = ElementType2.Doctype;
});

// node_modules/domhandler/lib/node.js
var require_node2 = __commonJS((exports) => {
  var __extends = exports && exports.__extends || function() {
    var extendStatics = function(d, b) {
      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
        d2.__proto__ = b2;
      } || function(d2, b2) {
        for (var p in b2)
          if (Object.prototype.hasOwnProperty.call(b2, p))
            d2[p] = b2[p];
      };
      return extendStatics(d, b);
    };
    return function(d, b) {
      if (typeof b !== "function" && b !== null)
        throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
      extendStatics(d, b);
      function __() {
        this.constructor = d;
      }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __);
    };
  }();
  var __assign = exports && exports.__assign || function() {
    __assign = Object.assign || function(t) {
      for (var s, i = 1, n = arguments.length;i < n; i++) {
        s = arguments[i];
        for (var p in s)
          if (Object.prototype.hasOwnProperty.call(s, p))
            t[p] = s[p];
      }
      return t;
    };
    return __assign.apply(this, arguments);
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.cloneNode = exports.hasChildren = exports.isDocument = exports.isDirective = exports.isComment = exports.isText = exports.isCDATA = exports.isTag = exports.Element = exports.Document = exports.CDATA = exports.NodeWithChildren = exports.ProcessingInstruction = exports.Comment = exports.Text = exports.DataNode = exports.Node = undefined;
  var domelementtype_1 = require_lib();
  var Node2 = function() {
    function Node3() {
      this.parent = null;
      this.prev = null;
      this.next = null;
      this.startIndex = null;
      this.endIndex = null;
    }
    Object.defineProperty(Node3.prototype, "parentNode", {
      get: function() {
        return this.parent;
      },
      set: function(parent) {
        this.parent = parent;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Node3.prototype, "previousSibling", {
      get: function() {
        return this.prev;
      },
      set: function(prev) {
        this.prev = prev;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Node3.prototype, "nextSibling", {
      get: function() {
        return this.next;
      },
      set: function(next2) {
        this.next = next2;
      },
      enumerable: false,
      configurable: true
    });
    Node3.prototype.cloneNode = function(recursive) {
      if (recursive === undefined) {
        recursive = false;
      }
      return cloneNode(this, recursive);
    };
    return Node3;
  }();
  exports.Node = Node2;
  var DataNode = function(_super) {
    __extends(DataNode2, _super);
    function DataNode2(data2) {
      var _this = _super.call(this) || this;
      _this.data = data2;
      return _this;
    }
    Object.defineProperty(DataNode2.prototype, "nodeValue", {
      get: function() {
        return this.data;
      },
      set: function(data2) {
        this.data = data2;
      },
      enumerable: false,
      configurable: true
    });
    return DataNode2;
  }(Node2);
  exports.DataNode = DataNode;
  var Text2 = function(_super) {
    __extends(Text3, _super);
    function Text3() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.type = domelementtype_1.ElementType.Text;
      return _this;
    }
    Object.defineProperty(Text3.prototype, "nodeType", {
      get: function() {
        return 3;
      },
      enumerable: false,
      configurable: true
    });
    return Text3;
  }(DataNode);
  exports.Text = Text2;
  var Comment3 = function(_super) {
    __extends(Comment4, _super);
    function Comment4() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.type = domelementtype_1.ElementType.Comment;
      return _this;
    }
    Object.defineProperty(Comment4.prototype, "nodeType", {
      get: function() {
        return 8;
      },
      enumerable: false,
      configurable: true
    });
    return Comment4;
  }(DataNode);
  exports.Comment = Comment3;
  var ProcessingInstruction = function(_super) {
    __extends(ProcessingInstruction2, _super);
    function ProcessingInstruction2(name2, data2) {
      var _this = _super.call(this, data2) || this;
      _this.name = name2;
      _this.type = domelementtype_1.ElementType.Directive;
      return _this;
    }
    Object.defineProperty(ProcessingInstruction2.prototype, "nodeType", {
      get: function() {
        return 1;
      },
      enumerable: false,
      configurable: true
    });
    return ProcessingInstruction2;
  }(DataNode);
  exports.ProcessingInstruction = ProcessingInstruction;
  var NodeWithChildren = function(_super) {
    __extends(NodeWithChildren2, _super);
    function NodeWithChildren2(children) {
      var _this = _super.call(this) || this;
      _this.children = children;
      return _this;
    }
    Object.defineProperty(NodeWithChildren2.prototype, "firstChild", {
      get: function() {
        var _a2;
        return (_a2 = this.children[0]) !== null && _a2 !== undefined ? _a2 : null;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(NodeWithChildren2.prototype, "lastChild", {
      get: function() {
        return this.children.length > 0 ? this.children[this.children.length - 1] : null;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(NodeWithChildren2.prototype, "childNodes", {
      get: function() {
        return this.children;
      },
      set: function(children) {
        this.children = children;
      },
      enumerable: false,
      configurable: true
    });
    return NodeWithChildren2;
  }(Node2);
  exports.NodeWithChildren = NodeWithChildren;
  var CDATA = function(_super) {
    __extends(CDATA2, _super);
    function CDATA2() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.type = domelementtype_1.ElementType.CDATA;
      return _this;
    }
    Object.defineProperty(CDATA2.prototype, "nodeType", {
      get: function() {
        return 4;
      },
      enumerable: false,
      configurable: true
    });
    return CDATA2;
  }(NodeWithChildren);
  exports.CDATA = CDATA;
  var Document2 = function(_super) {
    __extends(Document3, _super);
    function Document3() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.type = domelementtype_1.ElementType.Root;
      return _this;
    }
    Object.defineProperty(Document3.prototype, "nodeType", {
      get: function() {
        return 9;
      },
      enumerable: false,
      configurable: true
    });
    return Document3;
  }(NodeWithChildren);
  exports.Document = Document2;
  var Element3 = function(_super) {
    __extends(Element4, _super);
    function Element4(name2, attribs, children, type) {
      if (children === undefined) {
        children = [];
      }
      if (type === undefined) {
        type = name2 === "script" ? domelementtype_1.ElementType.Script : name2 === "style" ? domelementtype_1.ElementType.Style : domelementtype_1.ElementType.Tag;
      }
      var _this = _super.call(this, children) || this;
      _this.name = name2;
      _this.attribs = attribs;
      _this.type = type;
      return _this;
    }
    Object.defineProperty(Element4.prototype, "nodeType", {
      get: function() {
        return 1;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Element4.prototype, "tagName", {
      get: function() {
        return this.name;
      },
      set: function(name2) {
        this.name = name2;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Element4.prototype, "attributes", {
      get: function() {
        var _this = this;
        return Object.keys(this.attribs).map(function(name2) {
          var _a2, _b;
          return {
            name: name2,
            value: _this.attribs[name2],
            namespace: (_a2 = _this["x-attribsNamespace"]) === null || _a2 === undefined ? undefined : _a2[name2],
            prefix: (_b = _this["x-attribsPrefix"]) === null || _b === undefined ? undefined : _b[name2]
          };
        });
      },
      enumerable: false,
      configurable: true
    });
    return Element4;
  }(NodeWithChildren);
  exports.Element = Element3;
  function isTag(node) {
    return (0, domelementtype_1.isTag)(node);
  }
  exports.isTag = isTag;
  function isCDATA(node) {
    return node.type === domelementtype_1.ElementType.CDATA;
  }
  exports.isCDATA = isCDATA;
  function isText(node) {
    return node.type === domelementtype_1.ElementType.Text;
  }
  exports.isText = isText;
  function isComment(node) {
    return node.type === domelementtype_1.ElementType.Comment;
  }
  exports.isComment = isComment;
  function isDirective(node) {
    return node.type === domelementtype_1.ElementType.Directive;
  }
  exports.isDirective = isDirective;
  function isDocument(node) {
    return node.type === domelementtype_1.ElementType.Root;
  }
  exports.isDocument = isDocument;
  function hasChildren(node) {
    return Object.prototype.hasOwnProperty.call(node, "children");
  }
  exports.hasChildren = hasChildren;
  function cloneNode(node, recursive) {
    if (recursive === undefined) {
      recursive = false;
    }
    var result;
    if (isText(node)) {
      result = new Text2(node.data);
    } else if (isComment(node)) {
      result = new Comment3(node.data);
    } else if (isTag(node)) {
      var children = recursive ? cloneChildren(node.children) : [];
      var clone_1 = new Element3(node.name, __assign({}, node.attribs), children);
      children.forEach(function(child) {
        return child.parent = clone_1;
      });
      if (node.namespace != null) {
        clone_1.namespace = node.namespace;
      }
      if (node["x-attribsNamespace"]) {
        clone_1["x-attribsNamespace"] = __assign({}, node["x-attribsNamespace"]);
      }
      if (node["x-attribsPrefix"]) {
        clone_1["x-attribsPrefix"] = __assign({}, node["x-attribsPrefix"]);
      }
      result = clone_1;
    } else if (isCDATA(node)) {
      var children = recursive ? cloneChildren(node.children) : [];
      var clone_2 = new CDATA(children);
      children.forEach(function(child) {
        return child.parent = clone_2;
      });
      result = clone_2;
    } else if (isDocument(node)) {
      var children = recursive ? cloneChildren(node.children) : [];
      var clone_3 = new Document2(children);
      children.forEach(function(child) {
        return child.parent = clone_3;
      });
      if (node["x-mode"]) {
        clone_3["x-mode"] = node["x-mode"];
      }
      result = clone_3;
    } else if (isDirective(node)) {
      var instruction = new ProcessingInstruction(node.name, node.data);
      if (node["x-name"] != null) {
        instruction["x-name"] = node["x-name"];
        instruction["x-publicId"] = node["x-publicId"];
        instruction["x-systemId"] = node["x-systemId"];
      }
      result = instruction;
    } else {
      throw new Error("Not implemented yet: ".concat(node.type));
    }
    result.startIndex = node.startIndex;
    result.endIndex = node.endIndex;
    if (node.sourceCodeLocation != null) {
      result.sourceCodeLocation = node.sourceCodeLocation;
    }
    return result;
  }
  exports.cloneNode = cloneNode;
  function cloneChildren(childs) {
    var children = childs.map(function(child) {
      return cloneNode(child, true);
    });
    for (var i = 1;i < children.length; i++) {
      children[i].prev = children[i - 1];
      children[i - 1].next = children[i];
    }
    return children;
  }
});

// node_modules/domhandler/lib/index.js
var require_lib2 = __commonJS((exports) => {
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() {
        return m[k];
      } };
    }
    Object.defineProperty(o, k2, desc);
  } : function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    o[k2] = m[k];
  });
  var __exportStar = exports && exports.__exportStar || function(m, exports2) {
    for (var p in m)
      if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
        __createBinding(exports2, m, p);
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.DomHandler = undefined;
  var domelementtype_1 = require_lib();
  var node_js_1 = require_node2();
  __exportStar(require_node2(), exports);
  var defaultOpts = {
    withStartIndices: false,
    withEndIndices: false,
    xmlMode: false
  };
  var DomHandler = function() {
    function DomHandler2(callback, options, elementCB) {
      this.dom = [];
      this.root = new node_js_1.Document(this.dom);
      this.done = false;
      this.tagStack = [this.root];
      this.lastNode = null;
      this.parser = null;
      if (typeof options === "function") {
        elementCB = options;
        options = defaultOpts;
      }
      if (typeof callback === "object") {
        options = callback;
        callback = undefined;
      }
      this.callback = callback !== null && callback !== undefined ? callback : null;
      this.options = options !== null && options !== undefined ? options : defaultOpts;
      this.elementCB = elementCB !== null && elementCB !== undefined ? elementCB : null;
    }
    DomHandler2.prototype.onparserinit = function(parser2) {
      this.parser = parser2;
    };
    DomHandler2.prototype.onreset = function() {
      this.dom = [];
      this.root = new node_js_1.Document(this.dom);
      this.done = false;
      this.tagStack = [this.root];
      this.lastNode = null;
      this.parser = null;
    };
    DomHandler2.prototype.onend = function() {
      if (this.done)
        return;
      this.done = true;
      this.parser = null;
      this.handleCallback(null);
    };
    DomHandler2.prototype.onerror = function(error49) {
      this.handleCallback(error49);
    };
    DomHandler2.prototype.onclosetag = function() {
      this.lastNode = null;
      var elem = this.tagStack.pop();
      if (this.options.withEndIndices) {
        elem.endIndex = this.parser.endIndex;
      }
      if (this.elementCB)
        this.elementCB(elem);
    };
    DomHandler2.prototype.onopentag = function(name2, attribs) {
      var type = this.options.xmlMode ? domelementtype_1.ElementType.Tag : undefined;
      var element = new node_js_1.Element(name2, attribs, undefined, type);
      this.addNode(element);
      this.tagStack.push(element);
    };
    DomHandler2.prototype.ontext = function(data2) {
      var lastNode = this.lastNode;
      if (lastNode && lastNode.type === domelementtype_1.ElementType.Text) {
        lastNode.data += data2;
        if (this.options.withEndIndices) {
          lastNode.endIndex = this.parser.endIndex;
        }
      } else {
        var node = new node_js_1.Text(data2);
        this.addNode(node);
        this.lastNode = node;
      }
    };
    DomHandler2.prototype.oncomment = function(data2) {
      if (this.lastNode && this.lastNode.type === domelementtype_1.ElementType.Comment) {
        this.lastNode.data += data2;
        return;
      }
      var node = new node_js_1.Comment(data2);
      this.addNode(node);
      this.lastNode = node;
    };
    DomHandler2.prototype.oncommentend = function() {
      this.lastNode = null;
    };
    DomHandler2.prototype.oncdatastart = function() {
      var text3 = new node_js_1.Text("");
      var node = new node_js_1.CDATA([text3]);
      this.addNode(node);
      text3.parent = node;
      this.lastNode = text3;
    };
    DomHandler2.prototype.oncdataend = function() {
      this.lastNode = null;
    };
    DomHandler2.prototype.onprocessinginstruction = function(name2, data2) {
      var node = new node_js_1.ProcessingInstruction(name2, data2);
      this.addNode(node);
    };
    DomHandler2.prototype.handleCallback = function(error49) {
      if (typeof this.callback === "function") {
        this.callback(error49, this.dom);
      } else if (error49) {
        throw error49;
      }
    };
    DomHandler2.prototype.addNode = function(node) {
      var parent = this.tagStack[this.tagStack.length - 1];
      var previousSibling = parent.children[parent.children.length - 1];
      if (this.options.withStartIndices) {
        node.startIndex = this.parser.startIndex;
      }
      if (this.options.withEndIndices) {
        node.endIndex = this.parser.endIndex;
      }
      parent.children.push(node);
      if (previousSibling) {
        node.prev = previousSibling;
        previousSibling.next = node;
      }
      node.parent = parent;
      this.lastNode = null;
    };
    return DomHandler2;
  }();
  exports.DomHandler = DomHandler;
  exports.default = DomHandler;
});

// node_modules/entities/lib/generated/decode-data-html.js
var require_decode_data_html = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.default = new Uint16Array("ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\x00\x00\x00\x00\x00\x00ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀\uD835\uDD04rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀\uD835\uDD38plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀\uD835\uDC9Cign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀\uD835\uDD05pf;쀀\uD835\uDD39eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTǇǋǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀\uD835\uDC9EpĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀\uD835\uDD07Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\x00\x00\x00͔͂\x00Ѕf;쀀\uD835\uDD3Bƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\x00\x00ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\x00\x00ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\x00ц\x00ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\x00ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀\uD835\uDC9Frok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀\uD835\uDD08rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\x00\x00ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀\uD835\uDD3Csilon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀\uD835\uDD09lledɓ֗\x00\x00֣mallSquare;旼erySmallSquare;斪Ͱֺ\x00ֿ\x00\x00ׄf;쀀\uD835\uDD3DAll;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀\uD835\uDD0A;拙pf;쀀\uD835\uDD3Eeater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀\uD835\uDCA2;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\x00ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\x00ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀\uD835\uDD40a;䎙cr;愐ilde;䄨ǫޚ\x00ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀\uD835\uDD0Dpf;쀀\uD835\uDD41ǣ߇\x00ߌr;쀀\uD835\uDCA5rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀\uD835\uDD0Epf;쀀\uD835\uDD42cr;쀀\uD835\uDCA6րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\x00ࣃbleBracket;柦nǔࣈ\x00࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀\uD835\uDD0FĀ;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀\uD835\uDD43erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀\uD835\uDD10nusPlus;戓pf;쀀\uD835\uDD44cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀\uD835\uDD11ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀\uD835\uDCA9ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀\uD835\uDD12rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀\uD835\uDD46enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀\uD835\uDCAAash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀\uD835\uDD13i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀\uD835\uDCAB;䎨ȀUfos༑༖༛༟OT耻\"䀢r;쀀\uD835\uDD14pf;愚cr;쀀\uD835\uDCAC؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\x00စbleBracket;柧nǔည\x00နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀\uD835\uDD16ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀\uD835\uDD4Aɲᅭ\x00\x00ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀\uD835\uDCAEar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀\uD835\uDD17Āeiቻ኉ǲኀ\x00ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀\uD835\uDD4BipleDot;惛Āctዖዛr;쀀\uD835\uDCAFrok;䅦ૡዷጎጚጦ\x00ጬጱ\x00\x00\x00\x00\x00ጸጽ፷ᎅ\x00᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\x00጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀\uD835\uDD18rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀\uD835\uDD4CЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀\uD835\uDCB0ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀\uD835\uDD19pf;쀀\uD835\uDD4Dcr;쀀\uD835\uDCB1dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀\uD835\uDD1Apf;쀀\uD835\uDD4Ecr;쀀\uD835\uDCB2Ȁfiosᓋᓐᓒᓘr;쀀\uD835\uDD1B;䎞pf;쀀\uD835\uDD4Fcr;쀀\uD835\uDCB3ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀\uD835\uDD1Cpf;쀀\uD835\uDD50cr;쀀\uD835\uDCB4ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻ǲᕔ\x00ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀\uD835\uDCB5௡ᖃᖊᖐ\x00ᖰᖶᖿ\x00\x00\x00\x00ᗆᗛᗫᙟ᙭\x00ᚕ᚛ᚲᚹ\x00ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀\uD835\uDD1Erave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\x00\x00ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀\uD835\uDD52΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀\uD835\uDCB6;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀\uD835\uDD1Fg΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\x00\x00ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\x00ᠳƲᠯ\x00ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀\uD835\uDD53Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀\uD835\uDCB7mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\x00᧨ᨑᨕᨲ\x00ᨷᩐ\x00\x00᪴\x00\x00᫁\x00\x00ᬡᬮ᭍᭒\x00᯽\x00ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\x00᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀\uD835\uDD20ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\x00\x00᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\x00ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\x00\x00᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\x00ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀\uD835\uDD54oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀\uD835\uDCB8Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\x00\x00᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\x00\x00ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀\uD835\uDD21arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\x00\x00ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀\uD835\uDD55ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\x00\x00ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀\uD835\uDCB9;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀\uD835\uDD22ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤĳạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀\uD835\uDD56ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\x00\x00ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\x00ᾞ\x00ᾡᾧ\x00\x00ῆῌ\x00ΐ\x00ῦῪ \x00 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ﬃɩᾹ\x00\x00᾽g;耀ﬀig;耀ﬄ;쀀\uD835\uDD23lig;耀ﬁlig;쀀fjƀaltῙ῜ῡt;晭ig;耀ﬂns;斱of;䆒ǰ΅\x00ῳf;쀀\uD835\uDD57ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒α‚‰‸⁅⁈\x00⁐β•‥‧‪‬\x00‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\x00‶;慔;慖ʴ‾⁁\x00\x00⁃耻¾䂾;慗;慜5;慘ƶ⁌\x00⁎;慚;慝8;慞l;恄wn;挢cr;쀀\uD835\uDCBBࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀\uD835\uDD24Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀\uD835\uDD58Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\x00↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀\uD835\uDD25sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀\uD835\uDD59bar;怕ƀclt≯≴≸r;쀀\uD835\uDCBDasè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\x00⊪\x00⊸⋅⋎\x00⋕⋳\x00\x00⋸⌢⍧⍢⍿\x00⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀\uD835\uDD26rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀\uD835\uDD5Aa;䎹uest耻¿䂿Āci⎊⎏r;쀀\uD835\uDCBEnʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\x00⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀\uD835\uDD27ath;䈷pf;쀀\uD835\uDD5Bǣ⏬\x00⏱r;쀀\uD835\uDCBFrcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀\uD835\uDD28reen;䄸cy;䑅cy;䑜pf;쀀\uD835\uDD5Ccr;쀀\uD835\uDCC0஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\x00⒪\x00⒱\x00\x00\x00\x00\x00⒵Ⓔ\x00ⓆⓈⓍ\x00⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀\uD835\uDD29Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀\uD835\uDD5Dus;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀\uD835\uDCC1mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀\uD835\uDD2Ao;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀\uD835\uDD5EĀct⣸⣽r;쀀\uD835\uDCC2pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସǳ⧟\x00⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\x00⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀\uD835\uDD2BȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀\uD835\uDD5F膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀\uD835\uDCC3ortɭ⬅\x00\x00⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00ⴭ\x00ⴸⵈⵠⵥ⵲ⶄᬇ\x00\x00ⶍⶫ\x00ⷈⷎ\x00ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗǈⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀\uD835\uDD2Cͯ⵹\x00\x00⵼\x00ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀\uD835\uDD60ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\x00⹽\x00⺀⺝\x00⺢⺹\x00\x00⻋ຜ\x00⼓\x00\x00⼫⾼\x00⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\x00\x00⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀\uD835\uDD2Dƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀\uD835\uDD61nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀\uD835\uDCC5;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀\uD835\uDD2Epf;쀀\uD835\uDD62rime;恗cr;쀀\uD835\uDCC6ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀\uD835\uDD2FĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀\uD835\uDD63us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀\uD835\uDCC7Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\x00㍺㎤\x00\x00㏬㏰\x00㐨㑈㑚㒭㒱㓊㓱\x00㘖\x00\x00㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\x00㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀\uD835\uDD30Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\x00\x00㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀\uD835\uDD64aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀\uD835\uDCC8tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\x00㙾㛂\x00\x00\x00\x00\x00㛛㜃\x00㜉㝬\x00\x00\x00㞇ɲ㙖\x00\x00㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀\uD835\uDD31Ȁeiko㚆㚝㚵㚼ǲ㚋\x00㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀\uD835\uDD65rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀\uD835\uDCC9;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\x00㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀\uD835\uDD32rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\x00\x00㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀\uD835\uDD66̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\x00\x00㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀\uD835\uDCCAƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀\uD835\uDD33tré㦮suĀbp㧯㧱»ജ»൙pf;쀀\uD835\uDD67roð໻tré㦴Ācu㨆㨋r;쀀\uD835\uDCCBĀbp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀\uD835\uDD34pf;쀀\uD835\uDD68Ā;eᑹ㩦atèᑹcr;쀀\uD835\uDCCCૣណ㪇\x00㪋\x00㪐㪛\x00\x00㪝㪨㪫㪯\x00\x00㫃㫎\x00㫘ៜ៟tré៑r;쀀\uD835\uDD35ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀\uD835\uDD69imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀\uD835\uDCCDĀpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀\uD835\uDD36cy;䑗pf;쀀\uD835\uDD6Acr;쀀\uD835\uDCCEĀcm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀\uD835\uDD37cy;䐶grarr;懝pf;쀀\uD835\uDD6Bcr;쀀\uD835\uDCCFĀjn㮅㮇;怍j;怌".split("").map(function(c) {
    return c.charCodeAt(0);
  }));
});

// node_modules/entities/lib/generated/decode-data-xml.js
var require_decode_data_xml = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.default = new Uint16Array("Ȁaglq\t\x15\x18\x1Bɭ\x0F\x00\x00\x12p;䀦os;䀧t;䀾t;䀼uot;䀢".split("").map(function(c) {
    return c.charCodeAt(0);
  }));
});

// node_modules/entities/lib/decode_codepoint.js
var require_decode_codepoint = __commonJS((exports) => {
  var _a2;
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.replaceCodePoint = exports.fromCodePoint = undefined;
  var decodeMap = new Map([
    [0, 65533],
    [128, 8364],
    [130, 8218],
    [131, 402],
    [132, 8222],
    [133, 8230],
    [134, 8224],
    [135, 8225],
    [136, 710],
    [137, 8240],
    [138, 352],
    [139, 8249],
    [140, 338],
    [142, 381],
    [145, 8216],
    [146, 8217],
    [147, 8220],
    [148, 8221],
    [149, 8226],
    [150, 8211],
    [151, 8212],
    [152, 732],
    [153, 8482],
    [154, 353],
    [155, 8250],
    [156, 339],
    [158, 382],
    [159, 376]
  ]);
  exports.fromCodePoint = (_a2 = String.fromCodePoint) !== null && _a2 !== undefined ? _a2 : function(codePoint) {
    var output = "";
    if (codePoint > 65535) {
      codePoint -= 65536;
      output += String.fromCharCode(codePoint >>> 10 & 1023 | 55296);
      codePoint = 56320 | codePoint & 1023;
    }
    output += String.fromCharCode(codePoint);
    return output;
  };
  function replaceCodePoint(codePoint) {
    var _a3;
    if (codePoint >= 55296 && codePoint <= 57343 || codePoint > 1114111) {
      return 65533;
    }
    return (_a3 = decodeMap.get(codePoint)) !== null && _a3 !== undefined ? _a3 : codePoint;
  }
  exports.replaceCodePoint = replaceCodePoint;
  function decodeCodePoint(codePoint) {
    return (0, exports.fromCodePoint)(replaceCodePoint(codePoint));
  }
  exports.default = decodeCodePoint;
});

// node_modules/entities/lib/decode.js
var require_decode = __commonJS((exports) => {
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() {
        return m[k];
      } };
    }
    Object.defineProperty(o, k2, desc);
  } : function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    o[k2] = m[k];
  });
  var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
  } : function(o, v) {
    o["default"] = v;
  });
  var __importStar = exports && exports.__importStar || function(mod2) {
    if (mod2 && mod2.__esModule)
      return mod2;
    var result = {};
    if (mod2 != null) {
      for (var k in mod2)
        if (k !== "default" && Object.prototype.hasOwnProperty.call(mod2, k))
          __createBinding(result, mod2, k);
    }
    __setModuleDefault(result, mod2);
    return result;
  };
  var __importDefault = exports && exports.__importDefault || function(mod2) {
    return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.decodeXML = exports.decodeHTMLStrict = exports.decodeHTMLAttribute = exports.decodeHTML = exports.determineBranch = exports.EntityDecoder = exports.DecodingMode = exports.BinTrieFlags = exports.fromCodePoint = exports.replaceCodePoint = exports.decodeCodePoint = exports.xmlDecodeTree = exports.htmlDecodeTree = undefined;
  var decode_data_html_js_1 = __importDefault(require_decode_data_html());
  exports.htmlDecodeTree = decode_data_html_js_1.default;
  var decode_data_xml_js_1 = __importDefault(require_decode_data_xml());
  exports.xmlDecodeTree = decode_data_xml_js_1.default;
  var decode_codepoint_js_1 = __importStar(require_decode_codepoint());
  exports.decodeCodePoint = decode_codepoint_js_1.default;
  var decode_codepoint_js_2 = require_decode_codepoint();
  Object.defineProperty(exports, "replaceCodePoint", { enumerable: true, get: function() {
    return decode_codepoint_js_2.replaceCodePoint;
  } });
  Object.defineProperty(exports, "fromCodePoint", { enumerable: true, get: function() {
    return decode_codepoint_js_2.fromCodePoint;
  } });
  var CharCodes;
  (function(CharCodes2) {
    CharCodes2[CharCodes2["NUM"] = 35] = "NUM";
    CharCodes2[CharCodes2["SEMI"] = 59] = "SEMI";
    CharCodes2[CharCodes2["EQUALS"] = 61] = "EQUALS";
    CharCodes2[CharCodes2["ZERO"] = 48] = "ZERO";
    CharCodes2[CharCodes2["NINE"] = 57] = "NINE";
    CharCodes2[CharCodes2["LOWER_A"] = 97] = "LOWER_A";
    CharCodes2[CharCodes2["LOWER_F"] = 102] = "LOWER_F";
    CharCodes2[CharCodes2["LOWER_X"] = 120] = "LOWER_X";
    CharCodes2[CharCodes2["LOWER_Z"] = 122] = "LOWER_Z";
    CharCodes2[CharCodes2["UPPER_A"] = 65] = "UPPER_A";
    CharCodes2[CharCodes2["UPPER_F"] = 70] = "UPPER_F";
    CharCodes2[CharCodes2["UPPER_Z"] = 90] = "UPPER_Z";
  })(CharCodes || (CharCodes = {}));
  var TO_LOWER_BIT = 32;
  var BinTrieFlags;
  (function(BinTrieFlags2) {
    BinTrieFlags2[BinTrieFlags2["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
    BinTrieFlags2[BinTrieFlags2["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH";
    BinTrieFlags2[BinTrieFlags2["JUMP_TABLE"] = 127] = "JUMP_TABLE";
  })(BinTrieFlags = exports.BinTrieFlags || (exports.BinTrieFlags = {}));
  function isNumber2(code) {
    return code >= CharCodes.ZERO && code <= CharCodes.NINE;
  }
  function isHexadecimalCharacter(code) {
    return code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F || code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F;
  }
  function isAsciiAlphaNumeric(code) {
    return code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z || code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z || isNumber2(code);
  }
  function isEntityInAttributeInvalidEnd(code) {
    return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code);
  }
  var EntityDecoderState;
  (function(EntityDecoderState2) {
    EntityDecoderState2[EntityDecoderState2["EntityStart"] = 0] = "EntityStart";
    EntityDecoderState2[EntityDecoderState2["NumericStart"] = 1] = "NumericStart";
    EntityDecoderState2[EntityDecoderState2["NumericDecimal"] = 2] = "NumericDecimal";
    EntityDecoderState2[EntityDecoderState2["NumericHex"] = 3] = "NumericHex";
    EntityDecoderState2[EntityDecoderState2["NamedEntity"] = 4] = "NamedEntity";
  })(EntityDecoderState || (EntityDecoderState = {}));
  var DecodingMode;
  (function(DecodingMode2) {
    DecodingMode2[DecodingMode2["Legacy"] = 0] = "Legacy";
    DecodingMode2[DecodingMode2["Strict"] = 1] = "Strict";
    DecodingMode2[DecodingMode2["Attribute"] = 2] = "Attribute";
  })(DecodingMode = exports.DecodingMode || (exports.DecodingMode = {}));
  var EntityDecoder = function() {
    function EntityDecoder2(decodeTree, emitCodePoint, errors5) {
      this.decodeTree = decodeTree;
      this.emitCodePoint = emitCodePoint;
      this.errors = errors5;
      this.state = EntityDecoderState.EntityStart;
      this.consumed = 1;
      this.result = 0;
      this.treeIndex = 0;
      this.excess = 1;
      this.decodeMode = DecodingMode.Strict;
    }
    EntityDecoder2.prototype.startEntity = function(decodeMode) {
      this.decodeMode = decodeMode;
      this.state = EntityDecoderState.EntityStart;
      this.result = 0;
      this.treeIndex = 0;
      this.excess = 1;
      this.consumed = 1;
    };
    EntityDecoder2.prototype.write = function(str, offset) {
      switch (this.state) {
        case EntityDecoderState.EntityStart: {
          if (str.charCodeAt(offset) === CharCodes.NUM) {
            this.state = EntityDecoderState.NumericStart;
            this.consumed += 1;
            return this.stateNumericStart(str, offset + 1);
          }
          this.state = EntityDecoderState.NamedEntity;
          return this.stateNamedEntity(str, offset);
        }
        case EntityDecoderState.NumericStart: {
          return this.stateNumericStart(str, offset);
        }
        case EntityDecoderState.NumericDecimal: {
          return this.stateNumericDecimal(str, offset);
        }
        case EntityDecoderState.NumericHex: {
          return this.stateNumericHex(str, offset);
        }
        case EntityDecoderState.NamedEntity: {
          return this.stateNamedEntity(str, offset);
        }
      }
    };
    EntityDecoder2.prototype.stateNumericStart = function(str, offset) {
      if (offset >= str.length) {
        return -1;
      }
      if ((str.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
        this.state = EntityDecoderState.NumericHex;
        this.consumed += 1;
        return this.stateNumericHex(str, offset + 1);
      }
      this.state = EntityDecoderState.NumericDecimal;
      return this.stateNumericDecimal(str, offset);
    };
    EntityDecoder2.prototype.addToNumericResult = function(str, start, end, base) {
      if (start !== end) {
        var digitCount = end - start;
        this.result = this.result * Math.pow(base, digitCount) + parseInt(str.substr(start, digitCount), base);
        this.consumed += digitCount;
      }
    };
    EntityDecoder2.prototype.stateNumericHex = function(str, offset) {
      var startIdx = offset;
      while (offset < str.length) {
        var char = str.charCodeAt(offset);
        if (isNumber2(char) || isHexadecimalCharacter(char)) {
          offset += 1;
        } else {
          this.addToNumericResult(str, startIdx, offset, 16);
          return this.emitNumericEntity(char, 3);
        }
      }
      this.addToNumericResult(str, startIdx, offset, 16);
      return -1;
    };
    EntityDecoder2.prototype.stateNumericDecimal = function(str, offset) {
      var startIdx = offset;
      while (offset < str.length) {
        var char = str.charCodeAt(offset);
        if (isNumber2(char)) {
          offset += 1;
        } else {
          this.addToNumericResult(str, startIdx, offset, 10);
          return this.emitNumericEntity(char, 2);
        }
      }
      this.addToNumericResult(str, startIdx, offset, 10);
      return -1;
    };
    EntityDecoder2.prototype.emitNumericEntity = function(lastCp, expectedLength) {
      var _a2;
      if (this.consumed <= expectedLength) {
        (_a2 = this.errors) === null || _a2 === undefined || _a2.absenceOfDigitsInNumericCharacterReference(this.consumed);
        return 0;
      }
      if (lastCp === CharCodes.SEMI) {
        this.consumed += 1;
      } else if (this.decodeMode === DecodingMode.Strict) {
        return 0;
      }
      this.emitCodePoint((0, decode_codepoint_js_1.replaceCodePoint)(this.result), this.consumed);
      if (this.errors) {
        if (lastCp !== CharCodes.SEMI) {
          this.errors.missingSemicolonAfterCharacterReference();
        }
        this.errors.validateNumericCharacterReference(this.result);
      }
      return this.consumed;
    };
    EntityDecoder2.prototype.stateNamedEntity = function(str, offset) {
      var decodeTree = this.decodeTree;
      var current = decodeTree[this.treeIndex];
      var valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
      for (;offset < str.length; offset++, this.excess++) {
        var char = str.charCodeAt(offset);
        this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char);
        if (this.treeIndex < 0) {
          return this.result === 0 || this.decodeMode === DecodingMode.Attribute && (valueLength === 0 || isEntityInAttributeInvalidEnd(char)) ? 0 : this.emitNotTerminatedNamedEntity();
        }
        current = decodeTree[this.treeIndex];
        valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
        if (valueLength !== 0) {
          if (char === CharCodes.SEMI) {
            return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
          }
          if (this.decodeMode !== DecodingMode.Strict) {
            this.result = this.treeIndex;
            this.consumed += this.excess;
            this.excess = 0;
          }
        }
      }
      return -1;
    };
    EntityDecoder2.prototype.emitNotTerminatedNamedEntity = function() {
      var _a2;
      var _b = this, result = _b.result, decodeTree = _b.decodeTree;
      var valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14;
      this.emitNamedEntityData(result, valueLength, this.consumed);
      (_a2 = this.errors) === null || _a2 === undefined || _a2.missingSemicolonAfterCharacterReference();
      return this.consumed;
    };
    EntityDecoder2.prototype.emitNamedEntityData = function(result, valueLength, consumed) {
      var decodeTree = this.decodeTree;
      this.emitCodePoint(valueLength === 1 ? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH : decodeTree[result + 1], consumed);
      if (valueLength === 3) {
        this.emitCodePoint(decodeTree[result + 2], consumed);
      }
      return consumed;
    };
    EntityDecoder2.prototype.end = function() {
      var _a2;
      switch (this.state) {
        case EntityDecoderState.NamedEntity: {
          return this.result !== 0 && (this.decodeMode !== DecodingMode.Attribute || this.result === this.treeIndex) ? this.emitNotTerminatedNamedEntity() : 0;
        }
        case EntityDecoderState.NumericDecimal: {
          return this.emitNumericEntity(0, 2);
        }
        case EntityDecoderState.NumericHex: {
          return this.emitNumericEntity(0, 3);
        }
        case EntityDecoderState.NumericStart: {
          (_a2 = this.errors) === null || _a2 === undefined || _a2.absenceOfDigitsInNumericCharacterReference(this.consumed);
          return 0;
        }
        case EntityDecoderState.EntityStart: {
          return 0;
        }
      }
    };
    return EntityDecoder2;
  }();
  exports.EntityDecoder = EntityDecoder;
  function getDecoder(decodeTree) {
    var ret = "";
    var decoder = new EntityDecoder(decodeTree, function(str) {
      return ret += (0, decode_codepoint_js_1.fromCodePoint)(str);
    });
    return function decodeWithTrie(str, decodeMode) {
      var lastIndex = 0;
      var offset = 0;
      while ((offset = str.indexOf("&", offset)) >= 0) {
        ret += str.slice(lastIndex, offset);
        decoder.startEntity(decodeMode);
        var len = decoder.write(str, offset + 1);
        if (len < 0) {
          lastIndex = offset + decoder.end();
          break;
        }
        lastIndex = offset + len;
        offset = len === 0 ? lastIndex + 1 : lastIndex;
      }
      var result = ret + str.slice(lastIndex);
      ret = "";
      return result;
    };
  }
  function determineBranch(decodeTree, current, nodeIdx, char) {
    var branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
    var jumpOffset = current & BinTrieFlags.JUMP_TABLE;
    if (branchCount === 0) {
      return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1;
    }
    if (jumpOffset) {
      var value2 = char - jumpOffset;
      return value2 < 0 || value2 >= branchCount ? -1 : decodeTree[nodeIdx + value2] - 1;
    }
    var lo = nodeIdx;
    var hi = lo + branchCount - 1;
    while (lo <= hi) {
      var mid = lo + hi >>> 1;
      var midVal = decodeTree[mid];
      if (midVal < char) {
        lo = mid + 1;
      } else if (midVal > char) {
        hi = mid - 1;
      } else {
        return decodeTree[mid + branchCount];
      }
    }
    return -1;
  }
  exports.determineBranch = determineBranch;
  var htmlDecoder = getDecoder(decode_data_html_js_1.default);
  var xmlDecoder = getDecoder(decode_data_xml_js_1.default);
  function decodeHTML(str, mode) {
    if (mode === undefined) {
      mode = DecodingMode.Legacy;
    }
    return htmlDecoder(str, mode);
  }
  exports.decodeHTML = decodeHTML;
  function decodeHTMLAttribute(str) {
    return htmlDecoder(str, DecodingMode.Attribute);
  }
  exports.decodeHTMLAttribute = decodeHTMLAttribute;
  function decodeHTMLStrict(str) {
    return htmlDecoder(str, DecodingMode.Strict);
  }
  exports.decodeHTMLStrict = decodeHTMLStrict;
  function decodeXML(str) {
    return xmlDecoder(str, DecodingMode.Strict);
  }
  exports.decodeXML = decodeXML;
});

// node_modules/entities/lib/generated/encode-html.js
var require_encode_html = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  function restoreDiff(arr) {
    for (var i = 1;i < arr.length; i++) {
      arr[i][0] += arr[i - 1][0] + 1;
    }
    return arr;
  }
  exports.default = new Map(/* @__PURE__ */ restoreDiff([[9, "&Tab;"], [0, "&NewLine;"], [22, "&excl;"], [0, "&quot;"], [0, "&num;"], [0, "&dollar;"], [0, "&percnt;"], [0, "&amp;"], [0, "&apos;"], [0, "&lpar;"], [0, "&rpar;"], [0, "&ast;"], [0, "&plus;"], [0, "&comma;"], [1, "&period;"], [0, "&sol;"], [10, "&colon;"], [0, "&semi;"], [0, { v: "&lt;", n: 8402, o: "&nvlt;" }], [0, { v: "&equals;", n: 8421, o: "&bne;" }], [0, { v: "&gt;", n: 8402, o: "&nvgt;" }], [0, "&quest;"], [0, "&commat;"], [26, "&lbrack;"], [0, "&bsol;"], [0, "&rbrack;"], [0, "&Hat;"], [0, "&lowbar;"], [0, "&DiacriticalGrave;"], [5, { n: 106, o: "&fjlig;" }], [20, "&lbrace;"], [0, "&verbar;"], [0, "&rbrace;"], [34, "&nbsp;"], [0, "&iexcl;"], [0, "&cent;"], [0, "&pound;"], [0, "&curren;"], [0, "&yen;"], [0, "&brvbar;"], [0, "&sect;"], [0, "&die;"], [0, "&copy;"], [0, "&ordf;"], [0, "&laquo;"], [0, "&not;"], [0, "&shy;"], [0, "&circledR;"], [0, "&macr;"], [0, "&deg;"], [0, "&PlusMinus;"], [0, "&sup2;"], [0, "&sup3;"], [0, "&acute;"], [0, "&micro;"], [0, "&para;"], [0, "&centerdot;"], [0, "&cedil;"], [0, "&sup1;"], [0, "&ordm;"], [0, "&raquo;"], [0, "&frac14;"], [0, "&frac12;"], [0, "&frac34;"], [0, "&iquest;"], [0, "&Agrave;"], [0, "&Aacute;"], [0, "&Acirc;"], [0, "&Atilde;"], [0, "&Auml;"], [0, "&angst;"], [0, "&AElig;"], [0, "&Ccedil;"], [0, "&Egrave;"], [0, "&Eacute;"], [0, "&Ecirc;"], [0, "&Euml;"], [0, "&Igrave;"], [0, "&Iacute;"], [0, "&Icirc;"], [0, "&Iuml;"], [0, "&ETH;"], [0, "&Ntilde;"], [0, "&Ograve;"], [0, "&Oacute;"], [0, "&Ocirc;"], [0, "&Otilde;"], [0, "&Ouml;"], [0, "&times;"], [0, "&Oslash;"], [0, "&Ugrave;"], [0, "&Uacute;"], [0, "&Ucirc;"], [0, "&Uuml;"], [0, "&Yacute;"], [0, "&THORN;"], [0, "&szlig;"], [0, "&agrave;"], [0, "&aacute;"], [0, "&acirc;"], [0, "&atilde;"], [0, "&auml;"], [0, "&aring;"], [0, "&aelig;"], [0, "&ccedil;"], [0, "&egrave;"], [0, "&eacute;"], [0, "&ecirc;"], [0, "&euml;"], [0, "&igrave;"], [0, "&iacute;"], [0, "&icirc;"], [0, "&iuml;"], [0, "&eth;"], [0, "&ntilde;"], [0, "&ograve;"], [0, "&oacute;"], [0, "&ocirc;"], [0, "&otilde;"], [0, "&ouml;"], [0, "&div;"], [0, "&oslash;"], [0, "&ugrave;"], [0, "&uacute;"], [0, "&ucirc;"], [0, "&uuml;"], [0, "&yacute;"], [0, "&thorn;"], [0, "&yuml;"], [0, "&Amacr;"], [0, "&amacr;"], [0, "&Abreve;"], [0, "&abreve;"], [0, "&Aogon;"], [0, "&aogon;"], [0, "&Cacute;"], [0, "&cacute;"], [0, "&Ccirc;"], [0, "&ccirc;"], [0, "&Cdot;"], [0, "&cdot;"], [0, "&Ccaron;"], [0, "&ccaron;"], [0, "&Dcaron;"], [0, "&dcaron;"], [0, "&Dstrok;"], [0, "&dstrok;"], [0, "&Emacr;"], [0, "&emacr;"], [2, "&Edot;"], [0, "&edot;"], [0, "&Eogon;"], [0, "&eogon;"], [0, "&Ecaron;"], [0, "&ecaron;"], [0, "&Gcirc;"], [0, "&gcirc;"], [0, "&Gbreve;"], [0, "&gbreve;"], [0, "&Gdot;"], [0, "&gdot;"], [0, "&Gcedil;"], [1, "&Hcirc;"], [0, "&hcirc;"], [0, "&Hstrok;"], [0, "&hstrok;"], [0, "&Itilde;"], [0, "&itilde;"], [0, "&Imacr;"], [0, "&imacr;"], [2, "&Iogon;"], [0, "&iogon;"], [0, "&Idot;"], [0, "&imath;"], [0, "&IJlig;"], [0, "&ijlig;"], [0, "&Jcirc;"], [0, "&jcirc;"], [0, "&Kcedil;"], [0, "&kcedil;"], [0, "&kgreen;"], [0, "&Lacute;"], [0, "&lacute;"], [0, "&Lcedil;"], [0, "&lcedil;"], [0, "&Lcaron;"], [0, "&lcaron;"], [0, "&Lmidot;"], [0, "&lmidot;"], [0, "&Lstrok;"], [0, "&lstrok;"], [0, "&Nacute;"], [0, "&nacute;"], [0, "&Ncedil;"], [0, "&ncedil;"], [0, "&Ncaron;"], [0, "&ncaron;"], [0, "&napos;"], [0, "&ENG;"], [0, "&eng;"], [0, "&Omacr;"], [0, "&omacr;"], [2, "&Odblac;"], [0, "&odblac;"], [0, "&OElig;"], [0, "&oelig;"], [0, "&Racute;"], [0, "&racute;"], [0, "&Rcedil;"], [0, "&rcedil;"], [0, "&Rcaron;"], [0, "&rcaron;"], [0, "&Sacute;"], [0, "&sacute;"], [0, "&Scirc;"], [0, "&scirc;"], [0, "&Scedil;"], [0, "&scedil;"], [0, "&Scaron;"], [0, "&scaron;"], [0, "&Tcedil;"], [0, "&tcedil;"], [0, "&Tcaron;"], [0, "&tcaron;"], [0, "&Tstrok;"], [0, "&tstrok;"], [0, "&Utilde;"], [0, "&utilde;"], [0, "&Umacr;"], [0, "&umacr;"], [0, "&Ubreve;"], [0, "&ubreve;"], [0, "&Uring;"], [0, "&uring;"], [0, "&Udblac;"], [0, "&udblac;"], [0, "&Uogon;"], [0, "&uogon;"], [0, "&Wcirc;"], [0, "&wcirc;"], [0, "&Ycirc;"], [0, "&ycirc;"], [0, "&Yuml;"], [0, "&Zacute;"], [0, "&zacute;"], [0, "&Zdot;"], [0, "&zdot;"], [0, "&Zcaron;"], [0, "&zcaron;"], [19, "&fnof;"], [34, "&imped;"], [63, "&gacute;"], [65, "&jmath;"], [142, "&circ;"], [0, "&caron;"], [16, "&breve;"], [0, "&DiacriticalDot;"], [0, "&ring;"], [0, "&ogon;"], [0, "&DiacriticalTilde;"], [0, "&dblac;"], [51, "&DownBreve;"], [127, "&Alpha;"], [0, "&Beta;"], [0, "&Gamma;"], [0, "&Delta;"], [0, "&Epsilon;"], [0, "&Zeta;"], [0, "&Eta;"], [0, "&Theta;"], [0, "&Iota;"], [0, "&Kappa;"], [0, "&Lambda;"], [0, "&Mu;"], [0, "&Nu;"], [0, "&Xi;"], [0, "&Omicron;"], [0, "&Pi;"], [0, "&Rho;"], [1, "&Sigma;"], [0, "&Tau;"], [0, "&Upsilon;"], [0, "&Phi;"], [0, "&Chi;"], [0, "&Psi;"], [0, "&ohm;"], [7, "&alpha;"], [0, "&beta;"], [0, "&gamma;"], [0, "&delta;"], [0, "&epsi;"], [0, "&zeta;"], [0, "&eta;"], [0, "&theta;"], [0, "&iota;"], [0, "&kappa;"], [0, "&lambda;"], [0, "&mu;"], [0, "&nu;"], [0, "&xi;"], [0, "&omicron;"], [0, "&pi;"], [0, "&rho;"], [0, "&sigmaf;"], [0, "&sigma;"], [0, "&tau;"], [0, "&upsi;"], [0, "&phi;"], [0, "&chi;"], [0, "&psi;"], [0, "&omega;"], [7, "&thetasym;"], [0, "&Upsi;"], [2, "&phiv;"], [0, "&piv;"], [5, "&Gammad;"], [0, "&digamma;"], [18, "&kappav;"], [0, "&rhov;"], [3, "&epsiv;"], [0, "&backepsilon;"], [10, "&IOcy;"], [0, "&DJcy;"], [0, "&GJcy;"], [0, "&Jukcy;"], [0, "&DScy;"], [0, "&Iukcy;"], [0, "&YIcy;"], [0, "&Jsercy;"], [0, "&LJcy;"], [0, "&NJcy;"], [0, "&TSHcy;"], [0, "&KJcy;"], [1, "&Ubrcy;"], [0, "&DZcy;"], [0, "&Acy;"], [0, "&Bcy;"], [0, "&Vcy;"], [0, "&Gcy;"], [0, "&Dcy;"], [0, "&IEcy;"], [0, "&ZHcy;"], [0, "&Zcy;"], [0, "&Icy;"], [0, "&Jcy;"], [0, "&Kcy;"], [0, "&Lcy;"], [0, "&Mcy;"], [0, "&Ncy;"], [0, "&Ocy;"], [0, "&Pcy;"], [0, "&Rcy;"], [0, "&Scy;"], [0, "&Tcy;"], [0, "&Ucy;"], [0, "&Fcy;"], [0, "&KHcy;"], [0, "&TScy;"], [0, "&CHcy;"], [0, "&SHcy;"], [0, "&SHCHcy;"], [0, "&HARDcy;"], [0, "&Ycy;"], [0, "&SOFTcy;"], [0, "&Ecy;"], [0, "&YUcy;"], [0, "&YAcy;"], [0, "&acy;"], [0, "&bcy;"], [0, "&vcy;"], [0, "&gcy;"], [0, "&dcy;"], [0, "&iecy;"], [0, "&zhcy;"], [0, "&zcy;"], [0, "&icy;"], [0, "&jcy;"], [0, "&kcy;"], [0, "&lcy;"], [0, "&mcy;"], [0, "&ncy;"], [0, "&ocy;"], [0, "&pcy;"], [0, "&rcy;"], [0, "&scy;"], [0, "&tcy;"], [0, "&ucy;"], [0, "&fcy;"], [0, "&khcy;"], [0, "&tscy;"], [0, "&chcy;"], [0, "&shcy;"], [0, "&shchcy;"], [0, "&hardcy;"], [0, "&ycy;"], [0, "&softcy;"], [0, "&ecy;"], [0, "&yucy;"], [0, "&yacy;"], [1, "&iocy;"], [0, "&djcy;"], [0, "&gjcy;"], [0, "&jukcy;"], [0, "&dscy;"], [0, "&iukcy;"], [0, "&yicy;"], [0, "&jsercy;"], [0, "&ljcy;"], [0, "&njcy;"], [0, "&tshcy;"], [0, "&kjcy;"], [1, "&ubrcy;"], [0, "&dzcy;"], [7074, "&ensp;"], [0, "&emsp;"], [0, "&emsp13;"], [0, "&emsp14;"], [1, "&numsp;"], [0, "&puncsp;"], [0, "&ThinSpace;"], [0, "&hairsp;"], [0, "&NegativeMediumSpace;"], [0, "&zwnj;"], [0, "&zwj;"], [0, "&lrm;"], [0, "&rlm;"], [0, "&dash;"], [2, "&ndash;"], [0, "&mdash;"], [0, "&horbar;"], [0, "&Verbar;"], [1, "&lsquo;"], [0, "&CloseCurlyQuote;"], [0, "&lsquor;"], [1, "&ldquo;"], [0, "&CloseCurlyDoubleQuote;"], [0, "&bdquo;"], [1, "&dagger;"], [0, "&Dagger;"], [0, "&bull;"], [2, "&nldr;"], [0, "&hellip;"], [9, "&permil;"], [0, "&pertenk;"], [0, "&prime;"], [0, "&Prime;"], [0, "&tprime;"], [0, "&backprime;"], [3, "&lsaquo;"], [0, "&rsaquo;"], [3, "&oline;"], [2, "&caret;"], [1, "&hybull;"], [0, "&frasl;"], [10, "&bsemi;"], [7, "&qprime;"], [7, { v: "&MediumSpace;", n: 8202, o: "&ThickSpace;" }], [0, "&NoBreak;"], [0, "&af;"], [0, "&InvisibleTimes;"], [0, "&ic;"], [72, "&euro;"], [46, "&tdot;"], [0, "&DotDot;"], [37, "&complexes;"], [2, "&incare;"], [4, "&gscr;"], [0, "&hamilt;"], [0, "&Hfr;"], [0, "&Hopf;"], [0, "&planckh;"], [0, "&hbar;"], [0, "&imagline;"], [0, "&Ifr;"], [0, "&lagran;"], [0, "&ell;"], [1, "&naturals;"], [0, "&numero;"], [0, "&copysr;"], [0, "&weierp;"], [0, "&Popf;"], [0, "&Qopf;"], [0, "&realine;"], [0, "&real;"], [0, "&reals;"], [0, "&rx;"], [3, "&trade;"], [1, "&integers;"], [2, "&mho;"], [0, "&zeetrf;"], [0, "&iiota;"], [2, "&bernou;"], [0, "&Cayleys;"], [1, "&escr;"], [0, "&Escr;"], [0, "&Fouriertrf;"], [1, "&Mellintrf;"], [0, "&order;"], [0, "&alefsym;"], [0, "&beth;"], [0, "&gimel;"], [0, "&daleth;"], [12, "&CapitalDifferentialD;"], [0, "&dd;"], [0, "&ee;"], [0, "&ii;"], [10, "&frac13;"], [0, "&frac23;"], [0, "&frac15;"], [0, "&frac25;"], [0, "&frac35;"], [0, "&frac45;"], [0, "&frac16;"], [0, "&frac56;"], [0, "&frac18;"], [0, "&frac38;"], [0, "&frac58;"], [0, "&frac78;"], [49, "&larr;"], [0, "&ShortUpArrow;"], [0, "&rarr;"], [0, "&darr;"], [0, "&harr;"], [0, "&updownarrow;"], [0, "&nwarr;"], [0, "&nearr;"], [0, "&LowerRightArrow;"], [0, "&LowerLeftArrow;"], [0, "&nlarr;"], [0, "&nrarr;"], [1, { v: "&rarrw;", n: 824, o: "&nrarrw;" }], [0, "&Larr;"], [0, "&Uarr;"], [0, "&Rarr;"], [0, "&Darr;"], [0, "&larrtl;"], [0, "&rarrtl;"], [0, "&LeftTeeArrow;"], [0, "&mapstoup;"], [0, "&map;"], [0, "&DownTeeArrow;"], [1, "&hookleftarrow;"], [0, "&hookrightarrow;"], [0, "&larrlp;"], [0, "&looparrowright;"], [0, "&harrw;"], [0, "&nharr;"], [1, "&lsh;"], [0, "&rsh;"], [0, "&ldsh;"], [0, "&rdsh;"], [1, "&crarr;"], [0, "&cularr;"], [0, "&curarr;"], [2, "&circlearrowleft;"], [0, "&circlearrowright;"], [0, "&leftharpoonup;"], [0, "&DownLeftVector;"], [0, "&RightUpVector;"], [0, "&LeftUpVector;"], [0, "&rharu;"], [0, "&DownRightVector;"], [0, "&dharr;"], [0, "&dharl;"], [0, "&RightArrowLeftArrow;"], [0, "&udarr;"], [0, "&LeftArrowRightArrow;"], [0, "&leftleftarrows;"], [0, "&upuparrows;"], [0, "&rightrightarrows;"], [0, "&ddarr;"], [0, "&leftrightharpoons;"], [0, "&Equilibrium;"], [0, "&nlArr;"], [0, "&nhArr;"], [0, "&nrArr;"], [0, "&DoubleLeftArrow;"], [0, "&DoubleUpArrow;"], [0, "&DoubleRightArrow;"], [0, "&dArr;"], [0, "&DoubleLeftRightArrow;"], [0, "&DoubleUpDownArrow;"], [0, "&nwArr;"], [0, "&neArr;"], [0, "&seArr;"], [0, "&swArr;"], [0, "&lAarr;"], [0, "&rAarr;"], [1, "&zigrarr;"], [6, "&larrb;"], [0, "&rarrb;"], [15, "&DownArrowUpArrow;"], [7, "&loarr;"], [0, "&roarr;"], [0, "&hoarr;"], [0, "&forall;"], [0, "&comp;"], [0, { v: "&part;", n: 824, o: "&npart;" }], [0, "&exist;"], [0, "&nexist;"], [0, "&empty;"], [1, "&Del;"], [0, "&Element;"], [0, "&NotElement;"], [1, "&ni;"], [0, "&notni;"], [2, "&prod;"], [0, "&coprod;"], [0, "&sum;"], [0, "&minus;"], [0, "&MinusPlus;"], [0, "&dotplus;"], [1, "&Backslash;"], [0, "&lowast;"], [0, "&compfn;"], [1, "&radic;"], [2, "&prop;"], [0, "&infin;"], [0, "&angrt;"], [0, { v: "&ang;", n: 8402, o: "&nang;" }], [0, "&angmsd;"], [0, "&angsph;"], [0, "&mid;"], [0, "&nmid;"], [0, "&DoubleVerticalBar;"], [0, "&NotDoubleVerticalBar;"], [0, "&and;"], [0, "&or;"], [0, { v: "&cap;", n: 65024, o: "&caps;" }], [0, { v: "&cup;", n: 65024, o: "&cups;" }], [0, "&int;"], [0, "&Int;"], [0, "&iiint;"], [0, "&conint;"], [0, "&Conint;"], [0, "&Cconint;"], [0, "&cwint;"], [0, "&ClockwiseContourIntegral;"], [0, "&awconint;"], [0, "&there4;"], [0, "&becaus;"], [0, "&ratio;"], [0, "&Colon;"], [0, "&dotminus;"], [1, "&mDDot;"], [0, "&homtht;"], [0, { v: "&sim;", n: 8402, o: "&nvsim;" }], [0, { v: "&backsim;", n: 817, o: "&race;" }], [0, { v: "&ac;", n: 819, o: "&acE;" }], [0, "&acd;"], [0, "&VerticalTilde;"], [0, "&NotTilde;"], [0, { v: "&eqsim;", n: 824, o: "&nesim;" }], [0, "&sime;"], [0, "&NotTildeEqual;"], [0, "&cong;"], [0, "&simne;"], [0, "&ncong;"], [0, "&ap;"], [0, "&nap;"], [0, "&ape;"], [0, { v: "&apid;", n: 824, o: "&napid;" }], [0, "&backcong;"], [0, { v: "&asympeq;", n: 8402, o: "&nvap;" }], [0, { v: "&bump;", n: 824, o: "&nbump;" }], [0, { v: "&bumpe;", n: 824, o: "&nbumpe;" }], [0, { v: "&doteq;", n: 824, o: "&nedot;" }], [0, "&doteqdot;"], [0, "&efDot;"], [0, "&erDot;"], [0, "&Assign;"], [0, "&ecolon;"], [0, "&ecir;"], [0, "&circeq;"], [1, "&wedgeq;"], [0, "&veeeq;"], [1, "&triangleq;"], [2, "&equest;"], [0, "&ne;"], [0, { v: "&Congruent;", n: 8421, o: "&bnequiv;" }], [0, "&nequiv;"], [1, { v: "&le;", n: 8402, o: "&nvle;" }], [0, { v: "&ge;", n: 8402, o: "&nvge;" }], [0, { v: "&lE;", n: 824, o: "&nlE;" }], [0, { v: "&gE;", n: 824, o: "&ngE;" }], [0, { v: "&lnE;", n: 65024, o: "&lvertneqq;" }], [0, { v: "&gnE;", n: 65024, o: "&gvertneqq;" }], [0, { v: "&ll;", n: new Map(/* @__PURE__ */ restoreDiff([[824, "&nLtv;"], [7577, "&nLt;"]])) }], [0, { v: "&gg;", n: new Map(/* @__PURE__ */ restoreDiff([[824, "&nGtv;"], [7577, "&nGt;"]])) }], [0, "&between;"], [0, "&NotCupCap;"], [0, "&nless;"], [0, "&ngt;"], [0, "&nle;"], [0, "&nge;"], [0, "&lesssim;"], [0, "&GreaterTilde;"], [0, "&nlsim;"], [0, "&ngsim;"], [0, "&LessGreater;"], [0, "&gl;"], [0, "&NotLessGreater;"], [0, "&NotGreaterLess;"], [0, "&pr;"], [0, "&sc;"], [0, "&prcue;"], [0, "&sccue;"], [0, "&PrecedesTilde;"], [0, { v: "&scsim;", n: 824, o: "&NotSucceedsTilde;" }], [0, "&NotPrecedes;"], [0, "&NotSucceeds;"], [0, { v: "&sub;", n: 8402, o: "&NotSubset;" }], [0, { v: "&sup;", n: 8402, o: "&NotSuperset;" }], [0, "&nsub;"], [0, "&nsup;"], [0, "&sube;"], [0, "&supe;"], [0, "&NotSubsetEqual;"], [0, "&NotSupersetEqual;"], [0, { v: "&subne;", n: 65024, o: "&varsubsetneq;" }], [0, { v: "&supne;", n: 65024, o: "&varsupsetneq;" }], [1, "&cupdot;"], [0, "&UnionPlus;"], [0, { v: "&sqsub;", n: 824, o: "&NotSquareSubset;" }], [0, { v: "&sqsup;", n: 824, o: "&NotSquareSuperset;" }], [0, "&sqsube;"], [0, "&sqsupe;"], [0, { v: "&sqcap;", n: 65024, o: "&sqcaps;" }], [0, { v: "&sqcup;", n: 65024, o: "&sqcups;" }], [0, "&CirclePlus;"], [0, "&CircleMinus;"], [0, "&CircleTimes;"], [0, "&osol;"], [0, "&CircleDot;"], [0, "&circledcirc;"], [0, "&circledast;"], [1, "&circleddash;"], [0, "&boxplus;"], [0, "&boxminus;"], [0, "&boxtimes;"], [0, "&dotsquare;"], [0, "&RightTee;"], [0, "&dashv;"], [0, "&DownTee;"], [0, "&bot;"], [1, "&models;"], [0, "&DoubleRightTee;"], [0, "&Vdash;"], [0, "&Vvdash;"], [0, "&VDash;"], [0, "&nvdash;"], [0, "&nvDash;"], [0, "&nVdash;"], [0, "&nVDash;"], [0, "&prurel;"], [1, "&LeftTriangle;"], [0, "&RightTriangle;"], [0, { v: "&LeftTriangleEqual;", n: 8402, o: "&nvltrie;" }], [0, { v: "&RightTriangleEqual;", n: 8402, o: "&nvrtrie;" }], [0, "&origof;"], [0, "&imof;"], [0, "&multimap;"], [0, "&hercon;"], [0, "&intcal;"], [0, "&veebar;"], [1, "&barvee;"], [0, "&angrtvb;"], [0, "&lrtri;"], [0, "&bigwedge;"], [0, "&bigvee;"], [0, "&bigcap;"], [0, "&bigcup;"], [0, "&diam;"], [0, "&sdot;"], [0, "&sstarf;"], [0, "&divideontimes;"], [0, "&bowtie;"], [0, "&ltimes;"], [0, "&rtimes;"], [0, "&leftthreetimes;"], [0, "&rightthreetimes;"], [0, "&backsimeq;"], [0, "&curlyvee;"], [0, "&curlywedge;"], [0, "&Sub;"], [0, "&Sup;"], [0, "&Cap;"], [0, "&Cup;"], [0, "&fork;"], [0, "&epar;"], [0, "&lessdot;"], [0, "&gtdot;"], [0, { v: "&Ll;", n: 824, o: "&nLl;" }], [0, { v: "&Gg;", n: 824, o: "&nGg;" }], [0, { v: "&leg;", n: 65024, o: "&lesg;" }], [0, { v: "&gel;", n: 65024, o: "&gesl;" }], [2, "&cuepr;"], [0, "&cuesc;"], [0, "&NotPrecedesSlantEqual;"], [0, "&NotSucceedsSlantEqual;"], [0, "&NotSquareSubsetEqual;"], [0, "&NotSquareSupersetEqual;"], [2, "&lnsim;"], [0, "&gnsim;"], [0, "&precnsim;"], [0, "&scnsim;"], [0, "&nltri;"], [0, "&NotRightTriangle;"], [0, "&nltrie;"], [0, "&NotRightTriangleEqual;"], [0, "&vellip;"], [0, "&ctdot;"], [0, "&utdot;"], [0, "&dtdot;"], [0, "&disin;"], [0, "&isinsv;"], [0, "&isins;"], [0, { v: "&isindot;", n: 824, o: "&notindot;" }], [0, "&notinvc;"], [0, "&notinvb;"], [1, { v: "&isinE;", n: 824, o: "&notinE;" }], [0, "&nisd;"], [0, "&xnis;"], [0, "&nis;"], [0, "&notnivc;"], [0, "&notnivb;"], [6, "&barwed;"], [0, "&Barwed;"], [1, "&lceil;"], [0, "&rceil;"], [0, "&LeftFloor;"], [0, "&rfloor;"], [0, "&drcrop;"], [0, "&dlcrop;"], [0, "&urcrop;"], [0, "&ulcrop;"], [0, "&bnot;"], [1, "&profline;"], [0, "&profsurf;"], [1, "&telrec;"], [0, "&target;"], [5, "&ulcorn;"], [0, "&urcorn;"], [0, "&dlcorn;"], [0, "&drcorn;"], [2, "&frown;"], [0, "&smile;"], [9, "&cylcty;"], [0, "&profalar;"], [7, "&topbot;"], [6, "&ovbar;"], [1, "&solbar;"], [60, "&angzarr;"], [51, "&lmoustache;"], [0, "&rmoustache;"], [2, "&OverBracket;"], [0, "&bbrk;"], [0, "&bbrktbrk;"], [37, "&OverParenthesis;"], [0, "&UnderParenthesis;"], [0, "&OverBrace;"], [0, "&UnderBrace;"], [2, "&trpezium;"], [4, "&elinters;"], [59, "&blank;"], [164, "&circledS;"], [55, "&boxh;"], [1, "&boxv;"], [9, "&boxdr;"], [3, "&boxdl;"], [3, "&boxur;"], [3, "&boxul;"], [3, "&boxvr;"], [7, "&boxvl;"], [7, "&boxhd;"], [7, "&boxhu;"], [7, "&boxvh;"], [19, "&boxH;"], [0, "&boxV;"], [0, "&boxdR;"], [0, "&boxDr;"], [0, "&boxDR;"], [0, "&boxdL;"], [0, "&boxDl;"], [0, "&boxDL;"], [0, "&boxuR;"], [0, "&boxUr;"], [0, "&boxUR;"], [0, "&boxuL;"], [0, "&boxUl;"], [0, "&boxUL;"], [0, "&boxvR;"], [0, "&boxVr;"], [0, "&boxVR;"], [0, "&boxvL;"], [0, "&boxVl;"], [0, "&boxVL;"], [0, "&boxHd;"], [0, "&boxhD;"], [0, "&boxHD;"], [0, "&boxHu;"], [0, "&boxhU;"], [0, "&boxHU;"], [0, "&boxvH;"], [0, "&boxVh;"], [0, "&boxVH;"], [19, "&uhblk;"], [3, "&lhblk;"], [3, "&block;"], [8, "&blk14;"], [0, "&blk12;"], [0, "&blk34;"], [13, "&square;"], [8, "&blacksquare;"], [0, "&EmptyVerySmallSquare;"], [1, "&rect;"], [0, "&marker;"], [2, "&fltns;"], [1, "&bigtriangleup;"], [0, "&blacktriangle;"], [0, "&triangle;"], [2, "&blacktriangleright;"], [0, "&rtri;"], [3, "&bigtriangledown;"], [0, "&blacktriangledown;"], [0, "&dtri;"], [2, "&blacktriangleleft;"], [0, "&ltri;"], [6, "&loz;"], [0, "&cir;"], [32, "&tridot;"], [2, "&bigcirc;"], [8, "&ultri;"], [0, "&urtri;"], [0, "&lltri;"], [0, "&EmptySmallSquare;"], [0, "&FilledSmallSquare;"], [8, "&bigstar;"], [0, "&star;"], [7, "&phone;"], [49, "&female;"], [1, "&male;"], [29, "&spades;"], [2, "&clubs;"], [1, "&hearts;"], [0, "&diamondsuit;"], [3, "&sung;"], [2, "&flat;"], [0, "&natural;"], [0, "&sharp;"], [163, "&check;"], [3, "&cross;"], [8, "&malt;"], [21, "&sext;"], [33, "&VerticalSeparator;"], [25, "&lbbrk;"], [0, "&rbbrk;"], [84, "&bsolhsub;"], [0, "&suphsol;"], [28, "&LeftDoubleBracket;"], [0, "&RightDoubleBracket;"], [0, "&lang;"], [0, "&rang;"], [0, "&Lang;"], [0, "&Rang;"], [0, "&loang;"], [0, "&roang;"], [7, "&longleftarrow;"], [0, "&longrightarrow;"], [0, "&longleftrightarrow;"], [0, "&DoubleLongLeftArrow;"], [0, "&DoubleLongRightArrow;"], [0, "&DoubleLongLeftRightArrow;"], [1, "&longmapsto;"], [2, "&dzigrarr;"], [258, "&nvlArr;"], [0, "&nvrArr;"], [0, "&nvHarr;"], [0, "&Map;"], [6, "&lbarr;"], [0, "&bkarow;"], [0, "&lBarr;"], [0, "&dbkarow;"], [0, "&drbkarow;"], [0, "&DDotrahd;"], [0, "&UpArrowBar;"], [0, "&DownArrowBar;"], [2, "&Rarrtl;"], [2, "&latail;"], [0, "&ratail;"], [0, "&lAtail;"], [0, "&rAtail;"], [0, "&larrfs;"], [0, "&rarrfs;"], [0, "&larrbfs;"], [0, "&rarrbfs;"], [2, "&nwarhk;"], [0, "&nearhk;"], [0, "&hksearow;"], [0, "&hkswarow;"], [0, "&nwnear;"], [0, "&nesear;"], [0, "&seswar;"], [0, "&swnwar;"], [8, { v: "&rarrc;", n: 824, o: "&nrarrc;" }], [1, "&cudarrr;"], [0, "&ldca;"], [0, "&rdca;"], [0, "&cudarrl;"], [0, "&larrpl;"], [2, "&curarrm;"], [0, "&cularrp;"], [7, "&rarrpl;"], [2, "&harrcir;"], [0, "&Uarrocir;"], [0, "&lurdshar;"], [0, "&ldrushar;"], [2, "&LeftRightVector;"], [0, "&RightUpDownVector;"], [0, "&DownLeftRightVector;"], [0, "&LeftUpDownVector;"], [0, "&LeftVectorBar;"], [0, "&RightVectorBar;"], [0, "&RightUpVectorBar;"], [0, "&RightDownVectorBar;"], [0, "&DownLeftVectorBar;"], [0, "&DownRightVectorBar;"], [0, "&LeftUpVectorBar;"], [0, "&LeftDownVectorBar;"], [0, "&LeftTeeVector;"], [0, "&RightTeeVector;"], [0, "&RightUpTeeVector;"], [0, "&RightDownTeeVector;"], [0, "&DownLeftTeeVector;"], [0, "&DownRightTeeVector;"], [0, "&LeftUpTeeVector;"], [0, "&LeftDownTeeVector;"], [0, "&lHar;"], [0, "&uHar;"], [0, "&rHar;"], [0, "&dHar;"], [0, "&luruhar;"], [0, "&ldrdhar;"], [0, "&ruluhar;"], [0, "&rdldhar;"], [0, "&lharul;"], [0, "&llhard;"], [0, "&rharul;"], [0, "&lrhard;"], [0, "&udhar;"], [0, "&duhar;"], [0, "&RoundImplies;"], [0, "&erarr;"], [0, "&simrarr;"], [0, "&larrsim;"], [0, "&rarrsim;"], [0, "&rarrap;"], [0, "&ltlarr;"], [1, "&gtrarr;"], [0, "&subrarr;"], [1, "&suplarr;"], [0, "&lfisht;"], [0, "&rfisht;"], [0, "&ufisht;"], [0, "&dfisht;"], [5, "&lopar;"], [0, "&ropar;"], [4, "&lbrke;"], [0, "&rbrke;"], [0, "&lbrkslu;"], [0, "&rbrksld;"], [0, "&lbrksld;"], [0, "&rbrkslu;"], [0, "&langd;"], [0, "&rangd;"], [0, "&lparlt;"], [0, "&rpargt;"], [0, "&gtlPar;"], [0, "&ltrPar;"], [3, "&vzigzag;"], [1, "&vangrt;"], [0, "&angrtvbd;"], [6, "&ange;"], [0, "&range;"], [0, "&dwangle;"], [0, "&uwangle;"], [0, "&angmsdaa;"], [0, "&angmsdab;"], [0, "&angmsdac;"], [0, "&angmsdad;"], [0, "&angmsdae;"], [0, "&angmsdaf;"], [0, "&angmsdag;"], [0, "&angmsdah;"], [0, "&bemptyv;"], [0, "&demptyv;"], [0, "&cemptyv;"], [0, "&raemptyv;"], [0, "&laemptyv;"], [0, "&ohbar;"], [0, "&omid;"], [0, "&opar;"], [1, "&operp;"], [1, "&olcross;"], [0, "&odsold;"], [1, "&olcir;"], [0, "&ofcir;"], [0, "&olt;"], [0, "&ogt;"], [0, "&cirscir;"], [0, "&cirE;"], [0, "&solb;"], [0, "&bsolb;"], [3, "&boxbox;"], [3, "&trisb;"], [0, "&rtriltri;"], [0, { v: "&LeftTriangleBar;", n: 824, o: "&NotLeftTriangleBar;" }], [0, { v: "&RightTriangleBar;", n: 824, o: "&NotRightTriangleBar;" }], [11, "&iinfin;"], [0, "&infintie;"], [0, "&nvinfin;"], [4, "&eparsl;"], [0, "&smeparsl;"], [0, "&eqvparsl;"], [5, "&blacklozenge;"], [8, "&RuleDelayed;"], [1, "&dsol;"], [9, "&bigodot;"], [0, "&bigoplus;"], [0, "&bigotimes;"], [1, "&biguplus;"], [1, "&bigsqcup;"], [5, "&iiiint;"], [0, "&fpartint;"], [2, "&cirfnint;"], [0, "&awint;"], [0, "&rppolint;"], [0, "&scpolint;"], [0, "&npolint;"], [0, "&pointint;"], [0, "&quatint;"], [0, "&intlarhk;"], [10, "&pluscir;"], [0, "&plusacir;"], [0, "&simplus;"], [0, "&plusdu;"], [0, "&plussim;"], [0, "&plustwo;"], [1, "&mcomma;"], [0, "&minusdu;"], [2, "&loplus;"], [0, "&roplus;"], [0, "&Cross;"], [0, "&timesd;"], [0, "&timesbar;"], [1, "&smashp;"], [0, "&lotimes;"], [0, "&rotimes;"], [0, "&otimesas;"], [0, "&Otimes;"], [0, "&odiv;"], [0, "&triplus;"], [0, "&triminus;"], [0, "&tritime;"], [0, "&intprod;"], [2, "&amalg;"], [0, "&capdot;"], [1, "&ncup;"], [0, "&ncap;"], [0, "&capand;"], [0, "&cupor;"], [0, "&cupcap;"], [0, "&capcup;"], [0, "&cupbrcap;"], [0, "&capbrcup;"], [0, "&cupcup;"], [0, "&capcap;"], [0, "&ccups;"], [0, "&ccaps;"], [2, "&ccupssm;"], [2, "&And;"], [0, "&Or;"], [0, "&andand;"], [0, "&oror;"], [0, "&orslope;"], [0, "&andslope;"], [1, "&andv;"], [0, "&orv;"], [0, "&andd;"], [0, "&ord;"], [1, "&wedbar;"], [6, "&sdote;"], [3, "&simdot;"], [2, { v: "&congdot;", n: 824, o: "&ncongdot;" }], [0, "&easter;"], [0, "&apacir;"], [0, { v: "&apE;", n: 824, o: "&napE;" }], [0, "&eplus;"], [0, "&pluse;"], [0, "&Esim;"], [0, "&Colone;"], [0, "&Equal;"], [1, "&ddotseq;"], [0, "&equivDD;"], [0, "&ltcir;"], [0, "&gtcir;"], [0, "&ltquest;"], [0, "&gtquest;"], [0, { v: "&leqslant;", n: 824, o: "&nleqslant;" }], [0, { v: "&geqslant;", n: 824, o: "&ngeqslant;" }], [0, "&lesdot;"], [0, "&gesdot;"], [0, "&lesdoto;"], [0, "&gesdoto;"], [0, "&lesdotor;"], [0, "&gesdotol;"], [0, "&lap;"], [0, "&gap;"], [0, "&lne;"], [0, "&gne;"], [0, "&lnap;"], [0, "&gnap;"], [0, "&lEg;"], [0, "&gEl;"], [0, "&lsime;"], [0, "&gsime;"], [0, "&lsimg;"], [0, "&gsiml;"], [0, "&lgE;"], [0, "&glE;"], [0, "&lesges;"], [0, "&gesles;"], [0, "&els;"], [0, "&egs;"], [0, "&elsdot;"], [0, "&egsdot;"], [0, "&el;"], [0, "&eg;"], [2, "&siml;"], [0, "&simg;"], [0, "&simlE;"], [0, "&simgE;"], [0, { v: "&LessLess;", n: 824, o: "&NotNestedLessLess;" }], [0, { v: "&GreaterGreater;", n: 824, o: "&NotNestedGreaterGreater;" }], [1, "&glj;"], [0, "&gla;"], [0, "&ltcc;"], [0, "&gtcc;"], [0, "&lescc;"], [0, "&gescc;"], [0, "&smt;"], [0, "&lat;"], [0, { v: "&smte;", n: 65024, o: "&smtes;" }], [0, { v: "&late;", n: 65024, o: "&lates;" }], [0, "&bumpE;"], [0, { v: "&PrecedesEqual;", n: 824, o: "&NotPrecedesEqual;" }], [0, { v: "&sce;", n: 824, o: "&NotSucceedsEqual;" }], [2, "&prE;"], [0, "&scE;"], [0, "&precneqq;"], [0, "&scnE;"], [0, "&prap;"], [0, "&scap;"], [0, "&precnapprox;"], [0, "&scnap;"], [0, "&Pr;"], [0, "&Sc;"], [0, "&subdot;"], [0, "&supdot;"], [0, "&subplus;"], [0, "&supplus;"], [0, "&submult;"], [0, "&supmult;"], [0, "&subedot;"], [0, "&supedot;"], [0, { v: "&subE;", n: 824, o: "&nsubE;" }], [0, { v: "&supE;", n: 824, o: "&nsupE;" }], [0, "&subsim;"], [0, "&supsim;"], [2, { v: "&subnE;", n: 65024, o: "&varsubsetneqq;" }], [0, { v: "&supnE;", n: 65024, o: "&varsupsetneqq;" }], [2, "&csub;"], [0, "&csup;"], [0, "&csube;"], [0, "&csupe;"], [0, "&subsup;"], [0, "&supsub;"], [0, "&subsub;"], [0, "&supsup;"], [0, "&suphsub;"], [0, "&supdsub;"], [0, "&forkv;"], [0, "&topfork;"], [0, "&mlcp;"], [8, "&Dashv;"], [1, "&Vdashl;"], [0, "&Barv;"], [0, "&vBar;"], [0, "&vBarv;"], [1, "&Vbar;"], [0, "&Not;"], [0, "&bNot;"], [0, "&rnmid;"], [0, "&cirmid;"], [0, "&midcir;"], [0, "&topcir;"], [0, "&nhpar;"], [0, "&parsim;"], [9, { v: "&parsl;", n: 8421, o: "&nparsl;" }], [44343, { n: new Map(/* @__PURE__ */ restoreDiff([[56476, "&Ascr;"], [1, "&Cscr;"], [0, "&Dscr;"], [2, "&Gscr;"], [2, "&Jscr;"], [0, "&Kscr;"], [2, "&Nscr;"], [0, "&Oscr;"], [0, "&Pscr;"], [0, "&Qscr;"], [1, "&Sscr;"], [0, "&Tscr;"], [0, "&Uscr;"], [0, "&Vscr;"], [0, "&Wscr;"], [0, "&Xscr;"], [0, "&Yscr;"], [0, "&Zscr;"], [0, "&ascr;"], [0, "&bscr;"], [0, "&cscr;"], [0, "&dscr;"], [1, "&fscr;"], [1, "&hscr;"], [0, "&iscr;"], [0, "&jscr;"], [0, "&kscr;"], [0, "&lscr;"], [0, "&mscr;"], [0, "&nscr;"], [1, "&pscr;"], [0, "&qscr;"], [0, "&rscr;"], [0, "&sscr;"], [0, "&tscr;"], [0, "&uscr;"], [0, "&vscr;"], [0, "&wscr;"], [0, "&xscr;"], [0, "&yscr;"], [0, "&zscr;"], [52, "&Afr;"], [0, "&Bfr;"], [1, "&Dfr;"], [0, "&Efr;"], [0, "&Ffr;"], [0, "&Gfr;"], [2, "&Jfr;"], [0, "&Kfr;"], [0, "&Lfr;"], [0, "&Mfr;"], [0, "&Nfr;"], [0, "&Ofr;"], [0, "&Pfr;"], [0, "&Qfr;"], [1, "&Sfr;"], [0, "&Tfr;"], [0, "&Ufr;"], [0, "&Vfr;"], [0, "&Wfr;"], [0, "&Xfr;"], [0, "&Yfr;"], [1, "&afr;"], [0, "&bfr;"], [0, "&cfr;"], [0, "&dfr;"], [0, "&efr;"], [0, "&ffr;"], [0, "&gfr;"], [0, "&hfr;"], [0, "&ifr;"], [0, "&jfr;"], [0, "&kfr;"], [0, "&lfr;"], [0, "&mfr;"], [0, "&nfr;"], [0, "&ofr;"], [0, "&pfr;"], [0, "&qfr;"], [0, "&rfr;"], [0, "&sfr;"], [0, "&tfr;"], [0, "&ufr;"], [0, "&vfr;"], [0, "&wfr;"], [0, "&xfr;"], [0, "&yfr;"], [0, "&zfr;"], [0, "&Aopf;"], [0, "&Bopf;"], [1, "&Dopf;"], [0, "&Eopf;"], [0, "&Fopf;"], [0, "&Gopf;"], [1, "&Iopf;"], [0, "&Jopf;"], [0, "&Kopf;"], [0, "&Lopf;"], [0, "&Mopf;"], [1, "&Oopf;"], [3, "&Sopf;"], [0, "&Topf;"], [0, "&Uopf;"], [0, "&Vopf;"], [0, "&Wopf;"], [0, "&Xopf;"], [0, "&Yopf;"], [1, "&aopf;"], [0, "&bopf;"], [0, "&copf;"], [0, "&dopf;"], [0, "&eopf;"], [0, "&fopf;"], [0, "&gopf;"], [0, "&hopf;"], [0, "&iopf;"], [0, "&jopf;"], [0, "&kopf;"], [0, "&lopf;"], [0, "&mopf;"], [0, "&nopf;"], [0, "&oopf;"], [0, "&popf;"], [0, "&qopf;"], [0, "&ropf;"], [0, "&sopf;"], [0, "&topf;"], [0, "&uopf;"], [0, "&vopf;"], [0, "&wopf;"], [0, "&xopf;"], [0, "&yopf;"], [0, "&zopf;"]])) }], [8906, "&fflig;"], [0, "&filig;"], [0, "&fllig;"], [0, "&ffilig;"], [0, "&ffllig;"]]));
});

// node_modules/entities/lib/escape.js
var require_escape = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.escapeText = exports.escapeAttribute = exports.escapeUTF8 = exports.escape = exports.encodeXML = exports.getCodePoint = exports.xmlReplacer = undefined;
  exports.xmlReplacer = /["&'<>$\x80-\uFFFF]/g;
  var xmlCodeMap = new Map([
    [34, "&quot;"],
    [38, "&amp;"],
    [39, "&apos;"],
    [60, "&lt;"],
    [62, "&gt;"]
  ]);
  exports.getCodePoint = String.prototype.codePointAt != null ? function(str, index) {
    return str.codePointAt(index);
  } : function(c, index) {
    return (c.charCodeAt(index) & 64512) === 55296 ? (c.charCodeAt(index) - 55296) * 1024 + c.charCodeAt(index + 1) - 56320 + 65536 : c.charCodeAt(index);
  };
  function encodeXML(str) {
    var ret = "";
    var lastIdx = 0;
    var match;
    while ((match = exports.xmlReplacer.exec(str)) !== null) {
      var i = match.index;
      var char = str.charCodeAt(i);
      var next2 = xmlCodeMap.get(char);
      if (next2 !== undefined) {
        ret += str.substring(lastIdx, i) + next2;
        lastIdx = i + 1;
      } else {
        ret += "".concat(str.substring(lastIdx, i), "&#x").concat((0, exports.getCodePoint)(str, i).toString(16), ";");
        lastIdx = exports.xmlReplacer.lastIndex += Number((char & 64512) === 55296);
      }
    }
    return ret + str.substr(lastIdx);
  }
  exports.encodeXML = encodeXML;
  exports.escape = encodeXML;
  function getEscaper(regex, map4) {
    return function escape(data2) {
      var match;
      var lastIdx = 0;
      var result = "";
      while (match = regex.exec(data2)) {
        if (lastIdx !== match.index) {
          result += data2.substring(lastIdx, match.index);
        }
        result += map4.get(match[0].charCodeAt(0));
        lastIdx = match.index + 1;
      }
      return result + data2.substring(lastIdx);
    };
  }
  exports.escapeUTF8 = getEscaper(/[&<>'"]/g, xmlCodeMap);
  exports.escapeAttribute = getEscaper(/["&\u00A0]/g, new Map([
    [34, "&quot;"],
    [38, "&amp;"],
    [160, "&nbsp;"]
  ]));
  exports.escapeText = getEscaper(/[&<>\u00A0]/g, new Map([
    [38, "&amp;"],
    [60, "&lt;"],
    [62, "&gt;"],
    [160, "&nbsp;"]
  ]));
});

// node_modules/entities/lib/encode.js
var require_encode = __commonJS((exports) => {
  var __importDefault = exports && exports.__importDefault || function(mod2) {
    return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.encodeNonAsciiHTML = exports.encodeHTML = undefined;
  var encode_html_js_1 = __importDefault(require_encode_html());
  var escape_js_1 = require_escape();
  var htmlReplacer = /[\t\n!-,./:-@[-`\f{-}$\x80-\uFFFF]/g;
  function encodeHTML(data2) {
    return encodeHTMLTrieRe(htmlReplacer, data2);
  }
  exports.encodeHTML = encodeHTML;
  function encodeNonAsciiHTML(data2) {
    return encodeHTMLTrieRe(escape_js_1.xmlReplacer, data2);
  }
  exports.encodeNonAsciiHTML = encodeNonAsciiHTML;
  function encodeHTMLTrieRe(regExp, str) {
    var ret = "";
    var lastIdx = 0;
    var match;
    while ((match = regExp.exec(str)) !== null) {
      var i = match.index;
      ret += str.substring(lastIdx, i);
      var char = str.charCodeAt(i);
      var next2 = encode_html_js_1.default.get(char);
      if (typeof next2 === "object") {
        if (i + 1 < str.length) {
          var nextChar = str.charCodeAt(i + 1);
          var value2 = typeof next2.n === "number" ? next2.n === nextChar ? next2.o : undefined : next2.n.get(nextChar);
          if (value2 !== undefined) {
            ret += value2;
            lastIdx = regExp.lastIndex += 1;
            continue;
          }
        }
        next2 = next2.v;
      }
      if (next2 !== undefined) {
        ret += next2;
        lastIdx = i + 1;
      } else {
        var cp = (0, escape_js_1.getCodePoint)(str, i);
        ret += "&#x".concat(cp.toString(16), ";");
        lastIdx = regExp.lastIndex += Number(cp !== char);
      }
    }
    return ret + str.substr(lastIdx);
  }
});

// node_modules/entities/lib/index.js
var require_lib3 = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.decodeXMLStrict = exports.decodeHTML5Strict = exports.decodeHTML4Strict = exports.decodeHTML5 = exports.decodeHTML4 = exports.decodeHTMLAttribute = exports.decodeHTMLStrict = exports.decodeHTML = exports.decodeXML = exports.DecodingMode = exports.EntityDecoder = exports.encodeHTML5 = exports.encodeHTML4 = exports.encodeNonAsciiHTML = exports.encodeHTML = exports.escapeText = exports.escapeAttribute = exports.escapeUTF8 = exports.escape = exports.encodeXML = exports.encode = exports.decodeStrict = exports.decode = exports.EncodingMode = exports.EntityLevel = undefined;
  var decode_js_1 = require_decode();
  var encode_js_1 = require_encode();
  var escape_js_1 = require_escape();
  var EntityLevel;
  (function(EntityLevel2) {
    EntityLevel2[EntityLevel2["XML"] = 0] = "XML";
    EntityLevel2[EntityLevel2["HTML"] = 1] = "HTML";
  })(EntityLevel = exports.EntityLevel || (exports.EntityLevel = {}));
  var EncodingMode;
  (function(EncodingMode2) {
    EncodingMode2[EncodingMode2["UTF8"] = 0] = "UTF8";
    EncodingMode2[EncodingMode2["ASCII"] = 1] = "ASCII";
    EncodingMode2[EncodingMode2["Extensive"] = 2] = "Extensive";
    EncodingMode2[EncodingMode2["Attribute"] = 3] = "Attribute";
    EncodingMode2[EncodingMode2["Text"] = 4] = "Text";
  })(EncodingMode = exports.EncodingMode || (exports.EncodingMode = {}));
  function decode3(data2, options) {
    if (options === undefined) {
      options = EntityLevel.XML;
    }
    var level = typeof options === "number" ? options : options.level;
    if (level === EntityLevel.HTML) {
      var mode = typeof options === "object" ? options.mode : undefined;
      return (0, decode_js_1.decodeHTML)(data2, mode);
    }
    return (0, decode_js_1.decodeXML)(data2);
  }
  exports.decode = decode3;
  function decodeStrict(data2, options) {
    var _a2;
    if (options === undefined) {
      options = EntityLevel.XML;
    }
    var opts = typeof options === "number" ? { level: options } : options;
    (_a2 = opts.mode) !== null && _a2 !== undefined || (opts.mode = decode_js_1.DecodingMode.Strict);
    return decode3(data2, opts);
  }
  exports.decodeStrict = decodeStrict;
  function encode3(data2, options) {
    if (options === undefined) {
      options = EntityLevel.XML;
    }
    var opts = typeof options === "number" ? { level: options } : options;
    if (opts.mode === EncodingMode.UTF8)
      return (0, escape_js_1.escapeUTF8)(data2);
    if (opts.mode === EncodingMode.Attribute)
      return (0, escape_js_1.escapeAttribute)(data2);
    if (opts.mode === EncodingMode.Text)
      return (0, escape_js_1.escapeText)(data2);
    if (opts.level === EntityLevel.HTML) {
      if (opts.mode === EncodingMode.ASCII) {
        return (0, encode_js_1.encodeNonAsciiHTML)(data2);
      }
      return (0, encode_js_1.encodeHTML)(data2);
    }
    return (0, escape_js_1.encodeXML)(data2);
  }
  exports.encode = encode3;
  var escape_js_2 = require_escape();
  Object.defineProperty(exports, "encodeXML", { enumerable: true, get: function() {
    return escape_js_2.encodeXML;
  } });
  Object.defineProperty(exports, "escape", { enumerable: true, get: function() {
    return escape_js_2.escape;
  } });
  Object.defineProperty(exports, "escapeUTF8", { enumerable: true, get: function() {
    return escape_js_2.escapeUTF8;
  } });
  Object.defineProperty(exports, "escapeAttribute", { enumerable: true, get: function() {
    return escape_js_2.escapeAttribute;
  } });
  Object.defineProperty(exports, "escapeText", { enumerable: true, get: function() {
    return escape_js_2.escapeText;
  } });
  var encode_js_2 = require_encode();
  Object.defineProperty(exports, "encodeHTML", { enumerable: true, get: function() {
    return encode_js_2.encodeHTML;
  } });
  Object.defineProperty(exports, "encodeNonAsciiHTML", { enumerable: true, get: function() {
    return encode_js_2.encodeNonAsciiHTML;
  } });
  Object.defineProperty(exports, "encodeHTML4", { enumerable: true, get: function() {
    return encode_js_2.encodeHTML;
  } });
  Object.defineProperty(exports, "encodeHTML5", { enumerable: true, get: function() {
    return encode_js_2.encodeHTML;
  } });
  var decode_js_2 = require_decode();
  Object.defineProperty(exports, "EntityDecoder", { enumerable: true, get: function() {
    return decode_js_2.EntityDecoder;
  } });
  Object.defineProperty(exports, "DecodingMode", { enumerable: true, get: function() {
    return decode_js_2.DecodingMode;
  } });
  Object.defineProperty(exports, "decodeXML", { enumerable: true, get: function() {
    return decode_js_2.decodeXML;
  } });
  Object.defineProperty(exports, "decodeHTML", { enumerable: true, get: function() {
    return decode_js_2.decodeHTML;
  } });
  Object.defineProperty(exports, "decodeHTMLStrict", { enumerable: true, get: function() {
    return decode_js_2.decodeHTMLStrict;
  } });
  Object.defineProperty(exports, "decodeHTMLAttribute", { enumerable: true, get: function() {
    return decode_js_2.decodeHTMLAttribute;
  } });
  Object.defineProperty(exports, "decodeHTML4", { enumerable: true, get: function() {
    return decode_js_2.decodeHTML;
  } });
  Object.defineProperty(exports, "decodeHTML5", { enumerable: true, get: function() {
    return decode_js_2.decodeHTML;
  } });
  Object.defineProperty(exports, "decodeHTML4Strict", { enumerable: true, get: function() {
    return decode_js_2.decodeHTMLStrict;
  } });
  Object.defineProperty(exports, "decodeHTML5Strict", { enumerable: true, get: function() {
    return decode_js_2.decodeHTMLStrict;
  } });
  Object.defineProperty(exports, "decodeXMLStrict", { enumerable: true, get: function() {
    return decode_js_2.decodeXML;
  } });
});

// node_modules/dom-serializer/lib/foreignNames.js
var require_foreignNames = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.attributeNames = exports.elementNames = undefined;
  exports.elementNames = new Map([
    "altGlyph",
    "altGlyphDef",
    "altGlyphItem",
    "animateColor",
    "animateMotion",
    "animateTransform",
    "clipPath",
    "feBlend",
    "feColorMatrix",
    "feComponentTransfer",
    "feComposite",
    "feConvolveMatrix",
    "feDiffuseLighting",
    "feDisplacementMap",
    "feDistantLight",
    "feDropShadow",
    "feFlood",
    "feFuncA",
    "feFuncB",
    "feFuncG",
    "feFuncR",
    "feGaussianBlur",
    "feImage",
    "feMerge",
    "feMergeNode",
    "feMorphology",
    "feOffset",
    "fePointLight",
    "feSpecularLighting",
    "feSpotLight",
    "feTile",
    "feTurbulence",
    "foreignObject",
    "glyphRef",
    "linearGradient",
    "radialGradient",
    "textPath"
  ].map(function(val) {
    return [val.toLowerCase(), val];
  }));
  exports.attributeNames = new Map([
    "definitionURL",
    "attributeName",
    "attributeType",
    "baseFrequency",
    "baseProfile",
    "calcMode",
    "clipPathUnits",
    "diffuseConstant",
    "edgeMode",
    "filterUnits",
    "glyphRef",
    "gradientTransform",
    "gradientUnits",
    "kernelMatrix",
    "kernelUnitLength",
    "keyPoints",
    "keySplines",
    "keyTimes",
    "lengthAdjust",
    "limitingConeAngle",
    "markerHeight",
    "markerUnits",
    "markerWidth",
    "maskContentUnits",
    "maskUnits",
    "numOctaves",
    "pathLength",
    "patternContentUnits",
    "patternTransform",
    "patternUnits",
    "pointsAtX",
    "pointsAtY",
    "pointsAtZ",
    "preserveAlpha",
    "preserveAspectRatio",
    "primitiveUnits",
    "refX",
    "refY",
    "repeatCount",
    "repeatDur",
    "requiredExtensions",
    "requiredFeatures",
    "specularConstant",
    "specularExponent",
    "spreadMethod",
    "startOffset",
    "stdDeviation",
    "stitchTiles",
    "surfaceScale",
    "systemLanguage",
    "tableValues",
    "targetX",
    "targetY",
    "textLength",
    "viewBox",
    "viewTarget",
    "xChannelSelector",
    "yChannelSelector",
    "zoomAndPan"
  ].map(function(val) {
    return [val.toLowerCase(), val];
  }));
});

// node_modules/dom-serializer/lib/index.js
var require_lib4 = __commonJS((exports) => {
  var __assign = exports && exports.__assign || function() {
    __assign = Object.assign || function(t) {
      for (var s, i = 1, n = arguments.length;i < n; i++) {
        s = arguments[i];
        for (var p in s)
          if (Object.prototype.hasOwnProperty.call(s, p))
            t[p] = s[p];
      }
      return t;
    };
    return __assign.apply(this, arguments);
  };
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() {
        return m[k];
      } };
    }
    Object.defineProperty(o, k2, desc);
  } : function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    o[k2] = m[k];
  });
  var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
  } : function(o, v) {
    o["default"] = v;
  });
  var __importStar = exports && exports.__importStar || function(mod2) {
    if (mod2 && mod2.__esModule)
      return mod2;
    var result = {};
    if (mod2 != null) {
      for (var k in mod2)
        if (k !== "default" && Object.prototype.hasOwnProperty.call(mod2, k))
          __createBinding(result, mod2, k);
    }
    __setModuleDefault(result, mod2);
    return result;
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.render = undefined;
  var ElementType2 = __importStar(require_lib());
  var entities_1 = require_lib3();
  var foreignNames_js_1 = require_foreignNames();
  var unencodedElements = new Set([
    "style",
    "script",
    "xmp",
    "iframe",
    "noembed",
    "noframes",
    "plaintext",
    "noscript"
  ]);
  function replaceQuotes(value2) {
    return value2.replace(/"/g, "&quot;");
  }
  function formatAttributes(attributes, opts) {
    var _a2;
    if (!attributes)
      return;
    var encode3 = ((_a2 = opts.encodeEntities) !== null && _a2 !== undefined ? _a2 : opts.decodeEntities) === false ? replaceQuotes : opts.xmlMode || opts.encodeEntities !== "utf8" ? entities_1.encodeXML : entities_1.escapeAttribute;
    return Object.keys(attributes).map(function(key) {
      var _a3, _b;
      var value2 = (_a3 = attributes[key]) !== null && _a3 !== undefined ? _a3 : "";
      if (opts.xmlMode === "foreign") {
        key = (_b = foreignNames_js_1.attributeNames.get(key)) !== null && _b !== undefined ? _b : key;
      }
      if (!opts.emptyAttrs && !opts.xmlMode && value2 === "") {
        return key;
      }
      return "".concat(key, '="').concat(encode3(value2), '"');
    }).join(" ");
  }
  var singleTag = new Set([
    "area",
    "base",
    "basefont",
    "br",
    "col",
    "command",
    "embed",
    "frame",
    "hr",
    "img",
    "input",
    "isindex",
    "keygen",
    "link",
    "meta",
    "param",
    "source",
    "track",
    "wbr"
  ]);
  function render(node, options) {
    if (options === undefined) {
      options = {};
    }
    var nodes = "length" in node ? node : [node];
    var output = "";
    for (var i = 0;i < nodes.length; i++) {
      output += renderNode(nodes[i], options);
    }
    return output;
  }
  exports.render = render;
  exports.default = render;
  function renderNode(node, options) {
    switch (node.type) {
      case ElementType2.Root:
        return render(node.children, options);
      case ElementType2.Doctype:
      case ElementType2.Directive:
        return renderDirective(node);
      case ElementType2.Comment:
        return renderComment(node);
      case ElementType2.CDATA:
        return renderCdata(node);
      case ElementType2.Script:
      case ElementType2.Style:
      case ElementType2.Tag:
        return renderTag(node, options);
      case ElementType2.Text:
        return renderText(node, options);
    }
  }
  var foreignModeIntegrationPoints = new Set([
    "mi",
    "mo",
    "mn",
    "ms",
    "mtext",
    "annotation-xml",
    "foreignObject",
    "desc",
    "title"
  ]);
  var foreignElements = new Set(["svg", "math"]);
  function renderTag(elem, opts) {
    var _a2;
    if (opts.xmlMode === "foreign") {
      elem.name = (_a2 = foreignNames_js_1.elementNames.get(elem.name)) !== null && _a2 !== undefined ? _a2 : elem.name;
      if (elem.parent && foreignModeIntegrationPoints.has(elem.parent.name)) {
        opts = __assign(__assign({}, opts), { xmlMode: false });
      }
    }
    if (!opts.xmlMode && foreignElements.has(elem.name)) {
      opts = __assign(__assign({}, opts), { xmlMode: "foreign" });
    }
    var tag2 = "<".concat(elem.name);
    var attribs = formatAttributes(elem.attribs, opts);
    if (attribs) {
      tag2 += " ".concat(attribs);
    }
    if (elem.children.length === 0 && (opts.xmlMode ? opts.selfClosingTags !== false : opts.selfClosingTags && singleTag.has(elem.name))) {
      if (!opts.xmlMode)
        tag2 += " ";
      tag2 += "/>";
    } else {
      tag2 += ">";
      if (elem.children.length > 0) {
        tag2 += render(elem.children, opts);
      }
      if (opts.xmlMode || !singleTag.has(elem.name)) {
        tag2 += "</".concat(elem.name, ">");
      }
    }
    return tag2;
  }
  function renderDirective(elem) {
    return "<".concat(elem.data, ">");
  }
  function renderText(elem, opts) {
    var _a2;
    var data2 = elem.data || "";
    if (((_a2 = opts.encodeEntities) !== null && _a2 !== undefined ? _a2 : opts.decodeEntities) !== false && !(!opts.xmlMode && elem.parent && unencodedElements.has(elem.parent.name))) {
      data2 = opts.xmlMode || opts.encodeEntities !== "utf8" ? (0, entities_1.encodeXML)(data2) : (0, entities_1.escapeText)(data2);
    }
    return data2;
  }
  function renderCdata(elem) {
    return "<![CDATA[".concat(elem.children[0].data, "]]>");
  }
  function renderComment(elem) {
    return "<!--".concat(elem.data, "-->");
  }
});

// node_modules/domutils/lib/stringify.js
var require_stringify2 = __commonJS((exports) => {
  var __importDefault = exports && exports.__importDefault || function(mod2) {
    return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.getOuterHTML = getOuterHTML;
  exports.getInnerHTML = getInnerHTML;
  exports.getText = getText;
  exports.textContent = textContent;
  exports.innerText = innerText;
  var domhandler_1 = require_lib2();
  var dom_serializer_1 = __importDefault(require_lib4());
  var domelementtype_1 = require_lib();
  function getOuterHTML(node, options) {
    return (0, dom_serializer_1.default)(node, options);
  }
  function getInnerHTML(node, options) {
    return (0, domhandler_1.hasChildren)(node) ? node.children.map(function(node2) {
      return getOuterHTML(node2, options);
    }).join("") : "";
  }
  function getText(node) {
    if (Array.isArray(node))
      return node.map(getText).join("");
    if ((0, domhandler_1.isTag)(node))
      return node.name === "br" ? `
` : getText(node.children);
    if ((0, domhandler_1.isCDATA)(node))
      return getText(node.children);
    if ((0, domhandler_1.isText)(node))
      return node.data;
    return "";
  }
  function textContent(node) {
    if (Array.isArray(node))
      return node.map(textContent).join("");
    if ((0, domhandler_1.hasChildren)(node) && !(0, domhandler_1.isComment)(node)) {
      return textContent(node.children);
    }
    if ((0, domhandler_1.isText)(node))
      return node.data;
    return "";
  }
  function innerText(node) {
    if (Array.isArray(node))
      return node.map(innerText).join("");
    if ((0, domhandler_1.hasChildren)(node) && (node.type === domelementtype_1.ElementType.Tag || (0, domhandler_1.isCDATA)(node))) {
      return innerText(node.children);
    }
    if ((0, domhandler_1.isText)(node))
      return node.data;
    return "";
  }
});

// node_modules/domutils/lib/traversal.js
var require_traversal = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.getChildren = getChildren;
  exports.getParent = getParent;
  exports.getSiblings = getSiblings;
  exports.getAttributeValue = getAttributeValue;
  exports.hasAttrib = hasAttrib;
  exports.getName = getName;
  exports.nextElementSibling = nextElementSibling;
  exports.prevElementSibling = prevElementSibling;
  var domhandler_1 = require_lib2();
  function getChildren(elem) {
    return (0, domhandler_1.hasChildren)(elem) ? elem.children : [];
  }
  function getParent(elem) {
    return elem.parent || null;
  }
  function getSiblings(elem) {
    var _a2, _b;
    var parent = getParent(elem);
    if (parent != null)
      return getChildren(parent);
    var siblings = [elem];
    var { prev, next: next2 } = elem;
    while (prev != null) {
      siblings.unshift(prev);
      _a2 = prev, prev = _a2.prev;
    }
    while (next2 != null) {
      siblings.push(next2);
      _b = next2, next2 = _b.next;
    }
    return siblings;
  }
  function getAttributeValue(elem, name2) {
    var _a2;
    return (_a2 = elem.attribs) === null || _a2 === undefined ? undefined : _a2[name2];
  }
  function hasAttrib(elem, name2) {
    return elem.attribs != null && Object.prototype.hasOwnProperty.call(elem.attribs, name2) && elem.attribs[name2] != null;
  }
  function getName(elem) {
    return elem.name;
  }
  function nextElementSibling(elem) {
    var _a2;
    var next2 = elem.next;
    while (next2 !== null && !(0, domhandler_1.isTag)(next2))
      _a2 = next2, next2 = _a2.next;
    return next2;
  }
  function prevElementSibling(elem) {
    var _a2;
    var prev = elem.prev;
    while (prev !== null && !(0, domhandler_1.isTag)(prev))
      _a2 = prev, prev = _a2.prev;
    return prev;
  }
});

// node_modules/domutils/lib/manipulation.js
var require_manipulation = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.removeElement = removeElement;
  exports.replaceElement = replaceElement;
  exports.appendChild = appendChild;
  exports.append = append2;
  exports.prependChild = prependChild;
  exports.prepend = prepend;
  function removeElement(elem) {
    if (elem.prev)
      elem.prev.next = elem.next;
    if (elem.next)
      elem.next.prev = elem.prev;
    if (elem.parent) {
      var childs = elem.parent.children;
      var childsIndex = childs.lastIndexOf(elem);
      if (childsIndex >= 0) {
        childs.splice(childsIndex, 1);
      }
    }
    elem.next = null;
    elem.prev = null;
    elem.parent = null;
  }
  function replaceElement(elem, replacement) {
    var prev = replacement.prev = elem.prev;
    if (prev) {
      prev.next = replacement;
    }
    var next2 = replacement.next = elem.next;
    if (next2) {
      next2.prev = replacement;
    }
    var parent = replacement.parent = elem.parent;
    if (parent) {
      var childs = parent.children;
      childs[childs.lastIndexOf(elem)] = replacement;
      elem.parent = null;
    }
  }
  function appendChild(parent, child) {
    removeElement(child);
    child.next = null;
    child.parent = parent;
    if (parent.children.push(child) > 1) {
      var sibling = parent.children[parent.children.length - 2];
      sibling.next = child;
      child.prev = sibling;
    } else {
      child.prev = null;
    }
  }
  function append2(elem, next2) {
    removeElement(next2);
    var parent = elem.parent;
    var currNext = elem.next;
    next2.next = currNext;
    next2.prev = elem;
    elem.next = next2;
    next2.parent = parent;
    if (currNext) {
      currNext.prev = next2;
      if (parent) {
        var childs = parent.children;
        childs.splice(childs.lastIndexOf(currNext), 0, next2);
      }
    } else if (parent) {
      parent.children.push(next2);
    }
  }
  function prependChild(parent, child) {
    removeElement(child);
    child.parent = parent;
    child.prev = null;
    if (parent.children.unshift(child) !== 1) {
      var sibling = parent.children[1];
      sibling.prev = child;
      child.next = sibling;
    } else {
      child.next = null;
    }
  }
  function prepend(elem, prev) {
    removeElement(prev);
    var parent = elem.parent;
    if (parent) {
      var childs = parent.children;
      childs.splice(childs.indexOf(elem), 0, prev);
    }
    if (elem.prev) {
      elem.prev.next = prev;
    }
    prev.parent = parent;
    prev.prev = elem.prev;
    prev.next = elem;
    elem.prev = prev;
  }
});

// node_modules/domutils/lib/querying.js
var require_querying = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.filter = filter;
  exports.find = find2;
  exports.findOneChild = findOneChild;
  exports.findOne = findOne;
  exports.existsOne = existsOne;
  exports.findAll = findAll;
  var domhandler_1 = require_lib2();
  function filter(test, node, recurse, limit) {
    if (recurse === undefined) {
      recurse = true;
    }
    if (limit === undefined) {
      limit = Infinity;
    }
    return find2(test, Array.isArray(node) ? node : [node], recurse, limit);
  }
  function find2(test, nodes, recurse, limit) {
    var result = [];
    var nodeStack = [Array.isArray(nodes) ? nodes : [nodes]];
    var indexStack = [0];
    for (;; ) {
      if (indexStack[0] >= nodeStack[0].length) {
        if (indexStack.length === 1) {
          return result;
        }
        nodeStack.shift();
        indexStack.shift();
        continue;
      }
      var elem = nodeStack[0][indexStack[0]++];
      if (test(elem)) {
        result.push(elem);
        if (--limit <= 0)
          return result;
      }
      if (recurse && (0, domhandler_1.hasChildren)(elem) && elem.children.length > 0) {
        indexStack.unshift(0);
        nodeStack.unshift(elem.children);
      }
    }
  }
  function findOneChild(test, nodes) {
    return nodes.find(test);
  }
  function findOne(test, nodes, recurse) {
    if (recurse === undefined) {
      recurse = true;
    }
    var searchedNodes = Array.isArray(nodes) ? nodes : [nodes];
    for (var i = 0;i < searchedNodes.length; i++) {
      var node = searchedNodes[i];
      if ((0, domhandler_1.isTag)(node) && test(node)) {
        return node;
      }
      if (recurse && (0, domhandler_1.hasChildren)(node) && node.children.length > 0) {
        var found = findOne(test, node.children, true);
        if (found)
          return found;
      }
    }
    return null;
  }
  function existsOne(test, nodes) {
    return (Array.isArray(nodes) ? nodes : [nodes]).some(function(node) {
      return (0, domhandler_1.isTag)(node) && test(node) || (0, domhandler_1.hasChildren)(node) && existsOne(test, node.children);
    });
  }
  function findAll(test, nodes) {
    var result = [];
    var nodeStack = [Array.isArray(nodes) ? nodes : [nodes]];
    var indexStack = [0];
    for (;; ) {
      if (indexStack[0] >= nodeStack[0].length) {
        if (nodeStack.length === 1) {
          return result;
        }
        nodeStack.shift();
        indexStack.shift();
        continue;
      }
      var elem = nodeStack[0][indexStack[0]++];
      if ((0, domhandler_1.isTag)(elem) && test(elem))
        result.push(elem);
      if ((0, domhandler_1.hasChildren)(elem) && elem.children.length > 0) {
        indexStack.unshift(0);
        nodeStack.unshift(elem.children);
      }
    }
  }
});

// node_modules/domutils/lib/legacy.js
var require_legacy = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.testElement = testElement;
  exports.getElements = getElements;
  exports.getElementById = getElementById;
  exports.getElementsByTagName = getElementsByTagName;
  exports.getElementsByClassName = getElementsByClassName;
  exports.getElementsByTagType = getElementsByTagType;
  var domhandler_1 = require_lib2();
  var querying_js_1 = require_querying();
  var Checks = {
    tag_name: function(name2) {
      if (typeof name2 === "function") {
        return function(elem) {
          return (0, domhandler_1.isTag)(elem) && name2(elem.name);
        };
      } else if (name2 === "*") {
        return domhandler_1.isTag;
      }
      return function(elem) {
        return (0, domhandler_1.isTag)(elem) && elem.name === name2;
      };
    },
    tag_type: function(type) {
      if (typeof type === "function") {
        return function(elem) {
          return type(elem.type);
        };
      }
      return function(elem) {
        return elem.type === type;
      };
    },
    tag_contains: function(data2) {
      if (typeof data2 === "function") {
        return function(elem) {
          return (0, domhandler_1.isText)(elem) && data2(elem.data);
        };
      }
      return function(elem) {
        return (0, domhandler_1.isText)(elem) && elem.data === data2;
      };
    }
  };
  function getAttribCheck(attrib, value2) {
    if (typeof value2 === "function") {
      return function(elem) {
        return (0, domhandler_1.isTag)(elem) && value2(elem.attribs[attrib]);
      };
    }
    return function(elem) {
      return (0, domhandler_1.isTag)(elem) && elem.attribs[attrib] === value2;
    };
  }
  function combineFuncs(a, b) {
    return function(elem) {
      return a(elem) || b(elem);
    };
  }
  function compileTest(options) {
    var funcs = Object.keys(options).map(function(key) {
      var value2 = options[key];
      return Object.prototype.hasOwnProperty.call(Checks, key) ? Checks[key](value2) : getAttribCheck(key, value2);
    });
    return funcs.length === 0 ? null : funcs.reduce(combineFuncs);
  }
  function testElement(options, node) {
    var test = compileTest(options);
    return test ? test(node) : true;
  }
  function getElements(options, nodes, recurse, limit) {
    if (limit === undefined) {
      limit = Infinity;
    }
    var test = compileTest(options);
    return test ? (0, querying_js_1.filter)(test, nodes, recurse, limit) : [];
  }
  function getElementById(id2, nodes, recurse) {
    if (recurse === undefined) {
      recurse = true;
    }
    if (!Array.isArray(nodes))
      nodes = [nodes];
    return (0, querying_js_1.findOne)(getAttribCheck("id", id2), nodes, recurse);
  }
  function getElementsByTagName(tagName, nodes, recurse, limit) {
    if (recurse === undefined) {
      recurse = true;
    }
    if (limit === undefined) {
      limit = Infinity;
    }
    return (0, querying_js_1.filter)(Checks["tag_name"](tagName), nodes, recurse, limit);
  }
  function getElementsByClassName(className, nodes, recurse, limit) {
    if (recurse === undefined) {
      recurse = true;
    }
    if (limit === undefined) {
      limit = Infinity;
    }
    return (0, querying_js_1.filter)(getAttribCheck("class", className), nodes, recurse, limit);
  }
  function getElementsByTagType(type, nodes, recurse, limit) {
    if (recurse === undefined) {
      recurse = true;
    }
    if (limit === undefined) {
      limit = Infinity;
    }
    return (0, querying_js_1.filter)(Checks["tag_type"](type), nodes, recurse, limit);
  }
});

// node_modules/domutils/lib/helpers.js
var require_helpers = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.DocumentPosition = undefined;
  exports.removeSubsets = removeSubsets;
  exports.compareDocumentPosition = compareDocumentPosition;
  exports.uniqueSort = uniqueSort;
  var domhandler_1 = require_lib2();
  function removeSubsets(nodes) {
    var idx = nodes.length;
    while (--idx >= 0) {
      var node = nodes[idx];
      if (idx > 0 && nodes.lastIndexOf(node, idx - 1) >= 0) {
        nodes.splice(idx, 1);
        continue;
      }
      for (var ancestor = node.parent;ancestor; ancestor = ancestor.parent) {
        if (nodes.includes(ancestor)) {
          nodes.splice(idx, 1);
          break;
        }
      }
    }
    return nodes;
  }
  var DocumentPosition;
  (function(DocumentPosition2) {
    DocumentPosition2[DocumentPosition2["DISCONNECTED"] = 1] = "DISCONNECTED";
    DocumentPosition2[DocumentPosition2["PRECEDING"] = 2] = "PRECEDING";
    DocumentPosition2[DocumentPosition2["FOLLOWING"] = 4] = "FOLLOWING";
    DocumentPosition2[DocumentPosition2["CONTAINS"] = 8] = "CONTAINS";
    DocumentPosition2[DocumentPosition2["CONTAINED_BY"] = 16] = "CONTAINED_BY";
  })(DocumentPosition || (exports.DocumentPosition = DocumentPosition = {}));
  function compareDocumentPosition(nodeA, nodeB) {
    var aParents = [];
    var bParents = [];
    if (nodeA === nodeB) {
      return 0;
    }
    var current = (0, domhandler_1.hasChildren)(nodeA) ? nodeA : nodeA.parent;
    while (current) {
      aParents.unshift(current);
      current = current.parent;
    }
    current = (0, domhandler_1.hasChildren)(nodeB) ? nodeB : nodeB.parent;
    while (current) {
      bParents.unshift(current);
      current = current.parent;
    }
    var maxIdx = Math.min(aParents.length, bParents.length);
    var idx = 0;
    while (idx < maxIdx && aParents[idx] === bParents[idx]) {
      idx++;
    }
    if (idx === 0) {
      return DocumentPosition.DISCONNECTED;
    }
    var sharedParent = aParents[idx - 1];
    var siblings = sharedParent.children;
    var aSibling = aParents[idx];
    var bSibling = bParents[idx];
    if (siblings.indexOf(aSibling) > siblings.indexOf(bSibling)) {
      if (sharedParent === nodeB) {
        return DocumentPosition.FOLLOWING | DocumentPosition.CONTAINED_BY;
      }
      return DocumentPosition.FOLLOWING;
    }
    if (sharedParent === nodeA) {
      return DocumentPosition.PRECEDING | DocumentPosition.CONTAINS;
    }
    return DocumentPosition.PRECEDING;
  }
  function uniqueSort(nodes) {
    nodes = nodes.filter(function(node, i, arr) {
      return !arr.includes(node, i + 1);
    });
    nodes.sort(function(a, b) {
      var relative = compareDocumentPosition(a, b);
      if (relative & DocumentPosition.PRECEDING) {
        return -1;
      } else if (relative & DocumentPosition.FOLLOWING) {
        return 1;
      }
      return 0;
    });
    return nodes;
  }
});

// node_modules/domutils/lib/feeds.js
var require_feeds = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.getFeed = getFeed;
  var stringify_js_1 = require_stringify2();
  var legacy_js_1 = require_legacy();
  function getFeed(doc2) {
    var feedRoot = getOneElement(isValidFeed, doc2);
    return !feedRoot ? null : feedRoot.name === "feed" ? getAtomFeed(feedRoot) : getRssFeed(feedRoot);
  }
  function getAtomFeed(feedRoot) {
    var _a2;
    var childs = feedRoot.children;
    var feed = {
      type: "atom",
      items: (0, legacy_js_1.getElementsByTagName)("entry", childs).map(function(item) {
        var _a3;
        var children = item.children;
        var entry = { media: getMediaElements(children) };
        addConditionally(entry, "id", "id", children);
        addConditionally(entry, "title", "title", children);
        var href2 = (_a3 = getOneElement("link", children)) === null || _a3 === undefined ? undefined : _a3.attribs["href"];
        if (href2) {
          entry.link = href2;
        }
        var description = fetch2("summary", children) || fetch2("content", children);
        if (description) {
          entry.description = description;
        }
        var pubDate = fetch2("updated", children);
        if (pubDate) {
          entry.pubDate = new Date(pubDate);
        }
        return entry;
      })
    };
    addConditionally(feed, "id", "id", childs);
    addConditionally(feed, "title", "title", childs);
    var href = (_a2 = getOneElement("link", childs)) === null || _a2 === undefined ? undefined : _a2.attribs["href"];
    if (href) {
      feed.link = href;
    }
    addConditionally(feed, "description", "subtitle", childs);
    var updated = fetch2("updated", childs);
    if (updated) {
      feed.updated = new Date(updated);
    }
    addConditionally(feed, "author", "email", childs, true);
    return feed;
  }
  function getRssFeed(feedRoot) {
    var _a2, _b;
    var childs = (_b = (_a2 = getOneElement("channel", feedRoot.children)) === null || _a2 === undefined ? undefined : _a2.children) !== null && _b !== undefined ? _b : [];
    var feed = {
      type: feedRoot.name.substr(0, 3),
      id: "",
      items: (0, legacy_js_1.getElementsByTagName)("item", feedRoot.children).map(function(item) {
        var children = item.children;
        var entry = { media: getMediaElements(children) };
        addConditionally(entry, "id", "guid", children);
        addConditionally(entry, "title", "title", children);
        addConditionally(entry, "link", "link", children);
        addConditionally(entry, "description", "description", children);
        var pubDate = fetch2("pubDate", children) || fetch2("dc:date", children);
        if (pubDate)
          entry.pubDate = new Date(pubDate);
        return entry;
      })
    };
    addConditionally(feed, "title", "title", childs);
    addConditionally(feed, "link", "link", childs);
    addConditionally(feed, "description", "description", childs);
    var updated = fetch2("lastBuildDate", childs);
    if (updated) {
      feed.updated = new Date(updated);
    }
    addConditionally(feed, "author", "managingEditor", childs, true);
    return feed;
  }
  var MEDIA_KEYS_STRING = ["url", "type", "lang"];
  var MEDIA_KEYS_INT = [
    "fileSize",
    "bitrate",
    "framerate",
    "samplingrate",
    "channels",
    "duration",
    "height",
    "width"
  ];
  function getMediaElements(where) {
    return (0, legacy_js_1.getElementsByTagName)("media:content", where).map(function(elem) {
      var attribs = elem.attribs;
      var media = {
        medium: attribs["medium"],
        isDefault: !!attribs["isDefault"]
      };
      for (var _i = 0, MEDIA_KEYS_STRING_1 = MEDIA_KEYS_STRING;_i < MEDIA_KEYS_STRING_1.length; _i++) {
        var attrib = MEDIA_KEYS_STRING_1[_i];
        if (attribs[attrib]) {
          media[attrib] = attribs[attrib];
        }
      }
      for (var _a2 = 0, MEDIA_KEYS_INT_1 = MEDIA_KEYS_INT;_a2 < MEDIA_KEYS_INT_1.length; _a2++) {
        var attrib = MEDIA_KEYS_INT_1[_a2];
        if (attribs[attrib]) {
          media[attrib] = parseInt(attribs[attrib], 10);
        }
      }
      if (attribs["expression"]) {
        media.expression = attribs["expression"];
      }
      return media;
    });
  }
  function getOneElement(tagName, node) {
    return (0, legacy_js_1.getElementsByTagName)(tagName, node, true, 1)[0];
  }
  function fetch2(tagName, where, recurse) {
    if (recurse === undefined) {
      recurse = false;
    }
    return (0, stringify_js_1.textContent)((0, legacy_js_1.getElementsByTagName)(tagName, where, recurse, 1)).trim();
  }
  function addConditionally(obj, prop, tagName, where, recurse) {
    if (recurse === undefined) {
      recurse = false;
    }
    var val = fetch2(tagName, where, recurse);
    if (val)
      obj[prop] = val;
  }
  function isValidFeed(value2) {
    return value2 === "rss" || value2 === "feed" || value2 === "rdf:RDF";
  }
});

// node_modules/domutils/lib/index.js
var require_lib5 = __commonJS((exports) => {
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() {
        return m[k];
      } };
    }
    Object.defineProperty(o, k2, desc);
  } : function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    o[k2] = m[k];
  });
  var __exportStar = exports && exports.__exportStar || function(m, exports2) {
    for (var p in m)
      if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
        __createBinding(exports2, m, p);
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.hasChildren = exports.isDocument = exports.isComment = exports.isText = exports.isCDATA = exports.isTag = undefined;
  __exportStar(require_stringify2(), exports);
  __exportStar(require_traversal(), exports);
  __exportStar(require_manipulation(), exports);
  __exportStar(require_querying(), exports);
  __exportStar(require_legacy(), exports);
  __exportStar(require_helpers(), exports);
  __exportStar(require_feeds(), exports);
  var domhandler_1 = require_lib2();
  Object.defineProperty(exports, "isTag", { enumerable: true, get: function() {
    return domhandler_1.isTag;
  } });
  Object.defineProperty(exports, "isCDATA", { enumerable: true, get: function() {
    return domhandler_1.isCDATA;
  } });
  Object.defineProperty(exports, "isText", { enumerable: true, get: function() {
    return domhandler_1.isText;
  } });
  Object.defineProperty(exports, "isComment", { enumerable: true, get: function() {
    return domhandler_1.isComment;
  } });
  Object.defineProperty(exports, "isDocument", { enumerable: true, get: function() {
    return domhandler_1.isDocument;
  } });
  Object.defineProperty(exports, "hasChildren", { enumerable: true, get: function() {
    return domhandler_1.hasChildren;
  } });
});

// node_modules/boolbase/index.js
var require_boolbase = __commonJS((exports, module) => {
  module.exports = {
    trueFunc: function trueFunc() {
      return true;
    },
    falseFunc: function falseFunc() {
      return false;
    }
  };
});

// node_modules/css-what/lib/commonjs/types.js
var require_types = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.AttributeAction = exports.IgnoreCaseMode = exports.SelectorType = undefined;
  var SelectorType;
  (function(SelectorType2) {
    SelectorType2["Attribute"] = "attribute";
    SelectorType2["Pseudo"] = "pseudo";
    SelectorType2["PseudoElement"] = "pseudo-element";
    SelectorType2["Tag"] = "tag";
    SelectorType2["Universal"] = "universal";
    SelectorType2["Adjacent"] = "adjacent";
    SelectorType2["Child"] = "child";
    SelectorType2["Descendant"] = "descendant";
    SelectorType2["Parent"] = "parent";
    SelectorType2["Sibling"] = "sibling";
    SelectorType2["ColumnCombinator"] = "column-combinator";
  })(SelectorType = exports.SelectorType || (exports.SelectorType = {}));
  exports.IgnoreCaseMode = {
    Unknown: null,
    QuirksMode: "quirks",
    IgnoreCase: true,
    CaseSensitive: false
  };
  var AttributeAction;
  (function(AttributeAction2) {
    AttributeAction2["Any"] = "any";
    AttributeAction2["Element"] = "element";
    AttributeAction2["End"] = "end";
    AttributeAction2["Equals"] = "equals";
    AttributeAction2["Exists"] = "exists";
    AttributeAction2["Hyphen"] = "hyphen";
    AttributeAction2["Not"] = "not";
    AttributeAction2["Start"] = "start";
  })(AttributeAction = exports.AttributeAction || (exports.AttributeAction = {}));
});

// node_modules/css-what/lib/commonjs/parse.js
var require_parse = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.parse = exports.isTraversal = undefined;
  var types_1 = require_types();
  var reName = /^[^\\#]?(?:\\(?:[\da-f]{1,6}\s?|.)|[\w\-\u00b0-\uFFFF])+/;
  var reEscape = /\\([\da-f]{1,6}\s?|(\s)|.)/gi;
  var actionTypes = new Map([
    [126, types_1.AttributeAction.Element],
    [94, types_1.AttributeAction.Start],
    [36, types_1.AttributeAction.End],
    [42, types_1.AttributeAction.Any],
    [33, types_1.AttributeAction.Not],
    [124, types_1.AttributeAction.Hyphen]
  ]);
  var unpackPseudos = new Set([
    "has",
    "not",
    "matches",
    "is",
    "where",
    "host",
    "host-context"
  ]);
  function isTraversal(selector) {
    switch (selector.type) {
      case types_1.SelectorType.Adjacent:
      case types_1.SelectorType.Child:
      case types_1.SelectorType.Descendant:
      case types_1.SelectorType.Parent:
      case types_1.SelectorType.Sibling:
      case types_1.SelectorType.ColumnCombinator:
        return true;
      default:
        return false;
    }
  }
  exports.isTraversal = isTraversal;
  var stripQuotesFromPseudos = new Set(["contains", "icontains"]);
  function funescape(_, escaped, escapedWhitespace) {
    var high = parseInt(escaped, 16) - 65536;
    return high !== high || escapedWhitespace ? escaped : high < 0 ? String.fromCharCode(high + 65536) : String.fromCharCode(high >> 10 | 55296, high & 1023 | 56320);
  }
  function unescapeCSS(str) {
    return str.replace(reEscape, funescape);
  }
  function isQuote(c) {
    return c === 39 || c === 34;
  }
  function isWhitespace2(c) {
    return c === 32 || c === 9 || c === 10 || c === 12 || c === 13;
  }
  function parse6(selector) {
    var subselects = [];
    var endIndex = parseSelector(subselects, "".concat(selector), 0);
    if (endIndex < selector.length) {
      throw new Error("Unmatched selector: ".concat(selector.slice(endIndex)));
    }
    return subselects;
  }
  exports.parse = parse6;
  function parseSelector(subselects, selector, selectorIndex) {
    var tokens = [];
    function getName(offset) {
      var match = selector.slice(selectorIndex + offset).match(reName);
      if (!match) {
        throw new Error("Expected name, found ".concat(selector.slice(selectorIndex)));
      }
      var name2 = match[0];
      selectorIndex += offset + name2.length;
      return unescapeCSS(name2);
    }
    function stripWhitespace(offset) {
      selectorIndex += offset;
      while (selectorIndex < selector.length && isWhitespace2(selector.charCodeAt(selectorIndex))) {
        selectorIndex++;
      }
    }
    function readValueWithParenthesis() {
      selectorIndex += 1;
      var start = selectorIndex;
      var counter = 1;
      for (;counter > 0 && selectorIndex < selector.length; selectorIndex++) {
        if (selector.charCodeAt(selectorIndex) === 40 && !isEscaped(selectorIndex)) {
          counter++;
        } else if (selector.charCodeAt(selectorIndex) === 41 && !isEscaped(selectorIndex)) {
          counter--;
        }
      }
      if (counter) {
        throw new Error("Parenthesis not matched");
      }
      return unescapeCSS(selector.slice(start, selectorIndex - 1));
    }
    function isEscaped(pos) {
      var slashCount = 0;
      while (selector.charCodeAt(--pos) === 92)
        slashCount++;
      return (slashCount & 1) === 1;
    }
    function ensureNotTraversal() {
      if (tokens.length > 0 && isTraversal(tokens[tokens.length - 1])) {
        throw new Error("Did not expect successive traversals.");
      }
    }
    function addTraversal(type) {
      if (tokens.length > 0 && tokens[tokens.length - 1].type === types_1.SelectorType.Descendant) {
        tokens[tokens.length - 1].type = type;
        return;
      }
      ensureNotTraversal();
      tokens.push({ type });
    }
    function addSpecialAttribute(name2, action2) {
      tokens.push({
        type: types_1.SelectorType.Attribute,
        name: name2,
        action: action2,
        value: getName(1),
        namespace: null,
        ignoreCase: "quirks"
      });
    }
    function finalizeSubselector() {
      if (tokens.length && tokens[tokens.length - 1].type === types_1.SelectorType.Descendant) {
        tokens.pop();
      }
      if (tokens.length === 0) {
        throw new Error("Empty sub-selector");
      }
      subselects.push(tokens);
    }
    stripWhitespace(0);
    if (selector.length === selectorIndex) {
      return selectorIndex;
    }
    loop:
      while (selectorIndex < selector.length) {
        var firstChar = selector.charCodeAt(selectorIndex);
        switch (firstChar) {
          case 32:
          case 9:
          case 10:
          case 12:
          case 13: {
            if (tokens.length === 0 || tokens[0].type !== types_1.SelectorType.Descendant) {
              ensureNotTraversal();
              tokens.push({ type: types_1.SelectorType.Descendant });
            }
            stripWhitespace(1);
            break;
          }
          case 62: {
            addTraversal(types_1.SelectorType.Child);
            stripWhitespace(1);
            break;
          }
          case 60: {
            addTraversal(types_1.SelectorType.Parent);
            stripWhitespace(1);
            break;
          }
          case 126: {
            addTraversal(types_1.SelectorType.Sibling);
            stripWhitespace(1);
            break;
          }
          case 43: {
            addTraversal(types_1.SelectorType.Adjacent);
            stripWhitespace(1);
            break;
          }
          case 46: {
            addSpecialAttribute("class", types_1.AttributeAction.Element);
            break;
          }
          case 35: {
            addSpecialAttribute("id", types_1.AttributeAction.Equals);
            break;
          }
          case 91: {
            stripWhitespace(1);
            var name_1 = undefined;
            var namespace = null;
            if (selector.charCodeAt(selectorIndex) === 124) {
              name_1 = getName(1);
            } else if (selector.startsWith("*|", selectorIndex)) {
              namespace = "*";
              name_1 = getName(2);
            } else {
              name_1 = getName(0);
              if (selector.charCodeAt(selectorIndex) === 124 && selector.charCodeAt(selectorIndex + 1) !== 61) {
                namespace = name_1;
                name_1 = getName(1);
              }
            }
            stripWhitespace(0);
            var action = types_1.AttributeAction.Exists;
            var possibleAction = actionTypes.get(selector.charCodeAt(selectorIndex));
            if (possibleAction) {
              action = possibleAction;
              if (selector.charCodeAt(selectorIndex + 1) !== 61) {
                throw new Error("Expected `=`");
              }
              stripWhitespace(2);
            } else if (selector.charCodeAt(selectorIndex) === 61) {
              action = types_1.AttributeAction.Equals;
              stripWhitespace(1);
            }
            var value2 = "";
            var ignoreCase = null;
            if (action !== "exists") {
              if (isQuote(selector.charCodeAt(selectorIndex))) {
                var quote = selector.charCodeAt(selectorIndex);
                var sectionEnd = selectorIndex + 1;
                while (sectionEnd < selector.length && (selector.charCodeAt(sectionEnd) !== quote || isEscaped(sectionEnd))) {
                  sectionEnd += 1;
                }
                if (selector.charCodeAt(sectionEnd) !== quote) {
                  throw new Error("Attribute value didn't end");
                }
                value2 = unescapeCSS(selector.slice(selectorIndex + 1, sectionEnd));
                selectorIndex = sectionEnd + 1;
              } else {
                var valueStart = selectorIndex;
                while (selectorIndex < selector.length && (!isWhitespace2(selector.charCodeAt(selectorIndex)) && selector.charCodeAt(selectorIndex) !== 93 || isEscaped(selectorIndex))) {
                  selectorIndex += 1;
                }
                value2 = unescapeCSS(selector.slice(valueStart, selectorIndex));
              }
              stripWhitespace(0);
              var forceIgnore = selector.charCodeAt(selectorIndex) | 32;
              if (forceIgnore === 115) {
                ignoreCase = false;
                stripWhitespace(1);
              } else if (forceIgnore === 105) {
                ignoreCase = true;
                stripWhitespace(1);
              }
            }
            if (selector.charCodeAt(selectorIndex) !== 93) {
              throw new Error("Attribute selector didn't terminate");
            }
            selectorIndex += 1;
            var attributeSelector = {
              type: types_1.SelectorType.Attribute,
              name: name_1,
              action,
              value: value2,
              namespace,
              ignoreCase
            };
            tokens.push(attributeSelector);
            break;
          }
          case 58: {
            if (selector.charCodeAt(selectorIndex + 1) === 58) {
              tokens.push({
                type: types_1.SelectorType.PseudoElement,
                name: getName(2).toLowerCase(),
                data: selector.charCodeAt(selectorIndex) === 40 ? readValueWithParenthesis() : null
              });
              continue;
            }
            var name_2 = getName(1).toLowerCase();
            var data2 = null;
            if (selector.charCodeAt(selectorIndex) === 40) {
              if (unpackPseudos.has(name_2)) {
                if (isQuote(selector.charCodeAt(selectorIndex + 1))) {
                  throw new Error("Pseudo-selector ".concat(name_2, " cannot be quoted"));
                }
                data2 = [];
                selectorIndex = parseSelector(data2, selector, selectorIndex + 1);
                if (selector.charCodeAt(selectorIndex) !== 41) {
                  throw new Error("Missing closing parenthesis in :".concat(name_2, " (").concat(selector, ")"));
                }
                selectorIndex += 1;
              } else {
                data2 = readValueWithParenthesis();
                if (stripQuotesFromPseudos.has(name_2)) {
                  var quot = data2.charCodeAt(0);
                  if (quot === data2.charCodeAt(data2.length - 1) && isQuote(quot)) {
                    data2 = data2.slice(1, -1);
                  }
                }
                data2 = unescapeCSS(data2);
              }
            }
            tokens.push({ type: types_1.SelectorType.Pseudo, name: name_2, data: data2 });
            break;
          }
          case 44: {
            finalizeSubselector();
            tokens = [];
            stripWhitespace(1);
            break;
          }
          default: {
            if (selector.startsWith("/*", selectorIndex)) {
              var endIndex = selector.indexOf("*/", selectorIndex + 2);
              if (endIndex < 0) {
                throw new Error("Comment was not terminated");
              }
              selectorIndex = endIndex + 2;
              if (tokens.length === 0) {
                stripWhitespace(0);
              }
              break;
            }
            var namespace = null;
            var name_3 = undefined;
            if (firstChar === 42) {
              selectorIndex += 1;
              name_3 = "*";
            } else if (firstChar === 124) {
              name_3 = "";
              if (selector.charCodeAt(selectorIndex + 1) === 124) {
                addTraversal(types_1.SelectorType.ColumnCombinator);
                stripWhitespace(2);
                break;
              }
            } else if (reName.test(selector.slice(selectorIndex))) {
              name_3 = getName(0);
            } else {
              break loop;
            }
            if (selector.charCodeAt(selectorIndex) === 124 && selector.charCodeAt(selectorIndex + 1) !== 124) {
              namespace = name_3;
              if (selector.charCodeAt(selectorIndex + 1) === 42) {
                name_3 = "*";
                selectorIndex += 2;
              } else {
                name_3 = getName(1);
              }
            }
            tokens.push(name_3 === "*" ? { type: types_1.SelectorType.Universal, namespace } : { type: types_1.SelectorType.Tag, name: name_3, namespace });
          }
        }
      }
    finalizeSubselector();
    return selectorIndex;
  }
});

// node_modules/css-what/lib/commonjs/stringify.js
var require_stringify3 = __commonJS((exports) => {
  var __spreadArray = exports && exports.__spreadArray || function(to, from2, pack) {
    if (pack || arguments.length === 2)
      for (var i = 0, l = from2.length, ar;i < l; i++) {
        if (ar || !(i in from2)) {
          if (!ar)
            ar = Array.prototype.slice.call(from2, 0, i);
          ar[i] = from2[i];
        }
      }
    return to.concat(ar || Array.prototype.slice.call(from2));
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.stringify = undefined;
  var types_1 = require_types();
  var attribValChars = ["\\", '"'];
  var pseudoValChars = __spreadArray(__spreadArray([], attribValChars, true), ["(", ")"], false);
  var charsToEscapeInAttributeValue = new Set(attribValChars.map(function(c) {
    return c.charCodeAt(0);
  }));
  var charsToEscapeInPseudoValue = new Set(pseudoValChars.map(function(c) {
    return c.charCodeAt(0);
  }));
  var charsToEscapeInName = new Set(__spreadArray(__spreadArray([], pseudoValChars, true), [
    "~",
    "^",
    "$",
    "*",
    "+",
    "!",
    "|",
    ":",
    "[",
    "]",
    " ",
    "."
  ], false).map(function(c) {
    return c.charCodeAt(0);
  }));
  function stringify(selector) {
    return selector.map(function(token) {
      return token.map(stringifyToken).join("");
    }).join(", ");
  }
  exports.stringify = stringify;
  function stringifyToken(token, index, arr) {
    switch (token.type) {
      case types_1.SelectorType.Child:
        return index === 0 ? "> " : " > ";
      case types_1.SelectorType.Parent:
        return index === 0 ? "< " : " < ";
      case types_1.SelectorType.Sibling:
        return index === 0 ? "~ " : " ~ ";
      case types_1.SelectorType.Adjacent:
        return index === 0 ? "+ " : " + ";
      case types_1.SelectorType.Descendant:
        return " ";
      case types_1.SelectorType.ColumnCombinator:
        return index === 0 ? "|| " : " || ";
      case types_1.SelectorType.Universal:
        return token.namespace === "*" && index + 1 < arr.length && "name" in arr[index + 1] ? "" : "".concat(getNamespace(token.namespace), "*");
      case types_1.SelectorType.Tag:
        return getNamespacedName(token);
      case types_1.SelectorType.PseudoElement:
        return "::".concat(escapeName(token.name, charsToEscapeInName)).concat(token.data === null ? "" : "(".concat(escapeName(token.data, charsToEscapeInPseudoValue), ")"));
      case types_1.SelectorType.Pseudo:
        return ":".concat(escapeName(token.name, charsToEscapeInName)).concat(token.data === null ? "" : "(".concat(typeof token.data === "string" ? escapeName(token.data, charsToEscapeInPseudoValue) : stringify(token.data), ")"));
      case types_1.SelectorType.Attribute: {
        if (token.name === "id" && token.action === types_1.AttributeAction.Equals && token.ignoreCase === "quirks" && !token.namespace) {
          return "#".concat(escapeName(token.value, charsToEscapeInName));
        }
        if (token.name === "class" && token.action === types_1.AttributeAction.Element && token.ignoreCase === "quirks" && !token.namespace) {
          return ".".concat(escapeName(token.value, charsToEscapeInName));
        }
        var name_1 = getNamespacedName(token);
        if (token.action === types_1.AttributeAction.Exists) {
          return "[".concat(name_1, "]");
        }
        return "[".concat(name_1).concat(getActionValue(token.action), '="').concat(escapeName(token.value, charsToEscapeInAttributeValue), '"').concat(token.ignoreCase === null ? "" : token.ignoreCase ? " i" : " s", "]");
      }
    }
  }
  function getActionValue(action) {
    switch (action) {
      case types_1.AttributeAction.Equals:
        return "";
      case types_1.AttributeAction.Element:
        return "~";
      case types_1.AttributeAction.Start:
        return "^";
      case types_1.AttributeAction.End:
        return "$";
      case types_1.AttributeAction.Any:
        return "*";
      case types_1.AttributeAction.Not:
        return "!";
      case types_1.AttributeAction.Hyphen:
        return "|";
      case types_1.AttributeAction.Exists:
        throw new Error("Shouldn't be here");
    }
  }
  function getNamespacedName(token) {
    return "".concat(getNamespace(token.namespace)).concat(escapeName(token.name, charsToEscapeInName));
  }
  function getNamespace(namespace) {
    return namespace !== null ? "".concat(namespace === "*" ? "*" : escapeName(namespace, charsToEscapeInName), "|") : "";
  }
  function escapeName(str, charsToEscape) {
    var lastIdx = 0;
    var ret = "";
    for (var i = 0;i < str.length; i++) {
      if (charsToEscape.has(str.charCodeAt(i))) {
        ret += "".concat(str.slice(lastIdx, i), "\\").concat(str.charAt(i));
        lastIdx = i + 1;
      }
    }
    return ret.length > 0 ? ret + str.slice(lastIdx) : str;
  }
});

// node_modules/css-what/lib/commonjs/index.js
var require_commonjs = __commonJS((exports) => {
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() {
        return m[k];
      } };
    }
    Object.defineProperty(o, k2, desc);
  } : function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    o[k2] = m[k];
  });
  var __exportStar = exports && exports.__exportStar || function(m, exports2) {
    for (var p in m)
      if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
        __createBinding(exports2, m, p);
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.stringify = exports.parse = exports.isTraversal = undefined;
  __exportStar(require_types(), exports);
  var parse_1 = require_parse();
  Object.defineProperty(exports, "isTraversal", { enumerable: true, get: function() {
    return parse_1.isTraversal;
  } });
  Object.defineProperty(exports, "parse", { enumerable: true, get: function() {
    return parse_1.parse;
  } });
  var stringify_1 = require_stringify3();
  Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
    return stringify_1.stringify;
  } });
});

// node_modules/css-select/lib/sort.js
var require_sort = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.isTraversal = undefined;
  var css_what_1 = require_commonjs();
  var procedure = new Map([
    [css_what_1.SelectorType.Universal, 50],
    [css_what_1.SelectorType.Tag, 30],
    [css_what_1.SelectorType.Attribute, 1],
    [css_what_1.SelectorType.Pseudo, 0]
  ]);
  function isTraversal(token) {
    return !procedure.has(token.type);
  }
  exports.isTraversal = isTraversal;
  var attributes = new Map([
    [css_what_1.AttributeAction.Exists, 10],
    [css_what_1.AttributeAction.Equals, 8],
    [css_what_1.AttributeAction.Not, 7],
    [css_what_1.AttributeAction.Start, 6],
    [css_what_1.AttributeAction.End, 6],
    [css_what_1.AttributeAction.Any, 5]
  ]);
  function sortByProcedure(arr) {
    var procs = arr.map(getProcedure);
    for (var i = 1;i < arr.length; i++) {
      var procNew = procs[i];
      if (procNew < 0)
        continue;
      for (var j = i - 1;j >= 0 && procNew < procs[j]; j--) {
        var token = arr[j + 1];
        arr[j + 1] = arr[j];
        arr[j] = token;
        procs[j + 1] = procs[j];
        procs[j] = procNew;
      }
    }
  }
  exports.default = sortByProcedure;
  function getProcedure(token) {
    var _a2, _b;
    var proc = (_a2 = procedure.get(token.type)) !== null && _a2 !== undefined ? _a2 : -1;
    if (token.type === css_what_1.SelectorType.Attribute) {
      proc = (_b = attributes.get(token.action)) !== null && _b !== undefined ? _b : 4;
      if (token.action === css_what_1.AttributeAction.Equals && token.name === "id") {
        proc = 9;
      }
      if (token.ignoreCase) {
        proc >>= 1;
      }
    } else if (token.type === css_what_1.SelectorType.Pseudo) {
      if (!token.data) {
        proc = 3;
      } else if (token.name === "has" || token.name === "contains") {
        proc = 0;
      } else if (Array.isArray(token.data)) {
        proc = Math.min.apply(Math, token.data.map(function(d) {
          return Math.min.apply(Math, d.map(getProcedure));
        }));
        if (proc < 0) {
          proc = 0;
        }
      } else {
        proc = 2;
      }
    }
    return proc;
  }
});

// node_modules/css-select/lib/attributes.js
var require_attributes = __commonJS((exports) => {
  var __importDefault = exports && exports.__importDefault || function(mod2) {
    return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.attributeRules = undefined;
  var boolbase_1 = __importDefault(require_boolbase());
  var reChars = /[-[\]{}()*+?.,\\^$|#\s]/g;
  function escapeRegex2(value2) {
    return value2.replace(reChars, "\\$&");
  }
  var caseInsensitiveAttributes = new Set([
    "accept",
    "accept-charset",
    "align",
    "alink",
    "axis",
    "bgcolor",
    "charset",
    "checked",
    "clear",
    "codetype",
    "color",
    "compact",
    "declare",
    "defer",
    "dir",
    "direction",
    "disabled",
    "enctype",
    "face",
    "frame",
    "hreflang",
    "http-equiv",
    "lang",
    "language",
    "link",
    "media",
    "method",
    "multiple",
    "nohref",
    "noresize",
    "noshade",
    "nowrap",
    "readonly",
    "rel",
    "rev",
    "rules",
    "scope",
    "scrolling",
    "selected",
    "shape",
    "target",
    "text",
    "type",
    "valign",
    "valuetype",
    "vlink"
  ]);
  function shouldIgnoreCase(selector, options) {
    return typeof selector.ignoreCase === "boolean" ? selector.ignoreCase : selector.ignoreCase === "quirks" ? !!options.quirksMode : !options.xmlMode && caseInsensitiveAttributes.has(selector.name);
  }
  exports.attributeRules = {
    equals: function(next2, data2, options) {
      var adapter = options.adapter;
      var name2 = data2.name;
      var value2 = data2.value;
      if (shouldIgnoreCase(data2, options)) {
        value2 = value2.toLowerCase();
        return function(elem) {
          var attr = adapter.getAttributeValue(elem, name2);
          return attr != null && attr.length === value2.length && attr.toLowerCase() === value2 && next2(elem);
        };
      }
      return function(elem) {
        return adapter.getAttributeValue(elem, name2) === value2 && next2(elem);
      };
    },
    hyphen: function(next2, data2, options) {
      var adapter = options.adapter;
      var name2 = data2.name;
      var value2 = data2.value;
      var len = value2.length;
      if (shouldIgnoreCase(data2, options)) {
        value2 = value2.toLowerCase();
        return function hyphenIC(elem) {
          var attr = adapter.getAttributeValue(elem, name2);
          return attr != null && (attr.length === len || attr.charAt(len) === "-") && attr.substr(0, len).toLowerCase() === value2 && next2(elem);
        };
      }
      return function hyphen(elem) {
        var attr = adapter.getAttributeValue(elem, name2);
        return attr != null && (attr.length === len || attr.charAt(len) === "-") && attr.substr(0, len) === value2 && next2(elem);
      };
    },
    element: function(next2, data2, options) {
      var adapter = options.adapter;
      var { name: name2, value: value2 } = data2;
      if (/\s/.test(value2)) {
        return boolbase_1.default.falseFunc;
      }
      var regex = new RegExp("(?:^|\\s)".concat(escapeRegex2(value2), "(?:$|\\s)"), shouldIgnoreCase(data2, options) ? "i" : "");
      return function element(elem) {
        var attr = adapter.getAttributeValue(elem, name2);
        return attr != null && attr.length >= value2.length && regex.test(attr) && next2(elem);
      };
    },
    exists: function(next2, _a2, _b) {
      var name2 = _a2.name;
      var adapter = _b.adapter;
      return function(elem) {
        return adapter.hasAttrib(elem, name2) && next2(elem);
      };
    },
    start: function(next2, data2, options) {
      var adapter = options.adapter;
      var name2 = data2.name;
      var value2 = data2.value;
      var len = value2.length;
      if (len === 0) {
        return boolbase_1.default.falseFunc;
      }
      if (shouldIgnoreCase(data2, options)) {
        value2 = value2.toLowerCase();
        return function(elem) {
          var attr = adapter.getAttributeValue(elem, name2);
          return attr != null && attr.length >= len && attr.substr(0, len).toLowerCase() === value2 && next2(elem);
        };
      }
      return function(elem) {
        var _a2;
        return !!((_a2 = adapter.getAttributeValue(elem, name2)) === null || _a2 === undefined ? undefined : _a2.startsWith(value2)) && next2(elem);
      };
    },
    end: function(next2, data2, options) {
      var adapter = options.adapter;
      var name2 = data2.name;
      var value2 = data2.value;
      var len = -value2.length;
      if (len === 0) {
        return boolbase_1.default.falseFunc;
      }
      if (shouldIgnoreCase(data2, options)) {
        value2 = value2.toLowerCase();
        return function(elem) {
          var _a2;
          return ((_a2 = adapter.getAttributeValue(elem, name2)) === null || _a2 === undefined ? undefined : _a2.substr(len).toLowerCase()) === value2 && next2(elem);
        };
      }
      return function(elem) {
        var _a2;
        return !!((_a2 = adapter.getAttributeValue(elem, name2)) === null || _a2 === undefined ? undefined : _a2.endsWith(value2)) && next2(elem);
      };
    },
    any: function(next2, data2, options) {
      var adapter = options.adapter;
      var { name: name2, value: value2 } = data2;
      if (value2 === "") {
        return boolbase_1.default.falseFunc;
      }
      if (shouldIgnoreCase(data2, options)) {
        var regex_1 = new RegExp(escapeRegex2(value2), "i");
        return function anyIC(elem) {
          var attr = adapter.getAttributeValue(elem, name2);
          return attr != null && attr.length >= value2.length && regex_1.test(attr) && next2(elem);
        };
      }
      return function(elem) {
        var _a2;
        return !!((_a2 = adapter.getAttributeValue(elem, name2)) === null || _a2 === undefined ? undefined : _a2.includes(value2)) && next2(elem);
      };
    },
    not: function(next2, data2, options) {
      var adapter = options.adapter;
      var name2 = data2.name;
      var value2 = data2.value;
      if (value2 === "") {
        return function(elem) {
          return !!adapter.getAttributeValue(elem, name2) && next2(elem);
        };
      } else if (shouldIgnoreCase(data2, options)) {
        value2 = value2.toLowerCase();
        return function(elem) {
          var attr = adapter.getAttributeValue(elem, name2);
          return (attr == null || attr.length !== value2.length || attr.toLowerCase() !== value2) && next2(elem);
        };
      }
      return function(elem) {
        return adapter.getAttributeValue(elem, name2) !== value2 && next2(elem);
      };
    }
  };
});

// node_modules/nth-check/lib/parse.js
var require_parse2 = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.parse = undefined;
  var whitespace = new Set([9, 10, 12, 13, 32]);
  var ZERO = 48;
  var NINE = 57;
  function parse6(formula) {
    formula = formula.trim().toLowerCase();
    if (formula === "even") {
      return [2, 0];
    } else if (formula === "odd") {
      return [2, 1];
    }
    var idx = 0;
    var a = 0;
    var sign3 = readSign();
    var number6 = readNumber2();
    if (idx < formula.length && formula.charAt(idx) === "n") {
      idx++;
      a = sign3 * (number6 !== null && number6 !== undefined ? number6 : 1);
      skipWhitespace();
      if (idx < formula.length) {
        sign3 = readSign();
        skipWhitespace();
        number6 = readNumber2();
      } else {
        sign3 = number6 = 0;
      }
    }
    if (number6 === null || idx < formula.length) {
      throw new Error("n-th rule couldn't be parsed ('".concat(formula, "')"));
    }
    return [a, sign3 * number6];
    function readSign() {
      if (formula.charAt(idx) === "-") {
        idx++;
        return -1;
      }
      if (formula.charAt(idx) === "+") {
        idx++;
      }
      return 1;
    }
    function readNumber2() {
      var start = idx;
      var value2 = 0;
      while (idx < formula.length && formula.charCodeAt(idx) >= ZERO && formula.charCodeAt(idx) <= NINE) {
        value2 = value2 * 10 + (formula.charCodeAt(idx) - ZERO);
        idx++;
      }
      return idx === start ? null : value2;
    }
    function skipWhitespace() {
      while (idx < formula.length && whitespace.has(formula.charCodeAt(idx))) {
        idx++;
      }
    }
  }
  exports.parse = parse6;
});

// node_modules/nth-check/lib/compile.js
var require_compile = __commonJS((exports) => {
  var __importDefault = exports && exports.__importDefault || function(mod2) {
    return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.generate = exports.compile = undefined;
  var boolbase_1 = __importDefault(require_boolbase());
  function compile(parsed) {
    var a = parsed[0];
    var b = parsed[1] - 1;
    if (b < 0 && a <= 0)
      return boolbase_1.default.falseFunc;
    if (a === -1)
      return function(index) {
        return index <= b;
      };
    if (a === 0)
      return function(index) {
        return index === b;
      };
    if (a === 1)
      return b < 0 ? boolbase_1.default.trueFunc : function(index) {
        return index >= b;
      };
    var absA = Math.abs(a);
    var bMod = (b % absA + absA) % absA;
    return a > 1 ? function(index) {
      return index >= b && index % absA === bMod;
    } : function(index) {
      return index <= b && index % absA === bMod;
    };
  }
  exports.compile = compile;
  function generate(parsed) {
    var a = parsed[0];
    var b = parsed[1] - 1;
    var n = 0;
    if (a < 0) {
      var aPos_1 = -a;
      var minValue_1 = (b % aPos_1 + aPos_1) % aPos_1;
      return function() {
        var val = minValue_1 + aPos_1 * n++;
        return val > b ? null : val;
      };
    }
    if (a === 0)
      return b < 0 ? function() {
        return null;
      } : function() {
        return n++ === 0 ? b : null;
      };
    if (b < 0) {
      b += a * Math.ceil(-b / a);
    }
    return function() {
      return a * n++ + b;
    };
  }
  exports.generate = generate;
});

// node_modules/nth-check/lib/index.js
var require_lib6 = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.sequence = exports.generate = exports.compile = exports.parse = undefined;
  var parse_js_1 = require_parse2();
  Object.defineProperty(exports, "parse", { enumerable: true, get: function() {
    return parse_js_1.parse;
  } });
  var compile_js_1 = require_compile();
  Object.defineProperty(exports, "compile", { enumerable: true, get: function() {
    return compile_js_1.compile;
  } });
  Object.defineProperty(exports, "generate", { enumerable: true, get: function() {
    return compile_js_1.generate;
  } });
  function nthCheck(formula) {
    return (0, compile_js_1.compile)((0, parse_js_1.parse)(formula));
  }
  exports.default = nthCheck;
  function sequence(formula) {
    return (0, compile_js_1.generate)((0, parse_js_1.parse)(formula));
  }
  exports.sequence = sequence;
});

// node_modules/css-select/lib/pseudo-selectors/filters.js
var require_filters = __commonJS((exports) => {
  var __importDefault = exports && exports.__importDefault || function(mod2) {
    return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.filters = undefined;
  var nth_check_1 = __importDefault(require_lib6());
  var boolbase_1 = __importDefault(require_boolbase());
  function getChildFunc(next2, adapter) {
    return function(elem) {
      var parent = adapter.getParent(elem);
      return parent != null && adapter.isTag(parent) && next2(elem);
    };
  }
  exports.filters = {
    contains: function(next2, text3, _a2) {
      var adapter = _a2.adapter;
      return function contains(elem) {
        return next2(elem) && adapter.getText(elem).includes(text3);
      };
    },
    icontains: function(next2, text3, _a2) {
      var adapter = _a2.adapter;
      var itext = text3.toLowerCase();
      return function icontains(elem) {
        return next2(elem) && adapter.getText(elem).toLowerCase().includes(itext);
      };
    },
    "nth-child": function(next2, rule2, _a2) {
      var { adapter, equals: equals2 } = _a2;
      var func = (0, nth_check_1.default)(rule2);
      if (func === boolbase_1.default.falseFunc)
        return boolbase_1.default.falseFunc;
      if (func === boolbase_1.default.trueFunc)
        return getChildFunc(next2, adapter);
      return function nthChild(elem) {
        var siblings = adapter.getSiblings(elem);
        var pos = 0;
        for (var i = 0;i < siblings.length; i++) {
          if (equals2(elem, siblings[i]))
            break;
          if (adapter.isTag(siblings[i])) {
            pos++;
          }
        }
        return func(pos) && next2(elem);
      };
    },
    "nth-last-child": function(next2, rule2, _a2) {
      var { adapter, equals: equals2 } = _a2;
      var func = (0, nth_check_1.default)(rule2);
      if (func === boolbase_1.default.falseFunc)
        return boolbase_1.default.falseFunc;
      if (func === boolbase_1.default.trueFunc)
        return getChildFunc(next2, adapter);
      return function nthLastChild(elem) {
        var siblings = adapter.getSiblings(elem);
        var pos = 0;
        for (var i = siblings.length - 1;i >= 0; i--) {
          if (equals2(elem, siblings[i]))
            break;
          if (adapter.isTag(siblings[i])) {
            pos++;
          }
        }
        return func(pos) && next2(elem);
      };
    },
    "nth-of-type": function(next2, rule2, _a2) {
      var { adapter, equals: equals2 } = _a2;
      var func = (0, nth_check_1.default)(rule2);
      if (func === boolbase_1.default.falseFunc)
        return boolbase_1.default.falseFunc;
      if (func === boolbase_1.default.trueFunc)
        return getChildFunc(next2, adapter);
      return function nthOfType(elem) {
        var siblings = adapter.getSiblings(elem);
        var pos = 0;
        for (var i = 0;i < siblings.length; i++) {
          var currentSibling = siblings[i];
          if (equals2(elem, currentSibling))
            break;
          if (adapter.isTag(currentSibling) && adapter.getName(currentSibling) === adapter.getName(elem)) {
            pos++;
          }
        }
        return func(pos) && next2(elem);
      };
    },
    "nth-last-of-type": function(next2, rule2, _a2) {
      var { adapter, equals: equals2 } = _a2;
      var func = (0, nth_check_1.default)(rule2);
      if (func === boolbase_1.default.falseFunc)
        return boolbase_1.default.falseFunc;
      if (func === boolbase_1.default.trueFunc)
        return getChildFunc(next2, adapter);
      return function nthLastOfType(elem) {
        var siblings = adapter.getSiblings(elem);
        var pos = 0;
        for (var i = siblings.length - 1;i >= 0; i--) {
          var currentSibling = siblings[i];
          if (equals2(elem, currentSibling))
            break;
          if (adapter.isTag(currentSibling) && adapter.getName(currentSibling) === adapter.getName(elem)) {
            pos++;
          }
        }
        return func(pos) && next2(elem);
      };
    },
    root: function(next2, _rule, _a2) {
      var adapter = _a2.adapter;
      return function(elem) {
        var parent = adapter.getParent(elem);
        return (parent == null || !adapter.isTag(parent)) && next2(elem);
      };
    },
    scope: function(next2, rule2, options, context) {
      var equals2 = options.equals;
      if (!context || context.length === 0) {
        return exports.filters["root"](next2, rule2, options);
      }
      if (context.length === 1) {
        return function(elem) {
          return equals2(context[0], elem) && next2(elem);
        };
      }
      return function(elem) {
        return context.includes(elem) && next2(elem);
      };
    },
    hover: dynamicStatePseudo("isHovered"),
    visited: dynamicStatePseudo("isVisited"),
    active: dynamicStatePseudo("isActive")
  };
  function dynamicStatePseudo(name2) {
    return function dynamicPseudo(next2, _rule, _a2) {
      var adapter = _a2.adapter;
      var func = adapter[name2];
      if (typeof func !== "function") {
        return boolbase_1.default.falseFunc;
      }
      return function active(elem) {
        return func(elem) && next2(elem);
      };
    };
  }
});

// node_modules/css-select/lib/pseudo-selectors/pseudos.js
var require_pseudos = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.verifyPseudoArgs = exports.pseudos = undefined;
  exports.pseudos = {
    empty: function(elem, _a2) {
      var adapter = _a2.adapter;
      return !adapter.getChildren(elem).some(function(elem2) {
        return adapter.isTag(elem2) || adapter.getText(elem2) !== "";
      });
    },
    "first-child": function(elem, _a2) {
      var { adapter, equals: equals2 } = _a2;
      if (adapter.prevElementSibling) {
        return adapter.prevElementSibling(elem) == null;
      }
      var firstChild = adapter.getSiblings(elem).find(function(elem2) {
        return adapter.isTag(elem2);
      });
      return firstChild != null && equals2(elem, firstChild);
    },
    "last-child": function(elem, _a2) {
      var { adapter, equals: equals2 } = _a2;
      var siblings = adapter.getSiblings(elem);
      for (var i = siblings.length - 1;i >= 0; i--) {
        if (equals2(elem, siblings[i]))
          return true;
        if (adapter.isTag(siblings[i]))
          break;
      }
      return false;
    },
    "first-of-type": function(elem, _a2) {
      var { adapter, equals: equals2 } = _a2;
      var siblings = adapter.getSiblings(elem);
      var elemName = adapter.getName(elem);
      for (var i = 0;i < siblings.length; i++) {
        var currentSibling = siblings[i];
        if (equals2(elem, currentSibling))
          return true;
        if (adapter.isTag(currentSibling) && adapter.getName(currentSibling) === elemName) {
          break;
        }
      }
      return false;
    },
    "last-of-type": function(elem, _a2) {
      var { adapter, equals: equals2 } = _a2;
      var siblings = adapter.getSiblings(elem);
      var elemName = adapter.getName(elem);
      for (var i = siblings.length - 1;i >= 0; i--) {
        var currentSibling = siblings[i];
        if (equals2(elem, currentSibling))
          return true;
        if (adapter.isTag(currentSibling) && adapter.getName(currentSibling) === elemName) {
          break;
        }
      }
      return false;
    },
    "only-of-type": function(elem, _a2) {
      var { adapter, equals: equals2 } = _a2;
      var elemName = adapter.getName(elem);
      return adapter.getSiblings(elem).every(function(sibling) {
        return equals2(elem, sibling) || !adapter.isTag(sibling) || adapter.getName(sibling) !== elemName;
      });
    },
    "only-child": function(elem, _a2) {
      var { adapter, equals: equals2 } = _a2;
      return adapter.getSiblings(elem).every(function(sibling) {
        return equals2(elem, sibling) || !adapter.isTag(sibling);
      });
    }
  };
  function verifyPseudoArgs(func, name2, subselect, argIndex) {
    if (subselect === null) {
      if (func.length > argIndex) {
        throw new Error("Pseudo-class :".concat(name2, " requires an argument"));
      }
    } else if (func.length === argIndex) {
      throw new Error("Pseudo-class :".concat(name2, " doesn't have any arguments"));
    }
  }
  exports.verifyPseudoArgs = verifyPseudoArgs;
});

// node_modules/css-select/lib/pseudo-selectors/aliases.js
var require_aliases = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.aliases = undefined;
  exports.aliases = {
    "any-link": ":is(a, area, link)[href]",
    link: ":any-link:not(:visited)",
    disabled: `:is(
        :is(button, input, select, textarea, optgroup, option)[disabled],
        optgroup[disabled] > option,
        fieldset[disabled]:not(fieldset[disabled] legend:first-of-type *)
    )`,
    enabled: ":not(:disabled)",
    checked: ":is(:is(input[type=radio], input[type=checkbox])[checked], option:selected)",
    required: ":is(input, select, textarea)[required]",
    optional: ":is(input, select, textarea):not([required])",
    selected: "option:is([selected], select:not([multiple]):not(:has(> option[selected])) > :first-of-type)",
    checkbox: "[type=checkbox]",
    file: "[type=file]",
    password: "[type=password]",
    radio: "[type=radio]",
    reset: "[type=reset]",
    image: "[type=image]",
    submit: "[type=submit]",
    parent: ":not(:empty)",
    header: ":is(h1, h2, h3, h4, h5, h6)",
    button: ":is(button, input[type=button])",
    input: ":is(input, textarea, select, button)",
    text: "input:is(:not([type!='']), [type=text])"
  };
});

// node_modules/css-select/lib/pseudo-selectors/subselects.js
var require_subselects = __commonJS((exports) => {
  var __spreadArray = exports && exports.__spreadArray || function(to, from2, pack) {
    if (pack || arguments.length === 2)
      for (var i = 0, l = from2.length, ar;i < l; i++) {
        if (ar || !(i in from2)) {
          if (!ar)
            ar = Array.prototype.slice.call(from2, 0, i);
          ar[i] = from2[i];
        }
      }
    return to.concat(ar || Array.prototype.slice.call(from2));
  };
  var __importDefault = exports && exports.__importDefault || function(mod2) {
    return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.subselects = exports.getNextSiblings = exports.ensureIsTag = exports.PLACEHOLDER_ELEMENT = undefined;
  var boolbase_1 = __importDefault(require_boolbase());
  var sort_js_1 = require_sort();
  exports.PLACEHOLDER_ELEMENT = {};
  function ensureIsTag(next2, adapter) {
    if (next2 === boolbase_1.default.falseFunc)
      return boolbase_1.default.falseFunc;
    return function(elem) {
      return adapter.isTag(elem) && next2(elem);
    };
  }
  exports.ensureIsTag = ensureIsTag;
  function getNextSiblings(elem, adapter) {
    var siblings = adapter.getSiblings(elem);
    if (siblings.length <= 1)
      return [];
    var elemIndex = siblings.indexOf(elem);
    if (elemIndex < 0 || elemIndex === siblings.length - 1)
      return [];
    return siblings.slice(elemIndex + 1).filter(adapter.isTag);
  }
  exports.getNextSiblings = getNextSiblings;
  function copyOptions(options) {
    return {
      xmlMode: !!options.xmlMode,
      lowerCaseAttributeNames: !!options.lowerCaseAttributeNames,
      lowerCaseTags: !!options.lowerCaseTags,
      quirksMode: !!options.quirksMode,
      cacheResults: !!options.cacheResults,
      pseudos: options.pseudos,
      adapter: options.adapter,
      equals: options.equals
    };
  }
  var is = function(next2, token, options, context, compileToken) {
    var func = compileToken(token, copyOptions(options), context);
    return func === boolbase_1.default.trueFunc ? next2 : func === boolbase_1.default.falseFunc ? boolbase_1.default.falseFunc : function(elem) {
      return func(elem) && next2(elem);
    };
  };
  exports.subselects = {
    is,
    matches: is,
    where: is,
    not: function(next2, token, options, context, compileToken) {
      var func = compileToken(token, copyOptions(options), context);
      return func === boolbase_1.default.falseFunc ? next2 : func === boolbase_1.default.trueFunc ? boolbase_1.default.falseFunc : function(elem) {
        return !func(elem) && next2(elem);
      };
    },
    has: function(next2, subselect, options, _context, compileToken) {
      var adapter = options.adapter;
      var opts = copyOptions(options);
      opts.relativeSelector = true;
      var context = subselect.some(function(s) {
        return s.some(sort_js_1.isTraversal);
      }) ? [exports.PLACEHOLDER_ELEMENT] : undefined;
      var compiled = compileToken(subselect, opts, context);
      if (compiled === boolbase_1.default.falseFunc)
        return boolbase_1.default.falseFunc;
      var hasElement = ensureIsTag(compiled, adapter);
      if (context && compiled !== boolbase_1.default.trueFunc) {
        var _a2 = compiled.shouldTestNextSiblings, shouldTestNextSiblings_1 = _a2 === undefined ? false : _a2;
        return function(elem) {
          if (!next2(elem))
            return false;
          context[0] = elem;
          var childs = adapter.getChildren(elem);
          var nextElements = shouldTestNextSiblings_1 ? __spreadArray(__spreadArray([], childs, true), getNextSiblings(elem, adapter), true) : childs;
          return adapter.existsOne(hasElement, nextElements);
        };
      }
      return function(elem) {
        return next2(elem) && adapter.existsOne(hasElement, adapter.getChildren(elem));
      };
    }
  };
});

// node_modules/css-select/lib/pseudo-selectors/index.js
var require_pseudo_selectors = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.compilePseudoSelector = exports.aliases = exports.pseudos = exports.filters = undefined;
  var css_what_1 = require_commonjs();
  var filters_js_1 = require_filters();
  Object.defineProperty(exports, "filters", { enumerable: true, get: function() {
    return filters_js_1.filters;
  } });
  var pseudos_js_1 = require_pseudos();
  Object.defineProperty(exports, "pseudos", { enumerable: true, get: function() {
    return pseudos_js_1.pseudos;
  } });
  var aliases_js_1 = require_aliases();
  Object.defineProperty(exports, "aliases", { enumerable: true, get: function() {
    return aliases_js_1.aliases;
  } });
  var subselects_js_1 = require_subselects();
  function compilePseudoSelector(next2, selector, options, context, compileToken) {
    var _a2;
    var { name: name2, data: data2 } = selector;
    if (Array.isArray(data2)) {
      if (!(name2 in subselects_js_1.subselects)) {
        throw new Error("Unknown pseudo-class :".concat(name2, "(").concat(data2, ")"));
      }
      return subselects_js_1.subselects[name2](next2, data2, options, context, compileToken);
    }
    var userPseudo = (_a2 = options.pseudos) === null || _a2 === undefined ? undefined : _a2[name2];
    var stringPseudo = typeof userPseudo === "string" ? userPseudo : aliases_js_1.aliases[name2];
    if (typeof stringPseudo === "string") {
      if (data2 != null) {
        throw new Error("Pseudo ".concat(name2, " doesn't have any arguments"));
      }
      var alias = (0, css_what_1.parse)(stringPseudo);
      return subselects_js_1.subselects["is"](next2, alias, options, context, compileToken);
    }
    if (typeof userPseudo === "function") {
      (0, pseudos_js_1.verifyPseudoArgs)(userPseudo, name2, data2, 1);
      return function(elem) {
        return userPseudo(elem, data2) && next2(elem);
      };
    }
    if (name2 in filters_js_1.filters) {
      return filters_js_1.filters[name2](next2, data2, options, context);
    }
    if (name2 in pseudos_js_1.pseudos) {
      var pseudo_1 = pseudos_js_1.pseudos[name2];
      (0, pseudos_js_1.verifyPseudoArgs)(pseudo_1, name2, data2, 2);
      return function(elem) {
        return pseudo_1(elem, options, data2) && next2(elem);
      };
    }
    throw new Error("Unknown pseudo-class :".concat(name2));
  }
  exports.compilePseudoSelector = compilePseudoSelector;
});

// node_modules/css-select/lib/general.js
var require_general = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.compileGeneralSelector = undefined;
  var attributes_js_1 = require_attributes();
  var index_js_1 = require_pseudo_selectors();
  var css_what_1 = require_commonjs();
  function getElementParent(node, adapter) {
    var parent = adapter.getParent(node);
    if (parent && adapter.isTag(parent)) {
      return parent;
    }
    return null;
  }
  function compileGeneralSelector(next2, selector, options, context, compileToken) {
    var { adapter, equals: equals2 } = options;
    switch (selector.type) {
      case css_what_1.SelectorType.PseudoElement: {
        throw new Error("Pseudo-elements are not supported by css-select");
      }
      case css_what_1.SelectorType.ColumnCombinator: {
        throw new Error("Column combinators are not yet supported by css-select");
      }
      case css_what_1.SelectorType.Attribute: {
        if (selector.namespace != null) {
          throw new Error("Namespaced attributes are not yet supported by css-select");
        }
        if (!options.xmlMode || options.lowerCaseAttributeNames) {
          selector.name = selector.name.toLowerCase();
        }
        return attributes_js_1.attributeRules[selector.action](next2, selector, options);
      }
      case css_what_1.SelectorType.Pseudo: {
        return (0, index_js_1.compilePseudoSelector)(next2, selector, options, context, compileToken);
      }
      case css_what_1.SelectorType.Tag: {
        if (selector.namespace != null) {
          throw new Error("Namespaced tag names are not yet supported by css-select");
        }
        var name_1 = selector.name;
        if (!options.xmlMode || options.lowerCaseTags) {
          name_1 = name_1.toLowerCase();
        }
        return function tag(elem) {
          return adapter.getName(elem) === name_1 && next2(elem);
        };
      }
      case css_what_1.SelectorType.Descendant: {
        if (options.cacheResults === false || typeof WeakSet === "undefined") {
          return function descendant(elem) {
            var current = elem;
            while (current = getElementParent(current, adapter)) {
              if (next2(current)) {
                return true;
              }
            }
            return false;
          };
        }
        var isFalseCache_1 = new WeakSet;
        return function cachedDescendant(elem) {
          var current = elem;
          while (current = getElementParent(current, adapter)) {
            if (!isFalseCache_1.has(current)) {
              if (adapter.isTag(current) && next2(current)) {
                return true;
              }
              isFalseCache_1.add(current);
            }
          }
          return false;
        };
      }
      case "_flexibleDescendant": {
        return function flexibleDescendant(elem) {
          var current = elem;
          do {
            if (next2(current))
              return true;
          } while (current = getElementParent(current, adapter));
          return false;
        };
      }
      case css_what_1.SelectorType.Parent: {
        return function parent(elem) {
          return adapter.getChildren(elem).some(function(elem2) {
            return adapter.isTag(elem2) && next2(elem2);
          });
        };
      }
      case css_what_1.SelectorType.Child: {
        return function child(elem) {
          var parent = adapter.getParent(elem);
          return parent != null && adapter.isTag(parent) && next2(parent);
        };
      }
      case css_what_1.SelectorType.Sibling: {
        return function sibling(elem) {
          var siblings = adapter.getSiblings(elem);
          for (var i = 0;i < siblings.length; i++) {
            var currentSibling = siblings[i];
            if (equals2(elem, currentSibling))
              break;
            if (adapter.isTag(currentSibling) && next2(currentSibling)) {
              return true;
            }
          }
          return false;
        };
      }
      case css_what_1.SelectorType.Adjacent: {
        if (adapter.prevElementSibling) {
          return function adjacent(elem) {
            var previous2 = adapter.prevElementSibling(elem);
            return previous2 != null && next2(previous2);
          };
        }
        return function adjacent(elem) {
          var siblings = adapter.getSiblings(elem);
          var lastElement;
          for (var i = 0;i < siblings.length; i++) {
            var currentSibling = siblings[i];
            if (equals2(elem, currentSibling))
              break;
            if (adapter.isTag(currentSibling)) {
              lastElement = currentSibling;
            }
          }
          return !!lastElement && next2(lastElement);
        };
      }
      case css_what_1.SelectorType.Universal: {
        if (selector.namespace != null && selector.namespace !== "*") {
          throw new Error("Namespaced universal selectors are not yet supported by css-select");
        }
        return next2;
      }
    }
  }
  exports.compileGeneralSelector = compileGeneralSelector;
});

// node_modules/css-select/lib/compile.js
var require_compile2 = __commonJS((exports) => {
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() {
        return m[k];
      } };
    }
    Object.defineProperty(o, k2, desc);
  } : function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    o[k2] = m[k];
  });
  var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
  } : function(o, v) {
    o["default"] = v;
  });
  var __importStar = exports && exports.__importStar || function(mod2) {
    if (mod2 && mod2.__esModule)
      return mod2;
    var result = {};
    if (mod2 != null) {
      for (var k in mod2)
        if (k !== "default" && Object.prototype.hasOwnProperty.call(mod2, k))
          __createBinding(result, mod2, k);
    }
    __setModuleDefault(result, mod2);
    return result;
  };
  var __importDefault = exports && exports.__importDefault || function(mod2) {
    return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.compileToken = exports.compileUnsafe = exports.compile = undefined;
  var css_what_1 = require_commonjs();
  var boolbase_1 = __importDefault(require_boolbase());
  var sort_js_1 = __importStar(require_sort());
  var general_js_1 = require_general();
  var subselects_js_1 = require_subselects();
  function compile(selector, options, context) {
    var next2 = compileUnsafe(selector, options, context);
    return (0, subselects_js_1.ensureIsTag)(next2, options.adapter);
  }
  exports.compile = compile;
  function compileUnsafe(selector, options, context) {
    var token = typeof selector === "string" ? (0, css_what_1.parse)(selector) : selector;
    return compileToken(token, options, context);
  }
  exports.compileUnsafe = compileUnsafe;
  function includesScopePseudo(t) {
    return t.type === css_what_1.SelectorType.Pseudo && (t.name === "scope" || Array.isArray(t.data) && t.data.some(function(data2) {
      return data2.some(includesScopePseudo);
    }));
  }
  var DESCENDANT_TOKEN = { type: css_what_1.SelectorType.Descendant };
  var FLEXIBLE_DESCENDANT_TOKEN = {
    type: "_flexibleDescendant"
  };
  var SCOPE_TOKEN = {
    type: css_what_1.SelectorType.Pseudo,
    name: "scope",
    data: null
  };
  function absolutize(token, _a2, context) {
    var adapter = _a2.adapter;
    var hasContext = !!(context === null || context === undefined ? undefined : context.every(function(e) {
      var parent = adapter.isTag(e) && adapter.getParent(e);
      return e === subselects_js_1.PLACEHOLDER_ELEMENT || parent && adapter.isTag(parent);
    }));
    for (var _i = 0, token_1 = token;_i < token_1.length; _i++) {
      var t = token_1[_i];
      if (t.length > 0 && (0, sort_js_1.isTraversal)(t[0]) && t[0].type !== css_what_1.SelectorType.Descendant) {} else if (hasContext && !t.some(includesScopePseudo)) {
        t.unshift(DESCENDANT_TOKEN);
      } else {
        continue;
      }
      t.unshift(SCOPE_TOKEN);
    }
  }
  function compileToken(token, options, context) {
    var _a2;
    token.forEach(sort_js_1.default);
    context = (_a2 = options.context) !== null && _a2 !== undefined ? _a2 : context;
    var isArrayContext = Array.isArray(context);
    var finalContext = context && (Array.isArray(context) ? context : [context]);
    if (options.relativeSelector !== false) {
      absolutize(token, options, finalContext);
    } else if (token.some(function(t) {
      return t.length > 0 && (0, sort_js_1.isTraversal)(t[0]);
    })) {
      throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");
    }
    var shouldTestNextSiblings = false;
    var query = token.map(function(rules) {
      if (rules.length >= 2) {
        var first = rules[0], second = rules[1];
        if (first.type !== css_what_1.SelectorType.Pseudo || first.name !== "scope") {} else if (isArrayContext && second.type === css_what_1.SelectorType.Descendant) {
          rules[1] = FLEXIBLE_DESCENDANT_TOKEN;
        } else if (second.type === css_what_1.SelectorType.Adjacent || second.type === css_what_1.SelectorType.Sibling) {
          shouldTestNextSiblings = true;
        }
      }
      return compileRules(rules, options, finalContext);
    }).reduce(reduceRules, boolbase_1.default.falseFunc);
    query.shouldTestNextSiblings = shouldTestNextSiblings;
    return query;
  }
  exports.compileToken = compileToken;
  function compileRules(rules, options, context) {
    var _a2;
    return rules.reduce(function(previous2, rule2) {
      return previous2 === boolbase_1.default.falseFunc ? boolbase_1.default.falseFunc : (0, general_js_1.compileGeneralSelector)(previous2, rule2, options, context, compileToken);
    }, (_a2 = options.rootFunc) !== null && _a2 !== undefined ? _a2 : boolbase_1.default.trueFunc);
  }
  function reduceRules(a, b) {
    if (b === boolbase_1.default.falseFunc || a === boolbase_1.default.trueFunc) {
      return a;
    }
    if (a === boolbase_1.default.falseFunc || b === boolbase_1.default.trueFunc) {
      return b;
    }
    return function combine(elem) {
      return a(elem) || b(elem);
    };
  }
});

// node_modules/css-select/lib/index.js
var require_lib7 = __commonJS((exports) => {
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() {
        return m[k];
      } };
    }
    Object.defineProperty(o, k2, desc);
  } : function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    o[k2] = m[k];
  });
  var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
  } : function(o, v) {
    o["default"] = v;
  });
  var __importStar = exports && exports.__importStar || function(mod2) {
    if (mod2 && mod2.__esModule)
      return mod2;
    var result = {};
    if (mod2 != null) {
      for (var k in mod2)
        if (k !== "default" && Object.prototype.hasOwnProperty.call(mod2, k))
          __createBinding(result, mod2, k);
    }
    __setModuleDefault(result, mod2);
    return result;
  };
  var __importDefault = exports && exports.__importDefault || function(mod2) {
    return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.aliases = exports.pseudos = exports.filters = exports.is = exports.selectOne = exports.selectAll = exports.prepareContext = exports._compileToken = exports._compileUnsafe = exports.compile = undefined;
  var DomUtils = __importStar(require_lib5());
  var boolbase_1 = __importDefault(require_boolbase());
  var compile_js_1 = require_compile2();
  var subselects_js_1 = require_subselects();
  var defaultEquals = function(a, b) {
    return a === b;
  };
  var defaultOptions = {
    adapter: DomUtils,
    equals: defaultEquals
  };
  function convertOptionFormats(options) {
    var _a2, _b, _c, _d;
    var opts = options !== null && options !== undefined ? options : defaultOptions;
    (_a2 = opts.adapter) !== null && _a2 !== undefined || (opts.adapter = DomUtils);
    (_b = opts.equals) !== null && _b !== undefined || (opts.equals = (_d = (_c = opts.adapter) === null || _c === undefined ? undefined : _c.equals) !== null && _d !== undefined ? _d : defaultEquals);
    return opts;
  }
  function wrapCompile(func) {
    return function addAdapter(selector, options, context) {
      var opts = convertOptionFormats(options);
      return func(selector, opts, context);
    };
  }
  exports.compile = wrapCompile(compile_js_1.compile);
  exports._compileUnsafe = wrapCompile(compile_js_1.compileUnsafe);
  exports._compileToken = wrapCompile(compile_js_1.compileToken);
  function getSelectorFunc(searchFunc) {
    return function select(query, elements, options) {
      var opts = convertOptionFormats(options);
      if (typeof query !== "function") {
        query = (0, compile_js_1.compileUnsafe)(query, opts, elements);
      }
      var filteredElements = prepareContext(elements, opts.adapter, query.shouldTestNextSiblings);
      return searchFunc(query, filteredElements, opts);
    };
  }
  function prepareContext(elems, adapter, shouldTestNextSiblings) {
    if (shouldTestNextSiblings === undefined) {
      shouldTestNextSiblings = false;
    }
    if (shouldTestNextSiblings) {
      elems = appendNextSiblings(elems, adapter);
    }
    return Array.isArray(elems) ? adapter.removeSubsets(elems) : adapter.getChildren(elems);
  }
  exports.prepareContext = prepareContext;
  function appendNextSiblings(elem, adapter) {
    var elems = Array.isArray(elem) ? elem.slice(0) : [elem];
    var elemsLength = elems.length;
    for (var i = 0;i < elemsLength; i++) {
      var nextSiblings = (0, subselects_js_1.getNextSiblings)(elems[i], adapter);
      elems.push.apply(elems, nextSiblings);
    }
    return elems;
  }
  exports.selectAll = getSelectorFunc(function(query, elems, options) {
    return query === boolbase_1.default.falseFunc || !elems || elems.length === 0 ? [] : options.adapter.findAll(query, elems);
  });
  exports.selectOne = getSelectorFunc(function(query, elems, options) {
    return query === boolbase_1.default.falseFunc || !elems || elems.length === 0 ? null : options.adapter.findOne(query, elems);
  });
  function is(elem, query, options) {
    var opts = convertOptionFormats(options);
    return (typeof query === "function" ? query : (0, compile_js_1.compile)(query, opts))(elem);
  }
  exports.is = is;
  exports.default = exports.selectAll;
  var index_js_1 = require_pseudo_selectors();
  Object.defineProperty(exports, "filters", { enumerable: true, get: function() {
    return index_js_1.filters;
  } });
  Object.defineProperty(exports, "pseudos", { enumerable: true, get: function() {
    return index_js_1.pseudos;
  } });
  Object.defineProperty(exports, "aliases", { enumerable: true, get: function() {
    return index_js_1.aliases;
  } });
});

// node_modules/node-html-parser/dist/back.js
var require_back = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  function arr_back(arr) {
    return arr[arr.length - 1];
  }
  exports.default = arr_back;
});

// node_modules/node-html-parser/dist/matcher.js
var require_matcher = __commonJS((exports) => {
  var __importDefault = exports && exports.__importDefault || function(mod2) {
    return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  var type_1 = __importDefault(require_type());
  function isTag(node) {
    return node && node.nodeType === type_1.default.ELEMENT_NODE;
  }
  function getAttributeValue(elem, name2) {
    return isTag(elem) ? elem.getAttribute(name2) : undefined;
  }
  function getName(elem) {
    return (elem && elem.rawTagName || "").toLowerCase();
  }
  function getChildren(node) {
    return node && node.childNodes;
  }
  function getParent(node) {
    return node ? node.parentNode : null;
  }
  function getText(node) {
    return node.text;
  }
  function removeSubsets(nodes) {
    let idx = nodes.length;
    let node;
    let ancestor;
    let replace;
    while (--idx > -1) {
      node = ancestor = nodes[idx];
      nodes[idx] = null;
      replace = true;
      while (ancestor) {
        if (nodes.indexOf(ancestor) > -1) {
          replace = false;
          nodes.splice(idx, 1);
          break;
        }
        ancestor = getParent(ancestor);
      }
      if (replace) {
        nodes[idx] = node;
      }
    }
    return nodes;
  }
  function existsOne(test, elems) {
    return elems.some((elem) => {
      return isTag(elem) ? test(elem) || existsOne(test, getChildren(elem)) : false;
    });
  }
  function getSiblings(node) {
    const parent = getParent(node);
    return parent ? getChildren(parent) : [];
  }
  function hasAttrib(elem, name2) {
    return getAttributeValue(elem, name2) !== undefined;
  }
  function findOne(test, elems) {
    let elem = null;
    for (let i = 0, l = elems === null || elems === undefined ? undefined : elems.length;i < l && !elem; i++) {
      const el = elems[i];
      if (test(el)) {
        elem = el;
      } else {
        const childs = getChildren(el);
        if (childs && childs.length > 0) {
          elem = findOne(test, childs);
        }
      }
    }
    return elem;
  }
  function findAll(test, nodes) {
    let result = [];
    for (let i = 0, j = nodes.length;i < j; i++) {
      if (!isTag(nodes[i]))
        continue;
      if (test(nodes[i]))
        result.push(nodes[i]);
      const childs = getChildren(nodes[i]);
      if (childs)
        result = result.concat(findAll(test, childs));
    }
    return result;
  }
  exports.default = {
    isTag,
    getAttributeValue,
    getName,
    getChildren,
    getParent,
    getText,
    removeSubsets,
    existsOne,
    getSiblings,
    hasAttrib,
    findOne,
    findAll
  };
});

// node_modules/node-html-parser/dist/void-tag.js
var require_void_tag = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });

  class VoidTag {
    constructor(addClosingSlash = false, tags) {
      this.addClosingSlash = addClosingSlash;
      if (Array.isArray(tags)) {
        this.voidTags = tags.reduce((set2, tag2) => {
          return set2.add(tag2.toLowerCase()).add(tag2.toUpperCase()).add(tag2);
        }, new Set);
      } else {
        this.voidTags = ["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"].reduce((set2, tag2) => {
          return set2.add(tag2.toLowerCase()).add(tag2.toUpperCase()).add(tag2);
        }, new Set);
      }
    }
    formatNode(tag2, attrs, innerHTML) {
      const addClosingSlash = this.addClosingSlash;
      const closingSpace = addClosingSlash && attrs && !attrs.endsWith(" ") ? " " : "";
      const closingSlash = addClosingSlash ? `${closingSpace}/` : "";
      return this.isVoidElement(tag2.toLowerCase()) ? `<${tag2}${attrs}${closingSlash}>` : `<${tag2}${attrs}>${innerHTML}</${tag2}>`;
    }
    isVoidElement(tag2) {
      return this.voidTags.has(tag2);
    }
  }
  exports.default = VoidTag;
});

// node_modules/node-html-parser/dist/nodes/text.js
var require_text = __commonJS((exports) => {
  var __importDefault = exports && exports.__importDefault || function(mod2) {
    return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  var he_1 = require_he();
  var node_1 = __importDefault(require_node());
  var type_1 = __importDefault(require_type());

  class TextNode extends node_1.default {
    clone() {
      return new TextNode(this._rawText, null);
    }
    constructor(rawText, parentNode = null, range2) {
      super(parentNode, range2);
      this.nodeType = type_1.default.TEXT_NODE;
      this.rawTagName = "";
      this._rawText = rawText;
    }
    get rawText() {
      return this._rawText;
    }
    set rawText(text3) {
      this._rawText = text3;
      this._trimmedRawText = undefined;
      this._trimmedText = undefined;
    }
    get trimmedRawText() {
      if (this._trimmedRawText !== undefined)
        return this._trimmedRawText;
      this._trimmedRawText = trimText(this.rawText);
      return this._trimmedRawText;
    }
    get trimmedText() {
      if (this._trimmedText !== undefined)
        return this._trimmedText;
      this._trimmedText = trimText(this.text);
      return this._trimmedText;
    }
    get text() {
      return (0, he_1.decode)(this.rawText);
    }
    get isWhitespace() {
      return /^(\s|&nbsp;)*$/.test(this.rawText);
    }
    toString() {
      return this.rawText;
    }
  }
  exports.default = TextNode;
  function trimText(text3) {
    let i = 0;
    let startPos;
    let endPos;
    while (i >= 0 && i < text3.length) {
      if (/\S/.test(text3[i])) {
        if (startPos === undefined) {
          startPos = i;
          i = text3.length;
        } else {
          endPos = i;
          i = undefined;
        }
      }
      if (startPos === undefined)
        i++;
      else
        i--;
    }
    if (startPos === undefined)
      startPos = 0;
    if (endPos === undefined)
      endPos = text3.length - 1;
    const hasLeadingSpace = startPos > 0 && /[^\S\r\n]/.test(text3[startPos - 1]);
    const hasTrailingSpace = endPos < text3.length - 1 && /[^\S\r\n]/.test(text3[endPos + 1]);
    return (hasLeadingSpace ? " " : "") + text3.slice(startPos, endPos + 1) + (hasTrailingSpace ? " " : "");
  }
});

// node_modules/node-html-parser/dist/nodes/html.js
var require_html = __commonJS((exports) => {
  var __importDefault = exports && exports.__importDefault || function(mod2) {
    return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.parse = exports.base_parse = undefined;
  var css_select_1 = require_lib7();
  var he_1 = __importDefault(require_he());
  var back_1 = __importDefault(require_back());
  var matcher_1 = __importDefault(require_matcher());
  var void_tag_1 = __importDefault(require_void_tag());
  var comment_1 = __importDefault(require_comment());
  var node_1 = __importDefault(require_node());
  var text_1 = __importDefault(require_text());
  var type_1 = __importDefault(require_type());
  function decode3(val) {
    return JSON.parse(JSON.stringify(he_1.default.decode(val)));
  }
  var Htags = ["h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup"];
  var Dtags = ["details", "dialog", "dd", "div", "dt"];
  var Ftags = ["fieldset", "figcaption", "figure", "footer", "form"];
  var tableTags = ["table", "td", "tr"];
  var htmlTags = ["address", "article", "aside", "blockquote", "br", "hr", "li", "main", "nav", "ol", "p", "pre", "section", "ul"];
  var kBlockElements = new Set;
  function addToKBlockElement(...args2) {
    const addToSet = (array3) => {
      for (let index = 0;index < array3.length; index++) {
        const element = array3[index];
        kBlockElements.add(element);
        kBlockElements.add(element.toUpperCase());
      }
    };
    for (const arg of args2)
      addToSet(arg);
  }
  addToKBlockElement(Htags, Dtags, Ftags, tableTags, htmlTags);

  class DOMTokenList {
    _validate(c) {
      if (/\s/.test(c)) {
        throw new Error(`DOMException in DOMTokenList.add: The token '${c}' contains HTML space characters, which are not valid in tokens.`);
      }
    }
    constructor(valuesInit = [], afterUpdate = () => null) {
      this._set = new Set(valuesInit);
      this._afterUpdate = afterUpdate;
    }
    add(c) {
      this._validate(c);
      this._set.add(c);
      this._afterUpdate(this);
    }
    replace(c1, c2) {
      this._validate(c2);
      this._set.delete(c1);
      this._set.add(c2);
      this._afterUpdate(this);
    }
    remove(c) {
      this._set.delete(c) && this._afterUpdate(this);
    }
    toggle(c) {
      this._validate(c);
      if (this._set.has(c))
        this._set.delete(c);
      else
        this._set.add(c);
      this._afterUpdate(this);
    }
    contains(c) {
      return this._set.has(c);
    }
    get length() {
      return this._set.size;
    }
    values() {
      return this._set.values();
    }
    get value() {
      return Array.from(this._set.values());
    }
    toString() {
      return Array.from(this._set.values()).join(" ");
    }
  }

  class HTMLElement extends node_1.default {
    quoteAttribute(attr) {
      if (attr == null) {
        return "null";
      }
      return JSON.stringify(attr.replace(/"/g, "&quot;")).replace(/\\t/g, "\t").replace(/\\n/g, `
`).replace(/\\r/g, "\r").replace(/\\/g, "");
    }
    constructor(tagName, keyAttrs, rawAttrs = "", parentNode = null, range2, voidTag = new void_tag_1.default, _parseOptions = {}) {
      super(parentNode, range2);
      this.rawAttrs = rawAttrs;
      this.voidTag = voidTag;
      this.nodeType = type_1.default.ELEMENT_NODE;
      this.rawTagName = tagName;
      this.rawAttrs = rawAttrs || "";
      this._id = keyAttrs.id || "";
      this.childNodes = [];
      this._parseOptions = _parseOptions;
      this.classList = new DOMTokenList(keyAttrs.class ? keyAttrs.class.split(/\s+/) : [], (classList) => this.setAttribute("class", classList.toString()));
      if (keyAttrs.id) {
        if (!rawAttrs) {
          this.rawAttrs = `id="${keyAttrs.id}"`;
        }
      }
      if (keyAttrs.class) {
        if (!rawAttrs) {
          const cls = `class="${this.classList.toString()}"`;
          if (this.rawAttrs) {
            this.rawAttrs += ` ${cls}`;
          } else {
            this.rawAttrs = cls;
          }
        }
      }
    }
    removeChild(node) {
      this.childNodes = this.childNodes.filter((child) => {
        return child !== node;
      });
      return this;
    }
    exchangeChild(oldNode, newNode) {
      const children = this.childNodes;
      this.childNodes = children.map((child) => {
        if (child === oldNode) {
          return newNode;
        }
        return child;
      });
      return this;
    }
    get tagName() {
      return this.rawTagName ? this.rawTagName.toUpperCase() : this.rawTagName;
    }
    set tagName(newname) {
      this.rawTagName = newname.toLowerCase();
    }
    get localName() {
      return this.rawTagName.toLowerCase();
    }
    get isVoidElement() {
      return this.voidTag.isVoidElement(this.localName);
    }
    get id() {
      return this._id;
    }
    set id(newid) {
      this.setAttribute("id", newid);
    }
    get rawText() {
      if (/^br$/i.test(this.rawTagName)) {
        return `
`;
      }
      return this.childNodes.reduce((pre, cur) => {
        return pre += cur.rawText;
      }, "");
    }
    get textContent() {
      return decode3(this.rawText);
    }
    set textContent(val) {
      const content = [new text_1.default(val, this)];
      this.childNodes = content;
    }
    get text() {
      return decode3(this.rawText);
    }
    get structuredText() {
      let currentBlock = [];
      const blocks = [currentBlock];
      function dfs(node) {
        if (node.nodeType === type_1.default.ELEMENT_NODE) {
          if (kBlockElements.has(node.rawTagName)) {
            if (currentBlock.length > 0) {
              blocks.push(currentBlock = []);
            }
            node.childNodes.forEach(dfs);
            if (currentBlock.length > 0) {
              blocks.push(currentBlock = []);
            }
          } else {
            node.childNodes.forEach(dfs);
          }
        } else if (node.nodeType === type_1.default.TEXT_NODE) {
          if (node.isWhitespace) {
            currentBlock.prependWhitespace = true;
          } else {
            let text3 = node.trimmedText;
            if (currentBlock.prependWhitespace) {
              text3 = ` ${text3}`;
              currentBlock.prependWhitespace = false;
            }
            currentBlock.push(text3);
          }
        }
      }
      dfs(this);
      return blocks.map((block) => {
        return block.join("").replace(/\s{2,}/g, " ");
      }).join(`
`).replace(/\s+$/, "");
    }
    toString() {
      const tag2 = this.rawTagName;
      if (tag2) {
        const attrs = this.rawAttrs ? ` ${this.rawAttrs}` : "";
        return this.voidTag.formatNode(tag2, attrs, this.innerHTML);
      }
      return this.innerHTML;
    }
    get innerHTML() {
      return this.childNodes.map((child) => {
        return child.toString();
      }).join("");
    }
    set innerHTML(content) {
      const r = parse6(content, this._parseOptions);
      const nodes = r.childNodes.length ? r.childNodes : [new text_1.default(content, this)];
      resetParent(nodes, this);
      resetParent(this.childNodes, null);
      this.childNodes = nodes;
    }
    set_content(content, options = {}) {
      if (content instanceof node_1.default) {
        content = [content];
      } else if (typeof content == "string") {
        options = Object.assign(Object.assign({}, this._parseOptions), options);
        const r = parse6(content, options);
        content = r.childNodes.length ? r.childNodes : [new text_1.default(r.innerHTML, this)];
      }
      resetParent(this.childNodes, null);
      resetParent(content, this);
      this.childNodes = content;
      return this;
    }
    replaceWith(...nodes) {
      const parent = this.parentNode;
      const content = nodes.map((node) => {
        if (node instanceof node_1.default) {
          return [node];
        } else if (typeof node == "string") {
          const r = parse6(node, this._parseOptions);
          return r.childNodes.length ? r.childNodes : [new text_1.default(node, this)];
        }
        return [];
      }).flat();
      const idx = parent.childNodes.findIndex((child) => {
        return child === this;
      });
      resetParent([this], null);
      parent.childNodes = [...parent.childNodes.slice(0, idx), ...resetParent(content, parent), ...parent.childNodes.slice(idx + 1)];
      return this;
    }
    get outerHTML() {
      return this.toString();
    }
    trimRight(pattern) {
      for (let i = 0;i < this.childNodes.length; i++) {
        const childNode = this.childNodes[i];
        if (childNode.nodeType === type_1.default.ELEMENT_NODE) {
          childNode.trimRight(pattern);
        } else {
          const index = childNode.rawText.search(pattern);
          if (index > -1) {
            childNode.rawText = childNode.rawText.substr(0, index);
            this.childNodes.length = i + 1;
          }
        }
      }
      return this;
    }
    get structure() {
      const res = [];
      let indention = 0;
      function write2(str) {
        res.push("  ".repeat(indention) + str);
      }
      function dfs(node) {
        const idStr = node._id ? `#${node._id}` : "";
        const classStr = node.classList.length ? `.${node.classList.value.join(".")}` : "";
        write2(`${node.rawTagName}${idStr}${classStr}`);
        indention++;
        node.childNodes.forEach((childNode) => {
          if (childNode.nodeType === type_1.default.ELEMENT_NODE) {
            dfs(childNode);
          } else if (childNode.nodeType === type_1.default.TEXT_NODE) {
            if (!childNode.isWhitespace) {
              write2("#text");
            }
          }
        });
        indention--;
      }
      dfs(this);
      return res.join(`
`);
    }
    removeWhitespace() {
      let o = 0;
      this.childNodes.forEach((node) => {
        if (node.nodeType === type_1.default.TEXT_NODE) {
          if (node.isWhitespace) {
            return;
          }
          node.rawText = node.trimmedRawText;
        } else if (node.nodeType === type_1.default.ELEMENT_NODE) {
          node.removeWhitespace();
        }
        this.childNodes[o++] = node;
      });
      this.childNodes.length = o;
      const attrs = Object.keys(this.rawAttributes).map((key) => {
        const val = this.rawAttributes[key];
        return `${key}=${JSON.stringify(val)}`;
      }).join(" ");
      this.rawAttrs = attrs;
      delete this._rawAttrs;
      return this;
    }
    querySelectorAll(selector) {
      return (0, css_select_1.selectAll)(selector, this, {
        xmlMode: true,
        adapter: matcher_1.default
      });
    }
    querySelector(selector) {
      return (0, css_select_1.selectOne)(selector, this, {
        xmlMode: true,
        adapter: matcher_1.default
      });
    }
    matches(selector) {
      return (0, css_select_1.is)(this, selector, {
        xmlMode: true,
        adapter: matcher_1.default
      });
    }
    getElementsByTagName(tagName) {
      const upperCasedTagName = tagName.toUpperCase();
      const re2 = [];
      const stack = [];
      let currentNodeReference = this;
      let index = 0;
      while (index !== undefined) {
        let child;
        do {
          child = currentNodeReference.childNodes[index++];
        } while (index < currentNodeReference.childNodes.length && child === undefined);
        if (child === undefined) {
          currentNodeReference = currentNodeReference.parentNode;
          index = stack.pop();
          continue;
        }
        if (child.nodeType === type_1.default.ELEMENT_NODE) {
          if (tagName === "*" || child.tagName === upperCasedTagName)
            re2.push(child);
          if (child.childNodes.length > 0) {
            stack.push(index);
            currentNodeReference = child;
            index = 0;
          }
        }
      }
      return re2;
    }
    getElementById(id2) {
      const stack = [];
      let currentNodeReference = this;
      let index = 0;
      while (index !== undefined) {
        let child;
        do {
          child = currentNodeReference.childNodes[index++];
        } while (index < currentNodeReference.childNodes.length && child === undefined);
        if (child === undefined) {
          currentNodeReference = currentNodeReference.parentNode;
          index = stack.pop();
          continue;
        }
        if (child.nodeType === type_1.default.ELEMENT_NODE) {
          if (child._id === id2) {
            return child;
          }
          if (child.childNodes.length > 0) {
            stack.push(index);
            currentNodeReference = child;
            index = 0;
          }
        }
      }
      return null;
    }
    closest(selector) {
      const mapChild = new Map;
      let el = this;
      let old = null;
      function findOne(test, elems) {
        let elem = null;
        for (let i = 0, l = elems.length;i < l && !elem; i++) {
          const el2 = elems[i];
          if (test(el2)) {
            elem = el2;
          } else {
            const child = mapChild.get(el2);
            if (child) {
              elem = findOne(test, [child]);
            }
          }
        }
        return elem;
      }
      while (el) {
        mapChild.set(el, old);
        old = el;
        el = el.parentNode;
      }
      el = this;
      while (el) {
        const e = (0, css_select_1.selectOne)(selector, el, {
          xmlMode: true,
          adapter: Object.assign(Object.assign({}, matcher_1.default), {
            getChildren(node) {
              const child = mapChild.get(node);
              return child && [child];
            },
            getSiblings(node) {
              return [node];
            },
            findOne,
            findAll() {
              return [];
            }
          })
        });
        if (e) {
          return e;
        }
        el = el.parentNode;
      }
      return null;
    }
    appendChild(node) {
      this.append(node);
      return node;
    }
    get attrs() {
      if (this._attrs) {
        return this._attrs;
      }
      this._attrs = {};
      const attrs = this.rawAttributes;
      for (const key in attrs) {
        const val = attrs[key] || "";
        this._attrs[key.toLowerCase()] = decode3(val);
      }
      return this._attrs;
    }
    get attributes() {
      const ret_attrs = {};
      const attrs = this.rawAttributes;
      for (const key in attrs) {
        const val = attrs[key] || "";
        ret_attrs[key] = decode3(val);
      }
      return ret_attrs;
    }
    get rawAttributes() {
      if (this._rawAttrs) {
        return this._rawAttrs;
      }
      const attrs = {};
      if (this.rawAttrs) {
        const re2 = /([a-zA-Z()[\]#@$.?:][a-zA-Z0-9-._:()[\]#]*)(?:\s*=\s*((?:'[^']*')|(?:"[^"]*")|\S+))?/g;
        let match;
        while (match = re2.exec(this.rawAttrs)) {
          const key = match[1];
          let val = match[2] || null;
          if (val && (val[0] === `'` || val[0] === `"`))
            val = val.slice(1, val.length - 1);
          attrs[key] = attrs[key] || val;
        }
      }
      this._rawAttrs = attrs;
      return attrs;
    }
    removeAttribute(key) {
      const attrs = this.rawAttributes;
      delete attrs[key];
      if (this._attrs) {
        delete this._attrs[key];
      }
      this.rawAttrs = Object.keys(attrs).map((name2) => {
        const val = this.quoteAttribute(attrs[name2]);
        if (val === "null" || val === '""')
          return name2;
        return `${name2}=${val}`;
      }).join(" ");
      if (key === "id") {
        this._id = "";
      }
      return this;
    }
    hasAttribute(key) {
      return key.toLowerCase() in this.attrs;
    }
    getAttribute(key) {
      return this.attrs[key.toLowerCase()];
    }
    setAttribute(key, value2) {
      if (arguments.length < 2) {
        throw new Error("Failed to execute 'setAttribute' on 'Element'");
      }
      const k2 = key.toLowerCase();
      const attrs = this.rawAttributes;
      for (const k in attrs) {
        if (k.toLowerCase() === k2) {
          key = k;
          break;
        }
      }
      attrs[key] = String(value2);
      if (this._attrs) {
        this._attrs[k2] = decode3(attrs[key]);
      }
      this.rawAttrs = Object.keys(attrs).map((name2) => {
        const val = this.quoteAttribute(attrs[name2]);
        if (val === "null" || val === '""')
          return name2;
        return `${name2}=${val}`;
      }).join(" ");
      if (key === "id") {
        this._id = value2;
      }
      return this;
    }
    setAttributes(attributes) {
      if (this._attrs) {
        delete this._attrs;
      }
      if (this._rawAttrs) {
        delete this._rawAttrs;
      }
      this.rawAttrs = Object.keys(attributes).map((name2) => {
        const val = attributes[name2];
        if (val === "null" || val === '""')
          return name2;
        return `${name2}=${this.quoteAttribute(String(val))}`;
      }).join(" ");
      if ("id" in attributes) {
        this._id = attributes["id"];
      }
      return this;
    }
    insertAdjacentHTML(where, html) {
      if (arguments.length < 2) {
        throw new Error("2 arguments required");
      }
      const p = parse6(html, this._parseOptions);
      if (where === "afterend") {
        this.after(...p.childNodes);
      } else if (where === "afterbegin") {
        this.prepend(...p.childNodes);
      } else if (where === "beforeend") {
        this.append(...p.childNodes);
      } else if (where === "beforebegin") {
        this.before(...p.childNodes);
      } else {
        throw new Error(`The value provided ('${where}') is not one of 'beforebegin', 'afterbegin', 'beforeend', or 'afterend'`);
      }
      return this;
    }
    prepend(...insertable) {
      const nodes = resolveInsertable(insertable);
      resetParent(nodes, this);
      this.childNodes.unshift(...nodes);
    }
    append(...insertable) {
      const nodes = resolveInsertable(insertable);
      resetParent(nodes, this);
      this.childNodes.push(...nodes);
    }
    before(...insertable) {
      const nodes = resolveInsertable(insertable);
      const siblings = this.parentNode.childNodes;
      resetParent(nodes, this.parentNode);
      siblings.splice(siblings.indexOf(this), 0, ...nodes);
    }
    after(...insertable) {
      const nodes = resolveInsertable(insertable);
      const siblings = this.parentNode.childNodes;
      resetParent(nodes, this.parentNode);
      siblings.splice(siblings.indexOf(this) + 1, 0, ...nodes);
    }
    get nextSibling() {
      if (this.parentNode) {
        const children = this.parentNode.childNodes;
        let i = 0;
        while (i < children.length) {
          const child = children[i++];
          if (this === child)
            return children[i] || null;
        }
        return null;
      }
    }
    get nextElementSibling() {
      if (this.parentNode) {
        const children = this.parentNode.childNodes;
        let i = 0;
        let find2 = false;
        while (i < children.length) {
          const child = children[i++];
          if (find2) {
            if (child instanceof HTMLElement) {
              return child || null;
            }
          } else if (this === child) {
            find2 = true;
          }
        }
        return null;
      }
    }
    get previousSibling() {
      if (this.parentNode) {
        const children = this.parentNode.childNodes;
        let i = children.length;
        while (i > 0) {
          const child = children[--i];
          if (this === child)
            return children[i - 1] || null;
        }
        return null;
      }
    }
    get previousElementSibling() {
      if (this.parentNode) {
        const children = this.parentNode.childNodes;
        let i = children.length;
        let find2 = false;
        while (i > 0) {
          const child = children[--i];
          if (find2) {
            if (child instanceof HTMLElement) {
              return child || null;
            }
          } else if (this === child) {
            find2 = true;
          }
        }
        return null;
      }
    }
    get children() {
      const children = [];
      for (const childNode of this.childNodes) {
        if (childNode instanceof HTMLElement) {
          children.push(childNode);
        }
      }
      return children;
    }
    get firstChild() {
      return this.childNodes[0];
    }
    get firstElementChild() {
      return this.children[0];
    }
    get lastChild() {
      return (0, back_1.default)(this.childNodes);
    }
    get lastElementChild() {
      return this.children[this.children.length - 1];
    }
    get childElementCount() {
      return this.children.length;
    }
    get classNames() {
      return this.classList.toString();
    }
    clone() {
      return parse6(this.toString(), this._parseOptions).firstChild;
    }
  }
  exports.default = HTMLElement;
  var kMarkupPattern = /<!--[\s\S]*?-->|<(\/?)([a-zA-Z][-.:0-9_a-zA-Z@\xB7\xC0-\xD6\xD8-\xF6\u00F8-\u03A1\u03A3-\u03D9\u03DB-\u03EF\u03F7-\u03FF\u0400-\u04FF\u0500-\u052F\u1D00-\u1D2B\u1D6B-\u1D77\u1D79-\u1D9A\u1E00-\u1E9B\u1F00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2126\u212A-\u212B\u2132\u214E\u2160-\u2188\u2C60-\u2C7F\uA722-\uA787\uA78B-\uA78E\uA790-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA7FF\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64-\uAB65\uFB00-\uFB06\uFB13-\uFB17\uFF21-\uFF3A\uFF41-\uFF5A\x37F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]*)((?:\s+[^>]*?(?:(?:'[^']*')|(?:"[^"]*"))?)*)\s*(\/?)>/gu;
  var kAttributePattern = /(?:^|\s)(id|class)\s*=\s*((?:'[^']*')|(?:"[^"]*")|\S+)/gi;
  var kElementsClosedByOpening = {
    li: { li: true, LI: true },
    LI: { li: true, LI: true },
    p: { p: true, div: true, P: true, DIV: true },
    P: { p: true, div: true, P: true, DIV: true },
    b: { div: true, DIV: true },
    B: { div: true, DIV: true },
    td: { td: true, th: true, TD: true, TH: true },
    TD: { td: true, th: true, TD: true, TH: true },
    th: { td: true, th: true, TD: true, TH: true },
    TH: { td: true, th: true, TD: true, TH: true },
    h1: { h1: true, H1: true },
    H1: { h1: true, H1: true },
    h2: { h2: true, H2: true },
    H2: { h2: true, H2: true },
    h3: { h3: true, H3: true },
    H3: { h3: true, H3: true },
    h4: { h4: true, H4: true },
    H4: { h4: true, H4: true },
    h5: { h5: true, H5: true },
    H5: { h5: true, H5: true },
    h6: { h6: true, H6: true },
    H6: { h6: true, H6: true }
  };
  var kElementsClosedByClosing = {
    li: { ul: true, ol: true, UL: true, OL: true },
    LI: { ul: true, ol: true, UL: true, OL: true },
    a: { div: true, DIV: true },
    A: { div: true, DIV: true },
    b: { div: true, DIV: true },
    B: { div: true, DIV: true },
    i: { div: true, DIV: true },
    I: { div: true, DIV: true },
    p: { div: true, DIV: true },
    P: { div: true, DIV: true },
    td: { tr: true, table: true, TR: true, TABLE: true },
    TD: { tr: true, table: true, TR: true, TABLE: true },
    th: { tr: true, table: true, TR: true, TABLE: true },
    TH: { tr: true, table: true, TR: true, TABLE: true }
  };
  var kElementsClosedByClosingExcept = {
    p: { a: true, audio: true, del: true, ins: true, map: true, noscript: true, video: true }
  };
  var frameflag = "documentfragmentcontainer";
  function base_parse(data2, options = {}) {
    var _a2, _b;
    const voidTag = new void_tag_1.default((_a2 = options === null || options === undefined ? undefined : options.voidTag) === null || _a2 === undefined ? undefined : _a2.closingSlash, (_b = options === null || options === undefined ? undefined : options.voidTag) === null || _b === undefined ? undefined : _b.tags);
    const elements = options.blockTextElements || {
      script: true,
      noscript: true,
      style: true,
      pre: true
    };
    const element_names = Object.keys(elements);
    const kBlockTextElements = element_names.map((it) => new RegExp(`^${it}$`, "i"));
    const kIgnoreElements = element_names.filter((it) => Boolean(elements[it])).map((it) => new RegExp(`^${it}$`, "i"));
    function element_should_be_ignore(tag2) {
      return kIgnoreElements.some((it) => it.test(tag2));
    }
    function is_block_text_element(tag2) {
      return kBlockTextElements.some((it) => it.test(tag2));
    }
    const createRange = (startPos, endPos) => [startPos - frameFlagOffset, endPos - frameFlagOffset];
    const root = new HTMLElement(null, {}, "", null, [0, data2.length], voidTag, options);
    let currentParent = root;
    const stack = [root];
    let lastTextPos = -1;
    let noNestedTagIndex = undefined;
    let match;
    data2 = `<${frameflag}>${data2}</${frameflag}>`;
    const { lowerCaseTagName, fixNestedATags } = options;
    const dataEndPos = data2.length - (frameflag.length + 2);
    const frameFlagOffset = frameflag.length + 2;
    while (match = kMarkupPattern.exec(data2)) {
      let { 0: matchText, 1: leadingSlash, 2: tagName, 3: attributes, 4: closingSlash } = match;
      const matchLength = matchText.length;
      const tagStartPos = kMarkupPattern.lastIndex - matchLength;
      const tagEndPos = kMarkupPattern.lastIndex;
      if (lastTextPos > -1) {
        if (lastTextPos + matchLength < tagEndPos) {
          const text3 = data2.substring(lastTextPos, tagStartPos);
          currentParent.appendChild(new text_1.default(text3, currentParent, createRange(lastTextPos, tagStartPos)));
        }
      }
      lastTextPos = kMarkupPattern.lastIndex;
      if (tagName === frameflag)
        continue;
      if (matchText[1] === "!") {
        if (options.comment) {
          const text3 = data2.substring(tagStartPos + 4, tagEndPos - 3);
          currentParent.appendChild(new comment_1.default(text3, currentParent, createRange(tagStartPos, tagEndPos)));
        }
        continue;
      }
      if (lowerCaseTagName)
        tagName = tagName.toLowerCase();
      if (!leadingSlash) {
        const attrs = {};
        for (let attMatch;attMatch = kAttributePattern.exec(attributes); ) {
          const { 1: key, 2: val } = attMatch;
          const isQuoted = val[0] === `'` || val[0] === `"`;
          attrs[key.toLowerCase()] = isQuoted ? val.slice(1, val.length - 1) : val;
        }
        const parentTagName = currentParent.rawTagName;
        if (!closingSlash && !options.preserveTagNesting && kElementsClosedByOpening[parentTagName]) {
          if (kElementsClosedByOpening[parentTagName][tagName]) {
            stack.pop();
            currentParent = (0, back_1.default)(stack);
          }
        }
        if (fixNestedATags && (tagName === "a" || tagName === "A")) {
          if (noNestedTagIndex !== undefined) {
            stack.splice(noNestedTagIndex);
            currentParent = (0, back_1.default)(stack);
          }
          noNestedTagIndex = stack.length;
        }
        const tagEndPos2 = kMarkupPattern.lastIndex;
        const tagStartPos2 = tagEndPos2 - matchLength;
        currentParent = currentParent.appendChild(new HTMLElement(tagName, attrs, attributes.slice(1), null, createRange(tagStartPos2, tagEndPos2), voidTag, options));
        stack.push(currentParent);
        if (is_block_text_element(tagName)) {
          const closeMarkup = `</${tagName}>`;
          const closeIndex = lowerCaseTagName ? data2.toLocaleLowerCase().indexOf(closeMarkup, kMarkupPattern.lastIndex) : data2.indexOf(closeMarkup, kMarkupPattern.lastIndex);
          const textEndPos = closeIndex === -1 ? dataEndPos : closeIndex;
          if (element_should_be_ignore(tagName)) {
            const text3 = data2.substring(tagEndPos2, textEndPos);
            if (text3.length > 0 && /\S/.test(text3)) {
              currentParent.appendChild(new text_1.default(text3, currentParent, createRange(tagEndPos2, textEndPos)));
            }
          }
          if (closeIndex === -1) {
            lastTextPos = kMarkupPattern.lastIndex = data2.length + 1;
          } else {
            lastTextPos = kMarkupPattern.lastIndex = closeIndex + closeMarkup.length;
            leadingSlash = "/";
          }
        }
      }
      if (leadingSlash || closingSlash || voidTag.isVoidElement(tagName)) {
        while (true) {
          if (noNestedTagIndex != null && (tagName === "a" || tagName === "A"))
            noNestedTagIndex = undefined;
          if (currentParent.rawTagName === tagName) {
            currentParent.range[1] = createRange(-1, Math.max(lastTextPos, tagEndPos))[1];
            stack.pop();
            currentParent = (0, back_1.default)(stack);
            break;
          } else {
            const parentTagName = currentParent.tagName;
            if (kElementsClosedByClosing[parentTagName]) {
              if (kElementsClosedByClosing[parentTagName][tagName]) {
                stack.pop();
                currentParent = (0, back_1.default)(stack);
                continue;
              }
            }
            const openTag = currentParent.rawTagName ? currentParent.rawTagName.toLowerCase() : "";
            if (kElementsClosedByClosingExcept[openTag]) {
              const closingTag = tagName.toLowerCase();
              if (stack.length > 1) {
                const possibleContainer = stack[stack.length - 2];
                if (possibleContainer && possibleContainer.rawTagName && possibleContainer.rawTagName.toLowerCase() === closingTag && !kElementsClosedByClosingExcept[openTag][closingTag]) {
                  currentParent.range[1] = createRange(-1, Math.max(lastTextPos, tagEndPos))[1];
                  stack.pop();
                  currentParent = (0, back_1.default)(stack);
                  continue;
                }
              }
            }
            if (options.closeAllByClosing === true) {
              let i;
              for (i = stack.length - 2;i >= 0; i--) {
                if (stack[i].rawTagName === tagName)
                  break;
              }
              if (i >= 0) {
                while (stack.length > i) {
                  currentParent.range[1] = createRange(-1, Math.max(lastTextPos, tagEndPos))[1];
                  stack.pop();
                  currentParent = (0, back_1.default)(stack);
                }
                continue;
              }
            }
            break;
          }
        }
      }
    }
    return stack;
  }
  exports.base_parse = base_parse;
  function parse6(data2, options = {}) {
    const stack = base_parse(data2, options);
    const [root] = stack;
    while (stack.length > 1) {
      const last2 = stack.pop();
      const oneBefore = (0, back_1.default)(stack);
      if (last2.parentNode && last2.parentNode.parentNode) {
        if (last2.parentNode === oneBefore && last2.tagName === oneBefore.tagName) {
          if (options.parseNoneClosedTags !== true) {
            oneBefore.removeChild(last2);
            last2.childNodes.forEach((child) => {
              oneBefore.parentNode.appendChild(child);
            });
            stack.pop();
          }
        } else {
          if (options.parseNoneClosedTags !== true) {
            oneBefore.removeChild(last2);
            last2.childNodes.forEach((child) => {
              oneBefore.appendChild(child);
            });
          }
        }
      } else {}
    }
    return root;
  }
  exports.parse = parse6;
  function resolveInsertable(insertable) {
    return insertable.map((val) => {
      if (typeof val === "string") {
        return new text_1.default(val);
      }
      val.remove();
      return val;
    });
  }
  function resetParent(nodes, parent) {
    return nodes.map((node) => {
      node.parentNode = parent;
      return node;
    });
  }
});

// node_modules/node-html-parser/dist/parse.js
var require_parse3 = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.default = undefined;
  var html_1 = require_html();
  Object.defineProperty(exports, "default", { enumerable: true, get: function() {
    return html_1.parse;
  } });
});

// node_modules/node-html-parser/dist/valid.js
var require_valid = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  var html_1 = require_html();
  function valid(data2, options = {}) {
    const stack = (0, html_1.base_parse)(data2, options);
    return Boolean(stack.length === 1);
  }
  exports.default = valid;
});

// node_modules/node-html-parser/dist/index.js
var require_dist = __commonJS((exports) => {
  var __importDefault = exports && exports.__importDefault || function(mod2) {
    return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.NodeType = exports.TextNode = exports.Node = exports.valid = exports.CommentNode = exports.HTMLElement = exports.parse = undefined;
  var comment_1 = __importDefault(require_comment());
  exports.CommentNode = comment_1.default;
  var html_1 = __importDefault(require_html());
  exports.HTMLElement = html_1.default;
  var node_1 = __importDefault(require_node());
  exports.Node = node_1.default;
  var text_1 = __importDefault(require_text());
  exports.TextNode = text_1.default;
  var type_1 = __importDefault(require_type());
  exports.NodeType = type_1.default;
  var parse_1 = __importDefault(require_parse3());
  var valid_1 = __importDefault(require_valid());
  exports.valid = valid_1.default;
  function parse6(data2, options = {}) {
    return (0, parse_1.default)(data2, options);
  }
  exports.default = parse6;
  exports.parse = parse6;
  parse6.parse = parse_1.default;
  parse6.HTMLElement = html_1.default;
  parse6.CommentNode = comment_1.default;
  parse6.valid = valid_1.default;
  parse6.Node = node_1.default;
  parse6.TextNode = text_1.default;
  parse6.NodeType = type_1.default;
});

// node_modules/bail/index.js
function bail(error49) {
  if (error49) {
    throw error49;
  }
}

// node_modules/extend/index.js
var require_extend = __commonJS((exports, module) => {
  var hasOwn = Object.prototype.hasOwnProperty;
  var toStr = Object.prototype.toString;
  var defineProperty = Object.defineProperty;
  var gOPD = Object.getOwnPropertyDescriptor;
  var isArray2 = function isArray(arr) {
    if (typeof Array.isArray === "function") {
      return Array.isArray(arr);
    }
    return toStr.call(arr) === "[object Array]";
  };
  var isPlainObject3 = function isPlainObject(obj) {
    if (!obj || toStr.call(obj) !== "[object Object]") {
      return false;
    }
    var hasOwnConstructor = hasOwn.call(obj, "constructor");
    var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, "isPrototypeOf");
    if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
      return false;
    }
    var key;
    for (key in obj) {}
    return typeof key === "undefined" || hasOwn.call(obj, key);
  };
  var setProperty = function setProperty(target, options) {
    if (defineProperty && options.name === "__proto__") {
      defineProperty(target, options.name, {
        enumerable: true,
        configurable: true,
        value: options.newValue,
        writable: true
      });
    } else {
      target[options.name] = options.newValue;
    }
  };
  var getProperty = function getProperty(obj, name2) {
    if (name2 === "__proto__") {
      if (!hasOwn.call(obj, name2)) {
        return;
      } else if (gOPD) {
        return gOPD(obj, name2).value;
      }
    }
    return obj[name2];
  };
  module.exports = function extend() {
    var options, name2, src, copy3, copyIsArray, clone3;
    var target = arguments[0];
    var i = 1;
    var length2 = arguments.length;
    var deep = false;
    if (typeof target === "boolean") {
      deep = target;
      target = arguments[1] || {};
      i = 2;
    }
    if (target == null || typeof target !== "object" && typeof target !== "function") {
      target = {};
    }
    for (;i < length2; ++i) {
      options = arguments[i];
      if (options != null) {
        for (name2 in options) {
          src = getProperty(target, name2);
          copy3 = getProperty(options, name2);
          if (target !== copy3) {
            if (deep && copy3 && (isPlainObject3(copy3) || (copyIsArray = isArray2(copy3)))) {
              if (copyIsArray) {
                copyIsArray = false;
                clone3 = src && isArray2(src) ? src : [];
              } else {
                clone3 = src && isPlainObject3(src) ? src : {};
              }
              setProperty(target, { name: name2, newValue: extend(deep, clone3, copy3) });
            } else if (typeof copy3 !== "undefined") {
              setProperty(target, { name: name2, newValue: copy3 });
            }
          }
        }
      }
    }
    return target;
  };
});

// node_modules/dequal/dist/index.mjs
var init_dist = () => {};

// node_modules/devlop/lib/development.js
function ok(value2, message) {
  assert2(Boolean(value2), false, true, "ok", "Expected value to be truthy", message);
}
function assert2(bool, actual, expected, operator, defaultMessage, userMessage) {
  if (!bool) {
    throw userMessage instanceof Error ? userMessage : new AssertionError(userMessage || defaultMessage, actual, expected, operator, !userMessage);
  }
}
var codesWarned, AssertionError;
var init_development = __esm(() => {
  init_dist();
  codesWarned = new Set;
  AssertionError = class AssertionError extends Error {
    name = "Assertion";
    code = "ERR_ASSERTION";
    constructor(message, actual, expected, operator, generated) {
      super(message);
      if (Error.captureStackTrace) {
        Error.captureStackTrace(this, this.constructor);
      }
      this.actual = actual;
      this.expected = expected;
      this.generated = generated;
      this.operator = operator;
    }
  };
});

// node_modules/is-plain-obj/index.js
function isPlainObject3(value2) {
  if (typeof value2 !== "object" || value2 === null) {
    return false;
  }
  const prototype = Object.getPrototypeOf(value2);
  return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value2) && !(Symbol.iterator in value2);
}

// node_modules/trough/lib/index.js
function trough() {
  const fns = [];
  const pipeline = { run, use };
  return pipeline;
  function run(...values) {
    let middlewareIndex = -1;
    const callback = values.pop();
    if (typeof callback !== "function") {
      throw new TypeError("Expected function as last argument, not " + callback);
    }
    next2(null, ...values);
    function next2(error49, ...output) {
      const fn = fns[++middlewareIndex];
      let index = -1;
      if (error49) {
        callback(error49);
        return;
      }
      while (++index < values.length) {
        if (output[index] === null || output[index] === undefined) {
          output[index] = values[index];
        }
      }
      values = output;
      if (fn) {
        wrap2(fn, next2)(...output);
      } else {
        callback(null, ...output);
      }
    }
  }
  function use(middelware) {
    if (typeof middelware !== "function") {
      throw new TypeError("Expected `middelware` to be a function, not " + middelware);
    }
    fns.push(middelware);
    return pipeline;
  }
}
function wrap2(middleware, callback) {
  let called;
  return wrapped;
  function wrapped(...parameters) {
    const fnExpectsCallback = middleware.length > parameters.length;
    let result;
    if (fnExpectsCallback) {
      parameters.push(done);
    }
    try {
      result = middleware.apply(this, parameters);
    } catch (error49) {
      const exception = error49;
      if (fnExpectsCallback && called) {
        throw exception;
      }
      return done(exception);
    }
    if (!fnExpectsCallback) {
      if (result && result.then && typeof result.then === "function") {
        result.then(then, done);
      } else if (result instanceof Error) {
        done(result);
      } else {
        then(result);
      }
    }
  }
  function done(error49, ...output) {
    if (!called) {
      called = true;
      callback(error49, ...output);
    }
  }
  function then(value2) {
    done(null, value2);
  }
}

// node_modules/trough/index.js
var init_trough = () => {};

// node_modules/unist-util-stringify-position/lib/index.js
function stringifyPosition(value2) {
  if (!value2 || typeof value2 !== "object") {
    return "";
  }
  if ("position" in value2 || "type" in value2) {
    return position(value2.position);
  }
  if ("start" in value2 || "end" in value2) {
    return position(value2);
  }
  if ("line" in value2 || "column" in value2) {
    return point3(value2);
  }
  return "";
}
function point3(point4) {
  return index(point4 && point4.line) + ":" + index(point4 && point4.column);
}
function position(pos) {
  return point3(pos && pos.start) + "-" + point3(pos && pos.end);
}
function index(value2) {
  return value2 && typeof value2 === "number" ? value2 : 1;
}

// node_modules/unist-util-stringify-position/index.js
var init_unist_util_stringify_position = () => {};

// node_modules/vfile-message/lib/index.js
var VFileMessage;
var init_lib = __esm(() => {
  init_unist_util_stringify_position();
  VFileMessage = class VFileMessage extends Error {
    constructor(causeOrReason, optionsOrParentOrPlace, origin) {
      super();
      if (typeof optionsOrParentOrPlace === "string") {
        origin = optionsOrParentOrPlace;
        optionsOrParentOrPlace = undefined;
      }
      let reason = "";
      let options = {};
      let legacyCause = false;
      if (optionsOrParentOrPlace) {
        if ("line" in optionsOrParentOrPlace && "column" in optionsOrParentOrPlace) {
          options = { place: optionsOrParentOrPlace };
        } else if ("start" in optionsOrParentOrPlace && "end" in optionsOrParentOrPlace) {
          options = { place: optionsOrParentOrPlace };
        } else if ("type" in optionsOrParentOrPlace) {
          options = {
            ancestors: [optionsOrParentOrPlace],
            place: optionsOrParentOrPlace.position
          };
        } else {
          options = { ...optionsOrParentOrPlace };
        }
      }
      if (typeof causeOrReason === "string") {
        reason = causeOrReason;
      } else if (!options.cause && causeOrReason) {
        legacyCause = true;
        reason = causeOrReason.message;
        options.cause = causeOrReason;
      }
      if (!options.ruleId && !options.source && typeof origin === "string") {
        const index2 = origin.indexOf(":");
        if (index2 === -1) {
          options.ruleId = origin;
        } else {
          options.source = origin.slice(0, index2);
          options.ruleId = origin.slice(index2 + 1);
        }
      }
      if (!options.place && options.ancestors && options.ancestors) {
        const parent = options.ancestors[options.ancestors.length - 1];
        if (parent) {
          options.place = parent.position;
        }
      }
      const start = options.place && "start" in options.place ? options.place.start : options.place;
      this.ancestors = options.ancestors || undefined;
      this.cause = options.cause || undefined;
      this.column = start ? start.column : undefined;
      this.fatal = undefined;
      this.file = "";
      this.message = reason;
      this.line = start ? start.line : undefined;
      this.name = stringifyPosition(options.place) || "1:1";
      this.place = options.place || undefined;
      this.reason = this.message;
      this.ruleId = options.ruleId || undefined;
      this.source = options.source || undefined;
      this.stack = legacyCause && options.cause && typeof options.cause.stack === "string" ? options.cause.stack : "";
      this.actual = undefined;
      this.expected = undefined;
      this.note = undefined;
      this.url = undefined;
    }
  };
  VFileMessage.prototype.file = "";
  VFileMessage.prototype.name = "";
  VFileMessage.prototype.reason = "";
  VFileMessage.prototype.message = "";
  VFileMessage.prototype.stack = "";
  VFileMessage.prototype.column = undefined;
  VFileMessage.prototype.line = undefined;
  VFileMessage.prototype.ancestors = undefined;
  VFileMessage.prototype.cause = undefined;
  VFileMessage.prototype.fatal = undefined;
  VFileMessage.prototype.place = undefined;
  VFileMessage.prototype.ruleId = undefined;
  VFileMessage.prototype.source = undefined;
});

// node_modules/vfile-message/index.js
var init_vfile_message = __esm(() => {
  init_lib();
});

// node_modules/vfile/lib/minpath.js
import { default as default2 } from "node:path";
var init_minpath = () => {};

// node_modules/vfile/lib/minproc.js
import { default as default3 } from "node:process";
var init_minproc = () => {};

// node_modules/vfile/lib/minurl.shared.js
function isUrl(fileUrlOrPath) {
  return Boolean(fileUrlOrPath !== null && typeof fileUrlOrPath === "object" && "href" in fileUrlOrPath && fileUrlOrPath.href && "protocol" in fileUrlOrPath && fileUrlOrPath.protocol && fileUrlOrPath.auth === undefined);
}

// node_modules/vfile/lib/minurl.js
import { fileURLToPath } from "node:url";
var init_minurl = () => {};

// node_modules/vfile/lib/index.js
class VFile {
  constructor(value2) {
    let options;
    if (!value2) {
      options = {};
    } else if (isUrl(value2)) {
      options = { path: value2 };
    } else if (typeof value2 === "string" || isUint8Array(value2)) {
      options = { value: value2 };
    } else {
      options = value2;
    }
    this.cwd = "cwd" in options ? "" : default3.cwd();
    this.data = {};
    this.history = [];
    this.messages = [];
    this.value;
    this.map;
    this.result;
    this.stored;
    let index2 = -1;
    while (++index2 < order.length) {
      const field2 = order[index2];
      if (field2 in options && options[field2] !== undefined && options[field2] !== null) {
        this[field2] = field2 === "history" ? [...options[field2]] : options[field2];
      }
    }
    let field;
    for (field in options) {
      if (!order.includes(field)) {
        this[field] = options[field];
      }
    }
  }
  get basename() {
    return typeof this.path === "string" ? default2.basename(this.path) : undefined;
  }
  set basename(basename) {
    assertNonEmpty(basename, "basename");
    assertPart(basename, "basename");
    this.path = default2.join(this.dirname || "", basename);
  }
  get dirname() {
    return typeof this.path === "string" ? default2.dirname(this.path) : undefined;
  }
  set dirname(dirname) {
    assertPath(this.basename, "dirname");
    this.path = default2.join(dirname || "", this.basename);
  }
  get extname() {
    return typeof this.path === "string" ? default2.extname(this.path) : undefined;
  }
  set extname(extname) {
    assertPart(extname, "extname");
    assertPath(this.dirname, "extname");
    if (extname) {
      if (extname.codePointAt(0) !== 46) {
        throw new Error("`extname` must start with `.`");
      }
      if (extname.includes(".", 1)) {
        throw new Error("`extname` cannot contain multiple dots");
      }
    }
    this.path = default2.join(this.dirname, this.stem + (extname || ""));
  }
  get path() {
    return this.history[this.history.length - 1];
  }
  set path(path3) {
    if (isUrl(path3)) {
      path3 = fileURLToPath(path3);
    }
    assertNonEmpty(path3, "path");
    if (this.path !== path3) {
      this.history.push(path3);
    }
  }
  get stem() {
    return typeof this.path === "string" ? default2.basename(this.path, this.extname) : undefined;
  }
  set stem(stem) {
    assertNonEmpty(stem, "stem");
    assertPart(stem, "stem");
    this.path = default2.join(this.dirname || "", stem + (this.extname || ""));
  }
  fail(causeOrReason, optionsOrParentOrPlace, origin) {
    const message = this.message(causeOrReason, optionsOrParentOrPlace, origin);
    message.fatal = true;
    throw message;
  }
  info(causeOrReason, optionsOrParentOrPlace, origin) {
    const message = this.message(causeOrReason, optionsOrParentOrPlace, origin);
    message.fatal = undefined;
    return message;
  }
  message(causeOrReason, optionsOrParentOrPlace, origin) {
    const message = new VFileMessage(causeOrReason, optionsOrParentOrPlace, origin);
    if (this.path) {
      message.name = this.path + ":" + message.name;
      message.file = this.path;
    }
    message.fatal = false;
    this.messages.push(message);
    return message;
  }
  toString(encoding) {
    if (this.value === undefined) {
      return "";
    }
    if (typeof this.value === "string") {
      return this.value;
    }
    const decoder = new TextDecoder(encoding || undefined);
    return decoder.decode(this.value);
  }
}
function assertPart(part, name2) {
  if (part && part.includes(default2.sep)) {
    throw new Error("`" + name2 + "` cannot be a path: did not expect `" + default2.sep + "`");
  }
}
function assertNonEmpty(part, name2) {
  if (!part) {
    throw new Error("`" + name2 + "` cannot be empty");
  }
}
function assertPath(path3, name2) {
  if (!path3) {
    throw new Error("Setting `" + name2 + "` requires `path` to be set too");
  }
}
function isUint8Array(value2) {
  return Boolean(value2 && typeof value2 === "object" && "byteLength" in value2 && "byteOffset" in value2);
}
var order;
var init_lib2 = __esm(() => {
  init_vfile_message();
  init_minpath();
  init_minproc();
  init_minurl();
  order = [
    "history",
    "path",
    "basename",
    "stem",
    "extname",
    "dirname"
  ];
});

// node_modules/vfile/index.js
var init_vfile = __esm(() => {
  init_lib2();
});

// node_modules/unified/lib/callable-instance.js
var CallableInstance = function(property) {
  const self2 = this;
  const constr = self2.constructor;
  const proto = constr.prototype;
  const value2 = proto[property];
  const apply = function() {
    return value2.apply(apply, arguments);
  };
  Object.setPrototypeOf(apply, proto);
  return apply;
};

// node_modules/unified/lib/index.js
function assertParser(name2, value2) {
  if (typeof value2 !== "function") {
    throw new TypeError("Cannot `" + name2 + "` without `parser`");
  }
}
function assertCompiler(name2, value2) {
  if (typeof value2 !== "function") {
    throw new TypeError("Cannot `" + name2 + "` without `compiler`");
  }
}
function assertUnfrozen(name2, frozen) {
  if (frozen) {
    throw new Error("Cannot call `" + name2 + "` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.");
  }
}
function assertNode(node) {
  if (!isPlainObject3(node) || typeof node.type !== "string") {
    throw new TypeError("Expected node, got `" + node + "`");
  }
}
function assertDone(name2, asyncName, complete) {
  if (!complete) {
    throw new Error("`" + name2 + "` finished async. Use `" + asyncName + "` instead");
  }
}
function vfile(value2) {
  return looksLikeAVFile(value2) ? value2 : new VFile(value2);
}
function looksLikeAVFile(value2) {
  return Boolean(value2 && typeof value2 === "object" && "message" in value2 && "messages" in value2);
}
function looksLikeAValue(value2) {
  return typeof value2 === "string" || isUint8Array2(value2);
}
function isUint8Array2(value2) {
  return Boolean(value2 && typeof value2 === "object" && "byteLength" in value2 && "byteOffset" in value2);
}
var import_extend, own, Processor, unified;
var init_lib3 = __esm(() => {
  init_development();
  init_trough();
  init_vfile();
  import_extend = __toESM(require_extend(), 1);
  own = {}.hasOwnProperty;
  Processor = class Processor extends CallableInstance {
    constructor() {
      super("copy");
      this.Compiler = undefined;
      this.Parser = undefined;
      this.attachers = [];
      this.compiler = undefined;
      this.freezeIndex = -1;
      this.frozen = undefined;
      this.namespace = {};
      this.parser = undefined;
      this.transformers = trough();
    }
    copy() {
      const destination = new Processor;
      let index2 = -1;
      while (++index2 < this.attachers.length) {
        const attacher = this.attachers[index2];
        destination.use(...attacher);
      }
      destination.data(import_extend.default(true, {}, this.namespace));
      return destination;
    }
    data(key, value2) {
      if (typeof key === "string") {
        if (arguments.length === 2) {
          assertUnfrozen("data", this.frozen);
          this.namespace[key] = value2;
          return this;
        }
        return own.call(this.namespace, key) && this.namespace[key] || undefined;
      }
      if (key) {
        assertUnfrozen("data", this.frozen);
        this.namespace = key;
        return this;
      }
      return this.namespace;
    }
    freeze() {
      if (this.frozen) {
        return this;
      }
      const self2 = this;
      while (++this.freezeIndex < this.attachers.length) {
        const [attacher, ...options] = this.attachers[this.freezeIndex];
        if (options[0] === false) {
          continue;
        }
        if (options[0] === true) {
          options[0] = undefined;
        }
        const transformer2 = attacher.call(self2, ...options);
        if (typeof transformer2 === "function") {
          this.transformers.use(transformer2);
        }
      }
      this.frozen = true;
      this.freezeIndex = Number.POSITIVE_INFINITY;
      return this;
    }
    parse(file2) {
      this.freeze();
      const realFile = vfile(file2);
      const parser2 = this.parser || this.Parser;
      assertParser("parse", parser2);
      return parser2(String(realFile), realFile);
    }
    process(file2, done) {
      const self2 = this;
      this.freeze();
      assertParser("process", this.parser || this.Parser);
      assertCompiler("process", this.compiler || this.Compiler);
      return done ? executor(undefined, done) : new Promise(executor);
      function executor(resolve2, reject) {
        const realFile = vfile(file2);
        const parseTree = self2.parse(realFile);
        self2.run(parseTree, realFile, function(error49, tree, file3) {
          if (error49 || !tree || !file3) {
            return realDone(error49);
          }
          const compileTree = tree;
          const compileResult = self2.stringify(compileTree, file3);
          if (looksLikeAValue(compileResult)) {
            file3.value = compileResult;
          } else {
            file3.result = compileResult;
          }
          realDone(error49, file3);
        });
        function realDone(error49, file3) {
          if (error49 || !file3) {
            reject(error49);
          } else if (resolve2) {
            resolve2(file3);
          } else {
            ok(done, "`done` is defined if `resolve` is not");
            done(undefined, file3);
          }
        }
      }
    }
    processSync(file2) {
      let complete = false;
      let result;
      this.freeze();
      assertParser("processSync", this.parser || this.Parser);
      assertCompiler("processSync", this.compiler || this.Compiler);
      this.process(file2, realDone);
      assertDone("processSync", "process", complete);
      ok(result, "we either bailed on an error or have a tree");
      return result;
      function realDone(error49, file3) {
        complete = true;
        bail(error49);
        result = file3;
      }
    }
    run(tree, file2, done) {
      assertNode(tree);
      this.freeze();
      const transformers = this.transformers;
      if (!done && typeof file2 === "function") {
        done = file2;
        file2 = undefined;
      }
      return done ? executor(undefined, done) : new Promise(executor);
      function executor(resolve2, reject) {
        ok(typeof file2 !== "function", "`file` can’t be a `done` anymore, we checked");
        const realFile = vfile(file2);
        transformers.run(tree, realFile, realDone);
        function realDone(error49, outputTree, file3) {
          const resultingTree = outputTree || tree;
          if (error49) {
            reject(error49);
          } else if (resolve2) {
            resolve2(resultingTree);
          } else {
            ok(done, "`done` is defined if `resolve` is not");
            done(undefined, resultingTree, file3);
          }
        }
      }
    }
    runSync(tree, file2) {
      let complete = false;
      let result;
      this.run(tree, file2, realDone);
      assertDone("runSync", "run", complete);
      ok(result, "we either bailed on an error or have a tree");
      return result;
      function realDone(error49, tree2) {
        bail(error49);
        result = tree2;
        complete = true;
      }
    }
    stringify(tree, file2) {
      this.freeze();
      const realFile = vfile(file2);
      const compiler = this.compiler || this.Compiler;
      assertCompiler("stringify", compiler);
      assertNode(tree);
      return compiler(tree, realFile);
    }
    use(value2, ...parameters) {
      const attachers = this.attachers;
      const namespace = this.namespace;
      assertUnfrozen("use", this.frozen);
      if (value2 === null || value2 === undefined) {} else if (typeof value2 === "function") {
        addPlugin(value2, parameters);
      } else if (typeof value2 === "object") {
        if (Array.isArray(value2)) {
          addList(value2);
        } else {
          addPreset(value2);
        }
      } else {
        throw new TypeError("Expected usable value, not `" + value2 + "`");
      }
      return this;
      function add2(value3) {
        if (typeof value3 === "function") {
          addPlugin(value3, []);
        } else if (typeof value3 === "object") {
          if (Array.isArray(value3)) {
            const [plugin, ...parameters2] = value3;
            addPlugin(plugin, parameters2);
          } else {
            addPreset(value3);
          }
        } else {
          throw new TypeError("Expected usable value, not `" + value3 + "`");
        }
      }
      function addPreset(result) {
        if (!("plugins" in result) && !("settings" in result)) {
          throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");
        }
        addList(result.plugins);
        if (result.settings) {
          namespace.settings = import_extend.default(true, namespace.settings, result.settings);
        }
      }
      function addList(plugins) {
        let index2 = -1;
        if (plugins === null || plugins === undefined) {} else if (Array.isArray(plugins)) {
          while (++index2 < plugins.length) {
            const thing = plugins[index2];
            add2(thing);
          }
        } else {
          throw new TypeError("Expected a list of plugins, not `" + plugins + "`");
        }
      }
      function addPlugin(plugin, parameters2) {
        let index2 = -1;
        let entryIndex = -1;
        while (++index2 < attachers.length) {
          if (attachers[index2][0] === plugin) {
            entryIndex = index2;
            break;
          }
        }
        if (entryIndex === -1) {
          attachers.push([plugin, ...parameters2]);
        } else if (parameters2.length > 0) {
          let [primary, ...rest2] = parameters2;
          const currentPrimary = attachers[entryIndex][1];
          if (isPlainObject3(currentPrimary) && isPlainObject3(primary)) {
            primary = import_extend.default(true, currentPrimary, primary);
          }
          attachers[entryIndex] = [plugin, primary, ...rest2];
        }
      }
    }
  };
  unified = new Processor().freeze();
});

// node_modules/unified/index.js
var init_unified = __esm(() => {
  init_lib3();
});

// node_modules/mdast-util-to-string/lib/index.js
function toString(value2, options) {
  const settings = options || emptyOptions;
  const includeImageAlt = typeof settings.includeImageAlt === "boolean" ? settings.includeImageAlt : true;
  const includeHtml = typeof settings.includeHtml === "boolean" ? settings.includeHtml : true;
  return one2(value2, includeImageAlt, includeHtml);
}
function one2(value2, includeImageAlt, includeHtml) {
  if (node(value2)) {
    if ("value" in value2) {
      return value2.type === "html" && !includeHtml ? "" : value2.value;
    }
    if (includeImageAlt && "alt" in value2 && value2.alt) {
      return value2.alt;
    }
    if ("children" in value2) {
      return all2(value2.children, includeImageAlt, includeHtml);
    }
  }
  if (Array.isArray(value2)) {
    return all2(value2, includeImageAlt, includeHtml);
  }
  return "";
}
function all2(values, includeImageAlt, includeHtml) {
  const result = [];
  let index2 = -1;
  while (++index2 < values.length) {
    result[index2] = one2(values[index2], includeImageAlt, includeHtml);
  }
  return result.join("");
}
function node(value2) {
  return Boolean(value2 && typeof value2 === "object");
}
var emptyOptions;
var init_lib4 = __esm(() => {
  emptyOptions = {};
});

// node_modules/mdast-util-to-string/index.js
var init_mdast_util_to_string = __esm(() => {
  init_lib4();
});

// node_modules/character-entities/index.js
var characterEntities;
var init_character_entities = __esm(() => {
  characterEntities = {
    AElig: "Æ",
    AMP: "&",
    Aacute: "Á",
    Abreve: "Ă",
    Acirc: "Â",
    Acy: "А",
    Afr: "\uD835\uDD04",
    Agrave: "À",
    Alpha: "Α",
    Amacr: "Ā",
    And: "⩓",
    Aogon: "Ą",
    Aopf: "\uD835\uDD38",
    ApplyFunction: "⁡",
    Aring: "Å",
    Ascr: "\uD835\uDC9C",
    Assign: "≔",
    Atilde: "Ã",
    Auml: "Ä",
    Backslash: "∖",
    Barv: "⫧",
    Barwed: "⌆",
    Bcy: "Б",
    Because: "∵",
    Bernoullis: "ℬ",
    Beta: "Β",
    Bfr: "\uD835\uDD05",
    Bopf: "\uD835\uDD39",
    Breve: "˘",
    Bscr: "ℬ",
    Bumpeq: "≎",
    CHcy: "Ч",
    COPY: "©",
    Cacute: "Ć",
    Cap: "⋒",
    CapitalDifferentialD: "ⅅ",
    Cayleys: "ℭ",
    Ccaron: "Č",
    Ccedil: "Ç",
    Ccirc: "Ĉ",
    Cconint: "∰",
    Cdot: "Ċ",
    Cedilla: "¸",
    CenterDot: "·",
    Cfr: "ℭ",
    Chi: "Χ",
    CircleDot: "⊙",
    CircleMinus: "⊖",
    CirclePlus: "⊕",
    CircleTimes: "⊗",
    ClockwiseContourIntegral: "∲",
    CloseCurlyDoubleQuote: "”",
    CloseCurlyQuote: "’",
    Colon: "∷",
    Colone: "⩴",
    Congruent: "≡",
    Conint: "∯",
    ContourIntegral: "∮",
    Copf: "ℂ",
    Coproduct: "∐",
    CounterClockwiseContourIntegral: "∳",
    Cross: "⨯",
    Cscr: "\uD835\uDC9E",
    Cup: "⋓",
    CupCap: "≍",
    DD: "ⅅ",
    DDotrahd: "⤑",
    DJcy: "Ђ",
    DScy: "Ѕ",
    DZcy: "Џ",
    Dagger: "‡",
    Darr: "↡",
    Dashv: "⫤",
    Dcaron: "Ď",
    Dcy: "Д",
    Del: "∇",
    Delta: "Δ",
    Dfr: "\uD835\uDD07",
    DiacriticalAcute: "´",
    DiacriticalDot: "˙",
    DiacriticalDoubleAcute: "˝",
    DiacriticalGrave: "`",
    DiacriticalTilde: "˜",
    Diamond: "⋄",
    DifferentialD: "ⅆ",
    Dopf: "\uD835\uDD3B",
    Dot: "¨",
    DotDot: "⃜",
    DotEqual: "≐",
    DoubleContourIntegral: "∯",
    DoubleDot: "¨",
    DoubleDownArrow: "⇓",
    DoubleLeftArrow: "⇐",
    DoubleLeftRightArrow: "⇔",
    DoubleLeftTee: "⫤",
    DoubleLongLeftArrow: "⟸",
    DoubleLongLeftRightArrow: "⟺",
    DoubleLongRightArrow: "⟹",
    DoubleRightArrow: "⇒",
    DoubleRightTee: "⊨",
    DoubleUpArrow: "⇑",
    DoubleUpDownArrow: "⇕",
    DoubleVerticalBar: "∥",
    DownArrow: "↓",
    DownArrowBar: "⤓",
    DownArrowUpArrow: "⇵",
    DownBreve: "̑",
    DownLeftRightVector: "⥐",
    DownLeftTeeVector: "⥞",
    DownLeftVector: "↽",
    DownLeftVectorBar: "⥖",
    DownRightTeeVector: "⥟",
    DownRightVector: "⇁",
    DownRightVectorBar: "⥗",
    DownTee: "⊤",
    DownTeeArrow: "↧",
    Downarrow: "⇓",
    Dscr: "\uD835\uDC9F",
    Dstrok: "Đ",
    ENG: "Ŋ",
    ETH: "Ð",
    Eacute: "É",
    Ecaron: "Ě",
    Ecirc: "Ê",
    Ecy: "Э",
    Edot: "Ė",
    Efr: "\uD835\uDD08",
    Egrave: "È",
    Element: "∈",
    Emacr: "Ē",
    EmptySmallSquare: "◻",
    EmptyVerySmallSquare: "▫",
    Eogon: "Ę",
    Eopf: "\uD835\uDD3C",
    Epsilon: "Ε",
    Equal: "⩵",
    EqualTilde: "≂",
    Equilibrium: "⇌",
    Escr: "ℰ",
    Esim: "⩳",
    Eta: "Η",
    Euml: "Ë",
    Exists: "∃",
    ExponentialE: "ⅇ",
    Fcy: "Ф",
    Ffr: "\uD835\uDD09",
    FilledSmallSquare: "◼",
    FilledVerySmallSquare: "▪",
    Fopf: "\uD835\uDD3D",
    ForAll: "∀",
    Fouriertrf: "ℱ",
    Fscr: "ℱ",
    GJcy: "Ѓ",
    GT: ">",
    Gamma: "Γ",
    Gammad: "Ϝ",
    Gbreve: "Ğ",
    Gcedil: "Ģ",
    Gcirc: "Ĝ",
    Gcy: "Г",
    Gdot: "Ġ",
    Gfr: "\uD835\uDD0A",
    Gg: "⋙",
    Gopf: "\uD835\uDD3E",
    GreaterEqual: "≥",
    GreaterEqualLess: "⋛",
    GreaterFullEqual: "≧",
    GreaterGreater: "⪢",
    GreaterLess: "≷",
    GreaterSlantEqual: "⩾",
    GreaterTilde: "≳",
    Gscr: "\uD835\uDCA2",
    Gt: "≫",
    HARDcy: "Ъ",
    Hacek: "ˇ",
    Hat: "^",
    Hcirc: "Ĥ",
    Hfr: "ℌ",
    HilbertSpace: "ℋ",
    Hopf: "ℍ",
    HorizontalLine: "─",
    Hscr: "ℋ",
    Hstrok: "Ħ",
    HumpDownHump: "≎",
    HumpEqual: "≏",
    IEcy: "Е",
    IJlig: "Ĳ",
    IOcy: "Ё",
    Iacute: "Í",
    Icirc: "Î",
    Icy: "И",
    Idot: "İ",
    Ifr: "ℑ",
    Igrave: "Ì",
    Im: "ℑ",
    Imacr: "Ī",
    ImaginaryI: "ⅈ",
    Implies: "⇒",
    Int: "∬",
    Integral: "∫",
    Intersection: "⋂",
    InvisibleComma: "⁣",
    InvisibleTimes: "⁢",
    Iogon: "Į",
    Iopf: "\uD835\uDD40",
    Iota: "Ι",
    Iscr: "ℐ",
    Itilde: "Ĩ",
    Iukcy: "І",
    Iuml: "Ï",
    Jcirc: "Ĵ",
    Jcy: "Й",
    Jfr: "\uD835\uDD0D",
    Jopf: "\uD835\uDD41",
    Jscr: "\uD835\uDCA5",
    Jsercy: "Ј",
    Jukcy: "Є",
    KHcy: "Х",
    KJcy: "Ќ",
    Kappa: "Κ",
    Kcedil: "Ķ",
    Kcy: "К",
    Kfr: "\uD835\uDD0E",
    Kopf: "\uD835\uDD42",
    Kscr: "\uD835\uDCA6",
    LJcy: "Љ",
    LT: "<",
    Lacute: "Ĺ",
    Lambda: "Λ",
    Lang: "⟪",
    Laplacetrf: "ℒ",
    Larr: "↞",
    Lcaron: "Ľ",
    Lcedil: "Ļ",
    Lcy: "Л",
    LeftAngleBracket: "⟨",
    LeftArrow: "←",
    LeftArrowBar: "⇤",
    LeftArrowRightArrow: "⇆",
    LeftCeiling: "⌈",
    LeftDoubleBracket: "⟦",
    LeftDownTeeVector: "⥡",
    LeftDownVector: "⇃",
    LeftDownVectorBar: "⥙",
    LeftFloor: "⌊",
    LeftRightArrow: "↔",
    LeftRightVector: "⥎",
    LeftTee: "⊣",
    LeftTeeArrow: "↤",
    LeftTeeVector: "⥚",
    LeftTriangle: "⊲",
    LeftTriangleBar: "⧏",
    LeftTriangleEqual: "⊴",
    LeftUpDownVector: "⥑",
    LeftUpTeeVector: "⥠",
    LeftUpVector: "↿",
    LeftUpVectorBar: "⥘",
    LeftVector: "↼",
    LeftVectorBar: "⥒",
    Leftarrow: "⇐",
    Leftrightarrow: "⇔",
    LessEqualGreater: "⋚",
    LessFullEqual: "≦",
    LessGreater: "≶",
    LessLess: "⪡",
    LessSlantEqual: "⩽",
    LessTilde: "≲",
    Lfr: "\uD835\uDD0F",
    Ll: "⋘",
    Lleftarrow: "⇚",
    Lmidot: "Ŀ",
    LongLeftArrow: "⟵",
    LongLeftRightArrow: "⟷",
    LongRightArrow: "⟶",
    Longleftarrow: "⟸",
    Longleftrightarrow: "⟺",
    Longrightarrow: "⟹",
    Lopf: "\uD835\uDD43",
    LowerLeftArrow: "↙",
    LowerRightArrow: "↘",
    Lscr: "ℒ",
    Lsh: "↰",
    Lstrok: "Ł",
    Lt: "≪",
    Map: "⤅",
    Mcy: "М",
    MediumSpace: " ",
    Mellintrf: "ℳ",
    Mfr: "\uD835\uDD10",
    MinusPlus: "∓",
    Mopf: "\uD835\uDD44",
    Mscr: "ℳ",
    Mu: "Μ",
    NJcy: "Њ",
    Nacute: "Ń",
    Ncaron: "Ň",
    Ncedil: "Ņ",
    Ncy: "Н",
    NegativeMediumSpace: "​",
    NegativeThickSpace: "​",
    NegativeThinSpace: "​",
    NegativeVeryThinSpace: "​",
    NestedGreaterGreater: "≫",
    NestedLessLess: "≪",
    NewLine: `
`,
    Nfr: "\uD835\uDD11",
    NoBreak: "⁠",
    NonBreakingSpace: " ",
    Nopf: "ℕ",
    Not: "⫬",
    NotCongruent: "≢",
    NotCupCap: "≭",
    NotDoubleVerticalBar: "∦",
    NotElement: "∉",
    NotEqual: "≠",
    NotEqualTilde: "≂̸",
    NotExists: "∄",
    NotGreater: "≯",
    NotGreaterEqual: "≱",
    NotGreaterFullEqual: "≧̸",
    NotGreaterGreater: "≫̸",
    NotGreaterLess: "≹",
    NotGreaterSlantEqual: "⩾̸",
    NotGreaterTilde: "≵",
    NotHumpDownHump: "≎̸",
    NotHumpEqual: "≏̸",
    NotLeftTriangle: "⋪",
    NotLeftTriangleBar: "⧏̸",
    NotLeftTriangleEqual: "⋬",
    NotLess: "≮",
    NotLessEqual: "≰",
    NotLessGreater: "≸",
    NotLessLess: "≪̸",
    NotLessSlantEqual: "⩽̸",
    NotLessTilde: "≴",
    NotNestedGreaterGreater: "⪢̸",
    NotNestedLessLess: "⪡̸",
    NotPrecedes: "⊀",
    NotPrecedesEqual: "⪯̸",
    NotPrecedesSlantEqual: "⋠",
    NotReverseElement: "∌",
    NotRightTriangle: "⋫",
    NotRightTriangleBar: "⧐̸",
    NotRightTriangleEqual: "⋭",
    NotSquareSubset: "⊏̸",
    NotSquareSubsetEqual: "⋢",
    NotSquareSuperset: "⊐̸",
    NotSquareSupersetEqual: "⋣",
    NotSubset: "⊂⃒",
    NotSubsetEqual: "⊈",
    NotSucceeds: "⊁",
    NotSucceedsEqual: "⪰̸",
    NotSucceedsSlantEqual: "⋡",
    NotSucceedsTilde: "≿̸",
    NotSuperset: "⊃⃒",
    NotSupersetEqual: "⊉",
    NotTilde: "≁",
    NotTildeEqual: "≄",
    NotTildeFullEqual: "≇",
    NotTildeTilde: "≉",
    NotVerticalBar: "∤",
    Nscr: "\uD835\uDCA9",
    Ntilde: "Ñ",
    Nu: "Ν",
    OElig: "Œ",
    Oacute: "Ó",
    Ocirc: "Ô",
    Ocy: "О",
    Odblac: "Ő",
    Ofr: "\uD835\uDD12",
    Ograve: "Ò",
    Omacr: "Ō",
    Omega: "Ω",
    Omicron: "Ο",
    Oopf: "\uD835\uDD46",
    OpenCurlyDoubleQuote: "“",
    OpenCurlyQuote: "‘",
    Or: "⩔",
    Oscr: "\uD835\uDCAA",
    Oslash: "Ø",
    Otilde: "Õ",
    Otimes: "⨷",
    Ouml: "Ö",
    OverBar: "‾",
    OverBrace: "⏞",
    OverBracket: "⎴",
    OverParenthesis: "⏜",
    PartialD: "∂",
    Pcy: "П",
    Pfr: "\uD835\uDD13",
    Phi: "Φ",
    Pi: "Π",
    PlusMinus: "±",
    Poincareplane: "ℌ",
    Popf: "ℙ",
    Pr: "⪻",
    Precedes: "≺",
    PrecedesEqual: "⪯",
    PrecedesSlantEqual: "≼",
    PrecedesTilde: "≾",
    Prime: "″",
    Product: "∏",
    Proportion: "∷",
    Proportional: "∝",
    Pscr: "\uD835\uDCAB",
    Psi: "Ψ",
    QUOT: '"',
    Qfr: "\uD835\uDD14",
    Qopf: "ℚ",
    Qscr: "\uD835\uDCAC",
    RBarr: "⤐",
    REG: "®",
    Racute: "Ŕ",
    Rang: "⟫",
    Rarr: "↠",
    Rarrtl: "⤖",
    Rcaron: "Ř",
    Rcedil: "Ŗ",
    Rcy: "Р",
    Re: "ℜ",
    ReverseElement: "∋",
    ReverseEquilibrium: "⇋",
    ReverseUpEquilibrium: "⥯",
    Rfr: "ℜ",
    Rho: "Ρ",
    RightAngleBracket: "⟩",
    RightArrow: "→",
    RightArrowBar: "⇥",
    RightArrowLeftArrow: "⇄",
    RightCeiling: "⌉",
    RightDoubleBracket: "⟧",
    RightDownTeeVector: "⥝",
    RightDownVector: "⇂",
    RightDownVectorBar: "⥕",
    RightFloor: "⌋",
    RightTee: "⊢",
    RightTeeArrow: "↦",
    RightTeeVector: "⥛",
    RightTriangle: "⊳",
    RightTriangleBar: "⧐",
    RightTriangleEqual: "⊵",
    RightUpDownVector: "⥏",
    RightUpTeeVector: "⥜",
    RightUpVector: "↾",
    RightUpVectorBar: "⥔",
    RightVector: "⇀",
    RightVectorBar: "⥓",
    Rightarrow: "⇒",
    Ropf: "ℝ",
    RoundImplies: "⥰",
    Rrightarrow: "⇛",
    Rscr: "ℛ",
    Rsh: "↱",
    RuleDelayed: "⧴",
    SHCHcy: "Щ",
    SHcy: "Ш",
    SOFTcy: "Ь",
    Sacute: "Ś",
    Sc: "⪼",
    Scaron: "Š",
    Scedil: "Ş",
    Scirc: "Ŝ",
    Scy: "С",
    Sfr: "\uD835\uDD16",
    ShortDownArrow: "↓",
    ShortLeftArrow: "←",
    ShortRightArrow: "→",
    ShortUpArrow: "↑",
    Sigma: "Σ",
    SmallCircle: "∘",
    Sopf: "\uD835\uDD4A",
    Sqrt: "√",
    Square: "□",
    SquareIntersection: "⊓",
    SquareSubset: "⊏",
    SquareSubsetEqual: "⊑",
    SquareSuperset: "⊐",
    SquareSupersetEqual: "⊒",
    SquareUnion: "⊔",
    Sscr: "\uD835\uDCAE",
    Star: "⋆",
    Sub: "⋐",
    Subset: "⋐",
    SubsetEqual: "⊆",
    Succeeds: "≻",
    SucceedsEqual: "⪰",
    SucceedsSlantEqual: "≽",
    SucceedsTilde: "≿",
    SuchThat: "∋",
    Sum: "∑",
    Sup: "⋑",
    Superset: "⊃",
    SupersetEqual: "⊇",
    Supset: "⋑",
    THORN: "Þ",
    TRADE: "™",
    TSHcy: "Ћ",
    TScy: "Ц",
    Tab: "\t",
    Tau: "Τ",
    Tcaron: "Ť",
    Tcedil: "Ţ",
    Tcy: "Т",
    Tfr: "\uD835\uDD17",
    Therefore: "∴",
    Theta: "Θ",
    ThickSpace: "  ",
    ThinSpace: " ",
    Tilde: "∼",
    TildeEqual: "≃",
    TildeFullEqual: "≅",
    TildeTilde: "≈",
    Topf: "\uD835\uDD4B",
    TripleDot: "⃛",
    Tscr: "\uD835\uDCAF",
    Tstrok: "Ŧ",
    Uacute: "Ú",
    Uarr: "↟",
    Uarrocir: "⥉",
    Ubrcy: "Ў",
    Ubreve: "Ŭ",
    Ucirc: "Û",
    Ucy: "У",
    Udblac: "Ű",
    Ufr: "\uD835\uDD18",
    Ugrave: "Ù",
    Umacr: "Ū",
    UnderBar: "_",
    UnderBrace: "⏟",
    UnderBracket: "⎵",
    UnderParenthesis: "⏝",
    Union: "⋃",
    UnionPlus: "⊎",
    Uogon: "Ų",
    Uopf: "\uD835\uDD4C",
    UpArrow: "↑",
    UpArrowBar: "⤒",
    UpArrowDownArrow: "⇅",
    UpDownArrow: "↕",
    UpEquilibrium: "⥮",
    UpTee: "⊥",
    UpTeeArrow: "↥",
    Uparrow: "⇑",
    Updownarrow: "⇕",
    UpperLeftArrow: "↖",
    UpperRightArrow: "↗",
    Upsi: "ϒ",
    Upsilon: "Υ",
    Uring: "Ů",
    Uscr: "\uD835\uDCB0",
    Utilde: "Ũ",
    Uuml: "Ü",
    VDash: "⊫",
    Vbar: "⫫",
    Vcy: "В",
    Vdash: "⊩",
    Vdashl: "⫦",
    Vee: "⋁",
    Verbar: "‖",
    Vert: "‖",
    VerticalBar: "∣",
    VerticalLine: "|",
    VerticalSeparator: "❘",
    VerticalTilde: "≀",
    VeryThinSpace: " ",
    Vfr: "\uD835\uDD19",
    Vopf: "\uD835\uDD4D",
    Vscr: "\uD835\uDCB1",
    Vvdash: "⊪",
    Wcirc: "Ŵ",
    Wedge: "⋀",
    Wfr: "\uD835\uDD1A",
    Wopf: "\uD835\uDD4E",
    Wscr: "\uD835\uDCB2",
    Xfr: "\uD835\uDD1B",
    Xi: "Ξ",
    Xopf: "\uD835\uDD4F",
    Xscr: "\uD835\uDCB3",
    YAcy: "Я",
    YIcy: "Ї",
    YUcy: "Ю",
    Yacute: "Ý",
    Ycirc: "Ŷ",
    Ycy: "Ы",
    Yfr: "\uD835\uDD1C",
    Yopf: "\uD835\uDD50",
    Yscr: "\uD835\uDCB4",
    Yuml: "Ÿ",
    ZHcy: "Ж",
    Zacute: "Ź",
    Zcaron: "Ž",
    Zcy: "З",
    Zdot: "Ż",
    ZeroWidthSpace: "​",
    Zeta: "Ζ",
    Zfr: "ℨ",
    Zopf: "ℤ",
    Zscr: "\uD835\uDCB5",
    aacute: "á",
    abreve: "ă",
    ac: "∾",
    acE: "∾̳",
    acd: "∿",
    acirc: "â",
    acute: "´",
    acy: "а",
    aelig: "æ",
    af: "⁡",
    afr: "\uD835\uDD1E",
    agrave: "à",
    alefsym: "ℵ",
    aleph: "ℵ",
    alpha: "α",
    amacr: "ā",
    amalg: "⨿",
    amp: "&",
    and: "∧",
    andand: "⩕",
    andd: "⩜",
    andslope: "⩘",
    andv: "⩚",
    ang: "∠",
    ange: "⦤",
    angle: "∠",
    angmsd: "∡",
    angmsdaa: "⦨",
    angmsdab: "⦩",
    angmsdac: "⦪",
    angmsdad: "⦫",
    angmsdae: "⦬",
    angmsdaf: "⦭",
    angmsdag: "⦮",
    angmsdah: "⦯",
    angrt: "∟",
    angrtvb: "⊾",
    angrtvbd: "⦝",
    angsph: "∢",
    angst: "Å",
    angzarr: "⍼",
    aogon: "ą",
    aopf: "\uD835\uDD52",
    ap: "≈",
    apE: "⩰",
    apacir: "⩯",
    ape: "≊",
    apid: "≋",
    apos: "'",
    approx: "≈",
    approxeq: "≊",
    aring: "å",
    ascr: "\uD835\uDCB6",
    ast: "*",
    asymp: "≈",
    asympeq: "≍",
    atilde: "ã",
    auml: "ä",
    awconint: "∳",
    awint: "⨑",
    bNot: "⫭",
    backcong: "≌",
    backepsilon: "϶",
    backprime: "‵",
    backsim: "∽",
    backsimeq: "⋍",
    barvee: "⊽",
    barwed: "⌅",
    barwedge: "⌅",
    bbrk: "⎵",
    bbrktbrk: "⎶",
    bcong: "≌",
    bcy: "б",
    bdquo: "„",
    becaus: "∵",
    because: "∵",
    bemptyv: "⦰",
    bepsi: "϶",
    bernou: "ℬ",
    beta: "β",
    beth: "ℶ",
    between: "≬",
    bfr: "\uD835\uDD1F",
    bigcap: "⋂",
    bigcirc: "◯",
    bigcup: "⋃",
    bigodot: "⨀",
    bigoplus: "⨁",
    bigotimes: "⨂",
    bigsqcup: "⨆",
    bigstar: "★",
    bigtriangledown: "▽",
    bigtriangleup: "△",
    biguplus: "⨄",
    bigvee: "⋁",
    bigwedge: "⋀",
    bkarow: "⤍",
    blacklozenge: "⧫",
    blacksquare: "▪",
    blacktriangle: "▴",
    blacktriangledown: "▾",
    blacktriangleleft: "◂",
    blacktriangleright: "▸",
    blank: "␣",
    blk12: "▒",
    blk14: "░",
    blk34: "▓",
    block: "█",
    bne: "=⃥",
    bnequiv: "≡⃥",
    bnot: "⌐",
    bopf: "\uD835\uDD53",
    bot: "⊥",
    bottom: "⊥",
    bowtie: "⋈",
    boxDL: "╗",
    boxDR: "╔",
    boxDl: "╖",
    boxDr: "╓",
    boxH: "═",
    boxHD: "╦",
    boxHU: "╩",
    boxHd: "╤",
    boxHu: "╧",
    boxUL: "╝",
    boxUR: "╚",
    boxUl: "╜",
    boxUr: "╙",
    boxV: "║",
    boxVH: "╬",
    boxVL: "╣",
    boxVR: "╠",
    boxVh: "╫",
    boxVl: "╢",
    boxVr: "╟",
    boxbox: "⧉",
    boxdL: "╕",
    boxdR: "╒",
    boxdl: "┐",
    boxdr: "┌",
    boxh: "─",
    boxhD: "╥",
    boxhU: "╨",
    boxhd: "┬",
    boxhu: "┴",
    boxminus: "⊟",
    boxplus: "⊞",
    boxtimes: "⊠",
    boxuL: "╛",
    boxuR: "╘",
    boxul: "┘",
    boxur: "└",
    boxv: "│",
    boxvH: "╪",
    boxvL: "╡",
    boxvR: "╞",
    boxvh: "┼",
    boxvl: "┤",
    boxvr: "├",
    bprime: "‵",
    breve: "˘",
    brvbar: "¦",
    bscr: "\uD835\uDCB7",
    bsemi: "⁏",
    bsim: "∽",
    bsime: "⋍",
    bsol: "\\",
    bsolb: "⧅",
    bsolhsub: "⟈",
    bull: "•",
    bullet: "•",
    bump: "≎",
    bumpE: "⪮",
    bumpe: "≏",
    bumpeq: "≏",
    cacute: "ć",
    cap: "∩",
    capand: "⩄",
    capbrcup: "⩉",
    capcap: "⩋",
    capcup: "⩇",
    capdot: "⩀",
    caps: "∩︀",
    caret: "⁁",
    caron: "ˇ",
    ccaps: "⩍",
    ccaron: "č",
    ccedil: "ç",
    ccirc: "ĉ",
    ccups: "⩌",
    ccupssm: "⩐",
    cdot: "ċ",
    cedil: "¸",
    cemptyv: "⦲",
    cent: "¢",
    centerdot: "·",
    cfr: "\uD835\uDD20",
    chcy: "ч",
    check: "✓",
    checkmark: "✓",
    chi: "χ",
    cir: "○",
    cirE: "⧃",
    circ: "ˆ",
    circeq: "≗",
    circlearrowleft: "↺",
    circlearrowright: "↻",
    circledR: "®",
    circledS: "Ⓢ",
    circledast: "⊛",
    circledcirc: "⊚",
    circleddash: "⊝",
    cire: "≗",
    cirfnint: "⨐",
    cirmid: "⫯",
    cirscir: "⧂",
    clubs: "♣",
    clubsuit: "♣",
    colon: ":",
    colone: "≔",
    coloneq: "≔",
    comma: ",",
    commat: "@",
    comp: "∁",
    compfn: "∘",
    complement: "∁",
    complexes: "ℂ",
    cong: "≅",
    congdot: "⩭",
    conint: "∮",
    copf: "\uD835\uDD54",
    coprod: "∐",
    copy: "©",
    copysr: "℗",
    crarr: "↵",
    cross: "✗",
    cscr: "\uD835\uDCB8",
    csub: "⫏",
    csube: "⫑",
    csup: "⫐",
    csupe: "⫒",
    ctdot: "⋯",
    cudarrl: "⤸",
    cudarrr: "⤵",
    cuepr: "⋞",
    cuesc: "⋟",
    cularr: "↶",
    cularrp: "⤽",
    cup: "∪",
    cupbrcap: "⩈",
    cupcap: "⩆",
    cupcup: "⩊",
    cupdot: "⊍",
    cupor: "⩅",
    cups: "∪︀",
    curarr: "↷",
    curarrm: "⤼",
    curlyeqprec: "⋞",
    curlyeqsucc: "⋟",
    curlyvee: "⋎",
    curlywedge: "⋏",
    curren: "¤",
    curvearrowleft: "↶",
    curvearrowright: "↷",
    cuvee: "⋎",
    cuwed: "⋏",
    cwconint: "∲",
    cwint: "∱",
    cylcty: "⌭",
    dArr: "⇓",
    dHar: "⥥",
    dagger: "†",
    daleth: "ℸ",
    darr: "↓",
    dash: "‐",
    dashv: "⊣",
    dbkarow: "⤏",
    dblac: "˝",
    dcaron: "ď",
    dcy: "д",
    dd: "ⅆ",
    ddagger: "‡",
    ddarr: "⇊",
    ddotseq: "⩷",
    deg: "°",
    delta: "δ",
    demptyv: "⦱",
    dfisht: "⥿",
    dfr: "\uD835\uDD21",
    dharl: "⇃",
    dharr: "⇂",
    diam: "⋄",
    diamond: "⋄",
    diamondsuit: "♦",
    diams: "♦",
    die: "¨",
    digamma: "ϝ",
    disin: "⋲",
    div: "÷",
    divide: "÷",
    divideontimes: "⋇",
    divonx: "⋇",
    djcy: "ђ",
    dlcorn: "⌞",
    dlcrop: "⌍",
    dollar: "$",
    dopf: "\uD835\uDD55",
    dot: "˙",
    doteq: "≐",
    doteqdot: "≑",
    dotminus: "∸",
    dotplus: "∔",
    dotsquare: "⊡",
    doublebarwedge: "⌆",
    downarrow: "↓",
    downdownarrows: "⇊",
    downharpoonleft: "⇃",
    downharpoonright: "⇂",
    drbkarow: "⤐",
    drcorn: "⌟",
    drcrop: "⌌",
    dscr: "\uD835\uDCB9",
    dscy: "ѕ",
    dsol: "⧶",
    dstrok: "đ",
    dtdot: "⋱",
    dtri: "▿",
    dtrif: "▾",
    duarr: "⇵",
    duhar: "⥯",
    dwangle: "⦦",
    dzcy: "џ",
    dzigrarr: "⟿",
    eDDot: "⩷",
    eDot: "≑",
    eacute: "é",
    easter: "⩮",
    ecaron: "ě",
    ecir: "≖",
    ecirc: "ê",
    ecolon: "≕",
    ecy: "э",
    edot: "ė",
    ee: "ⅇ",
    efDot: "≒",
    efr: "\uD835\uDD22",
    eg: "⪚",
    egrave: "è",
    egs: "⪖",
    egsdot: "⪘",
    el: "⪙",
    elinters: "⏧",
    ell: "ℓ",
    els: "⪕",
    elsdot: "⪗",
    emacr: "ē",
    empty: "∅",
    emptyset: "∅",
    emptyv: "∅",
    emsp13: " ",
    emsp14: " ",
    emsp: " ",
    eng: "ŋ",
    ensp: " ",
    eogon: "ę",
    eopf: "\uD835\uDD56",
    epar: "⋕",
    eparsl: "⧣",
    eplus: "⩱",
    epsi: "ε",
    epsilon: "ε",
    epsiv: "ϵ",
    eqcirc: "≖",
    eqcolon: "≕",
    eqsim: "≂",
    eqslantgtr: "⪖",
    eqslantless: "⪕",
    equals: "=",
    equest: "≟",
    equiv: "≡",
    equivDD: "⩸",
    eqvparsl: "⧥",
    erDot: "≓",
    erarr: "⥱",
    escr: "ℯ",
    esdot: "≐",
    esim: "≂",
    eta: "η",
    eth: "ð",
    euml: "ë",
    euro: "€",
    excl: "!",
    exist: "∃",
    expectation: "ℰ",
    exponentiale: "ⅇ",
    fallingdotseq: "≒",
    fcy: "ф",
    female: "♀",
    ffilig: "ﬃ",
    fflig: "ﬀ",
    ffllig: "ﬄ",
    ffr: "\uD835\uDD23",
    filig: "ﬁ",
    fjlig: "fj",
    flat: "♭",
    fllig: "ﬂ",
    fltns: "▱",
    fnof: "ƒ",
    fopf: "\uD835\uDD57",
    forall: "∀",
    fork: "⋔",
    forkv: "⫙",
    fpartint: "⨍",
    frac12: "½",
    frac13: "⅓",
    frac14: "¼",
    frac15: "⅕",
    frac16: "⅙",
    frac18: "⅛",
    frac23: "⅔",
    frac25: "⅖",
    frac34: "¾",
    frac35: "⅗",
    frac38: "⅜",
    frac45: "⅘",
    frac56: "⅚",
    frac58: "⅝",
    frac78: "⅞",
    frasl: "⁄",
    frown: "⌢",
    fscr: "\uD835\uDCBB",
    gE: "≧",
    gEl: "⪌",
    gacute: "ǵ",
    gamma: "γ",
    gammad: "ϝ",
    gap: "⪆",
    gbreve: "ğ",
    gcirc: "ĝ",
    gcy: "г",
    gdot: "ġ",
    ge: "≥",
    gel: "⋛",
    geq: "≥",
    geqq: "≧",
    geqslant: "⩾",
    ges: "⩾",
    gescc: "⪩",
    gesdot: "⪀",
    gesdoto: "⪂",
    gesdotol: "⪄",
    gesl: "⋛︀",
    gesles: "⪔",
    gfr: "\uD835\uDD24",
    gg: "≫",
    ggg: "⋙",
    gimel: "ℷ",
    gjcy: "ѓ",
    gl: "≷",
    glE: "⪒",
    gla: "⪥",
    glj: "⪤",
    gnE: "≩",
    gnap: "⪊",
    gnapprox: "⪊",
    gne: "⪈",
    gneq: "⪈",
    gneqq: "≩",
    gnsim: "⋧",
    gopf: "\uD835\uDD58",
    grave: "`",
    gscr: "ℊ",
    gsim: "≳",
    gsime: "⪎",
    gsiml: "⪐",
    gt: ">",
    gtcc: "⪧",
    gtcir: "⩺",
    gtdot: "⋗",
    gtlPar: "⦕",
    gtquest: "⩼",
    gtrapprox: "⪆",
    gtrarr: "⥸",
    gtrdot: "⋗",
    gtreqless: "⋛",
    gtreqqless: "⪌",
    gtrless: "≷",
    gtrsim: "≳",
    gvertneqq: "≩︀",
    gvnE: "≩︀",
    hArr: "⇔",
    hairsp: " ",
    half: "½",
    hamilt: "ℋ",
    hardcy: "ъ",
    harr: "↔",
    harrcir: "⥈",
    harrw: "↭",
    hbar: "ℏ",
    hcirc: "ĥ",
    hearts: "♥",
    heartsuit: "♥",
    hellip: "…",
    hercon: "⊹",
    hfr: "\uD835\uDD25",
    hksearow: "⤥",
    hkswarow: "⤦",
    hoarr: "⇿",
    homtht: "∻",
    hookleftarrow: "↩",
    hookrightarrow: "↪",
    hopf: "\uD835\uDD59",
    horbar: "―",
    hscr: "\uD835\uDCBD",
    hslash: "ℏ",
    hstrok: "ħ",
    hybull: "⁃",
    hyphen: "‐",
    iacute: "í",
    ic: "⁣",
    icirc: "î",
    icy: "и",
    iecy: "е",
    iexcl: "¡",
    iff: "⇔",
    ifr: "\uD835\uDD26",
    igrave: "ì",
    ii: "ⅈ",
    iiiint: "⨌",
    iiint: "∭",
    iinfin: "⧜",
    iiota: "℩",
    ijlig: "ĳ",
    imacr: "ī",
    image: "ℑ",
    imagline: "ℐ",
    imagpart: "ℑ",
    imath: "ı",
    imof: "⊷",
    imped: "Ƶ",
    in: "∈",
    incare: "℅",
    infin: "∞",
    infintie: "⧝",
    inodot: "ı",
    int: "∫",
    intcal: "⊺",
    integers: "ℤ",
    intercal: "⊺",
    intlarhk: "⨗",
    intprod: "⨼",
    iocy: "ё",
    iogon: "į",
    iopf: "\uD835\uDD5A",
    iota: "ι",
    iprod: "⨼",
    iquest: "¿",
    iscr: "\uD835\uDCBE",
    isin: "∈",
    isinE: "⋹",
    isindot: "⋵",
    isins: "⋴",
    isinsv: "⋳",
    isinv: "∈",
    it: "⁢",
    itilde: "ĩ",
    iukcy: "і",
    iuml: "ï",
    jcirc: "ĵ",
    jcy: "й",
    jfr: "\uD835\uDD27",
    jmath: "ȷ",
    jopf: "\uD835\uDD5B",
    jscr: "\uD835\uDCBF",
    jsercy: "ј",
    jukcy: "є",
    kappa: "κ",
    kappav: "ϰ",
    kcedil: "ķ",
    kcy: "к",
    kfr: "\uD835\uDD28",
    kgreen: "ĸ",
    khcy: "х",
    kjcy: "ќ",
    kopf: "\uD835\uDD5C",
    kscr: "\uD835\uDCC0",
    lAarr: "⇚",
    lArr: "⇐",
    lAtail: "⤛",
    lBarr: "⤎",
    lE: "≦",
    lEg: "⪋",
    lHar: "⥢",
    lacute: "ĺ",
    laemptyv: "⦴",
    lagran: "ℒ",
    lambda: "λ",
    lang: "⟨",
    langd: "⦑",
    langle: "⟨",
    lap: "⪅",
    laquo: "«",
    larr: "←",
    larrb: "⇤",
    larrbfs: "⤟",
    larrfs: "⤝",
    larrhk: "↩",
    larrlp: "↫",
    larrpl: "⤹",
    larrsim: "⥳",
    larrtl: "↢",
    lat: "⪫",
    latail: "⤙",
    late: "⪭",
    lates: "⪭︀",
    lbarr: "⤌",
    lbbrk: "❲",
    lbrace: "{",
    lbrack: "[",
    lbrke: "⦋",
    lbrksld: "⦏",
    lbrkslu: "⦍",
    lcaron: "ľ",
    lcedil: "ļ",
    lceil: "⌈",
    lcub: "{",
    lcy: "л",
    ldca: "⤶",
    ldquo: "“",
    ldquor: "„",
    ldrdhar: "⥧",
    ldrushar: "⥋",
    ldsh: "↲",
    le: "≤",
    leftarrow: "←",
    leftarrowtail: "↢",
    leftharpoondown: "↽",
    leftharpoonup: "↼",
    leftleftarrows: "⇇",
    leftrightarrow: "↔",
    leftrightarrows: "⇆",
    leftrightharpoons: "⇋",
    leftrightsquigarrow: "↭",
    leftthreetimes: "⋋",
    leg: "⋚",
    leq: "≤",
    leqq: "≦",
    leqslant: "⩽",
    les: "⩽",
    lescc: "⪨",
    lesdot: "⩿",
    lesdoto: "⪁",
    lesdotor: "⪃",
    lesg: "⋚︀",
    lesges: "⪓",
    lessapprox: "⪅",
    lessdot: "⋖",
    lesseqgtr: "⋚",
    lesseqqgtr: "⪋",
    lessgtr: "≶",
    lesssim: "≲",
    lfisht: "⥼",
    lfloor: "⌊",
    lfr: "\uD835\uDD29",
    lg: "≶",
    lgE: "⪑",
    lhard: "↽",
    lharu: "↼",
    lharul: "⥪",
    lhblk: "▄",
    ljcy: "љ",
    ll: "≪",
    llarr: "⇇",
    llcorner: "⌞",
    llhard: "⥫",
    lltri: "◺",
    lmidot: "ŀ",
    lmoust: "⎰",
    lmoustache: "⎰",
    lnE: "≨",
    lnap: "⪉",
    lnapprox: "⪉",
    lne: "⪇",
    lneq: "⪇",
    lneqq: "≨",
    lnsim: "⋦",
    loang: "⟬",
    loarr: "⇽",
    lobrk: "⟦",
    longleftarrow: "⟵",
    longleftrightarrow: "⟷",
    longmapsto: "⟼",
    longrightarrow: "⟶",
    looparrowleft: "↫",
    looparrowright: "↬",
    lopar: "⦅",
    lopf: "\uD835\uDD5D",
    loplus: "⨭",
    lotimes: "⨴",
    lowast: "∗",
    lowbar: "_",
    loz: "◊",
    lozenge: "◊",
    lozf: "⧫",
    lpar: "(",
    lparlt: "⦓",
    lrarr: "⇆",
    lrcorner: "⌟",
    lrhar: "⇋",
    lrhard: "⥭",
    lrm: "‎",
    lrtri: "⊿",
    lsaquo: "‹",
    lscr: "\uD835\uDCC1",
    lsh: "↰",
    lsim: "≲",
    lsime: "⪍",
    lsimg: "⪏",
    lsqb: "[",
    lsquo: "‘",
    lsquor: "‚",
    lstrok: "ł",
    lt: "<",
    ltcc: "⪦",
    ltcir: "⩹",
    ltdot: "⋖",
    lthree: "⋋",
    ltimes: "⋉",
    ltlarr: "⥶",
    ltquest: "⩻",
    ltrPar: "⦖",
    ltri: "◃",
    ltrie: "⊴",
    ltrif: "◂",
    lurdshar: "⥊",
    luruhar: "⥦",
    lvertneqq: "≨︀",
    lvnE: "≨︀",
    mDDot: "∺",
    macr: "¯",
    male: "♂",
    malt: "✠",
    maltese: "✠",
    map: "↦",
    mapsto: "↦",
    mapstodown: "↧",
    mapstoleft: "↤",
    mapstoup: "↥",
    marker: "▮",
    mcomma: "⨩",
    mcy: "м",
    mdash: "—",
    measuredangle: "∡",
    mfr: "\uD835\uDD2A",
    mho: "℧",
    micro: "µ",
    mid: "∣",
    midast: "*",
    midcir: "⫰",
    middot: "·",
    minus: "−",
    minusb: "⊟",
    minusd: "∸",
    minusdu: "⨪",
    mlcp: "⫛",
    mldr: "…",
    mnplus: "∓",
    models: "⊧",
    mopf: "\uD835\uDD5E",
    mp: "∓",
    mscr: "\uD835\uDCC2",
    mstpos: "∾",
    mu: "μ",
    multimap: "⊸",
    mumap: "⊸",
    nGg: "⋙̸",
    nGt: "≫⃒",
    nGtv: "≫̸",
    nLeftarrow: "⇍",
    nLeftrightarrow: "⇎",
    nLl: "⋘̸",
    nLt: "≪⃒",
    nLtv: "≪̸",
    nRightarrow: "⇏",
    nVDash: "⊯",
    nVdash: "⊮",
    nabla: "∇",
    nacute: "ń",
    nang: "∠⃒",
    nap: "≉",
    napE: "⩰̸",
    napid: "≋̸",
    napos: "ŉ",
    napprox: "≉",
    natur: "♮",
    natural: "♮",
    naturals: "ℕ",
    nbsp: " ",
    nbump: "≎̸",
    nbumpe: "≏̸",
    ncap: "⩃",
    ncaron: "ň",
    ncedil: "ņ",
    ncong: "≇",
    ncongdot: "⩭̸",
    ncup: "⩂",
    ncy: "н",
    ndash: "–",
    ne: "≠",
    neArr: "⇗",
    nearhk: "⤤",
    nearr: "↗",
    nearrow: "↗",
    nedot: "≐̸",
    nequiv: "≢",
    nesear: "⤨",
    nesim: "≂̸",
    nexist: "∄",
    nexists: "∄",
    nfr: "\uD835\uDD2B",
    ngE: "≧̸",
    nge: "≱",
    ngeq: "≱",
    ngeqq: "≧̸",
    ngeqslant: "⩾̸",
    nges: "⩾̸",
    ngsim: "≵",
    ngt: "≯",
    ngtr: "≯",
    nhArr: "⇎",
    nharr: "↮",
    nhpar: "⫲",
    ni: "∋",
    nis: "⋼",
    nisd: "⋺",
    niv: "∋",
    njcy: "њ",
    nlArr: "⇍",
    nlE: "≦̸",
    nlarr: "↚",
    nldr: "‥",
    nle: "≰",
    nleftarrow: "↚",
    nleftrightarrow: "↮",
    nleq: "≰",
    nleqq: "≦̸",
    nleqslant: "⩽̸",
    nles: "⩽̸",
    nless: "≮",
    nlsim: "≴",
    nlt: "≮",
    nltri: "⋪",
    nltrie: "⋬",
    nmid: "∤",
    nopf: "\uD835\uDD5F",
    not: "¬",
    notin: "∉",
    notinE: "⋹̸",
    notindot: "⋵̸",
    notinva: "∉",
    notinvb: "⋷",
    notinvc: "⋶",
    notni: "∌",
    notniva: "∌",
    notnivb: "⋾",
    notnivc: "⋽",
    npar: "∦",
    nparallel: "∦",
    nparsl: "⫽⃥",
    npart: "∂̸",
    npolint: "⨔",
    npr: "⊀",
    nprcue: "⋠",
    npre: "⪯̸",
    nprec: "⊀",
    npreceq: "⪯̸",
    nrArr: "⇏",
    nrarr: "↛",
    nrarrc: "⤳̸",
    nrarrw: "↝̸",
    nrightarrow: "↛",
    nrtri: "⋫",
    nrtrie: "⋭",
    nsc: "⊁",
    nsccue: "⋡",
    nsce: "⪰̸",
    nscr: "\uD835\uDCC3",
    nshortmid: "∤",
    nshortparallel: "∦",
    nsim: "≁",
    nsime: "≄",
    nsimeq: "≄",
    nsmid: "∤",
    nspar: "∦",
    nsqsube: "⋢",
    nsqsupe: "⋣",
    nsub: "⊄",
    nsubE: "⫅̸",
    nsube: "⊈",
    nsubset: "⊂⃒",
    nsubseteq: "⊈",
    nsubseteqq: "⫅̸",
    nsucc: "⊁",
    nsucceq: "⪰̸",
    nsup: "⊅",
    nsupE: "⫆̸",
    nsupe: "⊉",
    nsupset: "⊃⃒",
    nsupseteq: "⊉",
    nsupseteqq: "⫆̸",
    ntgl: "≹",
    ntilde: "ñ",
    ntlg: "≸",
    ntriangleleft: "⋪",
    ntrianglelefteq: "⋬",
    ntriangleright: "⋫",
    ntrianglerighteq: "⋭",
    nu: "ν",
    num: "#",
    numero: "№",
    numsp: " ",
    nvDash: "⊭",
    nvHarr: "⤄",
    nvap: "≍⃒",
    nvdash: "⊬",
    nvge: "≥⃒",
    nvgt: ">⃒",
    nvinfin: "⧞",
    nvlArr: "⤂",
    nvle: "≤⃒",
    nvlt: "<⃒",
    nvltrie: "⊴⃒",
    nvrArr: "⤃",
    nvrtrie: "⊵⃒",
    nvsim: "∼⃒",
    nwArr: "⇖",
    nwarhk: "⤣",
    nwarr: "↖",
    nwarrow: "↖",
    nwnear: "⤧",
    oS: "Ⓢ",
    oacute: "ó",
    oast: "⊛",
    ocir: "⊚",
    ocirc: "ô",
    ocy: "о",
    odash: "⊝",
    odblac: "ő",
    odiv: "⨸",
    odot: "⊙",
    odsold: "⦼",
    oelig: "œ",
    ofcir: "⦿",
    ofr: "\uD835\uDD2C",
    ogon: "˛",
    ograve: "ò",
    ogt: "⧁",
    ohbar: "⦵",
    ohm: "Ω",
    oint: "∮",
    olarr: "↺",
    olcir: "⦾",
    olcross: "⦻",
    oline: "‾",
    olt: "⧀",
    omacr: "ō",
    omega: "ω",
    omicron: "ο",
    omid: "⦶",
    ominus: "⊖",
    oopf: "\uD835\uDD60",
    opar: "⦷",
    operp: "⦹",
    oplus: "⊕",
    or: "∨",
    orarr: "↻",
    ord: "⩝",
    order: "ℴ",
    orderof: "ℴ",
    ordf: "ª",
    ordm: "º",
    origof: "⊶",
    oror: "⩖",
    orslope: "⩗",
    orv: "⩛",
    oscr: "ℴ",
    oslash: "ø",
    osol: "⊘",
    otilde: "õ",
    otimes: "⊗",
    otimesas: "⨶",
    ouml: "ö",
    ovbar: "⌽",
    par: "∥",
    para: "¶",
    parallel: "∥",
    parsim: "⫳",
    parsl: "⫽",
    part: "∂",
    pcy: "п",
    percnt: "%",
    period: ".",
    permil: "‰",
    perp: "⊥",
    pertenk: "‱",
    pfr: "\uD835\uDD2D",
    phi: "φ",
    phiv: "ϕ",
    phmmat: "ℳ",
    phone: "☎",
    pi: "π",
    pitchfork: "⋔",
    piv: "ϖ",
    planck: "ℏ",
    planckh: "ℎ",
    plankv: "ℏ",
    plus: "+",
    plusacir: "⨣",
    plusb: "⊞",
    pluscir: "⨢",
    plusdo: "∔",
    plusdu: "⨥",
    pluse: "⩲",
    plusmn: "±",
    plussim: "⨦",
    plustwo: "⨧",
    pm: "±",
    pointint: "⨕",
    popf: "\uD835\uDD61",
    pound: "£",
    pr: "≺",
    prE: "⪳",
    prap: "⪷",
    prcue: "≼",
    pre: "⪯",
    prec: "≺",
    precapprox: "⪷",
    preccurlyeq: "≼",
    preceq: "⪯",
    precnapprox: "⪹",
    precneqq: "⪵",
    precnsim: "⋨",
    precsim: "≾",
    prime: "′",
    primes: "ℙ",
    prnE: "⪵",
    prnap: "⪹",
    prnsim: "⋨",
    prod: "∏",
    profalar: "⌮",
    profline: "⌒",
    profsurf: "⌓",
    prop: "∝",
    propto: "∝",
    prsim: "≾",
    prurel: "⊰",
    pscr: "\uD835\uDCC5",
    psi: "ψ",
    puncsp: " ",
    qfr: "\uD835\uDD2E",
    qint: "⨌",
    qopf: "\uD835\uDD62",
    qprime: "⁗",
    qscr: "\uD835\uDCC6",
    quaternions: "ℍ",
    quatint: "⨖",
    quest: "?",
    questeq: "≟",
    quot: '"',
    rAarr: "⇛",
    rArr: "⇒",
    rAtail: "⤜",
    rBarr: "⤏",
    rHar: "⥤",
    race: "∽̱",
    racute: "ŕ",
    radic: "√",
    raemptyv: "⦳",
    rang: "⟩",
    rangd: "⦒",
    range: "⦥",
    rangle: "⟩",
    raquo: "»",
    rarr: "→",
    rarrap: "⥵",
    rarrb: "⇥",
    rarrbfs: "⤠",
    rarrc: "⤳",
    rarrfs: "⤞",
    rarrhk: "↪",
    rarrlp: "↬",
    rarrpl: "⥅",
    rarrsim: "⥴",
    rarrtl: "↣",
    rarrw: "↝",
    ratail: "⤚",
    ratio: "∶",
    rationals: "ℚ",
    rbarr: "⤍",
    rbbrk: "❳",
    rbrace: "}",
    rbrack: "]",
    rbrke: "⦌",
    rbrksld: "⦎",
    rbrkslu: "⦐",
    rcaron: "ř",
    rcedil: "ŗ",
    rceil: "⌉",
    rcub: "}",
    rcy: "р",
    rdca: "⤷",
    rdldhar: "⥩",
    rdquo: "”",
    rdquor: "”",
    rdsh: "↳",
    real: "ℜ",
    realine: "ℛ",
    realpart: "ℜ",
    reals: "ℝ",
    rect: "▭",
    reg: "®",
    rfisht: "⥽",
    rfloor: "⌋",
    rfr: "\uD835\uDD2F",
    rhard: "⇁",
    rharu: "⇀",
    rharul: "⥬",
    rho: "ρ",
    rhov: "ϱ",
    rightarrow: "→",
    rightarrowtail: "↣",
    rightharpoondown: "⇁",
    rightharpoonup: "⇀",
    rightleftarrows: "⇄",
    rightleftharpoons: "⇌",
    rightrightarrows: "⇉",
    rightsquigarrow: "↝",
    rightthreetimes: "⋌",
    ring: "˚",
    risingdotseq: "≓",
    rlarr: "⇄",
    rlhar: "⇌",
    rlm: "‏",
    rmoust: "⎱",
    rmoustache: "⎱",
    rnmid: "⫮",
    roang: "⟭",
    roarr: "⇾",
    robrk: "⟧",
    ropar: "⦆",
    ropf: "\uD835\uDD63",
    roplus: "⨮",
    rotimes: "⨵",
    rpar: ")",
    rpargt: "⦔",
    rppolint: "⨒",
    rrarr: "⇉",
    rsaquo: "›",
    rscr: "\uD835\uDCC7",
    rsh: "↱",
    rsqb: "]",
    rsquo: "’",
    rsquor: "’",
    rthree: "⋌",
    rtimes: "⋊",
    rtri: "▹",
    rtrie: "⊵",
    rtrif: "▸",
    rtriltri: "⧎",
    ruluhar: "⥨",
    rx: "℞",
    sacute: "ś",
    sbquo: "‚",
    sc: "≻",
    scE: "⪴",
    scap: "⪸",
    scaron: "š",
    sccue: "≽",
    sce: "⪰",
    scedil: "ş",
    scirc: "ŝ",
    scnE: "⪶",
    scnap: "⪺",
    scnsim: "⋩",
    scpolint: "⨓",
    scsim: "≿",
    scy: "с",
    sdot: "⋅",
    sdotb: "⊡",
    sdote: "⩦",
    seArr: "⇘",
    searhk: "⤥",
    searr: "↘",
    searrow: "↘",
    sect: "§",
    semi: ";",
    seswar: "⤩",
    setminus: "∖",
    setmn: "∖",
    sext: "✶",
    sfr: "\uD835\uDD30",
    sfrown: "⌢",
    sharp: "♯",
    shchcy: "щ",
    shcy: "ш",
    shortmid: "∣",
    shortparallel: "∥",
    shy: "­",
    sigma: "σ",
    sigmaf: "ς",
    sigmav: "ς",
    sim: "∼",
    simdot: "⩪",
    sime: "≃",
    simeq: "≃",
    simg: "⪞",
    simgE: "⪠",
    siml: "⪝",
    simlE: "⪟",
    simne: "≆",
    simplus: "⨤",
    simrarr: "⥲",
    slarr: "←",
    smallsetminus: "∖",
    smashp: "⨳",
    smeparsl: "⧤",
    smid: "∣",
    smile: "⌣",
    smt: "⪪",
    smte: "⪬",
    smtes: "⪬︀",
    softcy: "ь",
    sol: "/",
    solb: "⧄",
    solbar: "⌿",
    sopf: "\uD835\uDD64",
    spades: "♠",
    spadesuit: "♠",
    spar: "∥",
    sqcap: "⊓",
    sqcaps: "⊓︀",
    sqcup: "⊔",
    sqcups: "⊔︀",
    sqsub: "⊏",
    sqsube: "⊑",
    sqsubset: "⊏",
    sqsubseteq: "⊑",
    sqsup: "⊐",
    sqsupe: "⊒",
    sqsupset: "⊐",
    sqsupseteq: "⊒",
    squ: "□",
    square: "□",
    squarf: "▪",
    squf: "▪",
    srarr: "→",
    sscr: "\uD835\uDCC8",
    ssetmn: "∖",
    ssmile: "⌣",
    sstarf: "⋆",
    star: "☆",
    starf: "★",
    straightepsilon: "ϵ",
    straightphi: "ϕ",
    strns: "¯",
    sub: "⊂",
    subE: "⫅",
    subdot: "⪽",
    sube: "⊆",
    subedot: "⫃",
    submult: "⫁",
    subnE: "⫋",
    subne: "⊊",
    subplus: "⪿",
    subrarr: "⥹",
    subset: "⊂",
    subseteq: "⊆",
    subseteqq: "⫅",
    subsetneq: "⊊",
    subsetneqq: "⫋",
    subsim: "⫇",
    subsub: "⫕",
    subsup: "⫓",
    succ: "≻",
    succapprox: "⪸",
    succcurlyeq: "≽",
    succeq: "⪰",
    succnapprox: "⪺",
    succneqq: "⪶",
    succnsim: "⋩",
    succsim: "≿",
    sum: "∑",
    sung: "♪",
    sup1: "¹",
    sup2: "²",
    sup3: "³",
    sup: "⊃",
    supE: "⫆",
    supdot: "⪾",
    supdsub: "⫘",
    supe: "⊇",
    supedot: "⫄",
    suphsol: "⟉",
    suphsub: "⫗",
    suplarr: "⥻",
    supmult: "⫂",
    supnE: "⫌",
    supne: "⊋",
    supplus: "⫀",
    supset: "⊃",
    supseteq: "⊇",
    supseteqq: "⫆",
    supsetneq: "⊋",
    supsetneqq: "⫌",
    supsim: "⫈",
    supsub: "⫔",
    supsup: "⫖",
    swArr: "⇙",
    swarhk: "⤦",
    swarr: "↙",
    swarrow: "↙",
    swnwar: "⤪",
    szlig: "ß",
    target: "⌖",
    tau: "τ",
    tbrk: "⎴",
    tcaron: "ť",
    tcedil: "ţ",
    tcy: "т",
    tdot: "⃛",
    telrec: "⌕",
    tfr: "\uD835\uDD31",
    there4: "∴",
    therefore: "∴",
    theta: "θ",
    thetasym: "ϑ",
    thetav: "ϑ",
    thickapprox: "≈",
    thicksim: "∼",
    thinsp: " ",
    thkap: "≈",
    thksim: "∼",
    thorn: "þ",
    tilde: "˜",
    times: "×",
    timesb: "⊠",
    timesbar: "⨱",
    timesd: "⨰",
    tint: "∭",
    toea: "⤨",
    top: "⊤",
    topbot: "⌶",
    topcir: "⫱",
    topf: "\uD835\uDD65",
    topfork: "⫚",
    tosa: "⤩",
    tprime: "‴",
    trade: "™",
    triangle: "▵",
    triangledown: "▿",
    triangleleft: "◃",
    trianglelefteq: "⊴",
    triangleq: "≜",
    triangleright: "▹",
    trianglerighteq: "⊵",
    tridot: "◬",
    trie: "≜",
    triminus: "⨺",
    triplus: "⨹",
    trisb: "⧍",
    tritime: "⨻",
    trpezium: "⏢",
    tscr: "\uD835\uDCC9",
    tscy: "ц",
    tshcy: "ћ",
    tstrok: "ŧ",
    twixt: "≬",
    twoheadleftarrow: "↞",
    twoheadrightarrow: "↠",
    uArr: "⇑",
    uHar: "⥣",
    uacute: "ú",
    uarr: "↑",
    ubrcy: "ў",
    ubreve: "ŭ",
    ucirc: "û",
    ucy: "у",
    udarr: "⇅",
    udblac: "ű",
    udhar: "⥮",
    ufisht: "⥾",
    ufr: "\uD835\uDD32",
    ugrave: "ù",
    uharl: "↿",
    uharr: "↾",
    uhblk: "▀",
    ulcorn: "⌜",
    ulcorner: "⌜",
    ulcrop: "⌏",
    ultri: "◸",
    umacr: "ū",
    uml: "¨",
    uogon: "ų",
    uopf: "\uD835\uDD66",
    uparrow: "↑",
    updownarrow: "↕",
    upharpoonleft: "↿",
    upharpoonright: "↾",
    uplus: "⊎",
    upsi: "υ",
    upsih: "ϒ",
    upsilon: "υ",
    upuparrows: "⇈",
    urcorn: "⌝",
    urcorner: "⌝",
    urcrop: "⌎",
    uring: "ů",
    urtri: "◹",
    uscr: "\uD835\uDCCA",
    utdot: "⋰",
    utilde: "ũ",
    utri: "▵",
    utrif: "▴",
    uuarr: "⇈",
    uuml: "ü",
    uwangle: "⦧",
    vArr: "⇕",
    vBar: "⫨",
    vBarv: "⫩",
    vDash: "⊨",
    vangrt: "⦜",
    varepsilon: "ϵ",
    varkappa: "ϰ",
    varnothing: "∅",
    varphi: "ϕ",
    varpi: "ϖ",
    varpropto: "∝",
    varr: "↕",
    varrho: "ϱ",
    varsigma: "ς",
    varsubsetneq: "⊊︀",
    varsubsetneqq: "⫋︀",
    varsupsetneq: "⊋︀",
    varsupsetneqq: "⫌︀",
    vartheta: "ϑ",
    vartriangleleft: "⊲",
    vartriangleright: "⊳",
    vcy: "в",
    vdash: "⊢",
    vee: "∨",
    veebar: "⊻",
    veeeq: "≚",
    vellip: "⋮",
    verbar: "|",
    vert: "|",
    vfr: "\uD835\uDD33",
    vltri: "⊲",
    vnsub: "⊂⃒",
    vnsup: "⊃⃒",
    vopf: "\uD835\uDD67",
    vprop: "∝",
    vrtri: "⊳",
    vscr: "\uD835\uDCCB",
    vsubnE: "⫋︀",
    vsubne: "⊊︀",
    vsupnE: "⫌︀",
    vsupne: "⊋︀",
    vzigzag: "⦚",
    wcirc: "ŵ",
    wedbar: "⩟",
    wedge: "∧",
    wedgeq: "≙",
    weierp: "℘",
    wfr: "\uD835\uDD34",
    wopf: "\uD835\uDD68",
    wp: "℘",
    wr: "≀",
    wreath: "≀",
    wscr: "\uD835\uDCCC",
    xcap: "⋂",
    xcirc: "◯",
    xcup: "⋃",
    xdtri: "▽",
    xfr: "\uD835\uDD35",
    xhArr: "⟺",
    xharr: "⟷",
    xi: "ξ",
    xlArr: "⟸",
    xlarr: "⟵",
    xmap: "⟼",
    xnis: "⋻",
    xodot: "⨀",
    xopf: "\uD835\uDD69",
    xoplus: "⨁",
    xotime: "⨂",
    xrArr: "⟹",
    xrarr: "⟶",
    xscr: "\uD835\uDCCD",
    xsqcup: "⨆",
    xuplus: "⨄",
    xutri: "△",
    xvee: "⋁",
    xwedge: "⋀",
    yacute: "ý",
    yacy: "я",
    ycirc: "ŷ",
    ycy: "ы",
    yen: "¥",
    yfr: "\uD835\uDD36",
    yicy: "ї",
    yopf: "\uD835\uDD6A",
    yscr: "\uD835\uDCCE",
    yucy: "ю",
    yuml: "ÿ",
    zacute: "ź",
    zcaron: "ž",
    zcy: "з",
    zdot: "ż",
    zeetrf: "ℨ",
    zeta: "ζ",
    zfr: "\uD835\uDD37",
    zhcy: "ж",
    zigrarr: "⇝",
    zopf: "\uD835\uDD6B",
    zscr: "\uD835\uDCCF",
    zwj: "‍",
    zwnj: "‌"
  };
});

// node_modules/decode-named-character-reference/index.js
function decodeNamedCharacterReference(value2) {
  return own2.call(characterEntities, value2) ? characterEntities[value2] : false;
}
var own2;
var init_decode_named_character_reference = __esm(() => {
  init_character_entities();
  own2 = {}.hasOwnProperty;
});

// node_modules/micromark-util-symbol/lib/codes.js
var codes;
var init_codes = __esm(() => {
  codes = {
    carriageReturn: -5,
    lineFeed: -4,
    carriageReturnLineFeed: -3,
    horizontalTab: -2,
    virtualSpace: -1,
    eof: null,
    nul: 0,
    soh: 1,
    stx: 2,
    etx: 3,
    eot: 4,
    enq: 5,
    ack: 6,
    bel: 7,
    bs: 8,
    ht: 9,
    lf: 10,
    vt: 11,
    ff: 12,
    cr: 13,
    so: 14,
    si: 15,
    dle: 16,
    dc1: 17,
    dc2: 18,
    dc3: 19,
    dc4: 20,
    nak: 21,
    syn: 22,
    etb: 23,
    can: 24,
    em: 25,
    sub: 26,
    esc: 27,
    fs: 28,
    gs: 29,
    rs: 30,
    us: 31,
    space: 32,
    exclamationMark: 33,
    quotationMark: 34,
    numberSign: 35,
    dollarSign: 36,
    percentSign: 37,
    ampersand: 38,
    apostrophe: 39,
    leftParenthesis: 40,
    rightParenthesis: 41,
    asterisk: 42,
    plusSign: 43,
    comma: 44,
    dash: 45,
    dot: 46,
    slash: 47,
    digit0: 48,
    digit1: 49,
    digit2: 50,
    digit3: 51,
    digit4: 52,
    digit5: 53,
    digit6: 54,
    digit7: 55,
    digit8: 56,
    digit9: 57,
    colon: 58,
    semicolon: 59,
    lessThan: 60,
    equalsTo: 61,
    greaterThan: 62,
    questionMark: 63,
    atSign: 64,
    uppercaseA: 65,
    uppercaseB: 66,
    uppercaseC: 67,
    uppercaseD: 68,
    uppercaseE: 69,
    uppercaseF: 70,
    uppercaseG: 71,
    uppercaseH: 72,
    uppercaseI: 73,
    uppercaseJ: 74,
    uppercaseK: 75,
    uppercaseL: 76,
    uppercaseM: 77,
    uppercaseN: 78,
    uppercaseO: 79,
    uppercaseP: 80,
    uppercaseQ: 81,
    uppercaseR: 82,
    uppercaseS: 83,
    uppercaseT: 84,
    uppercaseU: 85,
    uppercaseV: 86,
    uppercaseW: 87,
    uppercaseX: 88,
    uppercaseY: 89,
    uppercaseZ: 90,
    leftSquareBracket: 91,
    backslash: 92,
    rightSquareBracket: 93,
    caret: 94,
    underscore: 95,
    graveAccent: 96,
    lowercaseA: 97,
    lowercaseB: 98,
    lowercaseC: 99,
    lowercaseD: 100,
    lowercaseE: 101,
    lowercaseF: 102,
    lowercaseG: 103,
    lowercaseH: 104,
    lowercaseI: 105,
    lowercaseJ: 106,
    lowercaseK: 107,
    lowercaseL: 108,
    lowercaseM: 109,
    lowercaseN: 110,
    lowercaseO: 111,
    lowercaseP: 112,
    lowercaseQ: 113,
    lowercaseR: 114,
    lowercaseS: 115,
    lowercaseT: 116,
    lowercaseU: 117,
    lowercaseV: 118,
    lowercaseW: 119,
    lowercaseX: 120,
    lowercaseY: 121,
    lowercaseZ: 122,
    leftCurlyBrace: 123,
    verticalBar: 124,
    rightCurlyBrace: 125,
    tilde: 126,
    del: 127,
    byteOrderMarker: 65279,
    replacementCharacter: 65533
  };
});

// node_modules/micromark-util-symbol/lib/constants.js
var constants2;
var init_constants = __esm(() => {
  constants2 = {
    attentionSideAfter: 2,
    attentionSideBefore: 1,
    atxHeadingOpeningFenceSizeMax: 6,
    autolinkDomainSizeMax: 63,
    autolinkSchemeSizeMax: 32,
    cdataOpeningString: "CDATA[",
    characterGroupPunctuation: 2,
    characterGroupWhitespace: 1,
    characterReferenceDecimalSizeMax: 7,
    characterReferenceHexadecimalSizeMax: 6,
    characterReferenceNamedSizeMax: 31,
    codeFencedSequenceSizeMin: 3,
    contentTypeContent: "content",
    contentTypeDocument: "document",
    contentTypeFlow: "flow",
    contentTypeString: "string",
    contentTypeText: "text",
    hardBreakPrefixSizeMin: 2,
    htmlBasic: 6,
    htmlCdata: 5,
    htmlComment: 2,
    htmlComplete: 7,
    htmlDeclaration: 4,
    htmlInstruction: 3,
    htmlRawSizeMax: 8,
    htmlRaw: 1,
    linkResourceDestinationBalanceMax: 32,
    linkReferenceSizeMax: 999,
    listItemValueSizeMax: 10,
    numericBaseDecimal: 10,
    numericBaseHexadecimal: 16,
    tabSize: 4,
    thematicBreakMarkerCountMin: 3,
    v8MaxSafeChunkSize: 1e4
  };
});

// node_modules/micromark-util-symbol/lib/types.js
var types;
var init_types = __esm(() => {
  types = {
    data: "data",
    whitespace: "whitespace",
    lineEnding: "lineEnding",
    lineEndingBlank: "lineEndingBlank",
    linePrefix: "linePrefix",
    lineSuffix: "lineSuffix",
    atxHeading: "atxHeading",
    atxHeadingSequence: "atxHeadingSequence",
    atxHeadingText: "atxHeadingText",
    autolink: "autolink",
    autolinkEmail: "autolinkEmail",
    autolinkMarker: "autolinkMarker",
    autolinkProtocol: "autolinkProtocol",
    characterEscape: "characterEscape",
    characterEscapeValue: "characterEscapeValue",
    characterReference: "characterReference",
    characterReferenceMarker: "characterReferenceMarker",
    characterReferenceMarkerNumeric: "characterReferenceMarkerNumeric",
    characterReferenceMarkerHexadecimal: "characterReferenceMarkerHexadecimal",
    characterReferenceValue: "characterReferenceValue",
    codeFenced: "codeFenced",
    codeFencedFence: "codeFencedFence",
    codeFencedFenceSequence: "codeFencedFenceSequence",
    codeFencedFenceInfo: "codeFencedFenceInfo",
    codeFencedFenceMeta: "codeFencedFenceMeta",
    codeFlowValue: "codeFlowValue",
    codeIndented: "codeIndented",
    codeText: "codeText",
    codeTextData: "codeTextData",
    codeTextPadding: "codeTextPadding",
    codeTextSequence: "codeTextSequence",
    content: "content",
    definition: "definition",
    definitionDestination: "definitionDestination",
    definitionDestinationLiteral: "definitionDestinationLiteral",
    definitionDestinationLiteralMarker: "definitionDestinationLiteralMarker",
    definitionDestinationRaw: "definitionDestinationRaw",
    definitionDestinationString: "definitionDestinationString",
    definitionLabel: "definitionLabel",
    definitionLabelMarker: "definitionLabelMarker",
    definitionLabelString: "definitionLabelString",
    definitionMarker: "definitionMarker",
    definitionTitle: "definitionTitle",
    definitionTitleMarker: "definitionTitleMarker",
    definitionTitleString: "definitionTitleString",
    emphasis: "emphasis",
    emphasisSequence: "emphasisSequence",
    emphasisText: "emphasisText",
    escapeMarker: "escapeMarker",
    hardBreakEscape: "hardBreakEscape",
    hardBreakTrailing: "hardBreakTrailing",
    htmlFlow: "htmlFlow",
    htmlFlowData: "htmlFlowData",
    htmlText: "htmlText",
    htmlTextData: "htmlTextData",
    image: "image",
    label: "label",
    labelText: "labelText",
    labelLink: "labelLink",
    labelImage: "labelImage",
    labelMarker: "labelMarker",
    labelImageMarker: "labelImageMarker",
    labelEnd: "labelEnd",
    link: "link",
    paragraph: "paragraph",
    reference: "reference",
    referenceMarker: "referenceMarker",
    referenceString: "referenceString",
    resource: "resource",
    resourceDestination: "resourceDestination",
    resourceDestinationLiteral: "resourceDestinationLiteral",
    resourceDestinationLiteralMarker: "resourceDestinationLiteralMarker",
    resourceDestinationRaw: "resourceDestinationRaw",
    resourceDestinationString: "resourceDestinationString",
    resourceMarker: "resourceMarker",
    resourceTitle: "resourceTitle",
    resourceTitleMarker: "resourceTitleMarker",
    resourceTitleString: "resourceTitleString",
    setextHeading: "setextHeading",
    setextHeadingText: "setextHeadingText",
    setextHeadingLine: "setextHeadingLine",
    setextHeadingLineSequence: "setextHeadingLineSequence",
    strong: "strong",
    strongSequence: "strongSequence",
    strongText: "strongText",
    thematicBreak: "thematicBreak",
    thematicBreakSequence: "thematicBreakSequence",
    blockQuote: "blockQuote",
    blockQuotePrefix: "blockQuotePrefix",
    blockQuoteMarker: "blockQuoteMarker",
    blockQuotePrefixWhitespace: "blockQuotePrefixWhitespace",
    listOrdered: "listOrdered",
    listUnordered: "listUnordered",
    listItemIndent: "listItemIndent",
    listItemMarker: "listItemMarker",
    listItemPrefix: "listItemPrefix",
    listItemPrefixWhitespace: "listItemPrefixWhitespace",
    listItemValue: "listItemValue",
    chunkDocument: "chunkDocument",
    chunkContent: "chunkContent",
    chunkFlow: "chunkFlow",
    chunkText: "chunkText",
    chunkString: "chunkString"
  };
});

// node_modules/micromark-util-symbol/lib/values.js
var values;
var init_values = __esm(() => {
  values = {
    ht: "\t",
    lf: `
`,
    cr: "\r",
    space: " ",
    exclamationMark: "!",
    quotationMark: '"',
    numberSign: "#",
    dollarSign: "$",
    percentSign: "%",
    ampersand: "&",
    apostrophe: "'",
    leftParenthesis: "(",
    rightParenthesis: ")",
    asterisk: "*",
    plusSign: "+",
    comma: ",",
    dash: "-",
    dot: ".",
    slash: "/",
    digit0: "0",
    digit1: "1",
    digit2: "2",
    digit3: "3",
    digit4: "4",
    digit5: "5",
    digit6: "6",
    digit7: "7",
    digit8: "8",
    digit9: "9",
    colon: ":",
    semicolon: ";",
    lessThan: "<",
    equalsTo: "=",
    greaterThan: ">",
    questionMark: "?",
    atSign: "@",
    uppercaseA: "A",
    uppercaseB: "B",
    uppercaseC: "C",
    uppercaseD: "D",
    uppercaseE: "E",
    uppercaseF: "F",
    uppercaseG: "G",
    uppercaseH: "H",
    uppercaseI: "I",
    uppercaseJ: "J",
    uppercaseK: "K",
    uppercaseL: "L",
    uppercaseM: "M",
    uppercaseN: "N",
    uppercaseO: "O",
    uppercaseP: "P",
    uppercaseQ: "Q",
    uppercaseR: "R",
    uppercaseS: "S",
    uppercaseT: "T",
    uppercaseU: "U",
    uppercaseV: "V",
    uppercaseW: "W",
    uppercaseX: "X",
    uppercaseY: "Y",
    uppercaseZ: "Z",
    leftSquareBracket: "[",
    backslash: "\\",
    rightSquareBracket: "]",
    caret: "^",
    underscore: "_",
    graveAccent: "`",
    lowercaseA: "a",
    lowercaseB: "b",
    lowercaseC: "c",
    lowercaseD: "d",
    lowercaseE: "e",
    lowercaseF: "f",
    lowercaseG: "g",
    lowercaseH: "h",
    lowercaseI: "i",
    lowercaseJ: "j",
    lowercaseK: "k",
    lowercaseL: "l",
    lowercaseM: "m",
    lowercaseN: "n",
    lowercaseO: "o",
    lowercaseP: "p",
    lowercaseQ: "q",
    lowercaseR: "r",
    lowercaseS: "s",
    lowercaseT: "t",
    lowercaseU: "u",
    lowercaseV: "v",
    lowercaseW: "w",
    lowercaseX: "x",
    lowercaseY: "y",
    lowercaseZ: "z",
    leftCurlyBrace: "{",
    verticalBar: "|",
    rightCurlyBrace: "}",
    tilde: "~",
    replacementCharacter: "�"
  };
});

// node_modules/micromark-util-symbol/lib/default.js
var init_default = __esm(() => {
  init_codes();
  init_constants();
  init_types();
  init_values();
});

// node_modules/micromark-util-chunked/dev/index.js
function splice(list, start, remove, items) {
  const end = list.length;
  let chunkStart = 0;
  let parameters;
  if (start < 0) {
    start = -start > end ? 0 : end + start;
  } else {
    start = start > end ? end : start;
  }
  remove = remove > 0 ? remove : 0;
  if (items.length < constants2.v8MaxSafeChunkSize) {
    parameters = Array.from(items);
    parameters.unshift(start, remove);
    list.splice(...parameters);
  } else {
    if (remove)
      list.splice(start, remove);
    while (chunkStart < items.length) {
      parameters = items.slice(chunkStart, chunkStart + constants2.v8MaxSafeChunkSize);
      parameters.unshift(start, 0);
      list.splice(...parameters);
      chunkStart += constants2.v8MaxSafeChunkSize;
      start += constants2.v8MaxSafeChunkSize;
    }
  }
}
function push(list, items) {
  if (list.length > 0) {
    splice(list, list.length, 0, items);
    return list;
  }
  return items;
}
var init_dev = __esm(() => {
  init_default();
});

// node_modules/micromark-util-combine-extensions/index.js
function combineExtensions(extensions) {
  const all3 = {};
  let index2 = -1;
  while (++index2 < extensions.length) {
    syntaxExtension(all3, extensions[index2]);
  }
  return all3;
}
function syntaxExtension(all3, extension) {
  let hook;
  for (hook in extension) {
    const maybe = hasOwnProperty.call(all3, hook) ? all3[hook] : undefined;
    const left = maybe || (all3[hook] = {});
    const right = extension[hook];
    let code;
    if (right) {
      for (code in right) {
        if (!hasOwnProperty.call(left, code))
          left[code] = [];
        const value2 = right[code];
        constructs(left[code], Array.isArray(value2) ? value2 : value2 ? [value2] : []);
      }
    }
  }
}
function constructs(existing, list) {
  let index2 = -1;
  const before = [];
  while (++index2 < list.length) {
    (list[index2].add === "after" ? existing : before).push(list[index2]);
  }
  splice(existing, 0, 0, before);
}
var hasOwnProperty;
var init_micromark_util_combine_extensions = __esm(() => {
  init_dev();
  hasOwnProperty = {}.hasOwnProperty;
});

// node_modules/micromark-util-decode-numeric-character-reference/dev/index.js
function decodeNumericCharacterReference(value2, base) {
  const code = Number.parseInt(value2, base);
  if (code < codes.ht || code === codes.vt || code > codes.cr && code < codes.space || code > codes.tilde && code < 160 || code > 55295 && code < 57344 || code > 64975 && code < 65008 || (code & 65535) === 65535 || (code & 65535) === 65534 || code > 1114111) {
    return values.replacementCharacter;
  }
  return String.fromCodePoint(code);
}
var init_dev2 = __esm(() => {
  init_default();
});

// node_modules/micromark-util-normalize-identifier/dev/index.js
function normalizeIdentifier(value2) {
  return value2.replace(/[\t\n\r ]+/g, values.space).replace(/^ | $/g, "").toLowerCase().toUpperCase();
}
var init_dev3 = __esm(() => {
  init_default();
});

// node_modules/micromark-util-character/dev/index.js
function asciiControl(code) {
  return code !== null && (code < codes.space || code === codes.del);
}
function markdownLineEnding(code) {
  return code !== null && code < codes.horizontalTab;
}
function markdownLineEndingOrSpace(code) {
  return code !== null && (code < codes.nul || code === codes.space);
}
function markdownSpace(code) {
  return code === codes.horizontalTab || code === codes.virtualSpace || code === codes.space;
}
function regexCheck(regex) {
  return check2;
  function check2(code) {
    return code !== null && code > -1 && regex.test(String.fromCharCode(code));
  }
}
var asciiAlpha, asciiAlphanumeric, asciiAtext, asciiDigit, asciiHexDigit, asciiPunctuation, unicodePunctuation, unicodeWhitespace;
var init_dev4 = __esm(() => {
  init_default();
  asciiAlpha = regexCheck(/[A-Za-z]/);
  asciiAlphanumeric = regexCheck(/[\dA-Za-z]/);
  asciiAtext = regexCheck(/[#-'*+\--9=?A-Z^-~]/);
  asciiDigit = regexCheck(/\d/);
  asciiHexDigit = regexCheck(/[\dA-Fa-f]/);
  asciiPunctuation = regexCheck(/[!-/:-@[-`{-~]/);
  unicodePunctuation = regexCheck(/\p{P}|\p{S}/u);
  unicodeWhitespace = regexCheck(/\s/);
});

// node_modules/micromark-factory-space/dev/index.js
function factorySpace(effects, ok2, type, max5) {
  const limit = max5 ? max5 - 1 : Number.POSITIVE_INFINITY;
  let size2 = 0;
  return start;
  function start(code) {
    if (markdownSpace(code)) {
      effects.enter(type);
      return prefix(code);
    }
    return ok2(code);
  }
  function prefix(code) {
    if (markdownSpace(code) && size2++ < limit) {
      effects.consume(code);
      return prefix;
    }
    effects.exit(type);
    return ok2(code);
  }
}
var init_dev5 = __esm(() => {
  init_dev4();
});

// node_modules/micromark/dev/lib/initialize/content.js
function initializeContent(effects) {
  const contentStart = effects.attempt(this.parser.constructs.contentInitial, afterContentStartConstruct, paragraphInitial);
  let previous2;
  return contentStart;
  function afterContentStartConstruct(code) {
    ok(code === codes.eof || markdownLineEnding(code), "expected eol or eof");
    if (code === codes.eof) {
      effects.consume(code);
      return;
    }
    effects.enter(types.lineEnding);
    effects.consume(code);
    effects.exit(types.lineEnding);
    return factorySpace(effects, contentStart, types.linePrefix);
  }
  function paragraphInitial(code) {
    ok(code !== codes.eof && !markdownLineEnding(code), "expected anything other than a line ending or EOF");
    effects.enter(types.paragraph);
    return lineStart(code);
  }
  function lineStart(code) {
    const token = effects.enter(types.chunkText, {
      contentType: constants2.contentTypeText,
      previous: previous2
    });
    if (previous2) {
      previous2.next = token;
    }
    previous2 = token;
    return data2(code);
  }
  function data2(code) {
    if (code === codes.eof) {
      effects.exit(types.chunkText);
      effects.exit(types.paragraph);
      effects.consume(code);
      return;
    }
    if (markdownLineEnding(code)) {
      effects.consume(code);
      effects.exit(types.chunkText);
      return lineStart;
    }
    effects.consume(code);
    return data2;
  }
}
var content;
var init_content = __esm(() => {
  init_development();
  init_dev5();
  init_dev4();
  init_default();
  content = { tokenize: initializeContent };
});

// node_modules/micromark/dev/lib/initialize/document.js
function initializeDocument(effects) {
  const self2 = this;
  const stack = [];
  let continued = 0;
  let childFlow;
  let childToken;
  let lineStartOffset;
  return start;
  function start(code) {
    if (continued < stack.length) {
      const item = stack[continued];
      self2.containerState = item[1];
      ok(item[0].continuation, "expected `continuation` to be defined on container construct");
      return effects.attempt(item[0].continuation, documentContinue, checkNewContainers)(code);
    }
    return checkNewContainers(code);
  }
  function documentContinue(code) {
    ok(self2.containerState, "expected `containerState` to be defined after continuation");
    continued++;
    if (self2.containerState._closeFlow) {
      self2.containerState._closeFlow = undefined;
      if (childFlow) {
        closeFlow();
      }
      const indexBeforeExits = self2.events.length;
      let indexBeforeFlow = indexBeforeExits;
      let point4;
      while (indexBeforeFlow--) {
        if (self2.events[indexBeforeFlow][0] === "exit" && self2.events[indexBeforeFlow][1].type === types.chunkFlow) {
          point4 = self2.events[indexBeforeFlow][1].end;
          break;
        }
      }
      ok(point4, "could not find previous flow chunk");
      exitContainers(continued);
      let index2 = indexBeforeExits;
      while (index2 < self2.events.length) {
        self2.events[index2][1].end = { ...point4 };
        index2++;
      }
      splice(self2.events, indexBeforeFlow + 1, 0, self2.events.slice(indexBeforeExits));
      self2.events.length = index2;
      return checkNewContainers(code);
    }
    return start(code);
  }
  function checkNewContainers(code) {
    if (continued === stack.length) {
      if (!childFlow) {
        return documentContinued(code);
      }
      if (childFlow.currentConstruct && childFlow.currentConstruct.concrete) {
        return flowStart(code);
      }
      self2.interrupt = Boolean(childFlow.currentConstruct && !childFlow._gfmTableDynamicInterruptHack);
    }
    self2.containerState = {};
    return effects.check(containerConstruct, thereIsANewContainer, thereIsNoNewContainer)(code);
  }
  function thereIsANewContainer(code) {
    if (childFlow)
      closeFlow();
    exitContainers(continued);
    return documentContinued(code);
  }
  function thereIsNoNewContainer(code) {
    self2.parser.lazy[self2.now().line] = continued !== stack.length;
    lineStartOffset = self2.now().offset;
    return flowStart(code);
  }
  function documentContinued(code) {
    self2.containerState = {};
    return effects.attempt(containerConstruct, containerContinue, flowStart)(code);
  }
  function containerContinue(code) {
    ok(self2.currentConstruct, "expected `currentConstruct` to be defined on tokenizer");
    ok(self2.containerState, "expected `containerState` to be defined on tokenizer");
    continued++;
    stack.push([self2.currentConstruct, self2.containerState]);
    return documentContinued(code);
  }
  function flowStart(code) {
    if (code === codes.eof) {
      if (childFlow)
        closeFlow();
      exitContainers(0);
      effects.consume(code);
      return;
    }
    childFlow = childFlow || self2.parser.flow(self2.now());
    effects.enter(types.chunkFlow, {
      _tokenizer: childFlow,
      contentType: constants2.contentTypeFlow,
      previous: childToken
    });
    return flowContinue(code);
  }
  function flowContinue(code) {
    if (code === codes.eof) {
      writeToChild(effects.exit(types.chunkFlow), true);
      exitContainers(0);
      effects.consume(code);
      return;
    }
    if (markdownLineEnding(code)) {
      effects.consume(code);
      writeToChild(effects.exit(types.chunkFlow));
      continued = 0;
      self2.interrupt = undefined;
      return start;
    }
    effects.consume(code);
    return flowContinue;
  }
  function writeToChild(token, endOfFile) {
    ok(childFlow, "expected `childFlow` to be defined when continuing");
    const stream = self2.sliceStream(token);
    if (endOfFile)
      stream.push(null);
    token.previous = childToken;
    if (childToken)
      childToken.next = token;
    childToken = token;
    childFlow.defineSkip(token.start);
    childFlow.write(stream);
    if (self2.parser.lazy[token.start.line]) {
      let index2 = childFlow.events.length;
      while (index2--) {
        if (childFlow.events[index2][1].start.offset < lineStartOffset && (!childFlow.events[index2][1].end || childFlow.events[index2][1].end.offset > lineStartOffset)) {
          return;
        }
      }
      const indexBeforeExits = self2.events.length;
      let indexBeforeFlow = indexBeforeExits;
      let seen;
      let point4;
      while (indexBeforeFlow--) {
        if (self2.events[indexBeforeFlow][0] === "exit" && self2.events[indexBeforeFlow][1].type === types.chunkFlow) {
          if (seen) {
            point4 = self2.events[indexBeforeFlow][1].end;
            break;
          }
          seen = true;
        }
      }
      ok(point4, "could not find previous flow chunk");
      exitContainers(continued);
      index2 = indexBeforeExits;
      while (index2 < self2.events.length) {
        self2.events[index2][1].end = { ...point4 };
        index2++;
      }
      splice(self2.events, indexBeforeFlow + 1, 0, self2.events.slice(indexBeforeExits));
      self2.events.length = index2;
    }
  }
  function exitContainers(size2) {
    let index2 = stack.length;
    while (index2-- > size2) {
      const entry = stack[index2];
      self2.containerState = entry[1];
      ok(entry[0].exit, "expected `exit` to be defined on container construct");
      entry[0].exit.call(self2, effects);
    }
    stack.length = size2;
  }
  function closeFlow() {
    ok(self2.containerState, "expected `containerState` to be defined when closing flow");
    ok(childFlow, "expected `childFlow` to be defined when closing it");
    childFlow.write([codes.eof]);
    childToken = undefined;
    childFlow = undefined;
    self2.containerState._closeFlow = undefined;
  }
}
function tokenizeContainer(effects, ok2, nok) {
  ok(this.parser.constructs.disable.null, "expected `disable.null` to be populated");
  return factorySpace(effects, effects.attempt(this.parser.constructs.document, ok2, nok), types.linePrefix, this.parser.constructs.disable.null.includes("codeIndented") ? undefined : constants2.tabSize);
}
var document2, containerConstruct;
var init_document = __esm(() => {
  init_development();
  init_dev5();
  init_dev4();
  init_dev();
  init_default();
  document2 = { tokenize: initializeDocument };
  containerConstruct = { tokenize: tokenizeContainer };
});

// node_modules/micromark-util-classify-character/dev/index.js
function classifyCharacter(code) {
  if (code === codes.eof || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {
    return constants2.characterGroupWhitespace;
  }
  if (unicodePunctuation(code)) {
    return constants2.characterGroupPunctuation;
  }
}
var init_dev6 = __esm(() => {
  init_dev4();
  init_default();
});

// node_modules/micromark-util-resolve-all/index.js
function resolveAll(constructs2, events, context) {
  const called = [];
  let index2 = -1;
  while (++index2 < constructs2.length) {
    const resolve2 = constructs2[index2].resolveAll;
    if (resolve2 && !called.includes(resolve2)) {
      events = resolve2(events, context);
      called.push(resolve2);
    }
  }
  return events;
}

// node_modules/micromark-core-commonmark/dev/lib/attention.js
function resolveAllAttention(events, context) {
  let index2 = -1;
  let open;
  let group;
  let text3;
  let openingSequence;
  let closingSequence;
  let use;
  let nextEvents;
  let offset;
  while (++index2 < events.length) {
    if (events[index2][0] === "enter" && events[index2][1].type === "attentionSequence" && events[index2][1]._close) {
      open = index2;
      while (open--) {
        if (events[open][0] === "exit" && events[open][1].type === "attentionSequence" && events[open][1]._open && context.sliceSerialize(events[open][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) {
          if ((events[open][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open][1].end.offset - events[open][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3)) {
            continue;
          }
          use = events[open][1].end.offset - events[open][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1;
          const start = { ...events[open][1].end };
          const end = { ...events[index2][1].start };
          movePoint(start, -use);
          movePoint(end, use);
          openingSequence = {
            type: use > 1 ? types.strongSequence : types.emphasisSequence,
            start,
            end: { ...events[open][1].end }
          };
          closingSequence = {
            type: use > 1 ? types.strongSequence : types.emphasisSequence,
            start: { ...events[index2][1].start },
            end
          };
          text3 = {
            type: use > 1 ? types.strongText : types.emphasisText,
            start: { ...events[open][1].end },
            end: { ...events[index2][1].start }
          };
          group = {
            type: use > 1 ? types.strong : types.emphasis,
            start: { ...openingSequence.start },
            end: { ...closingSequence.end }
          };
          events[open][1].end = { ...openingSequence.start };
          events[index2][1].start = { ...closingSequence.end };
          nextEvents = [];
          if (events[open][1].end.offset - events[open][1].start.offset) {
            nextEvents = push(nextEvents, [
              ["enter", events[open][1], context],
              ["exit", events[open][1], context]
            ]);
          }
          nextEvents = push(nextEvents, [
            ["enter", group, context],
            ["enter", openingSequence, context],
            ["exit", openingSequence, context],
            ["enter", text3, context]
          ]);
          ok(context.parser.constructs.insideSpan.null, "expected `insideSpan` to be populated");
          nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open + 1, index2), context));
          nextEvents = push(nextEvents, [
            ["exit", text3, context],
            ["enter", closingSequence, context],
            ["exit", closingSequence, context],
            ["exit", group, context]
          ]);
          if (events[index2][1].end.offset - events[index2][1].start.offset) {
            offset = 2;
            nextEvents = push(nextEvents, [
              ["enter", events[index2][1], context],
              ["exit", events[index2][1], context]
            ]);
          } else {
            offset = 0;
          }
          splice(events, open - 1, index2 - open + 3, nextEvents);
          index2 = open + nextEvents.length - offset - 2;
          break;
        }
      }
    }
  }
  index2 = -1;
  while (++index2 < events.length) {
    if (events[index2][1].type === "attentionSequence") {
      events[index2][1].type = "data";
    }
  }
  return events;
}
function tokenizeAttention(effects, ok2) {
  const attentionMarkers = this.parser.constructs.attentionMarkers.null;
  const previous2 = this.previous;
  const before = classifyCharacter(previous2);
  let marker;
  return start;
  function start(code) {
    ok(code === codes.asterisk || code === codes.underscore, "expected asterisk or underscore");
    marker = code;
    effects.enter("attentionSequence");
    return inside(code);
  }
  function inside(code) {
    if (code === marker) {
      effects.consume(code);
      return inside;
    }
    const token = effects.exit("attentionSequence");
    const after = classifyCharacter(code);
    ok(attentionMarkers, "expected `attentionMarkers` to be populated");
    const open = !after || after === constants2.characterGroupPunctuation && before || attentionMarkers.includes(code);
    const close = !before || before === constants2.characterGroupPunctuation && after || attentionMarkers.includes(previous2);
    token._open = Boolean(marker === codes.asterisk ? open : open && (before || !close));
    token._close = Boolean(marker === codes.asterisk ? close : close && (after || !open));
    return ok2(code);
  }
}
function movePoint(point4, offset) {
  point4.column += offset;
  point4.offset += offset;
  point4._bufferIndex += offset;
}
var attention;
var init_attention = __esm(() => {
  init_development();
  init_dev();
  init_dev6();
  init_default();
  attention = {
    name: "attention",
    resolveAll: resolveAllAttention,
    tokenize: tokenizeAttention
  };
});

// node_modules/micromark-core-commonmark/dev/lib/autolink.js
function tokenizeAutolink(effects, ok2, nok) {
  let size2 = 0;
  return start;
  function start(code) {
    ok(code === codes.lessThan, "expected `<`");
    effects.enter(types.autolink);
    effects.enter(types.autolinkMarker);
    effects.consume(code);
    effects.exit(types.autolinkMarker);
    effects.enter(types.autolinkProtocol);
    return open;
  }
  function open(code) {
    if (asciiAlpha(code)) {
      effects.consume(code);
      return schemeOrEmailAtext;
    }
    if (code === codes.atSign) {
      return nok(code);
    }
    return emailAtext(code);
  }
  function schemeOrEmailAtext(code) {
    if (code === codes.plusSign || code === codes.dash || code === codes.dot || asciiAlphanumeric(code)) {
      size2 = 1;
      return schemeInsideOrEmailAtext(code);
    }
    return emailAtext(code);
  }
  function schemeInsideOrEmailAtext(code) {
    if (code === codes.colon) {
      effects.consume(code);
      size2 = 0;
      return urlInside;
    }
    if ((code === codes.plusSign || code === codes.dash || code === codes.dot || asciiAlphanumeric(code)) && size2++ < constants2.autolinkSchemeSizeMax) {
      effects.consume(code);
      return schemeInsideOrEmailAtext;
    }
    size2 = 0;
    return emailAtext(code);
  }
  function urlInside(code) {
    if (code === codes.greaterThan) {
      effects.exit(types.autolinkProtocol);
      effects.enter(types.autolinkMarker);
      effects.consume(code);
      effects.exit(types.autolinkMarker);
      effects.exit(types.autolink);
      return ok2;
    }
    if (code === codes.eof || code === codes.space || code === codes.lessThan || asciiControl(code)) {
      return nok(code);
    }
    effects.consume(code);
    return urlInside;
  }
  function emailAtext(code) {
    if (code === codes.atSign) {
      effects.consume(code);
      return emailAtSignOrDot;
    }
    if (asciiAtext(code)) {
      effects.consume(code);
      return emailAtext;
    }
    return nok(code);
  }
  function emailAtSignOrDot(code) {
    return asciiAlphanumeric(code) ? emailLabel(code) : nok(code);
  }
  function emailLabel(code) {
    if (code === codes.dot) {
      effects.consume(code);
      size2 = 0;
      return emailAtSignOrDot;
    }
    if (code === codes.greaterThan) {
      effects.exit(types.autolinkProtocol).type = types.autolinkEmail;
      effects.enter(types.autolinkMarker);
      effects.consume(code);
      effects.exit(types.autolinkMarker);
      effects.exit(types.autolink);
      return ok2;
    }
    return emailValue(code);
  }
  function emailValue(code) {
    if ((code === codes.dash || asciiAlphanumeric(code)) && size2++ < constants2.autolinkDomainSizeMax) {
      const next2 = code === codes.dash ? emailValue : emailLabel;
      effects.consume(code);
      return next2;
    }
    return nok(code);
  }
}
var autolink;
var init_autolink = __esm(() => {
  init_development();
  init_dev4();
  init_default();
  autolink = { name: "autolink", tokenize: tokenizeAutolink };
});

// node_modules/micromark-core-commonmark/dev/lib/blank-line.js
function tokenizeBlankLine(effects, ok2, nok) {
  return start;
  function start(code) {
    return markdownSpace(code) ? factorySpace(effects, after, types.linePrefix)(code) : after(code);
  }
  function after(code) {
    return code === codes.eof || markdownLineEnding(code) ? ok2(code) : nok(code);
  }
}
var blankLine;
var init_blank_line = __esm(() => {
  init_dev5();
  init_dev4();
  init_default();
  blankLine = { partial: true, tokenize: tokenizeBlankLine };
});

// node_modules/micromark-core-commonmark/dev/lib/block-quote.js
function tokenizeBlockQuoteStart(effects, ok2, nok) {
  const self2 = this;
  return start;
  function start(code) {
    if (code === codes.greaterThan) {
      const state = self2.containerState;
      ok(state, "expected `containerState` to be defined in container");
      if (!state.open) {
        effects.enter(types.blockQuote, { _container: true });
        state.open = true;
      }
      effects.enter(types.blockQuotePrefix);
      effects.enter(types.blockQuoteMarker);
      effects.consume(code);
      effects.exit(types.blockQuoteMarker);
      return after;
    }
    return nok(code);
  }
  function after(code) {
    if (markdownSpace(code)) {
      effects.enter(types.blockQuotePrefixWhitespace);
      effects.consume(code);
      effects.exit(types.blockQuotePrefixWhitespace);
      effects.exit(types.blockQuotePrefix);
      return ok2;
    }
    effects.exit(types.blockQuotePrefix);
    return ok2(code);
  }
}
function tokenizeBlockQuoteContinuation(effects, ok2, nok) {
  const self2 = this;
  return contStart;
  function contStart(code) {
    if (markdownSpace(code)) {
      ok(self2.parser.constructs.disable.null, "expected `disable.null` to be populated");
      return factorySpace(effects, contBefore, types.linePrefix, self2.parser.constructs.disable.null.includes("codeIndented") ? undefined : constants2.tabSize)(code);
    }
    return contBefore(code);
  }
  function contBefore(code) {
    return effects.attempt(blockQuote, ok2, nok)(code);
  }
}
function exit(effects) {
  effects.exit(types.blockQuote);
}
var blockQuote;
var init_block_quote = __esm(() => {
  init_development();
  init_dev5();
  init_dev4();
  init_default();
  blockQuote = {
    continuation: { tokenize: tokenizeBlockQuoteContinuation },
    exit,
    name: "blockQuote",
    tokenize: tokenizeBlockQuoteStart
  };
});

// node_modules/micromark-core-commonmark/dev/lib/character-escape.js
function tokenizeCharacterEscape(effects, ok2, nok) {
  return start;
  function start(code) {
    ok(code === codes.backslash, "expected `\\`");
    effects.enter(types.characterEscape);
    effects.enter(types.escapeMarker);
    effects.consume(code);
    effects.exit(types.escapeMarker);
    return inside;
  }
  function inside(code) {
    if (asciiPunctuation(code)) {
      effects.enter(types.characterEscapeValue);
      effects.consume(code);
      effects.exit(types.characterEscapeValue);
      effects.exit(types.characterEscape);
      return ok2;
    }
    return nok(code);
  }
}
var characterEscape;
var init_character_escape = __esm(() => {
  init_development();
  init_dev4();
  init_default();
  characterEscape = {
    name: "characterEscape",
    tokenize: tokenizeCharacterEscape
  };
});

// node_modules/micromark-core-commonmark/dev/lib/character-reference.js
function tokenizeCharacterReference(effects, ok2, nok) {
  const self2 = this;
  let size2 = 0;
  let max5;
  let test;
  return start;
  function start(code) {
    ok(code === codes.ampersand, "expected `&`");
    effects.enter(types.characterReference);
    effects.enter(types.characterReferenceMarker);
    effects.consume(code);
    effects.exit(types.characterReferenceMarker);
    return open;
  }
  function open(code) {
    if (code === codes.numberSign) {
      effects.enter(types.characterReferenceMarkerNumeric);
      effects.consume(code);
      effects.exit(types.characterReferenceMarkerNumeric);
      return numeric;
    }
    effects.enter(types.characterReferenceValue);
    max5 = constants2.characterReferenceNamedSizeMax;
    test = asciiAlphanumeric;
    return value2(code);
  }
  function numeric(code) {
    if (code === codes.uppercaseX || code === codes.lowercaseX) {
      effects.enter(types.characterReferenceMarkerHexadecimal);
      effects.consume(code);
      effects.exit(types.characterReferenceMarkerHexadecimal);
      effects.enter(types.characterReferenceValue);
      max5 = constants2.characterReferenceHexadecimalSizeMax;
      test = asciiHexDigit;
      return value2;
    }
    effects.enter(types.characterReferenceValue);
    max5 = constants2.characterReferenceDecimalSizeMax;
    test = asciiDigit;
    return value2(code);
  }
  function value2(code) {
    if (code === codes.semicolon && size2) {
      const token = effects.exit(types.characterReferenceValue);
      if (test === asciiAlphanumeric && !decodeNamedCharacterReference(self2.sliceSerialize(token))) {
        return nok(code);
      }
      effects.enter(types.characterReferenceMarker);
      effects.consume(code);
      effects.exit(types.characterReferenceMarker);
      effects.exit(types.characterReference);
      return ok2;
    }
    if (test(code) && size2++ < max5) {
      effects.consume(code);
      return value2;
    }
    return nok(code);
  }
}
var characterReference;
var init_character_reference = __esm(() => {
  init_development();
  init_decode_named_character_reference();
  init_dev4();
  init_default();
  characterReference = {
    name: "characterReference",
    tokenize: tokenizeCharacterReference
  };
});

// node_modules/micromark-core-commonmark/dev/lib/code-fenced.js
function tokenizeCodeFenced(effects, ok2, nok) {
  const self2 = this;
  const closeStart = { partial: true, tokenize: tokenizeCloseStart };
  let initialPrefix = 0;
  let sizeOpen = 0;
  let marker;
  return start;
  function start(code) {
    return beforeSequenceOpen(code);
  }
  function beforeSequenceOpen(code) {
    ok(code === codes.graveAccent || code === codes.tilde, "expected `` ` `` or `~`");
    const tail = self2.events[self2.events.length - 1];
    initialPrefix = tail && tail[1].type === types.linePrefix ? tail[2].sliceSerialize(tail[1], true).length : 0;
    marker = code;
    effects.enter(types.codeFenced);
    effects.enter(types.codeFencedFence);
    effects.enter(types.codeFencedFenceSequence);
    return sequenceOpen(code);
  }
  function sequenceOpen(code) {
    if (code === marker) {
      sizeOpen++;
      effects.consume(code);
      return sequenceOpen;
    }
    if (sizeOpen < constants2.codeFencedSequenceSizeMin) {
      return nok(code);
    }
    effects.exit(types.codeFencedFenceSequence);
    return markdownSpace(code) ? factorySpace(effects, infoBefore, types.whitespace)(code) : infoBefore(code);
  }
  function infoBefore(code) {
    if (code === codes.eof || markdownLineEnding(code)) {
      effects.exit(types.codeFencedFence);
      return self2.interrupt ? ok2(code) : effects.check(nonLazyContinuation, atNonLazyBreak, after)(code);
    }
    effects.enter(types.codeFencedFenceInfo);
    effects.enter(types.chunkString, { contentType: constants2.contentTypeString });
    return info(code);
  }
  function info(code) {
    if (code === codes.eof || markdownLineEnding(code)) {
      effects.exit(types.chunkString);
      effects.exit(types.codeFencedFenceInfo);
      return infoBefore(code);
    }
    if (markdownSpace(code)) {
      effects.exit(types.chunkString);
      effects.exit(types.codeFencedFenceInfo);
      return factorySpace(effects, metaBefore, types.whitespace)(code);
    }
    if (code === codes.graveAccent && code === marker) {
      return nok(code);
    }
    effects.consume(code);
    return info;
  }
  function metaBefore(code) {
    if (code === codes.eof || markdownLineEnding(code)) {
      return infoBefore(code);
    }
    effects.enter(types.codeFencedFenceMeta);
    effects.enter(types.chunkString, { contentType: constants2.contentTypeString });
    return meta3(code);
  }
  function meta3(code) {
    if (code === codes.eof || markdownLineEnding(code)) {
      effects.exit(types.chunkString);
      effects.exit(types.codeFencedFenceMeta);
      return infoBefore(code);
    }
    if (code === codes.graveAccent && code === marker) {
      return nok(code);
    }
    effects.consume(code);
    return meta3;
  }
  function atNonLazyBreak(code) {
    ok(markdownLineEnding(code), "expected eol");
    return effects.attempt(closeStart, after, contentBefore)(code);
  }
  function contentBefore(code) {
    ok(markdownLineEnding(code), "expected eol");
    effects.enter(types.lineEnding);
    effects.consume(code);
    effects.exit(types.lineEnding);
    return contentStart;
  }
  function contentStart(code) {
    return initialPrefix > 0 && markdownSpace(code) ? factorySpace(effects, beforeContentChunk, types.linePrefix, initialPrefix + 1)(code) : beforeContentChunk(code);
  }
  function beforeContentChunk(code) {
    if (code === codes.eof || markdownLineEnding(code)) {
      return effects.check(nonLazyContinuation, atNonLazyBreak, after)(code);
    }
    effects.enter(types.codeFlowValue);
    return contentChunk(code);
  }
  function contentChunk(code) {
    if (code === codes.eof || markdownLineEnding(code)) {
      effects.exit(types.codeFlowValue);
      return beforeContentChunk(code);
    }
    effects.consume(code);
    return contentChunk;
  }
  function after(code) {
    effects.exit(types.codeFenced);
    return ok2(code);
  }
  function tokenizeCloseStart(effects2, ok3, nok2) {
    let size2 = 0;
    return startBefore;
    function startBefore(code) {
      ok(markdownLineEnding(code), "expected eol");
      effects2.enter(types.lineEnding);
      effects2.consume(code);
      effects2.exit(types.lineEnding);
      return start2;
    }
    function start2(code) {
      ok(self2.parser.constructs.disable.null, "expected `disable.null` to be populated");
      effects2.enter(types.codeFencedFence);
      return markdownSpace(code) ? factorySpace(effects2, beforeSequenceClose, types.linePrefix, self2.parser.constructs.disable.null.includes("codeIndented") ? undefined : constants2.tabSize)(code) : beforeSequenceClose(code);
    }
    function beforeSequenceClose(code) {
      if (code === marker) {
        effects2.enter(types.codeFencedFenceSequence);
        return sequenceClose(code);
      }
      return nok2(code);
    }
    function sequenceClose(code) {
      if (code === marker) {
        size2++;
        effects2.consume(code);
        return sequenceClose;
      }
      if (size2 >= sizeOpen) {
        effects2.exit(types.codeFencedFenceSequence);
        return markdownSpace(code) ? factorySpace(effects2, sequenceCloseAfter, types.whitespace)(code) : sequenceCloseAfter(code);
      }
      return nok2(code);
    }
    function sequenceCloseAfter(code) {
      if (code === codes.eof || markdownLineEnding(code)) {
        effects2.exit(types.codeFencedFence);
        return ok3(code);
      }
      return nok2(code);
    }
  }
}
function tokenizeNonLazyContinuation(effects, ok2, nok) {
  const self2 = this;
  return start;
  function start(code) {
    if (code === codes.eof) {
      return nok(code);
    }
    ok(markdownLineEnding(code), "expected eol");
    effects.enter(types.lineEnding);
    effects.consume(code);
    effects.exit(types.lineEnding);
    return lineStart;
  }
  function lineStart(code) {
    return self2.parser.lazy[self2.now().line] ? nok(code) : ok2(code);
  }
}
var nonLazyContinuation, codeFenced;
var init_code_fenced = __esm(() => {
  init_development();
  init_dev5();
  init_dev4();
  init_default();
  nonLazyContinuation = {
    partial: true,
    tokenize: tokenizeNonLazyContinuation
  };
  codeFenced = {
    concrete: true,
    name: "codeFenced",
    tokenize: tokenizeCodeFenced
  };
});

// node_modules/micromark-core-commonmark/dev/lib/code-indented.js
function tokenizeCodeIndented(effects, ok2, nok) {
  const self2 = this;
  return start;
  function start(code) {
    ok(markdownSpace(code));
    effects.enter(types.codeIndented);
    return factorySpace(effects, afterPrefix, types.linePrefix, constants2.tabSize + 1)(code);
  }
  function afterPrefix(code) {
    const tail = self2.events[self2.events.length - 1];
    return tail && tail[1].type === types.linePrefix && tail[2].sliceSerialize(tail[1], true).length >= constants2.tabSize ? atBreak(code) : nok(code);
  }
  function atBreak(code) {
    if (code === codes.eof) {
      return after(code);
    }
    if (markdownLineEnding(code)) {
      return effects.attempt(furtherStart, atBreak, after)(code);
    }
    effects.enter(types.codeFlowValue);
    return inside(code);
  }
  function inside(code) {
    if (code === codes.eof || markdownLineEnding(code)) {
      effects.exit(types.codeFlowValue);
      return atBreak(code);
    }
    effects.consume(code);
    return inside;
  }
  function after(code) {
    effects.exit(types.codeIndented);
    return ok2(code);
  }
}
function tokenizeFurtherStart(effects, ok2, nok) {
  const self2 = this;
  return furtherStart2;
  function furtherStart2(code) {
    if (self2.parser.lazy[self2.now().line]) {
      return nok(code);
    }
    if (markdownLineEnding(code)) {
      effects.enter(types.lineEnding);
      effects.consume(code);
      effects.exit(types.lineEnding);
      return furtherStart2;
    }
    return factorySpace(effects, afterPrefix, types.linePrefix, constants2.tabSize + 1)(code);
  }
  function afterPrefix(code) {
    const tail = self2.events[self2.events.length - 1];
    return tail && tail[1].type === types.linePrefix && tail[2].sliceSerialize(tail[1], true).length >= constants2.tabSize ? ok2(code) : markdownLineEnding(code) ? furtherStart2(code) : nok(code);
  }
}
var codeIndented, furtherStart;
var init_code_indented = __esm(() => {
  init_development();
  init_dev5();
  init_dev4();
  init_default();
  codeIndented = {
    name: "codeIndented",
    tokenize: tokenizeCodeIndented
  };
  furtherStart = { partial: true, tokenize: tokenizeFurtherStart };
});

// node_modules/micromark-core-commonmark/dev/lib/code-text.js
function resolveCodeText(events) {
  let tailExitIndex = events.length - 4;
  let headEnterIndex = 3;
  let index2;
  let enter;
  if ((events[headEnterIndex][1].type === types.lineEnding || events[headEnterIndex][1].type === "space") && (events[tailExitIndex][1].type === types.lineEnding || events[tailExitIndex][1].type === "space")) {
    index2 = headEnterIndex;
    while (++index2 < tailExitIndex) {
      if (events[index2][1].type === types.codeTextData) {
        events[headEnterIndex][1].type = types.codeTextPadding;
        events[tailExitIndex][1].type = types.codeTextPadding;
        headEnterIndex += 2;
        tailExitIndex -= 2;
        break;
      }
    }
  }
  index2 = headEnterIndex - 1;
  tailExitIndex++;
  while (++index2 <= tailExitIndex) {
    if (enter === undefined) {
      if (index2 !== tailExitIndex && events[index2][1].type !== types.lineEnding) {
        enter = index2;
      }
    } else if (index2 === tailExitIndex || events[index2][1].type === types.lineEnding) {
      events[enter][1].type = types.codeTextData;
      if (index2 !== enter + 2) {
        events[enter][1].end = events[index2 - 1][1].end;
        events.splice(enter + 2, index2 - enter - 2);
        tailExitIndex -= index2 - enter - 2;
        index2 = enter + 2;
      }
      enter = undefined;
    }
  }
  return events;
}
function previous2(code) {
  return code !== codes.graveAccent || this.events[this.events.length - 1][1].type === types.characterEscape;
}
function tokenizeCodeText(effects, ok2, nok) {
  const self2 = this;
  let sizeOpen = 0;
  let size2;
  let token;
  return start;
  function start(code) {
    ok(code === codes.graveAccent, "expected `` ` ``");
    ok(previous2.call(self2, self2.previous), "expected correct previous");
    effects.enter(types.codeText);
    effects.enter(types.codeTextSequence);
    return sequenceOpen(code);
  }
  function sequenceOpen(code) {
    if (code === codes.graveAccent) {
      effects.consume(code);
      sizeOpen++;
      return sequenceOpen;
    }
    effects.exit(types.codeTextSequence);
    return between(code);
  }
  function between(code) {
    if (code === codes.eof) {
      return nok(code);
    }
    if (code === codes.space) {
      effects.enter("space");
      effects.consume(code);
      effects.exit("space");
      return between;
    }
    if (code === codes.graveAccent) {
      token = effects.enter(types.codeTextSequence);
      size2 = 0;
      return sequenceClose(code);
    }
    if (markdownLineEnding(code)) {
      effects.enter(types.lineEnding);
      effects.consume(code);
      effects.exit(types.lineEnding);
      return between;
    }
    effects.enter(types.codeTextData);
    return data2(code);
  }
  function data2(code) {
    if (code === codes.eof || code === codes.space || code === codes.graveAccent || markdownLineEnding(code)) {
      effects.exit(types.codeTextData);
      return between(code);
    }
    effects.consume(code);
    return data2;
  }
  function sequenceClose(code) {
    if (code === codes.graveAccent) {
      effects.consume(code);
      size2++;
      return sequenceClose;
    }
    if (size2 === sizeOpen) {
      effects.exit(types.codeTextSequence);
      effects.exit(types.codeText);
      return ok2(code);
    }
    token.type = types.codeTextData;
    return data2(code);
  }
}
var codeText;
var init_code_text = __esm(() => {
  init_development();
  init_dev4();
  init_default();
  codeText = {
    name: "codeText",
    previous: previous2,
    resolve: resolveCodeText,
    tokenize: tokenizeCodeText
  };
});

// node_modules/micromark-util-subtokenize/dev/lib/splice-buffer.js
class SpliceBuffer {
  constructor(initial2) {
    this.left = initial2 ? [...initial2] : [];
    this.right = [];
  }
  get(index2) {
    if (index2 < 0 || index2 >= this.left.length + this.right.length) {
      throw new RangeError("Cannot access index `" + index2 + "` in a splice buffer of size `" + (this.left.length + this.right.length) + "`");
    }
    if (index2 < this.left.length)
      return this.left[index2];
    return this.right[this.right.length - index2 + this.left.length - 1];
  }
  get length() {
    return this.left.length + this.right.length;
  }
  shift() {
    this.setCursor(0);
    return this.right.pop();
  }
  slice(start, end) {
    const stop = end === null || end === undefined ? Number.POSITIVE_INFINITY : end;
    if (stop < this.left.length) {
      return this.left.slice(start, stop);
    }
    if (start > this.left.length) {
      return this.right.slice(this.right.length - stop + this.left.length, this.right.length - start + this.left.length).reverse();
    }
    return this.left.slice(start).concat(this.right.slice(this.right.length - stop + this.left.length).reverse());
  }
  splice(start, deleteCount, items) {
    const count3 = deleteCount || 0;
    this.setCursor(Math.trunc(start));
    const removed = this.right.splice(this.right.length - count3, Number.POSITIVE_INFINITY);
    if (items)
      chunkedPush(this.left, items);
    return removed.reverse();
  }
  pop() {
    this.setCursor(Number.POSITIVE_INFINITY);
    return this.left.pop();
  }
  push(item) {
    this.setCursor(Number.POSITIVE_INFINITY);
    this.left.push(item);
  }
  pushMany(items) {
    this.setCursor(Number.POSITIVE_INFINITY);
    chunkedPush(this.left, items);
  }
  unshift(item) {
    this.setCursor(0);
    this.right.push(item);
  }
  unshiftMany(items) {
    this.setCursor(0);
    chunkedPush(this.right, items.reverse());
  }
  setCursor(n) {
    if (n === this.left.length || n > this.left.length && this.right.length === 0 || n < 0 && this.left.length === 0)
      return;
    if (n < this.left.length) {
      const removed = this.left.splice(n, Number.POSITIVE_INFINITY);
      chunkedPush(this.right, removed.reverse());
    } else {
      const removed = this.right.splice(this.left.length + this.right.length - n, Number.POSITIVE_INFINITY);
      chunkedPush(this.left, removed.reverse());
    }
  }
}
function chunkedPush(list, right) {
  let chunkStart = 0;
  if (right.length < constants2.v8MaxSafeChunkSize) {
    list.push(...right);
  } else {
    while (chunkStart < right.length) {
      list.push(...right.slice(chunkStart, chunkStart + constants2.v8MaxSafeChunkSize));
      chunkStart += constants2.v8MaxSafeChunkSize;
    }
  }
}
var init_splice_buffer = __esm(() => {
  init_default();
});

// node_modules/micromark-util-subtokenize/dev/index.js
function subtokenize(eventsArray) {
  const jumps = {};
  let index2 = -1;
  let event;
  let lineIndex;
  let otherIndex;
  let otherEvent;
  let parameters;
  let subevents;
  let more;
  const events = new SpliceBuffer(eventsArray);
  while (++index2 < events.length) {
    while (index2 in jumps) {
      index2 = jumps[index2];
    }
    event = events.get(index2);
    if (index2 && event[1].type === types.chunkFlow && events.get(index2 - 1)[1].type === types.listItemPrefix) {
      ok(event[1]._tokenizer, "expected `_tokenizer` on subtokens");
      subevents = event[1]._tokenizer.events;
      otherIndex = 0;
      if (otherIndex < subevents.length && subevents[otherIndex][1].type === types.lineEndingBlank) {
        otherIndex += 2;
      }
      if (otherIndex < subevents.length && subevents[otherIndex][1].type === types.content) {
        while (++otherIndex < subevents.length) {
          if (subevents[otherIndex][1].type === types.content) {
            break;
          }
          if (subevents[otherIndex][1].type === types.chunkText) {
            subevents[otherIndex][1]._isInFirstContentOfListItem = true;
            otherIndex++;
          }
        }
      }
    }
    if (event[0] === "enter") {
      if (event[1].contentType) {
        Object.assign(jumps, subcontent(events, index2));
        index2 = jumps[index2];
        more = true;
      }
    } else if (event[1]._container) {
      otherIndex = index2;
      lineIndex = undefined;
      while (otherIndex--) {
        otherEvent = events.get(otherIndex);
        if (otherEvent[1].type === types.lineEnding || otherEvent[1].type === types.lineEndingBlank) {
          if (otherEvent[0] === "enter") {
            if (lineIndex) {
              events.get(lineIndex)[1].type = types.lineEndingBlank;
            }
            otherEvent[1].type = types.lineEnding;
            lineIndex = otherIndex;
          }
        } else if (otherEvent[1].type === types.linePrefix || otherEvent[1].type === types.listItemIndent) {} else {
          break;
        }
      }
      if (lineIndex) {
        event[1].end = { ...events.get(lineIndex)[1].start };
        parameters = events.slice(lineIndex, index2);
        parameters.unshift(event);
        events.splice(lineIndex, index2 - lineIndex + 1, parameters);
      }
    }
  }
  splice(eventsArray, 0, Number.POSITIVE_INFINITY, events.slice(0));
  return !more;
}
function subcontent(events, eventIndex) {
  const token = events.get(eventIndex)[1];
  const context = events.get(eventIndex)[2];
  let startPosition = eventIndex - 1;
  const startPositions = [];
  ok(token.contentType, "expected `contentType` on subtokens");
  let tokenizer = token._tokenizer;
  if (!tokenizer) {
    tokenizer = context.parser[token.contentType](token.start);
    if (token._contentTypeTextTrailing) {
      tokenizer._contentTypeTextTrailing = true;
    }
  }
  const childEvents = tokenizer.events;
  const jumps = [];
  const gaps = {};
  let stream;
  let previous3;
  let index2 = -1;
  let current = token;
  let adjust = 0;
  let start = 0;
  const breaks = [start];
  while (current) {
    while (events.get(++startPosition)[1] !== current) {}
    ok(!previous3 || current.previous === previous3, "expected previous to match");
    ok(!previous3 || previous3.next === current, "expected next to match");
    startPositions.push(startPosition);
    if (!current._tokenizer) {
      stream = context.sliceStream(current);
      if (!current.next) {
        stream.push(codes.eof);
      }
      if (previous3) {
        tokenizer.defineSkip(current.start);
      }
      if (current._isInFirstContentOfListItem) {
        tokenizer._gfmTasklistFirstContentOfListItem = true;
      }
      tokenizer.write(stream);
      if (current._isInFirstContentOfListItem) {
        tokenizer._gfmTasklistFirstContentOfListItem = undefined;
      }
    }
    previous3 = current;
    current = current.next;
  }
  current = token;
  while (++index2 < childEvents.length) {
    if (childEvents[index2][0] === "exit" && childEvents[index2 - 1][0] === "enter" && childEvents[index2][1].type === childEvents[index2 - 1][1].type && childEvents[index2][1].start.line !== childEvents[index2][1].end.line) {
      ok(current, "expected a current token");
      start = index2 + 1;
      breaks.push(start);
      current._tokenizer = undefined;
      current.previous = undefined;
      current = current.next;
    }
  }
  tokenizer.events = [];
  if (current) {
    current._tokenizer = undefined;
    current.previous = undefined;
    ok(!current.next, "expected no next token");
  } else {
    breaks.pop();
  }
  index2 = breaks.length;
  while (index2--) {
    const slice3 = childEvents.slice(breaks[index2], breaks[index2 + 1]);
    const start2 = startPositions.pop();
    ok(start2 !== undefined, "expected a start position when splicing");
    jumps.push([start2, start2 + slice3.length - 1]);
    events.splice(start2, 2, slice3);
  }
  jumps.reverse();
  index2 = -1;
  while (++index2 < jumps.length) {
    gaps[adjust + jumps[index2][0]] = adjust + jumps[index2][1];
    adjust += jumps[index2][1] - jumps[index2][0] - 1;
  }
  return gaps;
}
var init_dev7 = __esm(() => {
  init_development();
  init_dev();
  init_default();
  init_splice_buffer();
});

// node_modules/micromark-core-commonmark/dev/lib/content.js
function resolveContent(events) {
  subtokenize(events);
  return events;
}
function tokenizeContent(effects, ok2) {
  let previous3;
  return chunkStart;
  function chunkStart(code) {
    ok(code !== codes.eof && !markdownLineEnding(code), "expected no eof or eol");
    effects.enter(types.content);
    previous3 = effects.enter(types.chunkContent, {
      contentType: constants2.contentTypeContent
    });
    return chunkInside(code);
  }
  function chunkInside(code) {
    if (code === codes.eof) {
      return contentEnd(code);
    }
    if (markdownLineEnding(code)) {
      return effects.check(continuationConstruct, contentContinue, contentEnd)(code);
    }
    effects.consume(code);
    return chunkInside;
  }
  function contentEnd(code) {
    effects.exit(types.chunkContent);
    effects.exit(types.content);
    return ok2(code);
  }
  function contentContinue(code) {
    ok(markdownLineEnding(code), "expected eol");
    effects.consume(code);
    effects.exit(types.chunkContent);
    ok(previous3, "expected previous token");
    previous3.next = effects.enter(types.chunkContent, {
      contentType: constants2.contentTypeContent,
      previous: previous3
    });
    previous3 = previous3.next;
    return chunkInside;
  }
}
function tokenizeContinuation(effects, ok2, nok) {
  const self2 = this;
  return startLookahead;
  function startLookahead(code) {
    ok(markdownLineEnding(code), "expected a line ending");
    effects.exit(types.chunkContent);
    effects.enter(types.lineEnding);
    effects.consume(code);
    effects.exit(types.lineEnding);
    return factorySpace(effects, prefixed, types.linePrefix);
  }
  function prefixed(code) {
    if (code === codes.eof || markdownLineEnding(code)) {
      return nok(code);
    }
    ok(self2.parser.constructs.disable.null, "expected `disable.null` to be populated");
    const tail = self2.events[self2.events.length - 1];
    if (!self2.parser.constructs.disable.null.includes("codeIndented") && tail && tail[1].type === types.linePrefix && tail[2].sliceSerialize(tail[1], true).length >= constants2.tabSize) {
      return ok2(code);
    }
    return effects.interrupt(self2.parser.constructs.flow, nok, ok2)(code);
  }
}
var content2, continuationConstruct;
var init_content2 = __esm(() => {
  init_development();
  init_dev5();
  init_dev4();
  init_dev7();
  init_default();
  content2 = { resolve: resolveContent, tokenize: tokenizeContent };
  continuationConstruct = { partial: true, tokenize: tokenizeContinuation };
});

// node_modules/micromark-factory-destination/dev/index.js
function factoryDestination(effects, ok2, nok, type, literalType, literalMarkerType, rawType, stringType, max5) {
  const limit = max5 || Number.POSITIVE_INFINITY;
  let balance = 0;
  return start;
  function start(code) {
    if (code === codes.lessThan) {
      effects.enter(type);
      effects.enter(literalType);
      effects.enter(literalMarkerType);
      effects.consume(code);
      effects.exit(literalMarkerType);
      return enclosedBefore;
    }
    if (code === codes.eof || code === codes.space || code === codes.rightParenthesis || asciiControl(code)) {
      return nok(code);
    }
    effects.enter(type);
    effects.enter(rawType);
    effects.enter(stringType);
    effects.enter(types.chunkString, { contentType: constants2.contentTypeString });
    return raw(code);
  }
  function enclosedBefore(code) {
    if (code === codes.greaterThan) {
      effects.enter(literalMarkerType);
      effects.consume(code);
      effects.exit(literalMarkerType);
      effects.exit(literalType);
      effects.exit(type);
      return ok2;
    }
    effects.enter(stringType);
    effects.enter(types.chunkString, { contentType: constants2.contentTypeString });
    return enclosed(code);
  }
  function enclosed(code) {
    if (code === codes.greaterThan) {
      effects.exit(types.chunkString);
      effects.exit(stringType);
      return enclosedBefore(code);
    }
    if (code === codes.eof || code === codes.lessThan || markdownLineEnding(code)) {
      return nok(code);
    }
    effects.consume(code);
    return code === codes.backslash ? enclosedEscape : enclosed;
  }
  function enclosedEscape(code) {
    if (code === codes.lessThan || code === codes.greaterThan || code === codes.backslash) {
      effects.consume(code);
      return enclosed;
    }
    return enclosed(code);
  }
  function raw(code) {
    if (!balance && (code === codes.eof || code === codes.rightParenthesis || markdownLineEndingOrSpace(code))) {
      effects.exit(types.chunkString);
      effects.exit(stringType);
      effects.exit(rawType);
      effects.exit(type);
      return ok2(code);
    }
    if (balance < limit && code === codes.leftParenthesis) {
      effects.consume(code);
      balance++;
      return raw;
    }
    if (code === codes.rightParenthesis) {
      effects.consume(code);
      balance--;
      return raw;
    }
    if (code === codes.eof || code === codes.space || code === codes.leftParenthesis || asciiControl(code)) {
      return nok(code);
    }
    effects.consume(code);
    return code === codes.backslash ? rawEscape : raw;
  }
  function rawEscape(code) {
    if (code === codes.leftParenthesis || code === codes.rightParenthesis || code === codes.backslash) {
      effects.consume(code);
      return raw;
    }
    return raw(code);
  }
}
var init_dev8 = __esm(() => {
  init_dev4();
  init_default();
});

// node_modules/micromark-factory-label/dev/index.js
function factoryLabel(effects, ok2, nok, type, markerType, stringType) {
  const self2 = this;
  let size2 = 0;
  let seen;
  return start;
  function start(code) {
    ok(code === codes.leftSquareBracket, "expected `[`");
    effects.enter(type);
    effects.enter(markerType);
    effects.consume(code);
    effects.exit(markerType);
    effects.enter(stringType);
    return atBreak;
  }
  function atBreak(code) {
    if (size2 > constants2.linkReferenceSizeMax || code === codes.eof || code === codes.leftSquareBracket || code === codes.rightSquareBracket && !seen || code === codes.caret && !size2 && "_hiddenFootnoteSupport" in self2.parser.constructs) {
      return nok(code);
    }
    if (code === codes.rightSquareBracket) {
      effects.exit(stringType);
      effects.enter(markerType);
      effects.consume(code);
      effects.exit(markerType);
      effects.exit(type);
      return ok2;
    }
    if (markdownLineEnding(code)) {
      effects.enter(types.lineEnding);
      effects.consume(code);
      effects.exit(types.lineEnding);
      return atBreak;
    }
    effects.enter(types.chunkString, { contentType: constants2.contentTypeString });
    return labelInside(code);
  }
  function labelInside(code) {
    if (code === codes.eof || code === codes.leftSquareBracket || code === codes.rightSquareBracket || markdownLineEnding(code) || size2++ > constants2.linkReferenceSizeMax) {
      effects.exit(types.chunkString);
      return atBreak(code);
    }
    effects.consume(code);
    if (!seen)
      seen = !markdownSpace(code);
    return code === codes.backslash ? labelEscape : labelInside;
  }
  function labelEscape(code) {
    if (code === codes.leftSquareBracket || code === codes.backslash || code === codes.rightSquareBracket) {
      effects.consume(code);
      size2++;
      return labelInside;
    }
    return labelInside(code);
  }
}
var init_dev9 = __esm(() => {
  init_development();
  init_dev4();
  init_default();
});

// node_modules/micromark-factory-title/dev/index.js
function factoryTitle(effects, ok2, nok, type, markerType, stringType) {
  let marker;
  return start;
  function start(code) {
    if (code === codes.quotationMark || code === codes.apostrophe || code === codes.leftParenthesis) {
      effects.enter(type);
      effects.enter(markerType);
      effects.consume(code);
      effects.exit(markerType);
      marker = code === codes.leftParenthesis ? codes.rightParenthesis : code;
      return begin;
    }
    return nok(code);
  }
  function begin(code) {
    if (code === marker) {
      effects.enter(markerType);
      effects.consume(code);
      effects.exit(markerType);
      effects.exit(type);
      return ok2;
    }
    effects.enter(stringType);
    return atBreak(code);
  }
  function atBreak(code) {
    if (code === marker) {
      effects.exit(stringType);
      return begin(marker);
    }
    if (code === codes.eof) {
      return nok(code);
    }
    if (markdownLineEnding(code)) {
      effects.enter(types.lineEnding);
      effects.consume(code);
      effects.exit(types.lineEnding);
      return factorySpace(effects, atBreak, types.linePrefix);
    }
    effects.enter(types.chunkString, { contentType: constants2.contentTypeString });
    return inside(code);
  }
  function inside(code) {
    if (code === marker || code === codes.eof || markdownLineEnding(code)) {
      effects.exit(types.chunkString);
      return atBreak(code);
    }
    effects.consume(code);
    return code === codes.backslash ? escape2 : inside;
  }
  function escape2(code) {
    if (code === marker || code === codes.backslash) {
      effects.consume(code);
      return inside;
    }
    return inside(code);
  }
}
var init_dev10 = __esm(() => {
  init_dev5();
  init_dev4();
  init_default();
});

// node_modules/micromark-factory-whitespace/dev/index.js
function factoryWhitespace(effects, ok2) {
  let seen;
  return start;
  function start(code) {
    if (markdownLineEnding(code)) {
      effects.enter(types.lineEnding);
      effects.consume(code);
      effects.exit(types.lineEnding);
      seen = true;
      return start;
    }
    if (markdownSpace(code)) {
      return factorySpace(effects, start, seen ? types.linePrefix : types.lineSuffix)(code);
    }
    return ok2(code);
  }
}
var init_dev11 = __esm(() => {
  init_dev5();
  init_dev4();
  init_default();
});

// node_modules/micromark-core-commonmark/dev/lib/definition.js
function tokenizeDefinition(effects, ok2, nok) {
  const self2 = this;
  let identifier;
  return start;
  function start(code) {
    effects.enter(types.definition);
    return before(code);
  }
  function before(code) {
    ok(code === codes.leftSquareBracket, "expected `[`");
    return factoryLabel.call(self2, effects, labelAfter, nok, types.definitionLabel, types.definitionLabelMarker, types.definitionLabelString)(code);
  }
  function labelAfter(code) {
    identifier = normalizeIdentifier(self2.sliceSerialize(self2.events[self2.events.length - 1][1]).slice(1, -1));
    if (code === codes.colon) {
      effects.enter(types.definitionMarker);
      effects.consume(code);
      effects.exit(types.definitionMarker);
      return markerAfter;
    }
    return nok(code);
  }
  function markerAfter(code) {
    return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, destinationBefore)(code) : destinationBefore(code);
  }
  function destinationBefore(code) {
    return factoryDestination(effects, destinationAfter, nok, types.definitionDestination, types.definitionDestinationLiteral, types.definitionDestinationLiteralMarker, types.definitionDestinationRaw, types.definitionDestinationString)(code);
  }
  function destinationAfter(code) {
    return effects.attempt(titleBefore, after, after)(code);
  }
  function after(code) {
    return markdownSpace(code) ? factorySpace(effects, afterWhitespace, types.whitespace)(code) : afterWhitespace(code);
  }
  function afterWhitespace(code) {
    if (code === codes.eof || markdownLineEnding(code)) {
      effects.exit(types.definition);
      self2.parser.defined.push(identifier);
      return ok2(code);
    }
    return nok(code);
  }
}
function tokenizeTitleBefore(effects, ok2, nok) {
  return titleBefore2;
  function titleBefore2(code) {
    return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, beforeMarker)(code) : nok(code);
  }
  function beforeMarker(code) {
    return factoryTitle(effects, titleAfter, nok, types.definitionTitle, types.definitionTitleMarker, types.definitionTitleString)(code);
  }
  function titleAfter(code) {
    return markdownSpace(code) ? factorySpace(effects, titleAfterOptionalWhitespace, types.whitespace)(code) : titleAfterOptionalWhitespace(code);
  }
  function titleAfterOptionalWhitespace(code) {
    return code === codes.eof || markdownLineEnding(code) ? ok2(code) : nok(code);
  }
}
var definition, titleBefore;
var init_definition = __esm(() => {
  init_development();
  init_dev8();
  init_dev9();
  init_dev5();
  init_dev10();
  init_dev11();
  init_dev4();
  init_dev3();
  init_default();
  definition = { name: "definition", tokenize: tokenizeDefinition };
  titleBefore = { partial: true, tokenize: tokenizeTitleBefore };
});

// node_modules/micromark-core-commonmark/dev/lib/hard-break-escape.js
function tokenizeHardBreakEscape(effects, ok2, nok) {
  return start;
  function start(code) {
    ok(code === codes.backslash, "expected `\\`");
    effects.enter(types.hardBreakEscape);
    effects.consume(code);
    return after;
  }
  function after(code) {
    if (markdownLineEnding(code)) {
      effects.exit(types.hardBreakEscape);
      return ok2(code);
    }
    return nok(code);
  }
}
var hardBreakEscape;
var init_hard_break_escape = __esm(() => {
  init_development();
  init_dev4();
  init_default();
  hardBreakEscape = {
    name: "hardBreakEscape",
    tokenize: tokenizeHardBreakEscape
  };
});

// node_modules/micromark-core-commonmark/dev/lib/heading-atx.js
function resolveHeadingAtx(events, context) {
  let contentEnd = events.length - 2;
  let contentStart = 3;
  let content3;
  let text3;
  if (events[contentStart][1].type === types.whitespace) {
    contentStart += 2;
  }
  if (contentEnd - 2 > contentStart && events[contentEnd][1].type === types.whitespace) {
    contentEnd -= 2;
  }
  if (events[contentEnd][1].type === types.atxHeadingSequence && (contentStart === contentEnd - 1 || contentEnd - 4 > contentStart && events[contentEnd - 2][1].type === types.whitespace)) {
    contentEnd -= contentStart + 1 === contentEnd ? 2 : 4;
  }
  if (contentEnd > contentStart) {
    content3 = {
      type: types.atxHeadingText,
      start: events[contentStart][1].start,
      end: events[contentEnd][1].end
    };
    text3 = {
      type: types.chunkText,
      start: events[contentStart][1].start,
      end: events[contentEnd][1].end,
      contentType: constants2.contentTypeText
    };
    splice(events, contentStart, contentEnd - contentStart + 1, [
      ["enter", content3, context],
      ["enter", text3, context],
      ["exit", text3, context],
      ["exit", content3, context]
    ]);
  }
  return events;
}
function tokenizeHeadingAtx(effects, ok2, nok) {
  let size2 = 0;
  return start;
  function start(code) {
    effects.enter(types.atxHeading);
    return before(code);
  }
  function before(code) {
    ok(code === codes.numberSign, "expected `#`");
    effects.enter(types.atxHeadingSequence);
    return sequenceOpen(code);
  }
  function sequenceOpen(code) {
    if (code === codes.numberSign && size2++ < constants2.atxHeadingOpeningFenceSizeMax) {
      effects.consume(code);
      return sequenceOpen;
    }
    if (code === codes.eof || markdownLineEndingOrSpace(code)) {
      effects.exit(types.atxHeadingSequence);
      return atBreak(code);
    }
    return nok(code);
  }
  function atBreak(code) {
    if (code === codes.numberSign) {
      effects.enter(types.atxHeadingSequence);
      return sequenceFurther(code);
    }
    if (code === codes.eof || markdownLineEnding(code)) {
      effects.exit(types.atxHeading);
      return ok2(code);
    }
    if (markdownSpace(code)) {
      return factorySpace(effects, atBreak, types.whitespace)(code);
    }
    effects.enter(types.atxHeadingText);
    return data2(code);
  }
  function sequenceFurther(code) {
    if (code === codes.numberSign) {
      effects.consume(code);
      return sequenceFurther;
    }
    effects.exit(types.atxHeadingSequence);
    return atBreak(code);
  }
  function data2(code) {
    if (code === codes.eof || code === codes.numberSign || markdownLineEndingOrSpace(code)) {
      effects.exit(types.atxHeadingText);
      return atBreak(code);
    }
    effects.consume(code);
    return data2;
  }
}
var headingAtx;
var init_heading_atx = __esm(() => {
  init_development();
  init_dev5();
  init_dev4();
  init_dev();
  init_default();
  headingAtx = {
    name: "headingAtx",
    resolve: resolveHeadingAtx,
    tokenize: tokenizeHeadingAtx
  };
});

// node_modules/micromark-util-html-tag-name/index.js
var htmlBlockNames, htmlRawNames;
var init_micromark_util_html_tag_name = __esm(() => {
  htmlBlockNames = [
    "address",
    "article",
    "aside",
    "base",
    "basefont",
    "blockquote",
    "body",
    "caption",
    "center",
    "col",
    "colgroup",
    "dd",
    "details",
    "dialog",
    "dir",
    "div",
    "dl",
    "dt",
    "fieldset",
    "figcaption",
    "figure",
    "footer",
    "form",
    "frame",
    "frameset",
    "h1",
    "h2",
    "h3",
    "h4",
    "h5",
    "h6",
    "head",
    "header",
    "hr",
    "html",
    "iframe",
    "legend",
    "li",
    "link",
    "main",
    "menu",
    "menuitem",
    "nav",
    "noframes",
    "ol",
    "optgroup",
    "option",
    "p",
    "param",
    "search",
    "section",
    "summary",
    "table",
    "tbody",
    "td",
    "tfoot",
    "th",
    "thead",
    "title",
    "tr",
    "track",
    "ul"
  ];
  htmlRawNames = ["pre", "script", "style", "textarea"];
});

// node_modules/micromark-core-commonmark/dev/lib/html-flow.js
function resolveToHtmlFlow(events) {
  let index2 = events.length;
  while (index2--) {
    if (events[index2][0] === "enter" && events[index2][1].type === types.htmlFlow) {
      break;
    }
  }
  if (index2 > 1 && events[index2 - 2][1].type === types.linePrefix) {
    events[index2][1].start = events[index2 - 2][1].start;
    events[index2 + 1][1].start = events[index2 - 2][1].start;
    events.splice(index2 - 2, 2);
  }
  return events;
}
function tokenizeHtmlFlow(effects, ok2, nok) {
  const self2 = this;
  let marker;
  let closingTag;
  let buffer;
  let index2;
  let markerB;
  return start;
  function start(code) {
    return before(code);
  }
  function before(code) {
    ok(code === codes.lessThan, "expected `<`");
    effects.enter(types.htmlFlow);
    effects.enter(types.htmlFlowData);
    effects.consume(code);
    return open;
  }
  function open(code) {
    if (code === codes.exclamationMark) {
      effects.consume(code);
      return declarationOpen;
    }
    if (code === codes.slash) {
      effects.consume(code);
      closingTag = true;
      return tagCloseStart;
    }
    if (code === codes.questionMark) {
      effects.consume(code);
      marker = constants2.htmlInstruction;
      return self2.interrupt ? ok2 : continuationDeclarationInside;
    }
    if (asciiAlpha(code)) {
      ok(code !== null);
      effects.consume(code);
      buffer = String.fromCharCode(code);
      return tagName;
    }
    return nok(code);
  }
  function declarationOpen(code) {
    if (code === codes.dash) {
      effects.consume(code);
      marker = constants2.htmlComment;
      return commentOpenInside;
    }
    if (code === codes.leftSquareBracket) {
      effects.consume(code);
      marker = constants2.htmlCdata;
      index2 = 0;
      return cdataOpenInside;
    }
    if (asciiAlpha(code)) {
      effects.consume(code);
      marker = constants2.htmlDeclaration;
      return self2.interrupt ? ok2 : continuationDeclarationInside;
    }
    return nok(code);
  }
  function commentOpenInside(code) {
    if (code === codes.dash) {
      effects.consume(code);
      return self2.interrupt ? ok2 : continuationDeclarationInside;
    }
    return nok(code);
  }
  function cdataOpenInside(code) {
    const value2 = constants2.cdataOpeningString;
    if (code === value2.charCodeAt(index2++)) {
      effects.consume(code);
      if (index2 === value2.length) {
        return self2.interrupt ? ok2 : continuation;
      }
      return cdataOpenInside;
    }
    return nok(code);
  }
  function tagCloseStart(code) {
    if (asciiAlpha(code)) {
      ok(code !== null);
      effects.consume(code);
      buffer = String.fromCharCode(code);
      return tagName;
    }
    return nok(code);
  }
  function tagName(code) {
    if (code === codes.eof || code === codes.slash || code === codes.greaterThan || markdownLineEndingOrSpace(code)) {
      const slash = code === codes.slash;
      const name2 = buffer.toLowerCase();
      if (!slash && !closingTag && htmlRawNames.includes(name2)) {
        marker = constants2.htmlRaw;
        return self2.interrupt ? ok2(code) : continuation(code);
      }
      if (htmlBlockNames.includes(buffer.toLowerCase())) {
        marker = constants2.htmlBasic;
        if (slash) {
          effects.consume(code);
          return basicSelfClosing;
        }
        return self2.interrupt ? ok2(code) : continuation(code);
      }
      marker = constants2.htmlComplete;
      return self2.interrupt && !self2.parser.lazy[self2.now().line] ? nok(code) : closingTag ? completeClosingTagAfter(code) : completeAttributeNameBefore(code);
    }
    if (code === codes.dash || asciiAlphanumeric(code)) {
      effects.consume(code);
      buffer += String.fromCharCode(code);
      return tagName;
    }
    return nok(code);
  }
  function basicSelfClosing(code) {
    if (code === codes.greaterThan) {
      effects.consume(code);
      return self2.interrupt ? ok2 : continuation;
    }
    return nok(code);
  }
  function completeClosingTagAfter(code) {
    if (markdownSpace(code)) {
      effects.consume(code);
      return completeClosingTagAfter;
    }
    return completeEnd(code);
  }
  function completeAttributeNameBefore(code) {
    if (code === codes.slash) {
      effects.consume(code);
      return completeEnd;
    }
    if (code === codes.colon || code === codes.underscore || asciiAlpha(code)) {
      effects.consume(code);
      return completeAttributeName;
    }
    if (markdownSpace(code)) {
      effects.consume(code);
      return completeAttributeNameBefore;
    }
    return completeEnd(code);
  }
  function completeAttributeName(code) {
    if (code === codes.dash || code === codes.dot || code === codes.colon || code === codes.underscore || asciiAlphanumeric(code)) {
      effects.consume(code);
      return completeAttributeName;
    }
    return completeAttributeNameAfter(code);
  }
  function completeAttributeNameAfter(code) {
    if (code === codes.equalsTo) {
      effects.consume(code);
      return completeAttributeValueBefore;
    }
    if (markdownSpace(code)) {
      effects.consume(code);
      return completeAttributeNameAfter;
    }
    return completeAttributeNameBefore(code);
  }
  function completeAttributeValueBefore(code) {
    if (code === codes.eof || code === codes.lessThan || code === codes.equalsTo || code === codes.greaterThan || code === codes.graveAccent) {
      return nok(code);
    }
    if (code === codes.quotationMark || code === codes.apostrophe) {
      effects.consume(code);
      markerB = code;
      return completeAttributeValueQuoted;
    }
    if (markdownSpace(code)) {
      effects.consume(code);
      return completeAttributeValueBefore;
    }
    return completeAttributeValueUnquoted(code);
  }
  function completeAttributeValueQuoted(code) {
    if (code === markerB) {
      effects.consume(code);
      markerB = null;
      return completeAttributeValueQuotedAfter;
    }
    if (code === codes.eof || markdownLineEnding(code)) {
      return nok(code);
    }
    effects.consume(code);
    return completeAttributeValueQuoted;
  }
  function completeAttributeValueUnquoted(code) {
    if (code === codes.eof || code === codes.quotationMark || code === codes.apostrophe || code === codes.slash || code === codes.lessThan || code === codes.equalsTo || code === codes.greaterThan || code === codes.graveAccent || markdownLineEndingOrSpace(code)) {
      return completeAttributeNameAfter(code);
    }
    effects.consume(code);
    return completeAttributeValueUnquoted;
  }
  function completeAttributeValueQuotedAfter(code) {
    if (code === codes.slash || code === codes.greaterThan || markdownSpace(code)) {
      return completeAttributeNameBefore(code);
    }
    return nok(code);
  }
  function completeEnd(code) {
    if (code === codes.greaterThan) {
      effects.consume(code);
      return completeAfter;
    }
    return nok(code);
  }
  function completeAfter(code) {
    if (code === codes.eof || markdownLineEnding(code)) {
      return continuation(code);
    }
    if (markdownSpace(code)) {
      effects.consume(code);
      return completeAfter;
    }
    return nok(code);
  }
  function continuation(code) {
    if (code === codes.dash && marker === constants2.htmlComment) {
      effects.consume(code);
      return continuationCommentInside;
    }
    if (code === codes.lessThan && marker === constants2.htmlRaw) {
      effects.consume(code);
      return continuationRawTagOpen;
    }
    if (code === codes.greaterThan && marker === constants2.htmlDeclaration) {
      effects.consume(code);
      return continuationClose;
    }
    if (code === codes.questionMark && marker === constants2.htmlInstruction) {
      effects.consume(code);
      return continuationDeclarationInside;
    }
    if (code === codes.rightSquareBracket && marker === constants2.htmlCdata) {
      effects.consume(code);
      return continuationCdataInside;
    }
    if (markdownLineEnding(code) && (marker === constants2.htmlBasic || marker === constants2.htmlComplete)) {
      effects.exit(types.htmlFlowData);
      return effects.check(blankLineBefore, continuationAfter, continuationStart)(code);
    }
    if (code === codes.eof || markdownLineEnding(code)) {
      effects.exit(types.htmlFlowData);
      return continuationStart(code);
    }
    effects.consume(code);
    return continuation;
  }
  function continuationStart(code) {
    return effects.check(nonLazyContinuationStart, continuationStartNonLazy, continuationAfter)(code);
  }
  function continuationStartNonLazy(code) {
    ok(markdownLineEnding(code));
    effects.enter(types.lineEnding);
    effects.consume(code);
    effects.exit(types.lineEnding);
    return continuationBefore;
  }
  function continuationBefore(code) {
    if (code === codes.eof || markdownLineEnding(code)) {
      return continuationStart(code);
    }
    effects.enter(types.htmlFlowData);
    return continuation(code);
  }
  function continuationCommentInside(code) {
    if (code === codes.dash) {
      effects.consume(code);
      return continuationDeclarationInside;
    }
    return continuation(code);
  }
  function continuationRawTagOpen(code) {
    if (code === codes.slash) {
      effects.consume(code);
      buffer = "";
      return continuationRawEndTag;
    }
    return continuation(code);
  }
  function continuationRawEndTag(code) {
    if (code === codes.greaterThan) {
      const name2 = buffer.toLowerCase();
      if (htmlRawNames.includes(name2)) {
        effects.consume(code);
        return continuationClose;
      }
      return continuation(code);
    }
    if (asciiAlpha(code) && buffer.length < constants2.htmlRawSizeMax) {
      ok(code !== null);
      effects.consume(code);
      buffer += String.fromCharCode(code);
      return continuationRawEndTag;
    }
    return continuation(code);
  }
  function continuationCdataInside(code) {
    if (code === codes.rightSquareBracket) {
      effects.consume(code);
      return continuationDeclarationInside;
    }
    return continuation(code);
  }
  function continuationDeclarationInside(code) {
    if (code === codes.greaterThan) {
      effects.consume(code);
      return continuationClose;
    }
    if (code === codes.dash && marker === constants2.htmlComment) {
      effects.consume(code);
      return continuationDeclarationInside;
    }
    return continuation(code);
  }
  function continuationClose(code) {
    if (code === codes.eof || markdownLineEnding(code)) {
      effects.exit(types.htmlFlowData);
      return continuationAfter(code);
    }
    effects.consume(code);
    return continuationClose;
  }
  function continuationAfter(code) {
    effects.exit(types.htmlFlow);
    return ok2(code);
  }
}
function tokenizeNonLazyContinuationStart(effects, ok2, nok) {
  const self2 = this;
  return start;
  function start(code) {
    if (markdownLineEnding(code)) {
      effects.enter(types.lineEnding);
      effects.consume(code);
      effects.exit(types.lineEnding);
      return after;
    }
    return nok(code);
  }
  function after(code) {
    return self2.parser.lazy[self2.now().line] ? nok(code) : ok2(code);
  }
}
function tokenizeBlankLineBefore(effects, ok2, nok) {
  return start;
  function start(code) {
    ok(markdownLineEnding(code), "expected a line ending");
    effects.enter(types.lineEnding);
    effects.consume(code);
    effects.exit(types.lineEnding);
    return effects.attempt(blankLine, ok2, nok);
  }
}
var htmlFlow, blankLineBefore, nonLazyContinuationStart;
var init_html_flow = __esm(() => {
  init_development();
  init_dev4();
  init_micromark_util_html_tag_name();
  init_default();
  init_blank_line();
  htmlFlow = {
    concrete: true,
    name: "htmlFlow",
    resolveTo: resolveToHtmlFlow,
    tokenize: tokenizeHtmlFlow
  };
  blankLineBefore = { partial: true, tokenize: tokenizeBlankLineBefore };
  nonLazyContinuationStart = {
    partial: true,
    tokenize: tokenizeNonLazyContinuationStart
  };
});

// node_modules/micromark-core-commonmark/dev/lib/html-text.js
function tokenizeHtmlText(effects, ok2, nok) {
  const self2 = this;
  let marker;
  let index2;
  let returnState;
  return start;
  function start(code) {
    ok(code === codes.lessThan, "expected `<`");
    effects.enter(types.htmlText);
    effects.enter(types.htmlTextData);
    effects.consume(code);
    return open;
  }
  function open(code) {
    if (code === codes.exclamationMark) {
      effects.consume(code);
      return declarationOpen;
    }
    if (code === codes.slash) {
      effects.consume(code);
      return tagCloseStart;
    }
    if (code === codes.questionMark) {
      effects.consume(code);
      return instruction;
    }
    if (asciiAlpha(code)) {
      effects.consume(code);
      return tagOpen;
    }
    return nok(code);
  }
  function declarationOpen(code) {
    if (code === codes.dash) {
      effects.consume(code);
      return commentOpenInside;
    }
    if (code === codes.leftSquareBracket) {
      effects.consume(code);
      index2 = 0;
      return cdataOpenInside;
    }
    if (asciiAlpha(code)) {
      effects.consume(code);
      return declaration;
    }
    return nok(code);
  }
  function commentOpenInside(code) {
    if (code === codes.dash) {
      effects.consume(code);
      return commentEnd;
    }
    return nok(code);
  }
  function comment(code) {
    if (code === codes.eof) {
      return nok(code);
    }
    if (code === codes.dash) {
      effects.consume(code);
      return commentClose;
    }
    if (markdownLineEnding(code)) {
      returnState = comment;
      return lineEndingBefore(code);
    }
    effects.consume(code);
    return comment;
  }
  function commentClose(code) {
    if (code === codes.dash) {
      effects.consume(code);
      return commentEnd;
    }
    return comment(code);
  }
  function commentEnd(code) {
    return code === codes.greaterThan ? end(code) : code === codes.dash ? commentClose(code) : comment(code);
  }
  function cdataOpenInside(code) {
    const value2 = constants2.cdataOpeningString;
    if (code === value2.charCodeAt(index2++)) {
      effects.consume(code);
      return index2 === value2.length ? cdata : cdataOpenInside;
    }
    return nok(code);
  }
  function cdata(code) {
    if (code === codes.eof) {
      return nok(code);
    }
    if (code === codes.rightSquareBracket) {
      effects.consume(code);
      return cdataClose;
    }
    if (markdownLineEnding(code)) {
      returnState = cdata;
      return lineEndingBefore(code);
    }
    effects.consume(code);
    return cdata;
  }
  function cdataClose(code) {
    if (code === codes.rightSquareBracket) {
      effects.consume(code);
      return cdataEnd;
    }
    return cdata(code);
  }
  function cdataEnd(code) {
    if (code === codes.greaterThan) {
      return end(code);
    }
    if (code === codes.rightSquareBracket) {
      effects.consume(code);
      return cdataEnd;
    }
    return cdata(code);
  }
  function declaration(code) {
    if (code === codes.eof || code === codes.greaterThan) {
      return end(code);
    }
    if (markdownLineEnding(code)) {
      returnState = declaration;
      return lineEndingBefore(code);
    }
    effects.consume(code);
    return declaration;
  }
  function instruction(code) {
    if (code === codes.eof) {
      return nok(code);
    }
    if (code === codes.questionMark) {
      effects.consume(code);
      return instructionClose;
    }
    if (markdownLineEnding(code)) {
      returnState = instruction;
      return lineEndingBefore(code);
    }
    effects.consume(code);
    return instruction;
  }
  function instructionClose(code) {
    return code === codes.greaterThan ? end(code) : instruction(code);
  }
  function tagCloseStart(code) {
    if (asciiAlpha(code)) {
      effects.consume(code);
      return tagClose;
    }
    return nok(code);
  }
  function tagClose(code) {
    if (code === codes.dash || asciiAlphanumeric(code)) {
      effects.consume(code);
      return tagClose;
    }
    return tagCloseBetween(code);
  }
  function tagCloseBetween(code) {
    if (markdownLineEnding(code)) {
      returnState = tagCloseBetween;
      return lineEndingBefore(code);
    }
    if (markdownSpace(code)) {
      effects.consume(code);
      return tagCloseBetween;
    }
    return end(code);
  }
  function tagOpen(code) {
    if (code === codes.dash || asciiAlphanumeric(code)) {
      effects.consume(code);
      return tagOpen;
    }
    if (code === codes.slash || code === codes.greaterThan || markdownLineEndingOrSpace(code)) {
      return tagOpenBetween(code);
    }
    return nok(code);
  }
  function tagOpenBetween(code) {
    if (code === codes.slash) {
      effects.consume(code);
      return end;
    }
    if (code === codes.colon || code === codes.underscore || asciiAlpha(code)) {
      effects.consume(code);
      return tagOpenAttributeName;
    }
    if (markdownLineEnding(code)) {
      returnState = tagOpenBetween;
      return lineEndingBefore(code);
    }
    if (markdownSpace(code)) {
      effects.consume(code);
      return tagOpenBetween;
    }
    return end(code);
  }
  function tagOpenAttributeName(code) {
    if (code === codes.dash || code === codes.dot || code === codes.colon || code === codes.underscore || asciiAlphanumeric(code)) {
      effects.consume(code);
      return tagOpenAttributeName;
    }
    return tagOpenAttributeNameAfter(code);
  }
  function tagOpenAttributeNameAfter(code) {
    if (code === codes.equalsTo) {
      effects.consume(code);
      return tagOpenAttributeValueBefore;
    }
    if (markdownLineEnding(code)) {
      returnState = tagOpenAttributeNameAfter;
      return lineEndingBefore(code);
    }
    if (markdownSpace(code)) {
      effects.consume(code);
      return tagOpenAttributeNameAfter;
    }
    return tagOpenBetween(code);
  }
  function tagOpenAttributeValueBefore(code) {
    if (code === codes.eof || code === codes.lessThan || code === codes.equalsTo || code === codes.greaterThan || code === codes.graveAccent) {
      return nok(code);
    }
    if (code === codes.quotationMark || code === codes.apostrophe) {
      effects.consume(code);
      marker = code;
      return tagOpenAttributeValueQuoted;
    }
    if (markdownLineEnding(code)) {
      returnState = tagOpenAttributeValueBefore;
      return lineEndingBefore(code);
    }
    if (markdownSpace(code)) {
      effects.consume(code);
      return tagOpenAttributeValueBefore;
    }
    effects.consume(code);
    return tagOpenAttributeValueUnquoted;
  }
  function tagOpenAttributeValueQuoted(code) {
    if (code === marker) {
      effects.consume(code);
      marker = undefined;
      return tagOpenAttributeValueQuotedAfter;
    }
    if (code === codes.eof) {
      return nok(code);
    }
    if (markdownLineEnding(code)) {
      returnState = tagOpenAttributeValueQuoted;
      return lineEndingBefore(code);
    }
    effects.consume(code);
    return tagOpenAttributeValueQuoted;
  }
  function tagOpenAttributeValueUnquoted(code) {
    if (code === codes.eof || code === codes.quotationMark || code === codes.apostrophe || code === codes.lessThan || code === codes.equalsTo || code === codes.graveAccent) {
      return nok(code);
    }
    if (code === codes.slash || code === codes.greaterThan || markdownLineEndingOrSpace(code)) {
      return tagOpenBetween(code);
    }
    effects.consume(code);
    return tagOpenAttributeValueUnquoted;
  }
  function tagOpenAttributeValueQuotedAfter(code) {
    if (code === codes.slash || code === codes.greaterThan || markdownLineEndingOrSpace(code)) {
      return tagOpenBetween(code);
    }
    return nok(code);
  }
  function end(code) {
    if (code === codes.greaterThan) {
      effects.consume(code);
      effects.exit(types.htmlTextData);
      effects.exit(types.htmlText);
      return ok2;
    }
    return nok(code);
  }
  function lineEndingBefore(code) {
    ok(returnState, "expected return state");
    ok(markdownLineEnding(code), "expected eol");
    effects.exit(types.htmlTextData);
    effects.enter(types.lineEnding);
    effects.consume(code);
    effects.exit(types.lineEnding);
    return lineEndingAfter;
  }
  function lineEndingAfter(code) {
    ok(self2.parser.constructs.disable.null, "expected `disable.null` to be populated");
    return markdownSpace(code) ? factorySpace(effects, lineEndingAfterPrefix, types.linePrefix, self2.parser.constructs.disable.null.includes("codeIndented") ? undefined : constants2.tabSize)(code) : lineEndingAfterPrefix(code);
  }
  function lineEndingAfterPrefix(code) {
    effects.enter(types.htmlTextData);
    return returnState(code);
  }
}
var htmlText;
var init_html_text = __esm(() => {
  init_development();
  init_dev5();
  init_dev4();
  init_default();
  htmlText = { name: "htmlText", tokenize: tokenizeHtmlText };
});

// node_modules/micromark-core-commonmark/dev/lib/label-end.js
function resolveAllLabelEnd(events) {
  let index2 = -1;
  const newEvents = [];
  while (++index2 < events.length) {
    const token = events[index2][1];
    newEvents.push(events[index2]);
    if (token.type === types.labelImage || token.type === types.labelLink || token.type === types.labelEnd) {
      const offset = token.type === types.labelImage ? 4 : 2;
      token.type = types.data;
      index2 += offset;
    }
  }
  if (events.length !== newEvents.length) {
    splice(events, 0, events.length, newEvents);
  }
  return events;
}
function resolveToLabelEnd(events, context) {
  let index2 = events.length;
  let offset = 0;
  let token;
  let open;
  let close;
  let media;
  while (index2--) {
    token = events[index2][1];
    if (open) {
      if (token.type === types.link || token.type === types.labelLink && token._inactive) {
        break;
      }
      if (events[index2][0] === "enter" && token.type === types.labelLink) {
        token._inactive = true;
      }
    } else if (close) {
      if (events[index2][0] === "enter" && (token.type === types.labelImage || token.type === types.labelLink) && !token._balanced) {
        open = index2;
        if (token.type !== types.labelLink) {
          offset = 2;
          break;
        }
      }
    } else if (token.type === types.labelEnd) {
      close = index2;
    }
  }
  ok(open !== undefined, "`open` is supposed to be found");
  ok(close !== undefined, "`close` is supposed to be found");
  const group = {
    type: events[open][1].type === types.labelLink ? types.link : types.image,
    start: { ...events[open][1].start },
    end: { ...events[events.length - 1][1].end }
  };
  const label = {
    type: types.label,
    start: { ...events[open][1].start },
    end: { ...events[close][1].end }
  };
  const text3 = {
    type: types.labelText,
    start: { ...events[open + offset + 2][1].end },
    end: { ...events[close - 2][1].start }
  };
  media = [
    ["enter", group, context],
    ["enter", label, context]
  ];
  media = push(media, events.slice(open + 1, open + offset + 3));
  media = push(media, [["enter", text3, context]]);
  ok(context.parser.constructs.insideSpan.null, "expected `insideSpan.null` to be populated");
  media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open + offset + 4, close - 3), context));
  media = push(media, [
    ["exit", text3, context],
    events[close - 2],
    events[close - 1],
    ["exit", label, context]
  ]);
  media = push(media, events.slice(close + 1));
  media = push(media, [["exit", group, context]]);
  splice(events, open, events.length, media);
  return events;
}
function tokenizeLabelEnd(effects, ok2, nok) {
  const self2 = this;
  let index2 = self2.events.length;
  let labelStart;
  let defined;
  while (index2--) {
    if ((self2.events[index2][1].type === types.labelImage || self2.events[index2][1].type === types.labelLink) && !self2.events[index2][1]._balanced) {
      labelStart = self2.events[index2][1];
      break;
    }
  }
  return start;
  function start(code) {
    ok(code === codes.rightSquareBracket, "expected `]`");
    if (!labelStart) {
      return nok(code);
    }
    if (labelStart._inactive) {
      return labelEndNok(code);
    }
    defined = self2.parser.defined.includes(normalizeIdentifier(self2.sliceSerialize({ start: labelStart.end, end: self2.now() })));
    effects.enter(types.labelEnd);
    effects.enter(types.labelMarker);
    effects.consume(code);
    effects.exit(types.labelMarker);
    effects.exit(types.labelEnd);
    return after;
  }
  function after(code) {
    if (code === codes.leftParenthesis) {
      return effects.attempt(resourceConstruct, labelEndOk, defined ? labelEndOk : labelEndNok)(code);
    }
    if (code === codes.leftSquareBracket) {
      return effects.attempt(referenceFullConstruct, labelEndOk, defined ? referenceNotFull : labelEndNok)(code);
    }
    return defined ? labelEndOk(code) : labelEndNok(code);
  }
  function referenceNotFull(code) {
    return effects.attempt(referenceCollapsedConstruct, labelEndOk, labelEndNok)(code);
  }
  function labelEndOk(code) {
    return ok2(code);
  }
  function labelEndNok(code) {
    labelStart._balanced = true;
    return nok(code);
  }
}
function tokenizeResource(effects, ok2, nok) {
  return resourceStart;
  function resourceStart(code) {
    ok(code === codes.leftParenthesis, "expected left paren");
    effects.enter(types.resource);
    effects.enter(types.resourceMarker);
    effects.consume(code);
    effects.exit(types.resourceMarker);
    return resourceBefore;
  }
  function resourceBefore(code) {
    return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, resourceOpen)(code) : resourceOpen(code);
  }
  function resourceOpen(code) {
    if (code === codes.rightParenthesis) {
      return resourceEnd(code);
    }
    return factoryDestination(effects, resourceDestinationAfter, resourceDestinationMissing, types.resourceDestination, types.resourceDestinationLiteral, types.resourceDestinationLiteralMarker, types.resourceDestinationRaw, types.resourceDestinationString, constants2.linkResourceDestinationBalanceMax)(code);
  }
  function resourceDestinationAfter(code) {
    return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, resourceBetween)(code) : resourceEnd(code);
  }
  function resourceDestinationMissing(code) {
    return nok(code);
  }
  function resourceBetween(code) {
    if (code === codes.quotationMark || code === codes.apostrophe || code === codes.leftParenthesis) {
      return factoryTitle(effects, resourceTitleAfter, nok, types.resourceTitle, types.resourceTitleMarker, types.resourceTitleString)(code);
    }
    return resourceEnd(code);
  }
  function resourceTitleAfter(code) {
    return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, resourceEnd)(code) : resourceEnd(code);
  }
  function resourceEnd(code) {
    if (code === codes.rightParenthesis) {
      effects.enter(types.resourceMarker);
      effects.consume(code);
      effects.exit(types.resourceMarker);
      effects.exit(types.resource);
      return ok2;
    }
    return nok(code);
  }
}
function tokenizeReferenceFull(effects, ok2, nok) {
  const self2 = this;
  return referenceFull;
  function referenceFull(code) {
    ok(code === codes.leftSquareBracket, "expected left bracket");
    return factoryLabel.call(self2, effects, referenceFullAfter, referenceFullMissing, types.reference, types.referenceMarker, types.referenceString)(code);
  }
  function referenceFullAfter(code) {
    return self2.parser.defined.includes(normalizeIdentifier(self2.sliceSerialize(self2.events[self2.events.length - 1][1]).slice(1, -1))) ? ok2(code) : nok(code);
  }
  function referenceFullMissing(code) {
    return nok(code);
  }
}
function tokenizeReferenceCollapsed(effects, ok2, nok) {
  return referenceCollapsedStart;
  function referenceCollapsedStart(code) {
    ok(code === codes.leftSquareBracket, "expected left bracket");
    effects.enter(types.reference);
    effects.enter(types.referenceMarker);
    effects.consume(code);
    effects.exit(types.referenceMarker);
    return referenceCollapsedOpen;
  }
  function referenceCollapsedOpen(code) {
    if (code === codes.rightSquareBracket) {
      effects.enter(types.referenceMarker);
      effects.consume(code);
      effects.exit(types.referenceMarker);
      effects.exit(types.reference);
      return ok2;
    }
    return nok(code);
  }
}
var labelEnd, resourceConstruct, referenceFullConstruct, referenceCollapsedConstruct;
var init_label_end = __esm(() => {
  init_development();
  init_dev8();
  init_dev9();
  init_dev10();
  init_dev11();
  init_dev4();
  init_dev();
  init_dev3();
  init_default();
  labelEnd = {
    name: "labelEnd",
    resolveAll: resolveAllLabelEnd,
    resolveTo: resolveToLabelEnd,
    tokenize: tokenizeLabelEnd
  };
  resourceConstruct = { tokenize: tokenizeResource };
  referenceFullConstruct = { tokenize: tokenizeReferenceFull };
  referenceCollapsedConstruct = { tokenize: tokenizeReferenceCollapsed };
});

// node_modules/micromark-core-commonmark/dev/lib/label-start-image.js
function tokenizeLabelStartImage(effects, ok2, nok) {
  const self2 = this;
  return start;
  function start(code) {
    ok(code === codes.exclamationMark, "expected `!`");
    effects.enter(types.labelImage);
    effects.enter(types.labelImageMarker);
    effects.consume(code);
    effects.exit(types.labelImageMarker);
    return open;
  }
  function open(code) {
    if (code === codes.leftSquareBracket) {
      effects.enter(types.labelMarker);
      effects.consume(code);
      effects.exit(types.labelMarker);
      effects.exit(types.labelImage);
      return after;
    }
    return nok(code);
  }
  function after(code) {
    return code === codes.caret && "_hiddenFootnoteSupport" in self2.parser.constructs ? nok(code) : ok2(code);
  }
}
var labelStartImage;
var init_label_start_image = __esm(() => {
  init_development();
  init_default();
  init_label_end();
  labelStartImage = {
    name: "labelStartImage",
    resolveAll: labelEnd.resolveAll,
    tokenize: tokenizeLabelStartImage
  };
});

// node_modules/micromark-core-commonmark/dev/lib/label-start-link.js
function tokenizeLabelStartLink(effects, ok2, nok) {
  const self2 = this;
  return start;
  function start(code) {
    ok(code === codes.leftSquareBracket, "expected `[`");
    effects.enter(types.labelLink);
    effects.enter(types.labelMarker);
    effects.consume(code);
    effects.exit(types.labelMarker);
    effects.exit(types.labelLink);
    return after;
  }
  function after(code) {
    return code === codes.caret && "_hiddenFootnoteSupport" in self2.parser.constructs ? nok(code) : ok2(code);
  }
}
var labelStartLink;
var init_label_start_link = __esm(() => {
  init_development();
  init_default();
  init_label_end();
  labelStartLink = {
    name: "labelStartLink",
    resolveAll: labelEnd.resolveAll,
    tokenize: tokenizeLabelStartLink
  };
});

// node_modules/micromark-core-commonmark/dev/lib/line-ending.js
function tokenizeLineEnding(effects, ok2) {
  return start;
  function start(code) {
    ok(markdownLineEnding(code), "expected eol");
    effects.enter(types.lineEnding);
    effects.consume(code);
    effects.exit(types.lineEnding);
    return factorySpace(effects, ok2, types.linePrefix);
  }
}
var lineEnding;
var init_line_ending = __esm(() => {
  init_development();
  init_dev5();
  init_dev4();
  init_default();
  lineEnding = { name: "lineEnding", tokenize: tokenizeLineEnding };
});

// node_modules/micromark-core-commonmark/dev/lib/thematic-break.js
function tokenizeThematicBreak(effects, ok2, nok) {
  let size2 = 0;
  let marker;
  return start;
  function start(code) {
    effects.enter(types.thematicBreak);
    return before(code);
  }
  function before(code) {
    ok(code === codes.asterisk || code === codes.dash || code === codes.underscore, "expected `*`, `-`, or `_`");
    marker = code;
    return atBreak(code);
  }
  function atBreak(code) {
    if (code === marker) {
      effects.enter(types.thematicBreakSequence);
      return sequence(code);
    }
    if (size2 >= constants2.thematicBreakMarkerCountMin && (code === codes.eof || markdownLineEnding(code))) {
      effects.exit(types.thematicBreak);
      return ok2(code);
    }
    return nok(code);
  }
  function sequence(code) {
    if (code === marker) {
      effects.consume(code);
      size2++;
      return sequence;
    }
    effects.exit(types.thematicBreakSequence);
    return markdownSpace(code) ? factorySpace(effects, atBreak, types.whitespace)(code) : atBreak(code);
  }
}
var thematicBreak;
var init_thematic_break = __esm(() => {
  init_development();
  init_dev5();
  init_dev4();
  init_default();
  thematicBreak = {
    name: "thematicBreak",
    tokenize: tokenizeThematicBreak
  };
});

// node_modules/micromark-core-commonmark/dev/lib/list.js
function tokenizeListStart(effects, ok2, nok) {
  const self2 = this;
  const tail = self2.events[self2.events.length - 1];
  let initialSize = tail && tail[1].type === types.linePrefix ? tail[2].sliceSerialize(tail[1], true).length : 0;
  let size2 = 0;
  return start;
  function start(code) {
    ok(self2.containerState, "expected state");
    const kind = self2.containerState.type || (code === codes.asterisk || code === codes.plusSign || code === codes.dash ? types.listUnordered : types.listOrdered);
    if (kind === types.listUnordered ? !self2.containerState.marker || code === self2.containerState.marker : asciiDigit(code)) {
      if (!self2.containerState.type) {
        self2.containerState.type = kind;
        effects.enter(kind, { _container: true });
      }
      if (kind === types.listUnordered) {
        effects.enter(types.listItemPrefix);
        return code === codes.asterisk || code === codes.dash ? effects.check(thematicBreak, nok, atMarker)(code) : atMarker(code);
      }
      if (!self2.interrupt || code === codes.digit1) {
        effects.enter(types.listItemPrefix);
        effects.enter(types.listItemValue);
        return inside(code);
      }
    }
    return nok(code);
  }
  function inside(code) {
    ok(self2.containerState, "expected state");
    if (asciiDigit(code) && ++size2 < constants2.listItemValueSizeMax) {
      effects.consume(code);
      return inside;
    }
    if ((!self2.interrupt || size2 < 2) && (self2.containerState.marker ? code === self2.containerState.marker : code === codes.rightParenthesis || code === codes.dot)) {
      effects.exit(types.listItemValue);
      return atMarker(code);
    }
    return nok(code);
  }
  function atMarker(code) {
    ok(self2.containerState, "expected state");
    ok(code !== codes.eof, "eof (`null`) is not a marker");
    effects.enter(types.listItemMarker);
    effects.consume(code);
    effects.exit(types.listItemMarker);
    self2.containerState.marker = self2.containerState.marker || code;
    return effects.check(blankLine, self2.interrupt ? nok : onBlank, effects.attempt(listItemPrefixWhitespaceConstruct, endOfPrefix, otherPrefix));
  }
  function onBlank(code) {
    ok(self2.containerState, "expected state");
    self2.containerState.initialBlankLine = true;
    initialSize++;
    return endOfPrefix(code);
  }
  function otherPrefix(code) {
    if (markdownSpace(code)) {
      effects.enter(types.listItemPrefixWhitespace);
      effects.consume(code);
      effects.exit(types.listItemPrefixWhitespace);
      return endOfPrefix;
    }
    return nok(code);
  }
  function endOfPrefix(code) {
    ok(self2.containerState, "expected state");
    self2.containerState.size = initialSize + self2.sliceSerialize(effects.exit(types.listItemPrefix), true).length;
    return ok2(code);
  }
}
function tokenizeListContinuation(effects, ok2, nok) {
  const self2 = this;
  ok(self2.containerState, "expected state");
  self2.containerState._closeFlow = undefined;
  return effects.check(blankLine, onBlank, notBlank);
  function onBlank(code) {
    ok(self2.containerState, "expected state");
    ok(typeof self2.containerState.size === "number", "expected size");
    self2.containerState.furtherBlankLines = self2.containerState.furtherBlankLines || self2.containerState.initialBlankLine;
    return factorySpace(effects, ok2, types.listItemIndent, self2.containerState.size + 1)(code);
  }
  function notBlank(code) {
    ok(self2.containerState, "expected state");
    if (self2.containerState.furtherBlankLines || !markdownSpace(code)) {
      self2.containerState.furtherBlankLines = undefined;
      self2.containerState.initialBlankLine = undefined;
      return notInCurrentItem(code);
    }
    self2.containerState.furtherBlankLines = undefined;
    self2.containerState.initialBlankLine = undefined;
    return effects.attempt(indentConstruct, ok2, notInCurrentItem)(code);
  }
  function notInCurrentItem(code) {
    ok(self2.containerState, "expected state");
    self2.containerState._closeFlow = true;
    self2.interrupt = undefined;
    ok(self2.parser.constructs.disable.null, "expected `disable.null` to be populated");
    return factorySpace(effects, effects.attempt(list, ok2, nok), types.linePrefix, self2.parser.constructs.disable.null.includes("codeIndented") ? undefined : constants2.tabSize)(code);
  }
}
function tokenizeIndent(effects, ok2, nok) {
  const self2 = this;
  ok(self2.containerState, "expected state");
  ok(typeof self2.containerState.size === "number", "expected size");
  return factorySpace(effects, afterPrefix, types.listItemIndent, self2.containerState.size + 1);
  function afterPrefix(code) {
    ok(self2.containerState, "expected state");
    const tail = self2.events[self2.events.length - 1];
    return tail && tail[1].type === types.listItemIndent && tail[2].sliceSerialize(tail[1], true).length === self2.containerState.size ? ok2(code) : nok(code);
  }
}
function tokenizeListEnd(effects) {
  ok(this.containerState, "expected state");
  ok(typeof this.containerState.type === "string", "expected type");
  effects.exit(this.containerState.type);
}
function tokenizeListItemPrefixWhitespace(effects, ok2, nok) {
  const self2 = this;
  ok(self2.parser.constructs.disable.null, "expected `disable.null` to be populated");
  return factorySpace(effects, afterPrefix, types.listItemPrefixWhitespace, self2.parser.constructs.disable.null.includes("codeIndented") ? undefined : constants2.tabSize + 1);
  function afterPrefix(code) {
    const tail = self2.events[self2.events.length - 1];
    return !markdownSpace(code) && tail && tail[1].type === types.listItemPrefixWhitespace ? ok2(code) : nok(code);
  }
}
var list, listItemPrefixWhitespaceConstruct, indentConstruct;
var init_list = __esm(() => {
  init_development();
  init_dev5();
  init_dev4();
  init_default();
  init_blank_line();
  init_thematic_break();
  list = {
    continuation: { tokenize: tokenizeListContinuation },
    exit: tokenizeListEnd,
    name: "list",
    tokenize: tokenizeListStart
  };
  listItemPrefixWhitespaceConstruct = {
    partial: true,
    tokenize: tokenizeListItemPrefixWhitespace
  };
  indentConstruct = { partial: true, tokenize: tokenizeIndent };
});

// node_modules/micromark-core-commonmark/dev/lib/setext-underline.js
function resolveToSetextUnderline(events, context) {
  let index2 = events.length;
  let content3;
  let text3;
  let definition2;
  while (index2--) {
    if (events[index2][0] === "enter") {
      if (events[index2][1].type === types.content) {
        content3 = index2;
        break;
      }
      if (events[index2][1].type === types.paragraph) {
        text3 = index2;
      }
    } else {
      if (events[index2][1].type === types.content) {
        events.splice(index2, 1);
      }
      if (!definition2 && events[index2][1].type === types.definition) {
        definition2 = index2;
      }
    }
  }
  ok(text3 !== undefined, "expected a `text` index to be found");
  ok(content3 !== undefined, "expected a `text` index to be found");
  ok(events[content3][2] === context, "enter context should be same");
  ok(events[events.length - 1][2] === context, "enter context should be same");
  const heading = {
    type: types.setextHeading,
    start: { ...events[content3][1].start },
    end: { ...events[events.length - 1][1].end }
  };
  events[text3][1].type = types.setextHeadingText;
  if (definition2) {
    events.splice(text3, 0, ["enter", heading, context]);
    events.splice(definition2 + 1, 0, ["exit", events[content3][1], context]);
    events[content3][1].end = { ...events[definition2][1].end };
  } else {
    events[content3][1] = heading;
  }
  events.push(["exit", heading, context]);
  return events;
}
function tokenizeSetextUnderline(effects, ok2, nok) {
  const self2 = this;
  let marker;
  return start;
  function start(code) {
    let index2 = self2.events.length;
    let paragraph;
    ok(code === codes.dash || code === codes.equalsTo, "expected `=` or `-`");
    while (index2--) {
      if (self2.events[index2][1].type !== types.lineEnding && self2.events[index2][1].type !== types.linePrefix && self2.events[index2][1].type !== types.content) {
        paragraph = self2.events[index2][1].type === types.paragraph;
        break;
      }
    }
    if (!self2.parser.lazy[self2.now().line] && (self2.interrupt || paragraph)) {
      effects.enter(types.setextHeadingLine);
      marker = code;
      return before(code);
    }
    return nok(code);
  }
  function before(code) {
    effects.enter(types.setextHeadingLineSequence);
    return inside(code);
  }
  function inside(code) {
    if (code === marker) {
      effects.consume(code);
      return inside;
    }
    effects.exit(types.setextHeadingLineSequence);
    return markdownSpace(code) ? factorySpace(effects, after, types.lineSuffix)(code) : after(code);
  }
  function after(code) {
    if (code === codes.eof || markdownLineEnding(code)) {
      effects.exit(types.setextHeadingLine);
      return ok2(code);
    }
    return nok(code);
  }
}
var setextUnderline;
var init_setext_underline = __esm(() => {
  init_development();
  init_dev5();
  init_dev4();
  init_default();
  setextUnderline = {
    name: "setextUnderline",
    resolveTo: resolveToSetextUnderline,
    tokenize: tokenizeSetextUnderline
  };
});

// node_modules/micromark-core-commonmark/dev/index.js
var init_dev12 = __esm(() => {
  init_attention();
  init_autolink();
  init_blank_line();
  init_block_quote();
  init_character_escape();
  init_character_reference();
  init_code_fenced();
  init_code_indented();
  init_code_text();
  init_content2();
  init_definition();
  init_hard_break_escape();
  init_heading_atx();
  init_html_flow();
  init_html_text();
  init_label_end();
  init_label_start_image();
  init_label_start_link();
  init_line_ending();
  init_list();
  init_setext_underline();
  init_thematic_break();
});

// node_modules/micromark/dev/lib/initialize/flow.js
function initializeFlow(effects) {
  const self2 = this;
  const initial2 = effects.attempt(blankLine, atBlankEnding, effects.attempt(this.parser.constructs.flowInitial, afterConstruct, factorySpace(effects, effects.attempt(this.parser.constructs.flow, afterConstruct, effects.attempt(content2, afterConstruct)), types.linePrefix)));
  return initial2;
  function atBlankEnding(code) {
    ok(code === codes.eof || markdownLineEnding(code), "expected eol or eof");
    if (code === codes.eof) {
      effects.consume(code);
      return;
    }
    effects.enter(types.lineEndingBlank);
    effects.consume(code);
    effects.exit(types.lineEndingBlank);
    self2.currentConstruct = undefined;
    return initial2;
  }
  function afterConstruct(code) {
    ok(code === codes.eof || markdownLineEnding(code), "expected eol or eof");
    if (code === codes.eof) {
      effects.consume(code);
      return;
    }
    effects.enter(types.lineEnding);
    effects.consume(code);
    effects.exit(types.lineEnding);
    self2.currentConstruct = undefined;
    return initial2;
  }
}
var flow;
var init_flow = __esm(() => {
  init_development();
  init_dev12();
  init_dev5();
  init_dev4();
  init_default();
  flow = { tokenize: initializeFlow };
});

// node_modules/micromark/dev/lib/initialize/text.js
function initializeFactory(field) {
  return {
    resolveAll: createResolver(field === "text" ? resolveAllLineSuffixes : undefined),
    tokenize: initializeText
  };
  function initializeText(effects) {
    const self2 = this;
    const constructs2 = this.parser.constructs[field];
    const text4 = effects.attempt(constructs2, start, notText);
    return start;
    function start(code) {
      return atBreak(code) ? text4(code) : notText(code);
    }
    function notText(code) {
      if (code === codes.eof) {
        effects.consume(code);
        return;
      }
      effects.enter(types.data);
      effects.consume(code);
      return data2;
    }
    function data2(code) {
      if (atBreak(code)) {
        effects.exit(types.data);
        return text4(code);
      }
      effects.consume(code);
      return data2;
    }
    function atBreak(code) {
      if (code === codes.eof) {
        return true;
      }
      const list2 = constructs2[code];
      let index2 = -1;
      if (list2) {
        ok(Array.isArray(list2), "expected `disable.null` to be populated");
        while (++index2 < list2.length) {
          const item = list2[index2];
          if (!item.previous || item.previous.call(self2, self2.previous)) {
            return true;
          }
        }
      }
      return false;
    }
  }
}
function createResolver(extraResolver) {
  return resolveAllText;
  function resolveAllText(events, context) {
    let index2 = -1;
    let enter;
    while (++index2 <= events.length) {
      if (enter === undefined) {
        if (events[index2] && events[index2][1].type === types.data) {
          enter = index2;
          index2++;
        }
      } else if (!events[index2] || events[index2][1].type !== types.data) {
        if (index2 !== enter + 2) {
          events[enter][1].end = events[index2 - 1][1].end;
          events.splice(enter + 2, index2 - enter - 2);
          index2 = enter + 2;
        }
        enter = undefined;
      }
    }
    return extraResolver ? extraResolver(events, context) : events;
  }
}
function resolveAllLineSuffixes(events, context) {
  let eventIndex = 0;
  while (++eventIndex <= events.length) {
    if ((eventIndex === events.length || events[eventIndex][1].type === types.lineEnding) && events[eventIndex - 1][1].type === types.data) {
      const data2 = events[eventIndex - 1][1];
      const chunks = context.sliceStream(data2);
      let index2 = chunks.length;
      let bufferIndex = -1;
      let size2 = 0;
      let tabs;
      while (index2--) {
        const chunk = chunks[index2];
        if (typeof chunk === "string") {
          bufferIndex = chunk.length;
          while (chunk.charCodeAt(bufferIndex - 1) === codes.space) {
            size2++;
            bufferIndex--;
          }
          if (bufferIndex)
            break;
          bufferIndex = -1;
        } else if (chunk === codes.horizontalTab) {
          tabs = true;
          size2++;
        } else if (chunk === codes.virtualSpace) {} else {
          index2++;
          break;
        }
      }
      if (context._contentTypeTextTrailing && eventIndex === events.length) {
        size2 = 0;
      }
      if (size2) {
        const token = {
          type: eventIndex === events.length || tabs || size2 < constants2.hardBreakPrefixSizeMin ? types.lineSuffix : types.hardBreakTrailing,
          start: {
            _bufferIndex: index2 ? bufferIndex : data2.start._bufferIndex + bufferIndex,
            _index: data2.start._index + index2,
            line: data2.end.line,
            column: data2.end.column - size2,
            offset: data2.end.offset - size2
          },
          end: { ...data2.end }
        };
        data2.end = { ...token.start };
        if (data2.start.offset === data2.end.offset) {
          Object.assign(data2, token);
        } else {
          events.splice(eventIndex, 0, ["enter", token, context], ["exit", token, context]);
          eventIndex += 2;
        }
      }
      eventIndex++;
    }
  }
  return events;
}
var resolver, string4, text3;
var init_text = __esm(() => {
  init_development();
  init_default();
  resolver = { resolveAll: createResolver() };
  string4 = initializeFactory("string");
  text3 = initializeFactory("text");
});

// node_modules/micromark/dev/lib/constructs.js
var exports_constructs = {};
__export(exports_constructs, {
  text: () => text4,
  string: () => string5,
  insideSpan: () => insideSpan,
  flowInitial: () => flowInitial,
  flow: () => flow2,
  document: () => document3,
  disable: () => disable,
  contentInitial: () => contentInitial,
  attentionMarkers: () => attentionMarkers
});
var document3, contentInitial, flowInitial, flow2, string5, text4, insideSpan, attentionMarkers, disable;
var init_constructs = __esm(() => {
  init_dev12();
  init_default();
  init_text();
  document3 = {
    [codes.asterisk]: list,
    [codes.plusSign]: list,
    [codes.dash]: list,
    [codes.digit0]: list,
    [codes.digit1]: list,
    [codes.digit2]: list,
    [codes.digit3]: list,
    [codes.digit4]: list,
    [codes.digit5]: list,
    [codes.digit6]: list,
    [codes.digit7]: list,
    [codes.digit8]: list,
    [codes.digit9]: list,
    [codes.greaterThan]: blockQuote
  };
  contentInitial = {
    [codes.leftSquareBracket]: definition
  };
  flowInitial = {
    [codes.horizontalTab]: codeIndented,
    [codes.virtualSpace]: codeIndented,
    [codes.space]: codeIndented
  };
  flow2 = {
    [codes.numberSign]: headingAtx,
    [codes.asterisk]: thematicBreak,
    [codes.dash]: [setextUnderline, thematicBreak],
    [codes.lessThan]: htmlFlow,
    [codes.equalsTo]: setextUnderline,
    [codes.underscore]: thematicBreak,
    [codes.graveAccent]: codeFenced,
    [codes.tilde]: codeFenced
  };
  string5 = {
    [codes.ampersand]: characterReference,
    [codes.backslash]: characterEscape
  };
  text4 = {
    [codes.carriageReturn]: lineEnding,
    [codes.lineFeed]: lineEnding,
    [codes.carriageReturnLineFeed]: lineEnding,
    [codes.exclamationMark]: labelStartImage,
    [codes.ampersand]: characterReference,
    [codes.asterisk]: attention,
    [codes.lessThan]: [autolink, htmlText],
    [codes.leftSquareBracket]: labelStartLink,
    [codes.backslash]: [hardBreakEscape, characterEscape],
    [codes.rightSquareBracket]: labelEnd,
    [codes.underscore]: attention,
    [codes.graveAccent]: codeText
  };
  insideSpan = { null: [attention, resolver] };
  attentionMarkers = { null: [codes.asterisk, codes.underscore] };
  disable = { null: [] };
});

// node_modules/ms/index.js
var require_ms = __commonJS((exports, module) => {
  var s = 1000;
  var m = s * 60;
  var h = m * 60;
  var d = h * 24;
  var w = d * 7;
  var y2 = d * 365.25;
  module.exports = function(val, options) {
    options = options || {};
    var type = typeof val;
    if (type === "string" && val.length > 0) {
      return parse7(val);
    } else if (type === "number" && isFinite(val)) {
      return options.long ? fmtLong(val) : fmtShort(val);
    }
    throw new Error("val is not a non-empty string or a valid number. val=" + JSON.stringify(val));
  };
  function parse7(str) {
    str = String(str);
    if (str.length > 100) {
      return;
    }
    var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);
    if (!match) {
      return;
    }
    var n = parseFloat(match[1]);
    var type = (match[2] || "ms").toLowerCase();
    switch (type) {
      case "years":
      case "year":
      case "yrs":
      case "yr":
      case "y":
        return n * y2;
      case "weeks":
      case "week":
      case "w":
        return n * w;
      case "days":
      case "day":
      case "d":
        return n * d;
      case "hours":
      case "hour":
      case "hrs":
      case "hr":
      case "h":
        return n * h;
      case "minutes":
      case "minute":
      case "mins":
      case "min":
      case "m":
        return n * m;
      case "seconds":
      case "second":
      case "secs":
      case "sec":
      case "s":
        return n * s;
      case "milliseconds":
      case "millisecond":
      case "msecs":
      case "msec":
      case "ms":
        return n;
      default:
        return;
    }
  }
  function fmtShort(ms) {
    var msAbs = Math.abs(ms);
    if (msAbs >= d) {
      return Math.round(ms / d) + "d";
    }
    if (msAbs >= h) {
      return Math.round(ms / h) + "h";
    }
    if (msAbs >= m) {
      return Math.round(ms / m) + "m";
    }
    if (msAbs >= s) {
      return Math.round(ms / s) + "s";
    }
    return ms + "ms";
  }
  function fmtLong(ms) {
    var msAbs = Math.abs(ms);
    if (msAbs >= d) {
      return plural(ms, msAbs, d, "day");
    }
    if (msAbs >= h) {
      return plural(ms, msAbs, h, "hour");
    }
    if (msAbs >= m) {
      return plural(ms, msAbs, m, "minute");
    }
    if (msAbs >= s) {
      return plural(ms, msAbs, s, "second");
    }
    return ms + " ms";
  }
  function plural(ms, msAbs, n, name2) {
    var isPlural = msAbs >= n * 1.5;
    return Math.round(ms / n) + " " + name2 + (isPlural ? "s" : "");
  }
});

// node_modules/debug/src/common.js
var require_common = __commonJS((exports, module) => {
  function setup(env) {
    createDebug.debug = createDebug;
    createDebug.default = createDebug;
    createDebug.coerce = coerce;
    createDebug.disable = disable2;
    createDebug.enable = enable;
    createDebug.enabled = enabled;
    createDebug.humanize = require_ms();
    createDebug.destroy = destroy;
    Object.keys(env).forEach((key) => {
      createDebug[key] = env[key];
    });
    createDebug.names = [];
    createDebug.skips = [];
    createDebug.formatters = {};
    function selectColor(namespace) {
      let hash2 = 0;
      for (let i = 0;i < namespace.length; i++) {
        hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i);
        hash2 |= 0;
      }
      return createDebug.colors[Math.abs(hash2) % createDebug.colors.length];
    }
    createDebug.selectColor = selectColor;
    function createDebug(namespace) {
      let prevTime;
      let enableOverride = null;
      let namespacesCache;
      let enabledCache;
      function debug(...args2) {
        if (!debug.enabled) {
          return;
        }
        const self2 = debug;
        const curr = Number(new Date);
        const ms = curr - (prevTime || curr);
        self2.diff = ms;
        self2.prev = prevTime;
        self2.curr = curr;
        prevTime = curr;
        args2[0] = createDebug.coerce(args2[0]);
        if (typeof args2[0] !== "string") {
          args2.unshift("%O");
        }
        let index2 = 0;
        args2[0] = args2[0].replace(/%([a-zA-Z%])/g, (match, format3) => {
          if (match === "%%") {
            return "%";
          }
          index2++;
          const formatter = createDebug.formatters[format3];
          if (typeof formatter === "function") {
            const val = args2[index2];
            match = formatter.call(self2, val);
            args2.splice(index2, 1);
            index2--;
          }
          return match;
        });
        createDebug.formatArgs.call(self2, args2);
        const logFn = self2.log || createDebug.log;
        logFn.apply(self2, args2);
      }
      debug.namespace = namespace;
      debug.useColors = createDebug.useColors();
      debug.color = createDebug.selectColor(namespace);
      debug.extend = extend4;
      debug.destroy = createDebug.destroy;
      Object.defineProperty(debug, "enabled", {
        enumerable: true,
        configurable: false,
        get: () => {
          if (enableOverride !== null) {
            return enableOverride;
          }
          if (namespacesCache !== createDebug.namespaces) {
            namespacesCache = createDebug.namespaces;
            enabledCache = createDebug.enabled(namespace);
          }
          return enabledCache;
        },
        set: (v) => {
          enableOverride = v;
        }
      });
      if (typeof createDebug.init === "function") {
        createDebug.init(debug);
      }
      return debug;
    }
    function extend4(namespace, delimiter) {
      const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
      newDebug.log = this.log;
      return newDebug;
    }
    function enable(namespaces) {
      createDebug.save(namespaces);
      createDebug.namespaces = namespaces;
      createDebug.names = [];
      createDebug.skips = [];
      const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
      for (const ns of split) {
        if (ns[0] === "-") {
          createDebug.skips.push(ns.slice(1));
        } else {
          createDebug.names.push(ns);
        }
      }
    }
    function matchesTemplate(search, template) {
      let searchIndex = 0;
      let templateIndex = 0;
      let starIndex = -1;
      let matchIndex = 0;
      while (searchIndex < search.length) {
        if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
          if (template[templateIndex] === "*") {
            starIndex = templateIndex;
            matchIndex = searchIndex;
            templateIndex++;
          } else {
            searchIndex++;
            templateIndex++;
          }
        } else if (starIndex !== -1) {
          templateIndex = starIndex + 1;
          matchIndex++;
          searchIndex = matchIndex;
        } else {
          return false;
        }
      }
      while (templateIndex < template.length && template[templateIndex] === "*") {
        templateIndex++;
      }
      return templateIndex === template.length;
    }
    function disable2() {
      const namespaces = [
        ...createDebug.names,
        ...createDebug.skips.map((namespace) => "-" + namespace)
      ].join(",");
      createDebug.enable("");
      return namespaces;
    }
    function enabled(name2) {
      for (const skip of createDebug.skips) {
        if (matchesTemplate(name2, skip)) {
          return false;
        }
      }
      for (const ns of createDebug.names) {
        if (matchesTemplate(name2, ns)) {
          return true;
        }
      }
      return false;
    }
    function coerce(val) {
      if (val instanceof Error) {
        return val.stack || val.message;
      }
      return val;
    }
    function destroy() {
      console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
    }
    createDebug.enable(createDebug.load());
    return createDebug;
  }
  module.exports = setup;
});

// node_modules/debug/src/browser.js
var require_browser = __commonJS((exports, module) => {
  exports.formatArgs = formatArgs;
  exports.save = save;
  exports.load = load;
  exports.useColors = useColors;
  exports.storage = localstorage();
  exports.destroy = (() => {
    let warned = false;
    return () => {
      if (!warned) {
        warned = true;
        console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
      }
    };
  })();
  exports.colors = [
    "#0000CC",
    "#0000FF",
    "#0033CC",
    "#0033FF",
    "#0066CC",
    "#0066FF",
    "#0099CC",
    "#0099FF",
    "#00CC00",
    "#00CC33",
    "#00CC66",
    "#00CC99",
    "#00CCCC",
    "#00CCFF",
    "#3300CC",
    "#3300FF",
    "#3333CC",
    "#3333FF",
    "#3366CC",
    "#3366FF",
    "#3399CC",
    "#3399FF",
    "#33CC00",
    "#33CC33",
    "#33CC66",
    "#33CC99",
    "#33CCCC",
    "#33CCFF",
    "#6600CC",
    "#6600FF",
    "#6633CC",
    "#6633FF",
    "#66CC00",
    "#66CC33",
    "#9900CC",
    "#9900FF",
    "#9933CC",
    "#9933FF",
    "#99CC00",
    "#99CC33",
    "#CC0000",
    "#CC0033",
    "#CC0066",
    "#CC0099",
    "#CC00CC",
    "#CC00FF",
    "#CC3300",
    "#CC3333",
    "#CC3366",
    "#CC3399",
    "#CC33CC",
    "#CC33FF",
    "#CC6600",
    "#CC6633",
    "#CC9900",
    "#CC9933",
    "#CCCC00",
    "#CCCC33",
    "#FF0000",
    "#FF0033",
    "#FF0066",
    "#FF0099",
    "#FF00CC",
    "#FF00FF",
    "#FF3300",
    "#FF3333",
    "#FF3366",
    "#FF3399",
    "#FF33CC",
    "#FF33FF",
    "#FF6600",
    "#FF6633",
    "#FF9900",
    "#FF9933",
    "#FFCC00",
    "#FFCC33"
  ];
  function useColors() {
    if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
      return true;
    }
    if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
      return false;
    }
    let m;
    return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
  }
  function formatArgs(args2) {
    args2[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args2[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff);
    if (!this.useColors) {
      return;
    }
    const c = "color: " + this.color;
    args2.splice(1, 0, c, "color: inherit");
    let index2 = 0;
    let lastC = 0;
    args2[0].replace(/%[a-zA-Z%]/g, (match) => {
      if (match === "%%") {
        return;
      }
      index2++;
      if (match === "%c") {
        lastC = index2;
      }
    });
    args2.splice(lastC, 0, c);
  }
  exports.log = console.debug || console.log || (() => {});
  function save(namespaces) {
    try {
      if (namespaces) {
        exports.storage.setItem("debug", namespaces);
      } else {
        exports.storage.removeItem("debug");
      }
    } catch (error49) {}
  }
  function load() {
    let r;
    try {
      r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG");
    } catch (error49) {}
    if (!r && typeof process !== "undefined" && "env" in process) {
      r = process.env.DEBUG;
    }
    return r;
  }
  function localstorage() {
    try {
      return localStorage;
    } catch (error49) {}
  }
  module.exports = require_common()(exports);
  var { formatters } = module.exports;
  formatters.j = function(v) {
    try {
      return JSON.stringify(v);
    } catch (error49) {
      return "[UnexpectedJSONParseError]: " + error49.message;
    }
  };
});

// node_modules/debug/src/node.js
var require_node3 = __commonJS((exports, module) => {
  var tty = __require("tty");
  var util = __require("util");
  exports.init = init;
  exports.log = log3;
  exports.formatArgs = formatArgs;
  exports.save = save;
  exports.load = load;
  exports.useColors = useColors;
  exports.destroy = util.deprecate(() => {}, "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
  exports.colors = [6, 2, 3, 4, 5, 1];
  try {
    const supportsColor2 = (()=>{throw new Error("Cannot require module "+"supports-color");})();
    if (supportsColor2 && (supportsColor2.stderr || supportsColor2).level >= 2) {
      exports.colors = [
        20,
        21,
        26,
        27,
        32,
        33,
        38,
        39,
        40,
        41,
        42,
        43,
        44,
        45,
        56,
        57,
        62,
        63,
        68,
        69,
        74,
        75,
        76,
        77,
        78,
        79,
        80,
        81,
        92,
        93,
        98,
        99,
        112,
        113,
        128,
        129,
        134,
        135,
        148,
        149,
        160,
        161,
        162,
        163,
        164,
        165,
        166,
        167,
        168,
        169,
        170,
        171,
        172,
        173,
        178,
        179,
        184,
        185,
        196,
        197,
        198,
        199,
        200,
        201,
        202,
        203,
        204,
        205,
        206,
        207,
        208,
        209,
        214,
        215,
        220,
        221
      ];
    }
  } catch (error49) {}
  exports.inspectOpts = Object.keys(process.env).filter((key) => {
    return /^debug_/i.test(key);
  }).reduce((obj, key) => {
    const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
      return k.toUpperCase();
    });
    let val = process.env[key];
    if (/^(yes|on|true|enabled)$/i.test(val)) {
      val = true;
    } else if (/^(no|off|false|disabled)$/i.test(val)) {
      val = false;
    } else if (val === "null") {
      val = null;
    } else {
      val = Number(val);
    }
    obj[prop] = val;
    return obj;
  }, {});
  function useColors() {
    return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd);
  }
  function formatArgs(args2) {
    const { namespace: name2, useColors: useColors2 } = this;
    if (useColors2) {
      const c = this.color;
      const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
      const prefix = `  ${colorCode};1m${name2} \x1B[0m`;
      args2[0] = prefix + args2[0].split(`
`).join(`
` + prefix);
      args2.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m");
    } else {
      args2[0] = getDate2() + name2 + " " + args2[0];
    }
  }
  function getDate2() {
    if (exports.inspectOpts.hideDate) {
      return "";
    }
    return new Date().toISOString() + " ";
  }
  function log3(...args2) {
    return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args2) + `
`);
  }
  function save(namespaces) {
    if (namespaces) {
      process.env.DEBUG = namespaces;
    } else {
      delete process.env.DEBUG;
    }
  }
  function load() {
    return process.env.DEBUG;
  }
  function init(debug) {
    debug.inspectOpts = {};
    const keys2 = Object.keys(exports.inspectOpts);
    for (let i = 0;i < keys2.length; i++) {
      debug.inspectOpts[keys2[i]] = exports.inspectOpts[keys2[i]];
    }
  }
  module.exports = require_common()(exports);
  var { formatters } = module.exports;
  formatters.o = function(v) {
    this.inspectOpts.colors = this.useColors;
    return util.inspect(v, this.inspectOpts).split(`
`).map((str) => str.trim()).join(" ");
  };
  formatters.O = function(v) {
    this.inspectOpts.colors = this.useColors;
    return util.inspect(v, this.inspectOpts);
  };
});

// node_modules/debug/src/index.js
var require_src = __commonJS((exports, module) => {
  if (typeof process === "undefined" || process.type === "renderer" || false || process.__nwjs) {
    module.exports = require_browser();
  } else {
    module.exports = require_node3();
  }
});

// node_modules/micromark/dev/lib/create-tokenizer.js
function createTokenizer(parser2, initialize, from2) {
  let point4 = {
    _bufferIndex: -1,
    _index: 0,
    line: from2 && from2.line || 1,
    column: from2 && from2.column || 1,
    offset: from2 && from2.offset || 0
  };
  const columnStart = {};
  const resolveAllConstructs = [];
  let chunks = [];
  let stack = [];
  let consumed = true;
  const effects = {
    attempt: constructFactory(onsuccessfulconstruct),
    check: constructFactory(onsuccessfulcheck),
    consume,
    enter,
    exit: exit2,
    interrupt: constructFactory(onsuccessfulcheck, { interrupt: true })
  };
  const context = {
    code: codes.eof,
    containerState: {},
    defineSkip,
    events: [],
    now,
    parser: parser2,
    previous: codes.eof,
    sliceSerialize,
    sliceStream,
    write: write2
  };
  let state = initialize.tokenize.call(context, effects);
  let expectedCode;
  if (initialize.resolveAll) {
    resolveAllConstructs.push(initialize);
  }
  return context;
  function write2(slice3) {
    chunks = push(chunks, slice3);
    main();
    if (chunks[chunks.length - 1] !== codes.eof) {
      return [];
    }
    addResult(initialize, 0);
    context.events = resolveAll(resolveAllConstructs, context.events, context);
    return context.events;
  }
  function sliceSerialize(token, expandTabs) {
    return serializeChunks(sliceStream(token), expandTabs);
  }
  function sliceStream(token) {
    return sliceChunks(chunks, token);
  }
  function now() {
    const { _bufferIndex, _index, line, column: column2, offset } = point4;
    return { _bufferIndex, _index, line, column: column2, offset };
  }
  function defineSkip(value2) {
    columnStart[value2.line] = value2.column;
    accountForPotentialSkip();
    debug("position: define skip: `%j`", point4);
  }
  function main() {
    let chunkIndex;
    while (point4._index < chunks.length) {
      const chunk = chunks[point4._index];
      if (typeof chunk === "string") {
        chunkIndex = point4._index;
        if (point4._bufferIndex < 0) {
          point4._bufferIndex = 0;
        }
        while (point4._index === chunkIndex && point4._bufferIndex < chunk.length) {
          go(chunk.charCodeAt(point4._bufferIndex));
        }
      } else {
        go(chunk);
      }
    }
  }
  function go(code) {
    ok(consumed === true, "expected character to be consumed");
    consumed = undefined;
    debug("main: passing `%s` to %s", code, state && state.name);
    expectedCode = code;
    ok(typeof state === "function", "expected state");
    state = state(code);
  }
  function consume(code) {
    ok(code === expectedCode, "expected given code to equal expected code");
    debug("consume: `%s`", code);
    ok(consumed === undefined, "expected code to not have been consumed: this might be because `return x(code)` instead of `return x` was used");
    ok(code === null ? context.events.length === 0 || context.events[context.events.length - 1][0] === "exit" : context.events[context.events.length - 1][0] === "enter", "expected last token to be open");
    if (markdownLineEnding(code)) {
      point4.line++;
      point4.column = 1;
      point4.offset += code === codes.carriageReturnLineFeed ? 2 : 1;
      accountForPotentialSkip();
      debug("position: after eol: `%j`", point4);
    } else if (code !== codes.virtualSpace) {
      point4.column++;
      point4.offset++;
    }
    if (point4._bufferIndex < 0) {
      point4._index++;
    } else {
      point4._bufferIndex++;
      if (point4._bufferIndex === chunks[point4._index].length) {
        point4._bufferIndex = -1;
        point4._index++;
      }
    }
    context.previous = code;
    consumed = true;
  }
  function enter(type, fields) {
    const token = fields || {};
    token.type = type;
    token.start = now();
    ok(typeof type === "string", "expected string type");
    ok(type.length > 0, "expected non-empty string");
    debug("enter: `%s`", type);
    context.events.push(["enter", token, context]);
    stack.push(token);
    return token;
  }
  function exit2(type) {
    ok(typeof type === "string", "expected string type");
    ok(type.length > 0, "expected non-empty string");
    const token = stack.pop();
    ok(token, "cannot close w/o open tokens");
    token.end = now();
    ok(type === token.type, "expected exit token to match current token");
    ok(!(token.start._index === token.end._index && token.start._bufferIndex === token.end._bufferIndex), "expected non-empty token (`" + type + "`)");
    debug("exit: `%s`", token.type);
    context.events.push(["exit", token, context]);
    return token;
  }
  function onsuccessfulconstruct(construct, info) {
    addResult(construct, info.from);
  }
  function onsuccessfulcheck(_, info) {
    info.restore();
  }
  function constructFactory(onreturn, fields) {
    return hook;
    function hook(constructs2, returnState, bogusState) {
      let listOfConstructs;
      let constructIndex;
      let currentConstruct;
      let info;
      return Array.isArray(constructs2) ? handleListOfConstructs(constructs2) : ("tokenize" in constructs2) ? handleListOfConstructs([constructs2]) : handleMapOfConstructs(constructs2);
      function handleMapOfConstructs(map4) {
        return start;
        function start(code) {
          const left = code !== null && map4[code];
          const all3 = code !== null && map4.null;
          const list2 = [
            ...Array.isArray(left) ? left : left ? [left] : [],
            ...Array.isArray(all3) ? all3 : all3 ? [all3] : []
          ];
          return handleListOfConstructs(list2)(code);
        }
      }
      function handleListOfConstructs(list2) {
        listOfConstructs = list2;
        constructIndex = 0;
        if (list2.length === 0) {
          ok(bogusState, "expected `bogusState` to be given");
          return bogusState;
        }
        return handleConstruct(list2[constructIndex]);
      }
      function handleConstruct(construct) {
        return start;
        function start(code) {
          info = store();
          currentConstruct = construct;
          if (!construct.partial) {
            context.currentConstruct = construct;
          }
          ok(context.parser.constructs.disable.null, "expected `disable.null` to be populated");
          if (construct.name && context.parser.constructs.disable.null.includes(construct.name)) {
            return nok(code);
          }
          return construct.tokenize.call(fields ? Object.assign(Object.create(context), fields) : context, effects, ok2, nok)(code);
        }
      }
      function ok2(code) {
        ok(code === expectedCode, "expected code");
        consumed = true;
        onreturn(currentConstruct, info);
        return returnState;
      }
      function nok(code) {
        ok(code === expectedCode, "expected code");
        consumed = true;
        info.restore();
        if (++constructIndex < listOfConstructs.length) {
          return handleConstruct(listOfConstructs[constructIndex]);
        }
        return bogusState;
      }
    }
  }
  function addResult(construct, from3) {
    if (construct.resolveAll && !resolveAllConstructs.includes(construct)) {
      resolveAllConstructs.push(construct);
    }
    if (construct.resolve) {
      splice(context.events, from3, context.events.length - from3, construct.resolve(context.events.slice(from3), context));
    }
    if (construct.resolveTo) {
      context.events = construct.resolveTo(context.events, context);
    }
    ok(construct.partial || context.events.length === 0 || context.events[context.events.length - 1][0] === "exit", "expected last token to end");
  }
  function store() {
    const startPoint = now();
    const startPrevious = context.previous;
    const startCurrentConstruct = context.currentConstruct;
    const startEventsIndex = context.events.length;
    const startStack = Array.from(stack);
    return { from: startEventsIndex, restore };
    function restore() {
      point4 = startPoint;
      context.previous = startPrevious;
      context.currentConstruct = startCurrentConstruct;
      context.events.length = startEventsIndex;
      stack = startStack;
      accountForPotentialSkip();
      debug("position: restore: `%j`", point4);
    }
  }
  function accountForPotentialSkip() {
    if (point4.line in columnStart && point4.column < 2) {
      point4.column = columnStart[point4.line];
      point4.offset += columnStart[point4.line] - 1;
    }
  }
}
function sliceChunks(chunks, token) {
  const startIndex = token.start._index;
  const startBufferIndex = token.start._bufferIndex;
  const endIndex = token.end._index;
  const endBufferIndex = token.end._bufferIndex;
  let view;
  if (startIndex === endIndex) {
    ok(endBufferIndex > -1, "expected non-negative end buffer index");
    ok(startBufferIndex > -1, "expected non-negative start buffer index");
    view = [chunks[startIndex].slice(startBufferIndex, endBufferIndex)];
  } else {
    view = chunks.slice(startIndex, endIndex);
    if (startBufferIndex > -1) {
      const head = view[0];
      if (typeof head === "string") {
        view[0] = head.slice(startBufferIndex);
      } else {
        ok(startBufferIndex === 0, "expected `startBufferIndex` to be `0`");
        view.shift();
      }
    }
    if (endBufferIndex > 0) {
      view.push(chunks[endIndex].slice(0, endBufferIndex));
    }
  }
  return view;
}
function serializeChunks(chunks, expandTabs) {
  let index2 = -1;
  const result = [];
  let atTab;
  while (++index2 < chunks.length) {
    const chunk = chunks[index2];
    let value2;
    if (typeof chunk === "string") {
      value2 = chunk;
    } else
      switch (chunk) {
        case codes.carriageReturn: {
          value2 = values.cr;
          break;
        }
        case codes.lineFeed: {
          value2 = values.lf;
          break;
        }
        case codes.carriageReturnLineFeed: {
          value2 = values.cr + values.lf;
          break;
        }
        case codes.horizontalTab: {
          value2 = expandTabs ? values.space : values.ht;
          break;
        }
        case codes.virtualSpace: {
          if (!expandTabs && atTab)
            continue;
          value2 = values.space;
          break;
        }
        default: {
          ok(typeof chunk === "number", "expected number");
          value2 = String.fromCharCode(chunk);
        }
      }
    atTab = chunk === codes.horizontalTab;
    result.push(value2);
  }
  return result.join("");
}
var import_debug, debug;
var init_create_tokenizer = __esm(() => {
  init_development();
  init_dev4();
  init_dev();
  init_default();
  import_debug = __toESM(require_src(), 1);
  debug = import_debug.default("micromark");
});

// node_modules/micromark/dev/lib/parse.js
function parse7(options) {
  const settings = options || {};
  const constructs2 = combineExtensions([exports_constructs, ...settings.extensions || []]);
  const parser2 = {
    constructs: constructs2,
    content: create6(content),
    defined: [],
    document: create6(document2),
    flow: create6(flow),
    lazy: {},
    string: create6(string4),
    text: create6(text3)
  };
  return parser2;
  function create6(initial2) {
    return creator;
    function creator(from2) {
      return createTokenizer(parser2, initial2, from2);
    }
  }
}
var init_parse = __esm(() => {
  init_micromark_util_combine_extensions();
  init_content();
  init_document();
  init_flow();
  init_text();
  init_constructs();
  init_create_tokenizer();
});

// node_modules/micromark/dev/lib/postprocess.js
function postprocess(events) {
  while (!subtokenize(events)) {}
  return events;
}
var init_postprocess = __esm(() => {
  init_dev7();
});

// node_modules/micromark/dev/lib/preprocess.js
function preprocess2() {
  let column2 = 1;
  let buffer = "";
  let start = true;
  let atCarriageReturn;
  return preprocessor;
  function preprocessor(value2, encoding, end) {
    const chunks = [];
    let match;
    let next2;
    let startPosition;
    let endPosition;
    let code;
    value2 = buffer + (typeof value2 === "string" ? value2.toString() : new TextDecoder(encoding || undefined).decode(value2));
    startPosition = 0;
    buffer = "";
    if (start) {
      if (value2.charCodeAt(0) === codes.byteOrderMarker) {
        startPosition++;
      }
      start = undefined;
    }
    while (startPosition < value2.length) {
      search.lastIndex = startPosition;
      match = search.exec(value2);
      endPosition = match && match.index !== undefined ? match.index : value2.length;
      code = value2.charCodeAt(endPosition);
      if (!match) {
        buffer = value2.slice(startPosition);
        break;
      }
      if (code === codes.lf && startPosition === endPosition && atCarriageReturn) {
        chunks.push(codes.carriageReturnLineFeed);
        atCarriageReturn = undefined;
      } else {
        if (atCarriageReturn) {
          chunks.push(codes.carriageReturn);
          atCarriageReturn = undefined;
        }
        if (startPosition < endPosition) {
          chunks.push(value2.slice(startPosition, endPosition));
          column2 += endPosition - startPosition;
        }
        switch (code) {
          case codes.nul: {
            chunks.push(codes.replacementCharacter);
            column2++;
            break;
          }
          case codes.ht: {
            next2 = Math.ceil(column2 / constants2.tabSize) * constants2.tabSize;
            chunks.push(codes.horizontalTab);
            while (column2++ < next2)
              chunks.push(codes.virtualSpace);
            break;
          }
          case codes.lf: {
            chunks.push(codes.lineFeed);
            column2 = 1;
            break;
          }
          default: {
            atCarriageReturn = true;
            column2 = 1;
          }
        }
      }
      startPosition = endPosition + 1;
    }
    if (end) {
      if (atCarriageReturn)
        chunks.push(codes.carriageReturn);
      if (buffer)
        chunks.push(buffer);
      chunks.push(codes.eof);
    }
    return chunks;
  }
}
var search;
var init_preprocess = __esm(() => {
  init_default();
  search = /[\0\t\n\r]/g;
});

// node_modules/micromark/dev/index.js
var init_dev13 = __esm(() => {
  init_parse();
  init_postprocess();
  init_preprocess();
});

// node_modules/micromark-util-decode-string/dev/index.js
function decodeString(value2) {
  return value2.replace(characterEscapeOrReference, decode3);
}
function decode3($0, $1, $2) {
  if ($1) {
    return $1;
  }
  const head = $2.charCodeAt(0);
  if (head === codes.numberSign) {
    const head2 = $2.charCodeAt(1);
    const hex4 = head2 === codes.lowercaseX || head2 === codes.uppercaseX;
    return decodeNumericCharacterReference($2.slice(hex4 ? 2 : 1), hex4 ? constants2.numericBaseHexadecimal : constants2.numericBaseDecimal);
  }
  return decodeNamedCharacterReference($2) || $0;
}
var characterEscapeOrReference;
var init_dev14 = __esm(() => {
  init_decode_named_character_reference();
  init_dev2();
  init_default();
  characterEscapeOrReference = /\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;
});

// node_modules/mdast-util-from-markdown/dev/lib/index.js
function fromMarkdown(value2, encoding, options) {
  if (encoding && typeof encoding === "object") {
    options = encoding;
    encoding = undefined;
  }
  return compiler(options)(postprocess(parse7(options).document().write(preprocess2()(value2, encoding, true))));
}
function compiler(options) {
  const config3 = {
    transforms: [],
    canContainEols: ["emphasis", "fragment", "heading", "paragraph", "strong"],
    enter: {
      autolink: opener(link2),
      autolinkProtocol: onenterdata,
      autolinkEmail: onenterdata,
      atxHeading: opener(heading),
      blockQuote: opener(blockQuote2),
      characterEscape: onenterdata,
      characterReference: onenterdata,
      codeFenced: opener(codeFlow),
      codeFencedFenceInfo: buffer,
      codeFencedFenceMeta: buffer,
      codeIndented: opener(codeFlow, buffer),
      codeText: opener(codeText2, buffer),
      codeTextData: onenterdata,
      data: onenterdata,
      codeFlowValue: onenterdata,
      definition: opener(definition2),
      definitionDestinationString: buffer,
      definitionLabelString: buffer,
      definitionTitleString: buffer,
      emphasis: opener(emphasis),
      hardBreakEscape: opener(hardBreak),
      hardBreakTrailing: opener(hardBreak),
      htmlFlow: opener(html, buffer),
      htmlFlowData: onenterdata,
      htmlText: opener(html, buffer),
      htmlTextData: onenterdata,
      image: opener(image2),
      label: buffer,
      link: opener(link2),
      listItem: opener(listItem),
      listItemValue: onenterlistitemvalue,
      listOrdered: opener(list2, onenterlistordered),
      listUnordered: opener(list2),
      paragraph: opener(paragraph),
      reference: onenterreference,
      referenceString: buffer,
      resourceDestinationString: buffer,
      resourceTitleString: buffer,
      setextHeading: opener(heading),
      strong: opener(strong),
      thematicBreak: opener(thematicBreak2)
    },
    exit: {
      atxHeading: closer(),
      atxHeadingSequence: onexitatxheadingsequence,
      autolink: closer(),
      autolinkEmail: onexitautolinkemail,
      autolinkProtocol: onexitautolinkprotocol,
      blockQuote: closer(),
      characterEscapeValue: onexitdata,
      characterReferenceMarkerHexadecimal: onexitcharacterreferencemarker,
      characterReferenceMarkerNumeric: onexitcharacterreferencemarker,
      characterReferenceValue: onexitcharacterreferencevalue,
      characterReference: onexitcharacterreference,
      codeFenced: closer(onexitcodefenced),
      codeFencedFence: onexitcodefencedfence,
      codeFencedFenceInfo: onexitcodefencedfenceinfo,
      codeFencedFenceMeta: onexitcodefencedfencemeta,
      codeFlowValue: onexitdata,
      codeIndented: closer(onexitcodeindented),
      codeText: closer(onexitcodetext),
      codeTextData: onexitdata,
      data: onexitdata,
      definition: closer(),
      definitionDestinationString: onexitdefinitiondestinationstring,
      definitionLabelString: onexitdefinitionlabelstring,
      definitionTitleString: onexitdefinitiontitlestring,
      emphasis: closer(),
      hardBreakEscape: closer(onexithardbreak),
      hardBreakTrailing: closer(onexithardbreak),
      htmlFlow: closer(onexithtmlflow),
      htmlFlowData: onexitdata,
      htmlText: closer(onexithtmltext),
      htmlTextData: onexitdata,
      image: closer(onexitimage),
      label: onexitlabel,
      labelText: onexitlabeltext,
      lineEnding: onexitlineending,
      link: closer(onexitlink),
      listItem: closer(),
      listOrdered: closer(),
      listUnordered: closer(),
      paragraph: closer(),
      referenceString: onexitreferencestring,
      resourceDestinationString: onexitresourcedestinationstring,
      resourceTitleString: onexitresourcetitlestring,
      resource: onexitresource,
      setextHeading: closer(onexitsetextheading),
      setextHeadingLineSequence: onexitsetextheadinglinesequence,
      setextHeadingText: onexitsetextheadingtext,
      strong: closer(),
      thematicBreak: closer()
    }
  };
  configure(config3, (options || {}).mdastExtensions || []);
  const data2 = {};
  return compile;
  function compile(events) {
    let tree = { type: "root", children: [] };
    const context = {
      stack: [tree],
      tokenStack: [],
      config: config3,
      enter,
      exit: exit2,
      buffer,
      resume,
      data: data2
    };
    const listStack = [];
    let index2 = -1;
    while (++index2 < events.length) {
      if (events[index2][1].type === types.listOrdered || events[index2][1].type === types.listUnordered) {
        if (events[index2][0] === "enter") {
          listStack.push(index2);
        } else {
          const tail = listStack.pop();
          ok(typeof tail === "number", "expected list to be open");
          index2 = prepareList(events, tail, index2);
        }
      }
    }
    index2 = -1;
    while (++index2 < events.length) {
      const handler = config3[events[index2][0]];
      if (own3.call(handler, events[index2][1].type)) {
        handler[events[index2][1].type].call(Object.assign({ sliceSerialize: events[index2][2].sliceSerialize }, context), events[index2][1]);
      }
    }
    if (context.tokenStack.length > 0) {
      const tail = context.tokenStack[context.tokenStack.length - 1];
      const handler = tail[1] || defaultOnError;
      handler.call(context, undefined, tail[0]);
    }
    tree.position = {
      start: point4(events.length > 0 ? events[0][1].start : { line: 1, column: 1, offset: 0 }),
      end: point4(events.length > 0 ? events[events.length - 2][1].end : { line: 1, column: 1, offset: 0 })
    };
    index2 = -1;
    while (++index2 < config3.transforms.length) {
      tree = config3.transforms[index2](tree) || tree;
    }
    return tree;
  }
  function prepareList(events, start, length2) {
    let index2 = start - 1;
    let containerBalance = -1;
    let listSpread = false;
    let listItem2;
    let lineIndex;
    let firstBlankLineIndex;
    let atMarker;
    while (++index2 <= length2) {
      const event = events[index2];
      switch (event[1].type) {
        case types.listUnordered:
        case types.listOrdered:
        case types.blockQuote: {
          if (event[0] === "enter") {
            containerBalance++;
          } else {
            containerBalance--;
          }
          atMarker = undefined;
          break;
        }
        case types.lineEndingBlank: {
          if (event[0] === "enter") {
            if (listItem2 && !atMarker && !containerBalance && !firstBlankLineIndex) {
              firstBlankLineIndex = index2;
            }
            atMarker = undefined;
          }
          break;
        }
        case types.linePrefix:
        case types.listItemValue:
        case types.listItemMarker:
        case types.listItemPrefix:
        case types.listItemPrefixWhitespace: {
          break;
        }
        default: {
          atMarker = undefined;
        }
      }
      if (!containerBalance && event[0] === "enter" && event[1].type === types.listItemPrefix || containerBalance === -1 && event[0] === "exit" && (event[1].type === types.listUnordered || event[1].type === types.listOrdered)) {
        if (listItem2) {
          let tailIndex = index2;
          lineIndex = undefined;
          while (tailIndex--) {
            const tailEvent = events[tailIndex];
            if (tailEvent[1].type === types.lineEnding || tailEvent[1].type === types.lineEndingBlank) {
              if (tailEvent[0] === "exit")
                continue;
              if (lineIndex) {
                events[lineIndex][1].type = types.lineEndingBlank;
                listSpread = true;
              }
              tailEvent[1].type = types.lineEnding;
              lineIndex = tailIndex;
            } else if (tailEvent[1].type === types.linePrefix || tailEvent[1].type === types.blockQuotePrefix || tailEvent[1].type === types.blockQuotePrefixWhitespace || tailEvent[1].type === types.blockQuoteMarker || tailEvent[1].type === types.listItemIndent) {} else {
              break;
            }
          }
          if (firstBlankLineIndex && (!lineIndex || firstBlankLineIndex < lineIndex)) {
            listItem2._spread = true;
          }
          listItem2.end = Object.assign({}, lineIndex ? events[lineIndex][1].start : event[1].end);
          events.splice(lineIndex || index2, 0, ["exit", listItem2, event[2]]);
          index2++;
          length2++;
        }
        if (event[1].type === types.listItemPrefix) {
          const item = {
            type: "listItem",
            _spread: false,
            start: Object.assign({}, event[1].start),
            end: undefined
          };
          listItem2 = item;
          events.splice(index2, 0, ["enter", item, event[2]]);
          index2++;
          length2++;
          firstBlankLineIndex = undefined;
          atMarker = true;
        }
      }
    }
    events[start][1]._spread = listSpread;
    return length2;
  }
  function opener(create6, and) {
    return open;
    function open(token) {
      enter.call(this, create6(token), token);
      if (and)
        and.call(this, token);
    }
  }
  function buffer() {
    this.stack.push({ type: "fragment", children: [] });
  }
  function enter(node2, token, errorHandler) {
    const parent = this.stack[this.stack.length - 1];
    ok(parent, "expected `parent`");
    ok("children" in parent, "expected `parent`");
    const siblings = parent.children;
    siblings.push(node2);
    this.stack.push(node2);
    this.tokenStack.push([token, errorHandler || undefined]);
    node2.position = {
      start: point4(token.start),
      end: undefined
    };
  }
  function closer(and) {
    return close;
    function close(token) {
      if (and)
        and.call(this, token);
      exit2.call(this, token);
    }
  }
  function exit2(token, onExitError) {
    const node2 = this.stack.pop();
    ok(node2, "expected `node`");
    const open = this.tokenStack.pop();
    if (!open) {
      throw new Error("Cannot close `" + token.type + "` (" + stringifyPosition({ start: token.start, end: token.end }) + "): it’s not open");
    } else if (open[0].type !== token.type) {
      if (onExitError) {
        onExitError.call(this, token, open[0]);
      } else {
        const handler = open[1] || defaultOnError;
        handler.call(this, token, open[0]);
      }
    }
    ok(node2.type !== "fragment", "unexpected fragment `exit`ed");
    ok(node2.position, "expected `position` to be defined");
    node2.position.end = point4(token.end);
  }
  function resume() {
    return toString(this.stack.pop());
  }
  function onenterlistordered() {
    this.data.expectingFirstListItemValue = true;
  }
  function onenterlistitemvalue(token) {
    if (this.data.expectingFirstListItemValue) {
      const ancestor = this.stack[this.stack.length - 2];
      ok(ancestor, "expected nodes on stack");
      ok(ancestor.type === "list", "expected list on stack");
      ancestor.start = Number.parseInt(this.sliceSerialize(token), constants2.numericBaseDecimal);
      this.data.expectingFirstListItemValue = undefined;
    }
  }
  function onexitcodefencedfenceinfo() {
    const data3 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "code", "expected code on stack");
    node2.lang = data3;
  }
  function onexitcodefencedfencemeta() {
    const data3 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "code", "expected code on stack");
    node2.meta = data3;
  }
  function onexitcodefencedfence() {
    if (this.data.flowCodeInside)
      return;
    this.buffer();
    this.data.flowCodeInside = true;
  }
  function onexitcodefenced() {
    const data3 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "code", "expected code on stack");
    node2.value = data3.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g, "");
    this.data.flowCodeInside = undefined;
  }
  function onexitcodeindented() {
    const data3 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "code", "expected code on stack");
    node2.value = data3.replace(/(\r?\n|\r)$/g, "");
  }
  function onexitdefinitionlabelstring(token) {
    const label = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "definition", "expected definition on stack");
    node2.label = label;
    node2.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase();
  }
  function onexitdefinitiontitlestring() {
    const data3 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "definition", "expected definition on stack");
    node2.title = data3;
  }
  function onexitdefinitiondestinationstring() {
    const data3 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "definition", "expected definition on stack");
    node2.url = data3;
  }
  function onexitatxheadingsequence(token) {
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "heading", "expected heading on stack");
    if (!node2.depth) {
      const depth = this.sliceSerialize(token).length;
      ok(depth === 1 || depth === 2 || depth === 3 || depth === 4 || depth === 5 || depth === 6, "expected `depth` between `1` and `6`");
      node2.depth = depth;
    }
  }
  function onexitsetextheadingtext() {
    this.data.setextHeadingSlurpLineEnding = true;
  }
  function onexitsetextheadinglinesequence(token) {
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "heading", "expected heading on stack");
    node2.depth = this.sliceSerialize(token).codePointAt(0) === codes.equalsTo ? 1 : 2;
  }
  function onexitsetextheading() {
    this.data.setextHeadingSlurpLineEnding = undefined;
  }
  function onenterdata(token) {
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok("children" in node2, "expected parent on stack");
    const siblings = node2.children;
    let tail = siblings[siblings.length - 1];
    if (!tail || tail.type !== "text") {
      tail = text5();
      tail.position = {
        start: point4(token.start),
        end: undefined
      };
      siblings.push(tail);
    }
    this.stack.push(tail);
  }
  function onexitdata(token) {
    const tail = this.stack.pop();
    ok(tail, "expected a `node` to be on the stack");
    ok("value" in tail, "expected a `literal` to be on the stack");
    ok(tail.position, "expected `node` to have an open position");
    tail.value += this.sliceSerialize(token);
    tail.position.end = point4(token.end);
  }
  function onexitlineending(token) {
    const context = this.stack[this.stack.length - 1];
    ok(context, "expected `node`");
    if (this.data.atHardBreak) {
      ok("children" in context, "expected `parent`");
      const tail = context.children[context.children.length - 1];
      ok(tail.position, "expected tail to have a starting position");
      tail.position.end = point4(token.end);
      this.data.atHardBreak = undefined;
      return;
    }
    if (!this.data.setextHeadingSlurpLineEnding && config3.canContainEols.includes(context.type)) {
      onenterdata.call(this, token);
      onexitdata.call(this, token);
    }
  }
  function onexithardbreak() {
    this.data.atHardBreak = true;
  }
  function onexithtmlflow() {
    const data3 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "html", "expected html on stack");
    node2.value = data3;
  }
  function onexithtmltext() {
    const data3 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "html", "expected html on stack");
    node2.value = data3;
  }
  function onexitcodetext() {
    const data3 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "inlineCode", "expected inline code on stack");
    node2.value = data3;
  }
  function onexitlink() {
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "link", "expected link on stack");
    if (this.data.inReference) {
      const referenceType = this.data.referenceType || "shortcut";
      node2.type += "Reference";
      node2.referenceType = referenceType;
      delete node2.url;
      delete node2.title;
    } else {
      delete node2.identifier;
      delete node2.label;
    }
    this.data.referenceType = undefined;
  }
  function onexitimage() {
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "image", "expected image on stack");
    if (this.data.inReference) {
      const referenceType = this.data.referenceType || "shortcut";
      node2.type += "Reference";
      node2.referenceType = referenceType;
      delete node2.url;
      delete node2.title;
    } else {
      delete node2.identifier;
      delete node2.label;
    }
    this.data.referenceType = undefined;
  }
  function onexitlabeltext(token) {
    const string6 = this.sliceSerialize(token);
    const ancestor = this.stack[this.stack.length - 2];
    ok(ancestor, "expected ancestor on stack");
    ok(ancestor.type === "image" || ancestor.type === "link", "expected image or link on stack");
    ancestor.label = decodeString(string6);
    ancestor.identifier = normalizeIdentifier(string6).toLowerCase();
  }
  function onexitlabel() {
    const fragment = this.stack[this.stack.length - 1];
    ok(fragment, "expected node on stack");
    ok(fragment.type === "fragment", "expected fragment on stack");
    const value2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "image" || node2.type === "link", "expected image or link on stack");
    this.data.inReference = true;
    if (node2.type === "link") {
      const children = fragment.children;
      node2.children = children;
    } else {
      node2.alt = value2;
    }
  }
  function onexitresourcedestinationstring() {
    const data3 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "image" || node2.type === "link", "expected image or link on stack");
    node2.url = data3;
  }
  function onexitresourcetitlestring() {
    const data3 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "image" || node2.type === "link", "expected image or link on stack");
    node2.title = data3;
  }
  function onexitresource() {
    this.data.inReference = undefined;
  }
  function onenterreference() {
    this.data.referenceType = "collapsed";
  }
  function onexitreferencestring(token) {
    const label = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "image" || node2.type === "link", "expected image reference or link reference on stack");
    node2.label = label;
    node2.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase();
    this.data.referenceType = "full";
  }
  function onexitcharacterreferencemarker(token) {
    ok(token.type === "characterReferenceMarkerNumeric" || token.type === "characterReferenceMarkerHexadecimal");
    this.data.characterReferenceType = token.type;
  }
  function onexitcharacterreferencevalue(token) {
    const data3 = this.sliceSerialize(token);
    const type = this.data.characterReferenceType;
    let value2;
    if (type) {
      value2 = decodeNumericCharacterReference(data3, type === types.characterReferenceMarkerNumeric ? constants2.numericBaseDecimal : constants2.numericBaseHexadecimal);
      this.data.characterReferenceType = undefined;
    } else {
      const result = decodeNamedCharacterReference(data3);
      ok(result !== false, "expected reference to decode");
      value2 = result;
    }
    const tail = this.stack[this.stack.length - 1];
    ok(tail, "expected `node`");
    ok("value" in tail, "expected `node.value`");
    tail.value += value2;
  }
  function onexitcharacterreference(token) {
    const tail = this.stack.pop();
    ok(tail, "expected `node`");
    ok(tail.position, "expected `node.position`");
    tail.position.end = point4(token.end);
  }
  function onexitautolinkprotocol(token) {
    onexitdata.call(this, token);
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "link", "expected link on stack");
    node2.url = this.sliceSerialize(token);
  }
  function onexitautolinkemail(token) {
    onexitdata.call(this, token);
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "link", "expected link on stack");
    node2.url = "mailto:" + this.sliceSerialize(token);
  }
  function blockQuote2() {
    return { type: "blockquote", children: [] };
  }
  function codeFlow() {
    return { type: "code", lang: null, meta: null, value: "" };
  }
  function codeText2() {
    return { type: "inlineCode", value: "" };
  }
  function definition2() {
    return {
      type: "definition",
      identifier: "",
      label: null,
      title: null,
      url: ""
    };
  }
  function emphasis() {
    return { type: "emphasis", children: [] };
  }
  function heading() {
    return {
      type: "heading",
      depth: 0,
      children: []
    };
  }
  function hardBreak() {
    return { type: "break" };
  }
  function html() {
    return { type: "html", value: "" };
  }
  function image2() {
    return { type: "image", title: null, url: "", alt: null };
  }
  function link2() {
    return { type: "link", title: null, url: "", children: [] };
  }
  function list2(token) {
    return {
      type: "list",
      ordered: token.type === "listOrdered",
      start: null,
      spread: token._spread,
      children: []
    };
  }
  function listItem(token) {
    return {
      type: "listItem",
      spread: token._spread,
      checked: null,
      children: []
    };
  }
  function paragraph() {
    return { type: "paragraph", children: [] };
  }
  function strong() {
    return { type: "strong", children: [] };
  }
  function text5() {
    return { type: "text", value: "" };
  }
  function thematicBreak2() {
    return { type: "thematicBreak" };
  }
}
function point4(d) {
  return { line: d.line, column: d.column, offset: d.offset };
}
function configure(combined, extensions) {
  let index2 = -1;
  while (++index2 < extensions.length) {
    const value2 = extensions[index2];
    if (Array.isArray(value2)) {
      configure(combined, value2);
    } else {
      extension(combined, value2);
    }
  }
}
function extension(combined, extension2) {
  let key;
  for (key in extension2) {
    if (own3.call(extension2, key)) {
      switch (key) {
        case "canContainEols": {
          const right = extension2[key];
          if (right) {
            combined[key].push(...right);
          }
          break;
        }
        case "transforms": {
          const right = extension2[key];
          if (right) {
            combined[key].push(...right);
          }
          break;
        }
        case "enter":
        case "exit": {
          const right = extension2[key];
          if (right) {
            Object.assign(combined[key], right);
          }
          break;
        }
      }
    }
  }
}
function defaultOnError(left, right) {
  if (left) {
    throw new Error("Cannot close `" + left.type + "` (" + stringifyPosition({ start: left.start, end: left.end }) + "): a different token (`" + right.type + "`, " + stringifyPosition({ start: right.start, end: right.end }) + ") is open");
  } else {
    throw new Error("Cannot close document, a token (`" + right.type + "`, " + stringifyPosition({ start: right.start, end: right.end }) + ") is still open");
  }
}
var own3;
var init_lib5 = __esm(() => {
  init_development();
  init_mdast_util_to_string();
  init_dev13();
  init_dev2();
  init_dev14();
  init_dev3();
  init_default();
  init_decode_named_character_reference();
  init_unist_util_stringify_position();
  own3 = {}.hasOwnProperty;
});

// node_modules/mdast-util-from-markdown/dev/index.js
var init_dev15 = __esm(() => {
  init_lib5();
});

// node_modules/remark-parse/lib/index.js
function remarkParse(options) {
  const self2 = this;
  self2.parser = parser2;
  function parser2(doc2) {
    return fromMarkdown(doc2, {
      ...self2.data("settings"),
      ...options,
      extensions: self2.data("micromarkExtensions") || [],
      mdastExtensions: self2.data("fromMarkdownExtensions") || []
    });
  }
}
var init_lib6 = __esm(() => {
  init_dev15();
});

// node_modules/remark-parse/index.js
var init_remark_parse = __esm(() => {
  init_lib6();
});

// node_modules/ccount/index.js
function ccount(value2, character) {
  const source = String(value2);
  if (typeof character !== "string") {
    throw new TypeError("Expected character");
  }
  let count3 = 0;
  let index2 = source.indexOf(character);
  while (index2 !== -1) {
    count3++;
    index2 = source.indexOf(character, index2 + character.length);
  }
  return count3;
}

// node_modules/escape-string-regexp/index.js
function escapeStringRegexp(string6) {
  if (typeof string6 !== "string") {
    throw new TypeError("Expected a string");
  }
  return string6.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
}

// node_modules/unist-util-is/lib/index.js
function anyFactory(tests) {
  const checks3 = [];
  let index2 = -1;
  while (++index2 < tests.length) {
    checks3[index2] = convert(tests[index2]);
  }
  return castFactory(any3);
  function any3(...parameters) {
    let index3 = -1;
    while (++index3 < checks3.length) {
      if (checks3[index3].apply(this, parameters))
        return true;
    }
    return false;
  }
}
function propertiesFactory(check2) {
  const checkAsRecord = check2;
  return castFactory(all3);
  function all3(node2) {
    const nodeAsRecord = node2;
    let key;
    for (key in check2) {
      if (nodeAsRecord[key] !== checkAsRecord[key])
        return false;
    }
    return true;
  }
}
function typeFactory(check2) {
  return castFactory(type);
  function type(node2) {
    return node2 && node2.type === check2;
  }
}
function castFactory(testFunction) {
  return check2;
  function check2(value2, index2, parent) {
    return Boolean(looksLikeANode(value2) && testFunction.call(this, value2, typeof index2 === "number" ? index2 : undefined, parent || undefined));
  }
}
function ok2() {
  return true;
}
function looksLikeANode(value2) {
  return value2 !== null && typeof value2 === "object" && "type" in value2;
}
var convert = function(test) {
  if (test === null || test === undefined) {
    return ok2;
  }
  if (typeof test === "function") {
    return castFactory(test);
  }
  if (typeof test === "object") {
    return Array.isArray(test) ? anyFactory(test) : propertiesFactory(test);
  }
  if (typeof test === "string") {
    return typeFactory(test);
  }
  throw new Error("Expected function, string, or object as test");
};

// node_modules/unist-util-is/index.js
var init_unist_util_is = () => {};

// node_modules/unist-util-visit-parents/lib/color.node.js
function color2(d) {
  return "\x1B[33m" + d + "\x1B[39m";
}

// node_modules/unist-util-visit-parents/lib/index.js
function visitParents(tree, test, visitor, reverse) {
  let check2;
  if (typeof test === "function" && typeof visitor !== "function") {
    reverse = visitor;
    visitor = test;
  } else {
    check2 = test;
  }
  const is2 = convert(check2);
  const step = reverse ? -1 : 1;
  factory(tree, undefined, [])();
  function factory(node2, index2, parents) {
    const value2 = node2 && typeof node2 === "object" ? node2 : {};
    if (typeof value2.type === "string") {
      const name2 = typeof value2.tagName === "string" ? value2.tagName : typeof value2.name === "string" ? value2.name : undefined;
      Object.defineProperty(visit2, "name", {
        value: "node (" + color2(node2.type + (name2 ? "<" + name2 + ">" : "")) + ")"
      });
    }
    return visit2;
    function visit2() {
      let result = empty;
      let subresult;
      let offset;
      let grandparents;
      if (!test || is2(node2, index2, parents[parents.length - 1] || undefined)) {
        result = toResult(visitor(node2, parents));
        if (result[0] === EXIT) {
          return result;
        }
      }
      if ("children" in node2 && node2.children) {
        const nodeAsParent = node2;
        if (nodeAsParent.children && result[0] !== SKIP) {
          offset = (reverse ? nodeAsParent.children.length : -1) + step;
          grandparents = parents.concat(nodeAsParent);
          while (offset > -1 && offset < nodeAsParent.children.length) {
            const child = nodeAsParent.children[offset];
            subresult = factory(child, offset, grandparents)();
            if (subresult[0] === EXIT) {
              return subresult;
            }
            offset = typeof subresult[1] === "number" ? subresult[1] : offset + step;
          }
        }
      }
      return result;
    }
  }
}
function toResult(value2) {
  if (Array.isArray(value2)) {
    return value2;
  }
  if (typeof value2 === "number") {
    return [CONTINUE, value2];
  }
  return value2 === null || value2 === undefined ? empty : [value2];
}
var empty, CONTINUE = true, EXIT = false, SKIP = "skip";
var init_lib7 = __esm(() => {
  init_unist_util_is();
  empty = [];
});

// node_modules/unist-util-visit-parents/index.js
var init_unist_util_visit_parents = __esm(() => {
  init_lib7();
});

// node_modules/mdast-util-find-and-replace/lib/index.js
function findAndReplace(tree, list2, options) {
  const settings = options || {};
  const ignored = convert(settings.ignore || []);
  const pairs = toPairs(list2);
  let pairIndex = -1;
  while (++pairIndex < pairs.length) {
    visitParents(tree, "text", visitor);
  }
  function visitor(node2, parents) {
    let index2 = -1;
    let grandparent;
    while (++index2 < parents.length) {
      const parent = parents[index2];
      const siblings = grandparent ? grandparent.children : undefined;
      if (ignored(parent, siblings ? siblings.indexOf(parent) : undefined, grandparent)) {
        return;
      }
      grandparent = parent;
    }
    if (grandparent) {
      return handler(node2, parents);
    }
  }
  function handler(node2, parents) {
    const parent = parents[parents.length - 1];
    const find2 = pairs[pairIndex][0];
    const replace = pairs[pairIndex][1];
    let start = 0;
    const siblings = parent.children;
    const index2 = siblings.indexOf(node2);
    let change = false;
    let nodes = [];
    find2.lastIndex = 0;
    let match = find2.exec(node2.value);
    while (match) {
      const position2 = match.index;
      const matchObject = {
        index: match.index,
        input: match.input,
        stack: [...parents, node2]
      };
      let value2 = replace(...match, matchObject);
      if (typeof value2 === "string") {
        value2 = value2.length > 0 ? { type: "text", value: value2 } : undefined;
      }
      if (value2 === false) {
        find2.lastIndex = position2 + 1;
      } else {
        if (start !== position2) {
          nodes.push({
            type: "text",
            value: node2.value.slice(start, position2)
          });
        }
        if (Array.isArray(value2)) {
          nodes.push(...value2);
        } else if (value2) {
          nodes.push(value2);
        }
        start = position2 + match[0].length;
        change = true;
      }
      if (!find2.global) {
        break;
      }
      match = find2.exec(node2.value);
    }
    if (change) {
      if (start < node2.value.length) {
        nodes.push({ type: "text", value: node2.value.slice(start) });
      }
      parent.children.splice(index2, 1, ...nodes);
    } else {
      nodes = [node2];
    }
    return index2 + nodes.length;
  }
}
function toPairs(tupleOrList) {
  const result = [];
  if (!Array.isArray(tupleOrList)) {
    throw new TypeError("Expected find and replace tuple or list of tuples");
  }
  const list2 = !tupleOrList[0] || Array.isArray(tupleOrList[0]) ? tupleOrList : [tupleOrList];
  let index2 = -1;
  while (++index2 < list2.length) {
    const tuple2 = list2[index2];
    result.push([toExpression(tuple2[0]), toFunction(tuple2[1])]);
  }
  return result;
}
function toExpression(find2) {
  return typeof find2 === "string" ? new RegExp(escapeStringRegexp(find2), "g") : find2;
}
function toFunction(replace) {
  return typeof replace === "function" ? replace : function() {
    return replace;
  };
}
var init_lib8 = __esm(() => {
  init_unist_util_visit_parents();
  init_unist_util_is();
});

// node_modules/mdast-util-find-and-replace/index.js
var init_mdast_util_find_and_replace = __esm(() => {
  init_lib8();
});

// node_modules/mdast-util-gfm-autolink-literal/lib/index.js
function gfmAutolinkLiteralFromMarkdown() {
  return {
    transforms: [transformGfmAutolinkLiterals],
    enter: {
      literalAutolink: enterLiteralAutolink,
      literalAutolinkEmail: enterLiteralAutolinkValue,
      literalAutolinkHttp: enterLiteralAutolinkValue,
      literalAutolinkWww: enterLiteralAutolinkValue
    },
    exit: {
      literalAutolink: exitLiteralAutolink,
      literalAutolinkEmail: exitLiteralAutolinkEmail,
      literalAutolinkHttp: exitLiteralAutolinkHttp,
      literalAutolinkWww: exitLiteralAutolinkWww
    }
  };
}
function gfmAutolinkLiteralToMarkdown() {
  return {
    unsafe: [
      {
        character: "@",
        before: "[+\\-.\\w]",
        after: "[\\-.\\w]",
        inConstruct,
        notInConstruct
      },
      {
        character: ".",
        before: "[Ww]",
        after: "[\\-.\\w]",
        inConstruct,
        notInConstruct
      },
      {
        character: ":",
        before: "[ps]",
        after: "\\/",
        inConstruct,
        notInConstruct
      }
    ]
  };
}
function enterLiteralAutolink(token) {
  this.enter({ type: "link", title: null, url: "", children: [] }, token);
}
function enterLiteralAutolinkValue(token) {
  this.config.enter.autolinkProtocol.call(this, token);
}
function exitLiteralAutolinkHttp(token) {
  this.config.exit.autolinkProtocol.call(this, token);
}
function exitLiteralAutolinkWww(token) {
  this.config.exit.data.call(this, token);
  const node2 = this.stack[this.stack.length - 1];
  ok(node2.type === "link");
  node2.url = "http://" + this.sliceSerialize(token);
}
function exitLiteralAutolinkEmail(token) {
  this.config.exit.autolinkEmail.call(this, token);
}
function exitLiteralAutolink(token) {
  this.exit(token);
}
function transformGfmAutolinkLiterals(tree) {
  findAndReplace(tree, [
    [/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi, findUrl],
    [/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu, findEmail]
  ], { ignore: ["link", "linkReference"] });
}
function findUrl(_, protocol, domain2, path3, match) {
  let prefix = "";
  if (!previous3(match)) {
    return false;
  }
  if (/^w/i.test(protocol)) {
    domain2 = protocol + domain2;
    protocol = "";
    prefix = "http://";
  }
  if (!isCorrectDomain(domain2)) {
    return false;
  }
  const parts = splitUrl(domain2 + path3);
  if (!parts[0])
    return false;
  const result = {
    type: "link",
    title: null,
    url: prefix + protocol + parts[0],
    children: [{ type: "text", value: protocol + parts[0] }]
  };
  if (parts[1]) {
    return [result, { type: "text", value: parts[1] }];
  }
  return result;
}
function findEmail(_, atext, label, match) {
  if (!previous3(match, true) || /[-\d_]$/.test(label)) {
    return false;
  }
  return {
    type: "link",
    title: null,
    url: "mailto:" + atext + "@" + label,
    children: [{ type: "text", value: atext + "@" + label }]
  };
}
function isCorrectDomain(domain2) {
  const parts = domain2.split(".");
  if (parts.length < 2 || parts[parts.length - 1] && (/_/.test(parts[parts.length - 1]) || !/[a-zA-Z\d]/.test(parts[parts.length - 1])) || parts[parts.length - 2] && (/_/.test(parts[parts.length - 2]) || !/[a-zA-Z\d]/.test(parts[parts.length - 2]))) {
    return false;
  }
  return true;
}
function splitUrl(url2) {
  const trailExec = /[!"&'),.:;<>?\]}]+$/.exec(url2);
  if (!trailExec) {
    return [url2, undefined];
  }
  url2 = url2.slice(0, trailExec.index);
  let trail = trailExec[0];
  let closingParenIndex = trail.indexOf(")");
  const openingParens = ccount(url2, "(");
  let closingParens = ccount(url2, ")");
  while (closingParenIndex !== -1 && openingParens > closingParens) {
    url2 += trail.slice(0, closingParenIndex + 1);
    trail = trail.slice(closingParenIndex + 1);
    closingParenIndex = trail.indexOf(")");
    closingParens++;
  }
  return [url2, trail];
}
function previous3(match, email3) {
  const code = match.input.charCodeAt(match.index - 1);
  return (match.index === 0 || unicodeWhitespace(code) || unicodePunctuation(code)) && (!email3 || code !== 47);
}
var inConstruct = "phrasing", notInConstruct;
var init_lib9 = __esm(() => {
  init_development();
  init_dev4();
  init_mdast_util_find_and_replace();
  notInConstruct = ["autolink", "link", "image", "label"];
});

// node_modules/mdast-util-gfm-autolink-literal/index.js
var init_mdast_util_gfm_autolink_literal = __esm(() => {
  init_lib9();
});

// node_modules/mdast-util-gfm-footnote/lib/index.js
function enterFootnoteCallString() {
  this.buffer();
}
function enterFootnoteCall(token) {
  this.enter({ type: "footnoteReference", identifier: "", label: "" }, token);
}
function enterFootnoteDefinitionLabelString() {
  this.buffer();
}
function enterFootnoteDefinition(token) {
  this.enter({ type: "footnoteDefinition", identifier: "", label: "", children: [] }, token);
}
function exitFootnoteCallString(token) {
  const label = this.resume();
  const node2 = this.stack[this.stack.length - 1];
  ok(node2.type === "footnoteReference");
  node2.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase();
  node2.label = label;
}
function exitFootnoteCall(token) {
  this.exit(token);
}
function exitFootnoteDefinitionLabelString(token) {
  const label = this.resume();
  const node2 = this.stack[this.stack.length - 1];
  ok(node2.type === "footnoteDefinition");
  node2.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase();
  node2.label = label;
}
function exitFootnoteDefinition(token) {
  this.exit(token);
}
function footnoteReferencePeek() {
  return "[";
}
function footnoteReference(node2, _, state, info) {
  const tracker = state.createTracker(info);
  let value2 = tracker.move("[^");
  const exit2 = state.enter("footnoteReference");
  const subexit = state.enter("reference");
  value2 += tracker.move(state.safe(state.associationId(node2), { after: "]", before: value2 }));
  subexit();
  exit2();
  value2 += tracker.move("]");
  return value2;
}
function gfmFootnoteFromMarkdown() {
  return {
    enter: {
      gfmFootnoteCallString: enterFootnoteCallString,
      gfmFootnoteCall: enterFootnoteCall,
      gfmFootnoteDefinitionLabelString: enterFootnoteDefinitionLabelString,
      gfmFootnoteDefinition: enterFootnoteDefinition
    },
    exit: {
      gfmFootnoteCallString: exitFootnoteCallString,
      gfmFootnoteCall: exitFootnoteCall,
      gfmFootnoteDefinitionLabelString: exitFootnoteDefinitionLabelString,
      gfmFootnoteDefinition: exitFootnoteDefinition
    }
  };
}
function gfmFootnoteToMarkdown(options) {
  let firstLineBlank = false;
  if (options && options.firstLineBlank) {
    firstLineBlank = true;
  }
  return {
    handlers: { footnoteDefinition, footnoteReference },
    unsafe: [{ character: "[", inConstruct: ["label", "phrasing", "reference"] }]
  };
  function footnoteDefinition(node2, _, state, info) {
    const tracker = state.createTracker(info);
    let value2 = tracker.move("[^");
    const exit2 = state.enter("footnoteDefinition");
    const subexit = state.enter("label");
    value2 += tracker.move(state.safe(state.associationId(node2), { before: value2, after: "]" }));
    subexit();
    value2 += tracker.move("]:");
    if (node2.children && node2.children.length > 0) {
      tracker.shift(4);
      value2 += tracker.move((firstLineBlank ? `
` : " ") + state.indentLines(state.containerFlow(node2, tracker.current()), firstLineBlank ? mapAll : mapExceptFirst));
    }
    exit2();
    return value2;
  }
}
function mapExceptFirst(line, index2, blank) {
  return index2 === 0 ? line : mapAll(line, index2, blank);
}
function mapAll(line, index2, blank) {
  return (blank ? "" : "    ") + line;
}
var init_lib10 = __esm(() => {
  init_development();
  init_dev3();
  footnoteReference.peek = footnoteReferencePeek;
});

// node_modules/mdast-util-gfm-footnote/index.js
var init_mdast_util_gfm_footnote = __esm(() => {
  init_lib10();
});

// node_modules/mdast-util-gfm-strikethrough/lib/index.js
function gfmStrikethroughFromMarkdown() {
  return {
    canContainEols: ["delete"],
    enter: { strikethrough: enterStrikethrough },
    exit: { strikethrough: exitStrikethrough }
  };
}
function gfmStrikethroughToMarkdown() {
  return {
    unsafe: [
      {
        character: "~",
        inConstruct: "phrasing",
        notInConstruct: constructsWithoutStrikethrough
      }
    ],
    handlers: { delete: handleDelete }
  };
}
function enterStrikethrough(token) {
  this.enter({ type: "delete", children: [] }, token);
}
function exitStrikethrough(token) {
  this.exit(token);
}
function handleDelete(node2, _, state, info) {
  const tracker = state.createTracker(info);
  const exit2 = state.enter("strikethrough");
  let value2 = tracker.move("~~");
  value2 += state.containerPhrasing(node2, {
    ...tracker.current(),
    before: value2,
    after: "~"
  });
  value2 += tracker.move("~~");
  exit2();
  return value2;
}
function peekDelete() {
  return "~";
}
var constructsWithoutStrikethrough;
var init_lib11 = __esm(() => {
  constructsWithoutStrikethrough = [
    "autolink",
    "destinationLiteral",
    "destinationRaw",
    "reference",
    "titleQuote",
    "titleApostrophe"
  ];
  handleDelete.peek = peekDelete;
});

// node_modules/mdast-util-gfm-strikethrough/index.js
var init_mdast_util_gfm_strikethrough = __esm(() => {
  init_lib11();
});

// node_modules/markdown-table/index.js
function defaultStringLength(value2) {
  return value2.length;
}
function markdownTable(table2, options) {
  const settings = options || {};
  const align = (settings.align || []).concat();
  const stringLength = settings.stringLength || defaultStringLength;
  const alignments = [];
  const cellMatrix = [];
  const sizeMatrix = [];
  const longestCellByColumn = [];
  let mostCellsPerRow = 0;
  let rowIndex2 = -1;
  while (++rowIndex2 < table2.length) {
    const row3 = [];
    const sizes2 = [];
    let columnIndex3 = -1;
    if (table2[rowIndex2].length > mostCellsPerRow) {
      mostCellsPerRow = table2[rowIndex2].length;
    }
    while (++columnIndex3 < table2[rowIndex2].length) {
      const cell = serialize2(table2[rowIndex2][columnIndex3]);
      if (settings.alignDelimiters !== false) {
        const size2 = stringLength(cell);
        sizes2[columnIndex3] = size2;
        if (longestCellByColumn[columnIndex3] === undefined || size2 > longestCellByColumn[columnIndex3]) {
          longestCellByColumn[columnIndex3] = size2;
        }
      }
      row3.push(cell);
    }
    cellMatrix[rowIndex2] = row3;
    sizeMatrix[rowIndex2] = sizes2;
  }
  let columnIndex2 = -1;
  if (typeof align === "object" && "length" in align) {
    while (++columnIndex2 < mostCellsPerRow) {
      alignments[columnIndex2] = toAlignment(align[columnIndex2]);
    }
  } else {
    const code = toAlignment(align);
    while (++columnIndex2 < mostCellsPerRow) {
      alignments[columnIndex2] = code;
    }
  }
  columnIndex2 = -1;
  const row2 = [];
  const sizes = [];
  while (++columnIndex2 < mostCellsPerRow) {
    const code = alignments[columnIndex2];
    let before = "";
    let after = "";
    if (code === 99) {
      before = ":";
      after = ":";
    } else if (code === 108) {
      before = ":";
    } else if (code === 114) {
      after = ":";
    }
    let size2 = settings.alignDelimiters === false ? 1 : Math.max(1, longestCellByColumn[columnIndex2] - before.length - after.length);
    const cell = before + "-".repeat(size2) + after;
    if (settings.alignDelimiters !== false) {
      size2 = before.length + size2 + after.length;
      if (size2 > longestCellByColumn[columnIndex2]) {
        longestCellByColumn[columnIndex2] = size2;
      }
      sizes[columnIndex2] = size2;
    }
    row2[columnIndex2] = cell;
  }
  cellMatrix.splice(1, 0, row2);
  sizeMatrix.splice(1, 0, sizes);
  rowIndex2 = -1;
  const lines = [];
  while (++rowIndex2 < cellMatrix.length) {
    const row3 = cellMatrix[rowIndex2];
    const sizes2 = sizeMatrix[rowIndex2];
    columnIndex2 = -1;
    const line = [];
    while (++columnIndex2 < mostCellsPerRow) {
      const cell = row3[columnIndex2] || "";
      let before = "";
      let after = "";
      if (settings.alignDelimiters !== false) {
        const size2 = longestCellByColumn[columnIndex2] - (sizes2[columnIndex2] || 0);
        const code = alignments[columnIndex2];
        if (code === 114) {
          before = " ".repeat(size2);
        } else if (code === 99) {
          if (size2 % 2) {
            before = " ".repeat(size2 / 2 + 0.5);
            after = " ".repeat(size2 / 2 - 0.5);
          } else {
            before = " ".repeat(size2 / 2);
            after = before;
          }
        } else {
          after = " ".repeat(size2);
        }
      }
      if (settings.delimiterStart !== false && !columnIndex2) {
        line.push("|");
      }
      if (settings.padding !== false && !(settings.alignDelimiters === false && cell === "") && (settings.delimiterStart !== false || columnIndex2)) {
        line.push(" ");
      }
      if (settings.alignDelimiters !== false) {
        line.push(before);
      }
      line.push(cell);
      if (settings.alignDelimiters !== false) {
        line.push(after);
      }
      if (settings.padding !== false) {
        line.push(" ");
      }
      if (settings.delimiterEnd !== false || columnIndex2 !== mostCellsPerRow - 1) {
        line.push("|");
      }
    }
    lines.push(settings.delimiterEnd === false ? line.join("").replace(/ +$/, "") : line.join(""));
  }
  return lines.join(`
`);
}
function serialize2(value2) {
  return value2 === null || value2 === undefined ? "" : String(value2);
}
function toAlignment(value2) {
  const code = typeof value2 === "string" ? value2.codePointAt(0) : 0;
  return code === 67 || code === 99 ? 99 : code === 76 || code === 108 ? 108 : code === 82 || code === 114 ? 114 : 0;
}

// node_modules/mdast-util-to-markdown/lib/handle/blockquote.js
function blockquote(node2, _, state, info) {
  const exit2 = state.enter("blockquote");
  const tracker = state.createTracker(info);
  tracker.move("> ");
  tracker.shift(2);
  const value2 = state.indentLines(state.containerFlow(node2, tracker.current()), map4);
  exit2();
  return value2;
}
function map4(line, _, blank) {
  return ">" + (blank ? "" : " ") + line;
}

// node_modules/mdast-util-to-markdown/lib/util/pattern-in-scope.js
function patternInScope(stack, pattern) {
  return listInScope(stack, pattern.inConstruct, true) && !listInScope(stack, pattern.notInConstruct, false);
}
function listInScope(stack, list2, none) {
  if (typeof list2 === "string") {
    list2 = [list2];
  }
  if (!list2 || list2.length === 0) {
    return none;
  }
  let index2 = -1;
  while (++index2 < list2.length) {
    if (stack.includes(list2[index2])) {
      return true;
    }
  }
  return false;
}

// node_modules/mdast-util-to-markdown/lib/handle/break.js
function hardBreak(_, _1, state, info) {
  let index2 = -1;
  while (++index2 < state.unsafe.length) {
    if (state.unsafe[index2].character === `
` && patternInScope(state.stack, state.unsafe[index2])) {
      return /[ \t]/.test(info.before) ? "" : " ";
    }
  }
  return "\\\n";
}
var init_break = () => {};

// node_modules/longest-streak/index.js
function longestStreak(value2, substring) {
  const source = String(value2);
  let index2 = source.indexOf(substring);
  let expected = index2;
  let count3 = 0;
  let max5 = 0;
  if (typeof substring !== "string") {
    throw new TypeError("Expected substring");
  }
  while (index2 !== -1) {
    if (index2 === expected) {
      if (++count3 > max5) {
        max5 = count3;
      }
    } else {
      count3 = 1;
    }
    expected = index2 + substring.length;
    index2 = source.indexOf(substring, expected);
  }
  return max5;
}

// node_modules/mdast-util-to-markdown/lib/util/format-code-as-indented.js
function formatCodeAsIndented(node2, state) {
  return Boolean(state.options.fences === false && node2.value && !node2.lang && /[^ \r\n]/.test(node2.value) && !/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(node2.value));
}

// node_modules/mdast-util-to-markdown/lib/util/check-fence.js
function checkFence(state) {
  const marker = state.options.fence || "`";
  if (marker !== "`" && marker !== "~") {
    throw new Error("Cannot serialize code with `" + marker + "` for `options.fence`, expected `` ` `` or `~`");
  }
  return marker;
}

// node_modules/mdast-util-to-markdown/lib/handle/code.js
function code(node2, _, state, info) {
  const marker = checkFence(state);
  const raw = node2.value || "";
  const suffix = marker === "`" ? "GraveAccent" : "Tilde";
  if (formatCodeAsIndented(node2, state)) {
    const exit3 = state.enter("codeIndented");
    const value3 = state.indentLines(raw, map5);
    exit3();
    return value3;
  }
  const tracker = state.createTracker(info);
  const sequence = marker.repeat(Math.max(longestStreak(raw, marker) + 1, 3));
  const exit2 = state.enter("codeFenced");
  let value2 = tracker.move(sequence);
  if (node2.lang) {
    const subexit = state.enter(`codeFencedLang${suffix}`);
    value2 += tracker.move(state.safe(node2.lang, {
      before: value2,
      after: " ",
      encode: ["`"],
      ...tracker.current()
    }));
    subexit();
  }
  if (node2.lang && node2.meta) {
    const subexit = state.enter(`codeFencedMeta${suffix}`);
    value2 += tracker.move(" ");
    value2 += tracker.move(state.safe(node2.meta, {
      before: value2,
      after: `
`,
      encode: ["`"],
      ...tracker.current()
    }));
    subexit();
  }
  value2 += tracker.move(`
`);
  if (raw) {
    value2 += tracker.move(raw + `
`);
  }
  value2 += tracker.move(sequence);
  exit2();
  return value2;
}
function map5(line, _, blank) {
  return (blank ? "" : "    ") + line;
}
var init_code = () => {};

// node_modules/mdast-util-to-markdown/lib/util/check-quote.js
function checkQuote(state) {
  const marker = state.options.quote || '"';
  if (marker !== '"' && marker !== "'") {
    throw new Error("Cannot serialize title with `" + marker + "` for `options.quote`, expected `\"`, or `'`");
  }
  return marker;
}

// node_modules/mdast-util-to-markdown/lib/handle/definition.js
function definition2(node2, _, state, info) {
  const quote = checkQuote(state);
  const suffix = quote === '"' ? "Quote" : "Apostrophe";
  const exit2 = state.enter("definition");
  let subexit = state.enter("label");
  const tracker = state.createTracker(info);
  let value2 = tracker.move("[");
  value2 += tracker.move(state.safe(state.associationId(node2), {
    before: value2,
    after: "]",
    ...tracker.current()
  }));
  value2 += tracker.move("]: ");
  subexit();
  if (!node2.url || /[\0- \u007F]/.test(node2.url)) {
    subexit = state.enter("destinationLiteral");
    value2 += tracker.move("<");
    value2 += tracker.move(state.safe(node2.url, { before: value2, after: ">", ...tracker.current() }));
    value2 += tracker.move(">");
  } else {
    subexit = state.enter("destinationRaw");
    value2 += tracker.move(state.safe(node2.url, {
      before: value2,
      after: node2.title ? " " : `
`,
      ...tracker.current()
    }));
  }
  subexit();
  if (node2.title) {
    subexit = state.enter(`title${suffix}`);
    value2 += tracker.move(" " + quote);
    value2 += tracker.move(state.safe(node2.title, {
      before: value2,
      after: quote,
      ...tracker.current()
    }));
    value2 += tracker.move(quote);
    subexit();
  }
  exit2();
  return value2;
}
var init_definition2 = () => {};

// node_modules/mdast-util-to-markdown/lib/util/check-emphasis.js
function checkEmphasis(state) {
  const marker = state.options.emphasis || "*";
  if (marker !== "*" && marker !== "_") {
    throw new Error("Cannot serialize emphasis with `" + marker + "` for `options.emphasis`, expected `*`, or `_`");
  }
  return marker;
}

// node_modules/mdast-util-to-markdown/lib/util/encode-character-reference.js
function encodeCharacterReference(code2) {
  return "&#x" + code2.toString(16).toUpperCase() + ";";
}

// node_modules/mdast-util-to-markdown/lib/util/encode-info.js
function encodeInfo(outside, inside, marker) {
  const outsideKind = classifyCharacter(outside);
  const insideKind = classifyCharacter(inside);
  if (outsideKind === undefined) {
    return insideKind === undefined ? marker === "_" ? { inside: true, outside: true } : { inside: false, outside: false } : insideKind === 1 ? { inside: true, outside: true } : { inside: false, outside: true };
  }
  if (outsideKind === 1) {
    return insideKind === undefined ? { inside: false, outside: false } : insideKind === 1 ? { inside: true, outside: true } : { inside: false, outside: false };
  }
  return insideKind === undefined ? { inside: false, outside: false } : insideKind === 1 ? { inside: true, outside: false } : { inside: false, outside: false };
}
var init_encode_info = __esm(() => {
  init_dev6();
});

// node_modules/mdast-util-to-markdown/lib/handle/emphasis.js
function emphasis(node2, _, state, info) {
  const marker = checkEmphasis(state);
  const exit2 = state.enter("emphasis");
  const tracker = state.createTracker(info);
  const before = tracker.move(marker);
  let between = tracker.move(state.containerPhrasing(node2, {
    after: marker,
    before,
    ...tracker.current()
  }));
  const betweenHead = between.charCodeAt(0);
  const open = encodeInfo(info.before.charCodeAt(info.before.length - 1), betweenHead, marker);
  if (open.inside) {
    between = encodeCharacterReference(betweenHead) + between.slice(1);
  }
  const betweenTail = between.charCodeAt(between.length - 1);
  const close = encodeInfo(info.after.charCodeAt(0), betweenTail, marker);
  if (close.inside) {
    between = between.slice(0, -1) + encodeCharacterReference(betweenTail);
  }
  const after = tracker.move(marker);
  exit2();
  state.attentionEncodeSurroundingInfo = {
    after: close.outside,
    before: open.outside
  };
  return before + between + after;
}
function emphasisPeek(_, _1, state) {
  return state.options.emphasis || "*";
}
var init_emphasis = __esm(() => {
  init_encode_info();
  emphasis.peek = emphasisPeek;
});

// node_modules/unist-util-visit/lib/index.js
function visit2(tree, testOrVisitor, visitorOrReverse, maybeReverse) {
  let reverse;
  let test;
  let visitor;
  if (typeof testOrVisitor === "function" && typeof visitorOrReverse !== "function") {
    test = undefined;
    visitor = testOrVisitor;
    reverse = visitorOrReverse;
  } else {
    test = testOrVisitor;
    visitor = visitorOrReverse;
    reverse = maybeReverse;
  }
  visitParents(tree, test, overload, reverse);
  function overload(node2, parents) {
    const parent = parents[parents.length - 1];
    const index2 = parent ? parent.children.indexOf(node2) : undefined;
    return visitor(node2, index2, parent);
  }
}
var init_lib12 = __esm(() => {
  init_unist_util_visit_parents();
  init_unist_util_visit_parents();
});

// node_modules/unist-util-visit/index.js
var init_unist_util_visit = __esm(() => {
  init_lib12();
});

// node_modules/mdast-util-to-markdown/lib/util/format-heading-as-setext.js
function formatHeadingAsSetext(node2, state) {
  let literalWithBreak = false;
  visit2(node2, function(node3) {
    if ("value" in node3 && /\r?\n|\r/.test(node3.value) || node3.type === "break") {
      literalWithBreak = true;
      return EXIT;
    }
  });
  return Boolean((!node2.depth || node2.depth < 3) && toString(node2) && (state.options.setext || literalWithBreak));
}
var init_format_heading_as_setext = __esm(() => {
  init_unist_util_visit();
  init_mdast_util_to_string();
});

// node_modules/mdast-util-to-markdown/lib/handle/heading.js
function heading(node2, _, state, info) {
  const rank = Math.max(Math.min(6, node2.depth || 1), 1);
  const tracker = state.createTracker(info);
  if (formatHeadingAsSetext(node2, state)) {
    const exit3 = state.enter("headingSetext");
    const subexit2 = state.enter("phrasing");
    const value3 = state.containerPhrasing(node2, {
      ...tracker.current(),
      before: `
`,
      after: `
`
    });
    subexit2();
    exit3();
    return value3 + `
` + (rank === 1 ? "=" : "-").repeat(value3.length - (Math.max(value3.lastIndexOf("\r"), value3.lastIndexOf(`
`)) + 1));
  }
  const sequence = "#".repeat(rank);
  const exit2 = state.enter("headingAtx");
  const subexit = state.enter("phrasing");
  tracker.move(sequence + " ");
  let value2 = state.containerPhrasing(node2, {
    before: "# ",
    after: `
`,
    ...tracker.current()
  });
  if (/^[\t ]/.test(value2)) {
    value2 = encodeCharacterReference(value2.charCodeAt(0)) + value2.slice(1);
  }
  value2 = value2 ? sequence + " " + value2 : sequence;
  if (state.options.closeAtx) {
    value2 += " " + sequence;
  }
  subexit();
  exit2();
  return value2;
}
var init_heading = __esm(() => {
  init_format_heading_as_setext();
});

// node_modules/mdast-util-to-markdown/lib/handle/html.js
function html(node2) {
  return node2.value || "";
}
function htmlPeek() {
  return "<";
}
var init_html = __esm(() => {
  html.peek = htmlPeek;
});

// node_modules/mdast-util-to-markdown/lib/handle/image.js
function image2(node2, _, state, info) {
  const quote = checkQuote(state);
  const suffix = quote === '"' ? "Quote" : "Apostrophe";
  const exit2 = state.enter("image");
  let subexit = state.enter("label");
  const tracker = state.createTracker(info);
  let value2 = tracker.move("![");
  value2 += tracker.move(state.safe(node2.alt, { before: value2, after: "]", ...tracker.current() }));
  value2 += tracker.move("](");
  subexit();
  if (!node2.url && node2.title || /[\0- \u007F]/.test(node2.url)) {
    subexit = state.enter("destinationLiteral");
    value2 += tracker.move("<");
    value2 += tracker.move(state.safe(node2.url, { before: value2, after: ">", ...tracker.current() }));
    value2 += tracker.move(">");
  } else {
    subexit = state.enter("destinationRaw");
    value2 += tracker.move(state.safe(node2.url, {
      before: value2,
      after: node2.title ? " " : ")",
      ...tracker.current()
    }));
  }
  subexit();
  if (node2.title) {
    subexit = state.enter(`title${suffix}`);
    value2 += tracker.move(" " + quote);
    value2 += tracker.move(state.safe(node2.title, {
      before: value2,
      after: quote,
      ...tracker.current()
    }));
    value2 += tracker.move(quote);
    subexit();
  }
  value2 += tracker.move(")");
  exit2();
  return value2;
}
function imagePeek() {
  return "!";
}
var init_image = __esm(() => {
  image2.peek = imagePeek;
});

// node_modules/mdast-util-to-markdown/lib/handle/image-reference.js
function imageReference(node2, _, state, info) {
  const type = node2.referenceType;
  const exit2 = state.enter("imageReference");
  let subexit = state.enter("label");
  const tracker = state.createTracker(info);
  let value2 = tracker.move("![");
  const alt = state.safe(node2.alt, {
    before: value2,
    after: "]",
    ...tracker.current()
  });
  value2 += tracker.move(alt + "][");
  subexit();
  const stack = state.stack;
  state.stack = [];
  subexit = state.enter("reference");
  const reference = state.safe(state.associationId(node2), {
    before: value2,
    after: "]",
    ...tracker.current()
  });
  subexit();
  state.stack = stack;
  exit2();
  if (type === "full" || !alt || alt !== reference) {
    value2 += tracker.move(reference + "]");
  } else if (type === "shortcut") {
    value2 = value2.slice(0, -1);
  } else {
    value2 += tracker.move("]");
  }
  return value2;
}
function imageReferencePeek() {
  return "!";
}
var init_image_reference = __esm(() => {
  imageReference.peek = imageReferencePeek;
});

// node_modules/mdast-util-to-markdown/lib/handle/inline-code.js
function inlineCode(node2, _, state) {
  let value2 = node2.value || "";
  let sequence = "`";
  let index2 = -1;
  while (new RegExp("(^|[^`])" + sequence + "([^`]|$)").test(value2)) {
    sequence += "`";
  }
  if (/[^ \r\n]/.test(value2) && (/^[ \r\n]/.test(value2) && /[ \r\n]$/.test(value2) || /^`|`$/.test(value2))) {
    value2 = " " + value2 + " ";
  }
  while (++index2 < state.unsafe.length) {
    const pattern = state.unsafe[index2];
    const expression2 = state.compilePattern(pattern);
    let match;
    if (!pattern.atBreak)
      continue;
    while (match = expression2.exec(value2)) {
      let position2 = match.index;
      if (value2.charCodeAt(position2) === 10 && value2.charCodeAt(position2 - 1) === 13) {
        position2--;
      }
      value2 = value2.slice(0, position2) + " " + value2.slice(match.index + 1);
    }
  }
  return sequence + value2 + sequence;
}
function inlineCodePeek() {
  return "`";
}
var init_inline_code = __esm(() => {
  inlineCode.peek = inlineCodePeek;
});

// node_modules/mdast-util-to-markdown/lib/util/format-link-as-autolink.js
function formatLinkAsAutolink(node2, state) {
  const raw = toString(node2);
  return Boolean(!state.options.resourceLink && node2.url && !node2.title && node2.children && node2.children.length === 1 && node2.children[0].type === "text" && (raw === node2.url || "mailto:" + raw === node2.url) && /^[a-z][a-z+.-]+:/i.test(node2.url) && !/[\0- <>\u007F]/.test(node2.url));
}
var init_format_link_as_autolink = __esm(() => {
  init_mdast_util_to_string();
});

// node_modules/mdast-util-to-markdown/lib/handle/link.js
function link2(node2, _, state, info) {
  const quote = checkQuote(state);
  const suffix = quote === '"' ? "Quote" : "Apostrophe";
  const tracker = state.createTracker(info);
  let exit2;
  let subexit;
  if (formatLinkAsAutolink(node2, state)) {
    const stack = state.stack;
    state.stack = [];
    exit2 = state.enter("autolink");
    let value3 = tracker.move("<");
    value3 += tracker.move(state.containerPhrasing(node2, {
      before: value3,
      after: ">",
      ...tracker.current()
    }));
    value3 += tracker.move(">");
    exit2();
    state.stack = stack;
    return value3;
  }
  exit2 = state.enter("link");
  subexit = state.enter("label");
  let value2 = tracker.move("[");
  value2 += tracker.move(state.containerPhrasing(node2, {
    before: value2,
    after: "](",
    ...tracker.current()
  }));
  value2 += tracker.move("](");
  subexit();
  if (!node2.url && node2.title || /[\0- \u007F]/.test(node2.url)) {
    subexit = state.enter("destinationLiteral");
    value2 += tracker.move("<");
    value2 += tracker.move(state.safe(node2.url, { before: value2, after: ">", ...tracker.current() }));
    value2 += tracker.move(">");
  } else {
    subexit = state.enter("destinationRaw");
    value2 += tracker.move(state.safe(node2.url, {
      before: value2,
      after: node2.title ? " " : ")",
      ...tracker.current()
    }));
  }
  subexit();
  if (node2.title) {
    subexit = state.enter(`title${suffix}`);
    value2 += tracker.move(" " + quote);
    value2 += tracker.move(state.safe(node2.title, {
      before: value2,
      after: quote,
      ...tracker.current()
    }));
    value2 += tracker.move(quote);
    subexit();
  }
  value2 += tracker.move(")");
  exit2();
  return value2;
}
function linkPeek(node2, _, state) {
  return formatLinkAsAutolink(node2, state) ? "<" : "[";
}
var init_link = __esm(() => {
  init_format_link_as_autolink();
  link2.peek = linkPeek;
});

// node_modules/mdast-util-to-markdown/lib/handle/link-reference.js
function linkReference(node2, _, state, info) {
  const type = node2.referenceType;
  const exit2 = state.enter("linkReference");
  let subexit = state.enter("label");
  const tracker = state.createTracker(info);
  let value2 = tracker.move("[");
  const text5 = state.containerPhrasing(node2, {
    before: value2,
    after: "]",
    ...tracker.current()
  });
  value2 += tracker.move(text5 + "][");
  subexit();
  const stack = state.stack;
  state.stack = [];
  subexit = state.enter("reference");
  const reference = state.safe(state.associationId(node2), {
    before: value2,
    after: "]",
    ...tracker.current()
  });
  subexit();
  state.stack = stack;
  exit2();
  if (type === "full" || !text5 || text5 !== reference) {
    value2 += tracker.move(reference + "]");
  } else if (type === "shortcut") {
    value2 = value2.slice(0, -1);
  } else {
    value2 += tracker.move("]");
  }
  return value2;
}
function linkReferencePeek() {
  return "[";
}
var init_link_reference = __esm(() => {
  linkReference.peek = linkReferencePeek;
});

// node_modules/mdast-util-to-markdown/lib/util/check-bullet.js
function checkBullet(state) {
  const marker = state.options.bullet || "*";
  if (marker !== "*" && marker !== "+" && marker !== "-") {
    throw new Error("Cannot serialize items with `" + marker + "` for `options.bullet`, expected `*`, `+`, or `-`");
  }
  return marker;
}

// node_modules/mdast-util-to-markdown/lib/util/check-bullet-other.js
function checkBulletOther(state) {
  const bullet = checkBullet(state);
  const bulletOther = state.options.bulletOther;
  if (!bulletOther) {
    return bullet === "*" ? "-" : "*";
  }
  if (bulletOther !== "*" && bulletOther !== "+" && bulletOther !== "-") {
    throw new Error("Cannot serialize items with `" + bulletOther + "` for `options.bulletOther`, expected `*`, `+`, or `-`");
  }
  if (bulletOther === bullet) {
    throw new Error("Expected `bullet` (`" + bullet + "`) and `bulletOther` (`" + bulletOther + "`) to be different");
  }
  return bulletOther;
}
var init_check_bullet_other = () => {};

// node_modules/mdast-util-to-markdown/lib/util/check-bullet-ordered.js
function checkBulletOrdered(state) {
  const marker = state.options.bulletOrdered || ".";
  if (marker !== "." && marker !== ")") {
    throw new Error("Cannot serialize items with `" + marker + "` for `options.bulletOrdered`, expected `.` or `)`");
  }
  return marker;
}

// node_modules/mdast-util-to-markdown/lib/util/check-rule.js
function checkRule(state) {
  const marker = state.options.rule || "*";
  if (marker !== "*" && marker !== "-" && marker !== "_") {
    throw new Error("Cannot serialize rules with `" + marker + "` for `options.rule`, expected `*`, `-`, or `_`");
  }
  return marker;
}

// node_modules/mdast-util-to-markdown/lib/handle/list.js
function list2(node2, parent, state, info) {
  const exit2 = state.enter("list");
  const bulletCurrent = state.bulletCurrent;
  let bullet = node2.ordered ? checkBulletOrdered(state) : checkBullet(state);
  const bulletOther = node2.ordered ? bullet === "." ? ")" : "." : checkBulletOther(state);
  let useDifferentMarker = parent && state.bulletLastUsed ? bullet === state.bulletLastUsed : false;
  if (!node2.ordered) {
    const firstListItem = node2.children ? node2.children[0] : undefined;
    if ((bullet === "*" || bullet === "-") && firstListItem && (!firstListItem.children || !firstListItem.children[0]) && state.stack[state.stack.length - 1] === "list" && state.stack[state.stack.length - 2] === "listItem" && state.stack[state.stack.length - 3] === "list" && state.stack[state.stack.length - 4] === "listItem" && state.indexStack[state.indexStack.length - 1] === 0 && state.indexStack[state.indexStack.length - 2] === 0 && state.indexStack[state.indexStack.length - 3] === 0) {
      useDifferentMarker = true;
    }
    if (checkRule(state) === bullet && firstListItem) {
      let index2 = -1;
      while (++index2 < node2.children.length) {
        const item = node2.children[index2];
        if (item && item.type === "listItem" && item.children && item.children[0] && item.children[0].type === "thematicBreak") {
          useDifferentMarker = true;
          break;
        }
      }
    }
  }
  if (useDifferentMarker) {
    bullet = bulletOther;
  }
  state.bulletCurrent = bullet;
  const value2 = state.containerFlow(node2, info);
  state.bulletLastUsed = bullet;
  state.bulletCurrent = bulletCurrent;
  exit2();
  return value2;
}
var init_list2 = __esm(() => {
  init_check_bullet_other();
});

// node_modules/mdast-util-to-markdown/lib/util/check-list-item-indent.js
function checkListItemIndent(state) {
  const style = state.options.listItemIndent || "one";
  if (style !== "tab" && style !== "one" && style !== "mixed") {
    throw new Error("Cannot serialize items with `" + style + "` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");
  }
  return style;
}

// node_modules/mdast-util-to-markdown/lib/handle/list-item.js
function listItem(node2, parent, state, info) {
  const listItemIndent = checkListItemIndent(state);
  let bullet = state.bulletCurrent || checkBullet(state);
  if (parent && parent.type === "list" && parent.ordered) {
    bullet = (typeof parent.start === "number" && parent.start > -1 ? parent.start : 1) + (state.options.incrementListMarker === false ? 0 : parent.children.indexOf(node2)) + bullet;
  }
  let size2 = bullet.length + 1;
  if (listItemIndent === "tab" || listItemIndent === "mixed" && (parent && parent.type === "list" && parent.spread || node2.spread)) {
    size2 = Math.ceil(size2 / 4) * 4;
  }
  const tracker = state.createTracker(info);
  tracker.move(bullet + " ".repeat(size2 - bullet.length));
  tracker.shift(size2);
  const exit2 = state.enter("listItem");
  const value2 = state.indentLines(state.containerFlow(node2, tracker.current()), map6);
  exit2();
  return value2;
  function map6(line, index2, blank) {
    if (index2) {
      return (blank ? "" : " ".repeat(size2)) + line;
    }
    return (blank ? bullet : bullet + " ".repeat(size2 - bullet.length)) + line;
  }
}
var init_list_item = () => {};

// node_modules/mdast-util-to-markdown/lib/handle/paragraph.js
function paragraph(node2, _, state, info) {
  const exit2 = state.enter("paragraph");
  const subexit = state.enter("phrasing");
  const value2 = state.containerPhrasing(node2, info);
  subexit();
  exit2();
  return value2;
}

// node_modules/mdast-util-phrasing/lib/index.js
var phrasing;
var init_lib13 = __esm(() => {
  init_unist_util_is();
  phrasing = convert([
    "break",
    "delete",
    "emphasis",
    "footnote",
    "footnoteReference",
    "image",
    "imageReference",
    "inlineCode",
    "inlineMath",
    "link",
    "linkReference",
    "mdxJsxTextElement",
    "mdxTextExpression",
    "strong",
    "text",
    "textDirective"
  ]);
});

// node_modules/mdast-util-phrasing/index.js
var init_mdast_util_phrasing = __esm(() => {
  init_lib13();
});

// node_modules/mdast-util-to-markdown/lib/handle/root.js
function root(node2, _, state, info) {
  const hasPhrasing = node2.children.some(function(d) {
    return phrasing(d);
  });
  const container = hasPhrasing ? state.containerPhrasing : state.containerFlow;
  return container.call(state, node2, info);
}
var init_root = __esm(() => {
  init_mdast_util_phrasing();
});

// node_modules/mdast-util-to-markdown/lib/util/check-strong.js
function checkStrong(state) {
  const marker = state.options.strong || "*";
  if (marker !== "*" && marker !== "_") {
    throw new Error("Cannot serialize strong with `" + marker + "` for `options.strong`, expected `*`, or `_`");
  }
  return marker;
}

// node_modules/mdast-util-to-markdown/lib/handle/strong.js
function strong(node2, _, state, info) {
  const marker = checkStrong(state);
  const exit2 = state.enter("strong");
  const tracker = state.createTracker(info);
  const before = tracker.move(marker + marker);
  let between = tracker.move(state.containerPhrasing(node2, {
    after: marker,
    before,
    ...tracker.current()
  }));
  const betweenHead = between.charCodeAt(0);
  const open = encodeInfo(info.before.charCodeAt(info.before.length - 1), betweenHead, marker);
  if (open.inside) {
    between = encodeCharacterReference(betweenHead) + between.slice(1);
  }
  const betweenTail = between.charCodeAt(between.length - 1);
  const close = encodeInfo(info.after.charCodeAt(0), betweenTail, marker);
  if (close.inside) {
    between = between.slice(0, -1) + encodeCharacterReference(betweenTail);
  }
  const after = tracker.move(marker + marker);
  exit2();
  state.attentionEncodeSurroundingInfo = {
    after: close.outside,
    before: open.outside
  };
  return before + between + after;
}
function strongPeek(_, _1, state) {
  return state.options.strong || "*";
}
var init_strong = __esm(() => {
  init_encode_info();
  strong.peek = strongPeek;
});

// node_modules/mdast-util-to-markdown/lib/handle/text.js
function text5(node2, _, state, info) {
  return state.safe(node2.value, info);
}

// node_modules/mdast-util-to-markdown/lib/util/check-rule-repetition.js
function checkRuleRepetition(state) {
  const repetition = state.options.ruleRepetition || 3;
  if (repetition < 3) {
    throw new Error("Cannot serialize rules with repetition `" + repetition + "` for `options.ruleRepetition`, expected `3` or more");
  }
  return repetition;
}

// node_modules/mdast-util-to-markdown/lib/handle/thematic-break.js
function thematicBreak2(_, _1, state) {
  const value2 = (checkRule(state) + (state.options.ruleSpaces ? " " : "")).repeat(checkRuleRepetition(state));
  return state.options.ruleSpaces ? value2.slice(0, -1) : value2;
}
var init_thematic_break2 = () => {};

// node_modules/mdast-util-to-markdown/lib/handle/index.js
var handle;
var init_handle = __esm(() => {
  init_break();
  init_code();
  init_definition2();
  init_emphasis();
  init_heading();
  init_html();
  init_image();
  init_image_reference();
  init_inline_code();
  init_link();
  init_link_reference();
  init_list2();
  init_list_item();
  init_root();
  init_strong();
  init_thematic_break2();
  handle = {
    blockquote,
    break: hardBreak,
    code,
    definition: definition2,
    emphasis,
    hardBreak,
    heading,
    html,
    image: image2,
    imageReference,
    inlineCode,
    link: link2,
    linkReference,
    list: list2,
    listItem,
    paragraph,
    root,
    strong,
    text: text5,
    thematicBreak: thematicBreak2
  };
});

// node_modules/mdast-util-to-markdown/index.js
var init_mdast_util_to_markdown = __esm(() => {
  init_handle();
});

// node_modules/mdast-util-gfm-table/lib/index.js
function gfmTableFromMarkdown() {
  return {
    enter: {
      table: enterTable,
      tableData: enterCell,
      tableHeader: enterCell,
      tableRow: enterRow
    },
    exit: {
      codeText: exitCodeText,
      table: exitTable,
      tableData: exit2,
      tableHeader: exit2,
      tableRow: exit2
    }
  };
}
function enterTable(token) {
  const align = token._align;
  ok(align, "expected `_align` on table");
  this.enter({
    type: "table",
    align: align.map(function(d) {
      return d === "none" ? null : d;
    }),
    children: []
  }, token);
  this.data.inTable = true;
}
function exitTable(token) {
  this.exit(token);
  this.data.inTable = undefined;
}
function enterRow(token) {
  this.enter({ type: "tableRow", children: [] }, token);
}
function exit2(token) {
  this.exit(token);
}
function enterCell(token) {
  this.enter({ type: "tableCell", children: [] }, token);
}
function exitCodeText(token) {
  let value2 = this.resume();
  if (this.data.inTable) {
    value2 = value2.replace(/\\([\\|])/g, replace);
  }
  const node2 = this.stack[this.stack.length - 1];
  ok(node2.type === "inlineCode");
  node2.value = value2;
  this.exit(token);
}
function replace($0, $1) {
  return $1 === "|" ? $1 : $0;
}
function gfmTableToMarkdown(options) {
  const settings = options || {};
  const padding = settings.tableCellPadding;
  const alignDelimiters = settings.tablePipeAlign;
  const stringLength = settings.stringLength;
  const around = padding ? " " : "|";
  return {
    unsafe: [
      { character: "\r", inConstruct: "tableCell" },
      { character: `
`, inConstruct: "tableCell" },
      { atBreak: true, character: "|", after: "[\t :-]" },
      { character: "|", inConstruct: "tableCell" },
      { atBreak: true, character: ":", after: "-" },
      { atBreak: true, character: "-", after: "[:|-]" }
    ],
    handlers: {
      inlineCode: inlineCodeWithTable,
      table: handleTable,
      tableCell: handleTableCell,
      tableRow: handleTableRow
    }
  };
  function handleTable(node2, _, state, info) {
    return serializeData(handleTableAsData(node2, state, info), node2.align);
  }
  function handleTableRow(node2, _, state, info) {
    const row2 = handleTableRowAsData(node2, state, info);
    const value2 = serializeData([row2]);
    return value2.slice(0, value2.indexOf(`
`));
  }
  function handleTableCell(node2, _, state, info) {
    const exit3 = state.enter("tableCell");
    const subexit = state.enter("phrasing");
    const value2 = state.containerPhrasing(node2, {
      ...info,
      before: around,
      after: around
    });
    subexit();
    exit3();
    return value2;
  }
  function serializeData(matrix, align) {
    return markdownTable(matrix, {
      align,
      alignDelimiters,
      padding,
      stringLength
    });
  }
  function handleTableAsData(node2, state, info) {
    const children = node2.children;
    let index2 = -1;
    const result = [];
    const subexit = state.enter("table");
    while (++index2 < children.length) {
      result[index2] = handleTableRowAsData(children[index2], state, info);
    }
    subexit();
    return result;
  }
  function handleTableRowAsData(node2, state, info) {
    const children = node2.children;
    let index2 = -1;
    const result = [];
    const subexit = state.enter("tableRow");
    while (++index2 < children.length) {
      result[index2] = handleTableCell(children[index2], node2, state, info);
    }
    subexit();
    return result;
  }
  function inlineCodeWithTable(node2, parent, state) {
    let value2 = handle.inlineCode(node2, parent, state);
    if (state.stack.includes("tableCell")) {
      value2 = value2.replace(/\|/g, "\\$&");
    }
    return value2;
  }
}
var init_lib14 = __esm(() => {
  init_development();
  init_mdast_util_to_markdown();
});

// node_modules/mdast-util-gfm-table/index.js
var init_mdast_util_gfm_table = __esm(() => {
  init_lib14();
});

// node_modules/mdast-util-gfm-task-list-item/lib/index.js
function gfmTaskListItemFromMarkdown() {
  return {
    exit: {
      taskListCheckValueChecked: exitCheck,
      taskListCheckValueUnchecked: exitCheck,
      paragraph: exitParagraphWithTaskListItem
    }
  };
}
function gfmTaskListItemToMarkdown() {
  return {
    unsafe: [{ atBreak: true, character: "-", after: "[:|-]" }],
    handlers: { listItem: listItemWithTaskListItem }
  };
}
function exitCheck(token) {
  const node2 = this.stack[this.stack.length - 2];
  ok(node2.type === "listItem");
  node2.checked = token.type === "taskListCheckValueChecked";
}
function exitParagraphWithTaskListItem(token) {
  const parent = this.stack[this.stack.length - 2];
  if (parent && parent.type === "listItem" && typeof parent.checked === "boolean") {
    const node2 = this.stack[this.stack.length - 1];
    ok(node2.type === "paragraph");
    const head = node2.children[0];
    if (head && head.type === "text") {
      const siblings = parent.children;
      let index2 = -1;
      let firstParaghraph;
      while (++index2 < siblings.length) {
        const sibling = siblings[index2];
        if (sibling.type === "paragraph") {
          firstParaghraph = sibling;
          break;
        }
      }
      if (firstParaghraph === node2) {
        head.value = head.value.slice(1);
        if (head.value.length === 0) {
          node2.children.shift();
        } else if (node2.position && head.position && typeof head.position.start.offset === "number") {
          head.position.start.column++;
          head.position.start.offset++;
          node2.position.start = Object.assign({}, head.position.start);
        }
      }
    }
  }
  this.exit(token);
}
function listItemWithTaskListItem(node2, parent, state, info) {
  const head = node2.children[0];
  const checkable = typeof node2.checked === "boolean" && head && head.type === "paragraph";
  const checkbox = "[" + (node2.checked ? "x" : " ") + "] ";
  const tracker = state.createTracker(info);
  if (checkable) {
    tracker.move(checkbox);
  }
  let value2 = handle.listItem(node2, parent, state, {
    ...info,
    ...tracker.current()
  });
  if (checkable) {
    value2 = value2.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/, check2);
  }
  return value2;
  function check2($0) {
    return $0 + checkbox;
  }
}
var init_lib15 = __esm(() => {
  init_development();
  init_mdast_util_to_markdown();
});

// node_modules/mdast-util-gfm-task-list-item/index.js
var init_mdast_util_gfm_task_list_item = __esm(() => {
  init_lib15();
});

// node_modules/mdast-util-gfm/lib/index.js
function gfmFromMarkdown() {
  return [
    gfmAutolinkLiteralFromMarkdown(),
    gfmFootnoteFromMarkdown(),
    gfmStrikethroughFromMarkdown(),
    gfmTableFromMarkdown(),
    gfmTaskListItemFromMarkdown()
  ];
}
function gfmToMarkdown(options) {
  return {
    extensions: [
      gfmAutolinkLiteralToMarkdown(),
      gfmFootnoteToMarkdown(options),
      gfmStrikethroughToMarkdown(),
      gfmTableToMarkdown(options),
      gfmTaskListItemToMarkdown()
    ]
  };
}
var init_lib16 = __esm(() => {
  init_mdast_util_gfm_autolink_literal();
  init_mdast_util_gfm_footnote();
  init_mdast_util_gfm_strikethrough();
  init_mdast_util_gfm_table();
  init_mdast_util_gfm_task_list_item();
});

// node_modules/mdast-util-gfm/index.js
var init_mdast_util_gfm = __esm(() => {
  init_lib16();
});

// node_modules/micromark-extension-gfm-autolink-literal/dev/lib/syntax.js
function gfmAutolinkLiteral() {
  return { text: text6 };
}
function tokenizeEmailAutolink(effects, ok3, nok) {
  const self2 = this;
  let dot2;
  let data2;
  return start;
  function start(code3) {
    if (!gfmAtext(code3) || !previousEmail.call(self2, self2.previous) || previousUnbalanced(self2.events)) {
      return nok(code3);
    }
    effects.enter("literalAutolink");
    effects.enter("literalAutolinkEmail");
    return atext(code3);
  }
  function atext(code3) {
    if (gfmAtext(code3)) {
      effects.consume(code3);
      return atext;
    }
    if (code3 === codes.atSign) {
      effects.consume(code3);
      return emailDomain;
    }
    return nok(code3);
  }
  function emailDomain(code3) {
    if (code3 === codes.dot) {
      return effects.check(emailDomainDotTrail, emailDomainAfter, emailDomainDot)(code3);
    }
    if (code3 === codes.dash || code3 === codes.underscore || asciiAlphanumeric(code3)) {
      data2 = true;
      effects.consume(code3);
      return emailDomain;
    }
    return emailDomainAfter(code3);
  }
  function emailDomainDot(code3) {
    effects.consume(code3);
    dot2 = true;
    return emailDomain;
  }
  function emailDomainAfter(code3) {
    if (data2 && dot2 && asciiAlpha(self2.previous)) {
      effects.exit("literalAutolinkEmail");
      effects.exit("literalAutolink");
      return ok3(code3);
    }
    return nok(code3);
  }
}
function tokenizeWwwAutolink(effects, ok3, nok) {
  const self2 = this;
  return wwwStart;
  function wwwStart(code3) {
    if (code3 !== codes.uppercaseW && code3 !== codes.lowercaseW || !previousWww.call(self2, self2.previous) || previousUnbalanced(self2.events)) {
      return nok(code3);
    }
    effects.enter("literalAutolink");
    effects.enter("literalAutolinkWww");
    return effects.check(wwwPrefix, effects.attempt(domain2, effects.attempt(path3, wwwAfter), nok), nok)(code3);
  }
  function wwwAfter(code3) {
    effects.exit("literalAutolinkWww");
    effects.exit("literalAutolink");
    return ok3(code3);
  }
}
function tokenizeProtocolAutolink(effects, ok3, nok) {
  const self2 = this;
  let buffer = "";
  let seen = false;
  return protocolStart;
  function protocolStart(code3) {
    if ((code3 === codes.uppercaseH || code3 === codes.lowercaseH) && previousProtocol.call(self2, self2.previous) && !previousUnbalanced(self2.events)) {
      effects.enter("literalAutolink");
      effects.enter("literalAutolinkHttp");
      buffer += String.fromCodePoint(code3);
      effects.consume(code3);
      return protocolPrefixInside;
    }
    return nok(code3);
  }
  function protocolPrefixInside(code3) {
    if (asciiAlpha(code3) && buffer.length < 5) {
      buffer += String.fromCodePoint(code3);
      effects.consume(code3);
      return protocolPrefixInside;
    }
    if (code3 === codes.colon) {
      const protocol = buffer.toLowerCase();
      if (protocol === "http" || protocol === "https") {
        effects.consume(code3);
        return protocolSlashesInside;
      }
    }
    return nok(code3);
  }
  function protocolSlashesInside(code3) {
    if (code3 === codes.slash) {
      effects.consume(code3);
      if (seen) {
        return afterProtocol;
      }
      seen = true;
      return protocolSlashesInside;
    }
    return nok(code3);
  }
  function afterProtocol(code3) {
    return code3 === codes.eof || asciiControl(code3) || markdownLineEndingOrSpace(code3) || unicodeWhitespace(code3) || unicodePunctuation(code3) ? nok(code3) : effects.attempt(domain2, effects.attempt(path3, protocolAfter), nok)(code3);
  }
  function protocolAfter(code3) {
    effects.exit("literalAutolinkHttp");
    effects.exit("literalAutolink");
    return ok3(code3);
  }
}
function tokenizeWwwPrefix(effects, ok3, nok) {
  let size2 = 0;
  return wwwPrefixInside;
  function wwwPrefixInside(code3) {
    if ((code3 === codes.uppercaseW || code3 === codes.lowercaseW) && size2 < 3) {
      size2++;
      effects.consume(code3);
      return wwwPrefixInside;
    }
    if (code3 === codes.dot && size2 === 3) {
      effects.consume(code3);
      return wwwPrefixAfter;
    }
    return nok(code3);
  }
  function wwwPrefixAfter(code3) {
    return code3 === codes.eof ? nok(code3) : ok3(code3);
  }
}
function tokenizeDomain(effects, ok3, nok) {
  let underscoreInLastSegment;
  let underscoreInLastLastSegment;
  let seen;
  return domainInside;
  function domainInside(code3) {
    if (code3 === codes.dot || code3 === codes.underscore) {
      return effects.check(trail, domainAfter, domainAtPunctuation)(code3);
    }
    if (code3 === codes.eof || markdownLineEndingOrSpace(code3) || unicodeWhitespace(code3) || code3 !== codes.dash && unicodePunctuation(code3)) {
      return domainAfter(code3);
    }
    seen = true;
    effects.consume(code3);
    return domainInside;
  }
  function domainAtPunctuation(code3) {
    if (code3 === codes.underscore) {
      underscoreInLastSegment = true;
    } else {
      underscoreInLastLastSegment = underscoreInLastSegment;
      underscoreInLastSegment = undefined;
    }
    effects.consume(code3);
    return domainInside;
  }
  function domainAfter(code3) {
    if (underscoreInLastLastSegment || underscoreInLastSegment || !seen) {
      return nok(code3);
    }
    return ok3(code3);
  }
}
function tokenizePath(effects, ok3) {
  let sizeOpen = 0;
  let sizeClose = 0;
  return pathInside;
  function pathInside(code3) {
    if (code3 === codes.leftParenthesis) {
      sizeOpen++;
      effects.consume(code3);
      return pathInside;
    }
    if (code3 === codes.rightParenthesis && sizeClose < sizeOpen) {
      return pathAtPunctuation(code3);
    }
    if (code3 === codes.exclamationMark || code3 === codes.quotationMark || code3 === codes.ampersand || code3 === codes.apostrophe || code3 === codes.rightParenthesis || code3 === codes.asterisk || code3 === codes.comma || code3 === codes.dot || code3 === codes.colon || code3 === codes.semicolon || code3 === codes.lessThan || code3 === codes.questionMark || code3 === codes.rightSquareBracket || code3 === codes.underscore || code3 === codes.tilde) {
      return effects.check(trail, ok3, pathAtPunctuation)(code3);
    }
    if (code3 === codes.eof || markdownLineEndingOrSpace(code3) || unicodeWhitespace(code3)) {
      return ok3(code3);
    }
    effects.consume(code3);
    return pathInside;
  }
  function pathAtPunctuation(code3) {
    if (code3 === codes.rightParenthesis) {
      sizeClose++;
    }
    effects.consume(code3);
    return pathInside;
  }
}
function tokenizeTrail(effects, ok3, nok) {
  return trail2;
  function trail2(code3) {
    if (code3 === codes.exclamationMark || code3 === codes.quotationMark || code3 === codes.apostrophe || code3 === codes.rightParenthesis || code3 === codes.asterisk || code3 === codes.comma || code3 === codes.dot || code3 === codes.colon || code3 === codes.semicolon || code3 === codes.questionMark || code3 === codes.underscore || code3 === codes.tilde) {
      effects.consume(code3);
      return trail2;
    }
    if (code3 === codes.ampersand) {
      effects.consume(code3);
      return trailCharacterReferenceStart;
    }
    if (code3 === codes.rightSquareBracket) {
      effects.consume(code3);
      return trailBracketAfter;
    }
    if (code3 === codes.lessThan || code3 === codes.eof || markdownLineEndingOrSpace(code3) || unicodeWhitespace(code3)) {
      return ok3(code3);
    }
    return nok(code3);
  }
  function trailBracketAfter(code3) {
    if (code3 === codes.eof || code3 === codes.leftParenthesis || code3 === codes.leftSquareBracket || markdownLineEndingOrSpace(code3) || unicodeWhitespace(code3)) {
      return ok3(code3);
    }
    return trail2(code3);
  }
  function trailCharacterReferenceStart(code3) {
    return asciiAlpha(code3) ? trailCharacterReferenceInside(code3) : nok(code3);
  }
  function trailCharacterReferenceInside(code3) {
    if (code3 === codes.semicolon) {
      effects.consume(code3);
      return trail2;
    }
    if (asciiAlpha(code3)) {
      effects.consume(code3);
      return trailCharacterReferenceInside;
    }
    return nok(code3);
  }
}
function tokenizeEmailDomainDotTrail(effects, ok3, nok) {
  return start;
  function start(code3) {
    effects.consume(code3);
    return after;
  }
  function after(code3) {
    return asciiAlphanumeric(code3) ? nok(code3) : ok3(code3);
  }
}
function previousWww(code3) {
  return code3 === codes.eof || code3 === codes.leftParenthesis || code3 === codes.asterisk || code3 === codes.underscore || code3 === codes.leftSquareBracket || code3 === codes.rightSquareBracket || code3 === codes.tilde || markdownLineEndingOrSpace(code3);
}
function previousProtocol(code3) {
  return !asciiAlpha(code3);
}
function previousEmail(code3) {
  return !(code3 === codes.slash || gfmAtext(code3));
}
function gfmAtext(code3) {
  return code3 === codes.plusSign || code3 === codes.dash || code3 === codes.dot || code3 === codes.underscore || asciiAlphanumeric(code3);
}
function previousUnbalanced(events) {
  let index2 = events.length;
  let result = false;
  while (index2--) {
    const token = events[index2][1];
    if ((token.type === "labelLink" || token.type === "labelImage") && !token._balanced) {
      result = true;
      break;
    }
    if (token._gfmAutolinkLiteralWalkedInto) {
      result = false;
      break;
    }
  }
  if (events.length > 0 && !result) {
    events[events.length - 1][1]._gfmAutolinkLiteralWalkedInto = true;
  }
  return result;
}
var wwwPrefix, domain2, path3, trail, emailDomainDotTrail, wwwAutolink, protocolAutolink, emailAutolink, text6, code2;
var init_syntax = __esm(() => {
  init_dev4();
  init_default();
  wwwPrefix = { tokenize: tokenizeWwwPrefix, partial: true };
  domain2 = { tokenize: tokenizeDomain, partial: true };
  path3 = { tokenize: tokenizePath, partial: true };
  trail = { tokenize: tokenizeTrail, partial: true };
  emailDomainDotTrail = {
    tokenize: tokenizeEmailDomainDotTrail,
    partial: true
  };
  wwwAutolink = {
    name: "wwwAutolink",
    tokenize: tokenizeWwwAutolink,
    previous: previousWww
  };
  protocolAutolink = {
    name: "protocolAutolink",
    tokenize: tokenizeProtocolAutolink,
    previous: previousProtocol
  };
  emailAutolink = {
    name: "emailAutolink",
    tokenize: tokenizeEmailAutolink,
    previous: previousEmail
  };
  text6 = {};
  code2 = codes.digit0;
  while (code2 < codes.leftCurlyBrace) {
    text6[code2] = emailAutolink;
    code2++;
    if (code2 === codes.colon)
      code2 = codes.uppercaseA;
    else if (code2 === codes.leftSquareBracket)
      code2 = codes.lowercaseA;
  }
  text6[codes.plusSign] = emailAutolink;
  text6[codes.dash] = emailAutolink;
  text6[codes.dot] = emailAutolink;
  text6[codes.underscore] = emailAutolink;
  text6[codes.uppercaseH] = [emailAutolink, protocolAutolink];
  text6[codes.lowercaseH] = [emailAutolink, protocolAutolink];
  text6[codes.uppercaseW] = [emailAutolink, wwwAutolink];
  text6[codes.lowercaseW] = [emailAutolink, wwwAutolink];
});

// node_modules/micromark-extension-gfm-autolink-literal/dev/index.js
var init_dev16 = __esm(() => {
  init_syntax();
});

// node_modules/micromark-extension-gfm-footnote/dev/lib/syntax.js
function gfmFootnote() {
  return {
    document: {
      [codes.leftSquareBracket]: {
        name: "gfmFootnoteDefinition",
        tokenize: tokenizeDefinitionStart,
        continuation: { tokenize: tokenizeDefinitionContinuation },
        exit: gfmFootnoteDefinitionEnd
      }
    },
    text: {
      [codes.leftSquareBracket]: {
        name: "gfmFootnoteCall",
        tokenize: tokenizeGfmFootnoteCall
      },
      [codes.rightSquareBracket]: {
        name: "gfmPotentialFootnoteCall",
        add: "after",
        tokenize: tokenizePotentialGfmFootnoteCall,
        resolveTo: resolveToPotentialGfmFootnoteCall
      }
    }
  };
}
function tokenizePotentialGfmFootnoteCall(effects, ok3, nok) {
  const self2 = this;
  let index2 = self2.events.length;
  const defined = self2.parser.gfmFootnotes || (self2.parser.gfmFootnotes = []);
  let labelStart;
  while (index2--) {
    const token = self2.events[index2][1];
    if (token.type === types.labelImage) {
      labelStart = token;
      break;
    }
    if (token.type === "gfmFootnoteCall" || token.type === types.labelLink || token.type === types.label || token.type === types.image || token.type === types.link) {
      break;
    }
  }
  return start;
  function start(code3) {
    ok(code3 === codes.rightSquareBracket, "expected `]`");
    if (!labelStart || !labelStart._balanced) {
      return nok(code3);
    }
    const id2 = normalizeIdentifier(self2.sliceSerialize({ start: labelStart.end, end: self2.now() }));
    if (id2.codePointAt(0) !== codes.caret || !defined.includes(id2.slice(1))) {
      return nok(code3);
    }
    effects.enter("gfmFootnoteCallLabelMarker");
    effects.consume(code3);
    effects.exit("gfmFootnoteCallLabelMarker");
    return ok3(code3);
  }
}
function resolveToPotentialGfmFootnoteCall(events, context) {
  let index2 = events.length;
  let labelStart;
  while (index2--) {
    if (events[index2][1].type === types.labelImage && events[index2][0] === "enter") {
      labelStart = events[index2][1];
      break;
    }
  }
  ok(labelStart, "expected `labelStart` to resolve");
  events[index2 + 1][1].type = types.data;
  events[index2 + 3][1].type = "gfmFootnoteCallLabelMarker";
  const call = {
    type: "gfmFootnoteCall",
    start: Object.assign({}, events[index2 + 3][1].start),
    end: Object.assign({}, events[events.length - 1][1].end)
  };
  const marker = {
    type: "gfmFootnoteCallMarker",
    start: Object.assign({}, events[index2 + 3][1].end),
    end: Object.assign({}, events[index2 + 3][1].end)
  };
  marker.end.column++;
  marker.end.offset++;
  marker.end._bufferIndex++;
  const string6 = {
    type: "gfmFootnoteCallString",
    start: Object.assign({}, marker.end),
    end: Object.assign({}, events[events.length - 1][1].start)
  };
  const chunk = {
    type: types.chunkString,
    contentType: "string",
    start: Object.assign({}, string6.start),
    end: Object.assign({}, string6.end)
  };
  const replacement = [
    events[index2 + 1],
    events[index2 + 2],
    ["enter", call, context],
    events[index2 + 3],
    events[index2 + 4],
    ["enter", marker, context],
    ["exit", marker, context],
    ["enter", string6, context],
    ["enter", chunk, context],
    ["exit", chunk, context],
    ["exit", string6, context],
    events[events.length - 2],
    events[events.length - 1],
    ["exit", call, context]
  ];
  events.splice(index2, events.length - index2 + 1, ...replacement);
  return events;
}
function tokenizeGfmFootnoteCall(effects, ok3, nok) {
  const self2 = this;
  const defined = self2.parser.gfmFootnotes || (self2.parser.gfmFootnotes = []);
  let size2 = 0;
  let data2;
  return start;
  function start(code3) {
    ok(code3 === codes.leftSquareBracket, "expected `[`");
    effects.enter("gfmFootnoteCall");
    effects.enter("gfmFootnoteCallLabelMarker");
    effects.consume(code3);
    effects.exit("gfmFootnoteCallLabelMarker");
    return callStart;
  }
  function callStart(code3) {
    if (code3 !== codes.caret)
      return nok(code3);
    effects.enter("gfmFootnoteCallMarker");
    effects.consume(code3);
    effects.exit("gfmFootnoteCallMarker");
    effects.enter("gfmFootnoteCallString");
    effects.enter("chunkString").contentType = "string";
    return callData;
  }
  function callData(code3) {
    if (size2 > constants2.linkReferenceSizeMax || code3 === codes.rightSquareBracket && !data2 || code3 === codes.eof || code3 === codes.leftSquareBracket || markdownLineEndingOrSpace(code3)) {
      return nok(code3);
    }
    if (code3 === codes.rightSquareBracket) {
      effects.exit("chunkString");
      const token = effects.exit("gfmFootnoteCallString");
      if (!defined.includes(normalizeIdentifier(self2.sliceSerialize(token)))) {
        return nok(code3);
      }
      effects.enter("gfmFootnoteCallLabelMarker");
      effects.consume(code3);
      effects.exit("gfmFootnoteCallLabelMarker");
      effects.exit("gfmFootnoteCall");
      return ok3;
    }
    if (!markdownLineEndingOrSpace(code3)) {
      data2 = true;
    }
    size2++;
    effects.consume(code3);
    return code3 === codes.backslash ? callEscape : callData;
  }
  function callEscape(code3) {
    if (code3 === codes.leftSquareBracket || code3 === codes.backslash || code3 === codes.rightSquareBracket) {
      effects.consume(code3);
      size2++;
      return callData;
    }
    return callData(code3);
  }
}
function tokenizeDefinitionStart(effects, ok3, nok) {
  const self2 = this;
  const defined = self2.parser.gfmFootnotes || (self2.parser.gfmFootnotes = []);
  let identifier;
  let size2 = 0;
  let data2;
  return start;
  function start(code3) {
    ok(code3 === codes.leftSquareBracket, "expected `[`");
    effects.enter("gfmFootnoteDefinition")._container = true;
    effects.enter("gfmFootnoteDefinitionLabel");
    effects.enter("gfmFootnoteDefinitionLabelMarker");
    effects.consume(code3);
    effects.exit("gfmFootnoteDefinitionLabelMarker");
    return labelAtMarker;
  }
  function labelAtMarker(code3) {
    if (code3 === codes.caret) {
      effects.enter("gfmFootnoteDefinitionMarker");
      effects.consume(code3);
      effects.exit("gfmFootnoteDefinitionMarker");
      effects.enter("gfmFootnoteDefinitionLabelString");
      effects.enter("chunkString").contentType = "string";
      return labelInside;
    }
    return nok(code3);
  }
  function labelInside(code3) {
    if (size2 > constants2.linkReferenceSizeMax || code3 === codes.rightSquareBracket && !data2 || code3 === codes.eof || code3 === codes.leftSquareBracket || markdownLineEndingOrSpace(code3)) {
      return nok(code3);
    }
    if (code3 === codes.rightSquareBracket) {
      effects.exit("chunkString");
      const token = effects.exit("gfmFootnoteDefinitionLabelString");
      identifier = normalizeIdentifier(self2.sliceSerialize(token));
      effects.enter("gfmFootnoteDefinitionLabelMarker");
      effects.consume(code3);
      effects.exit("gfmFootnoteDefinitionLabelMarker");
      effects.exit("gfmFootnoteDefinitionLabel");
      return labelAfter;
    }
    if (!markdownLineEndingOrSpace(code3)) {
      data2 = true;
    }
    size2++;
    effects.consume(code3);
    return code3 === codes.backslash ? labelEscape : labelInside;
  }
  function labelEscape(code3) {
    if (code3 === codes.leftSquareBracket || code3 === codes.backslash || code3 === codes.rightSquareBracket) {
      effects.consume(code3);
      size2++;
      return labelInside;
    }
    return labelInside(code3);
  }
  function labelAfter(code3) {
    if (code3 === codes.colon) {
      effects.enter("definitionMarker");
      effects.consume(code3);
      effects.exit("definitionMarker");
      if (!defined.includes(identifier)) {
        defined.push(identifier);
      }
      return factorySpace(effects, whitespaceAfter, "gfmFootnoteDefinitionWhitespace");
    }
    return nok(code3);
  }
  function whitespaceAfter(code3) {
    return ok3(code3);
  }
}
function tokenizeDefinitionContinuation(effects, ok3, nok) {
  return effects.check(blankLine, ok3, effects.attempt(indent, ok3, nok));
}
function gfmFootnoteDefinitionEnd(effects) {
  effects.exit("gfmFootnoteDefinition");
}
function tokenizeIndent2(effects, ok3, nok) {
  const self2 = this;
  return factorySpace(effects, afterPrefix, "gfmFootnoteDefinitionIndent", constants2.tabSize + 1);
  function afterPrefix(code3) {
    const tail = self2.events[self2.events.length - 1];
    return tail && tail[1].type === "gfmFootnoteDefinitionIndent" && tail[2].sliceSerialize(tail[1], true).length === constants2.tabSize ? ok3(code3) : nok(code3);
  }
}
var indent;
var init_syntax2 = __esm(() => {
  init_development();
  init_dev12();
  init_dev5();
  init_dev4();
  init_dev3();
  init_default();
  indent = { tokenize: tokenizeIndent2, partial: true };
});

// node_modules/micromark-extension-gfm-footnote/dev/index.js
var init_dev17 = __esm(() => {
  init_syntax2();
});

// node_modules/micromark-extension-gfm-strikethrough/dev/lib/syntax.js
function gfmStrikethrough(options) {
  const options_ = options || {};
  let single = options_.singleTilde;
  const tokenizer = {
    name: "strikethrough",
    tokenize: tokenizeStrikethrough,
    resolveAll: resolveAllStrikethrough
  };
  if (single === null || single === undefined) {
    single = true;
  }
  return {
    text: { [codes.tilde]: tokenizer },
    insideSpan: { null: [tokenizer] },
    attentionMarkers: { null: [codes.tilde] }
  };
  function resolveAllStrikethrough(events, context) {
    let index2 = -1;
    while (++index2 < events.length) {
      if (events[index2][0] === "enter" && events[index2][1].type === "strikethroughSequenceTemporary" && events[index2][1]._close) {
        let open = index2;
        while (open--) {
          if (events[open][0] === "exit" && events[open][1].type === "strikethroughSequenceTemporary" && events[open][1]._open && events[index2][1].end.offset - events[index2][1].start.offset === events[open][1].end.offset - events[open][1].start.offset) {
            events[index2][1].type = "strikethroughSequence";
            events[open][1].type = "strikethroughSequence";
            const strikethrough = {
              type: "strikethrough",
              start: Object.assign({}, events[open][1].start),
              end: Object.assign({}, events[index2][1].end)
            };
            const text7 = {
              type: "strikethroughText",
              start: Object.assign({}, events[open][1].end),
              end: Object.assign({}, events[index2][1].start)
            };
            const nextEvents = [
              ["enter", strikethrough, context],
              ["enter", events[open][1], context],
              ["exit", events[open][1], context],
              ["enter", text7, context]
            ];
            const insideSpan2 = context.parser.constructs.insideSpan.null;
            if (insideSpan2) {
              splice(nextEvents, nextEvents.length, 0, resolveAll(insideSpan2, events.slice(open + 1, index2), context));
            }
            splice(nextEvents, nextEvents.length, 0, [
              ["exit", text7, context],
              ["enter", events[index2][1], context],
              ["exit", events[index2][1], context],
              ["exit", strikethrough, context]
            ]);
            splice(events, open - 1, index2 - open + 3, nextEvents);
            index2 = open + nextEvents.length - 2;
            break;
          }
        }
      }
    }
    index2 = -1;
    while (++index2 < events.length) {
      if (events[index2][1].type === "strikethroughSequenceTemporary") {
        events[index2][1].type = types.data;
      }
    }
    return events;
  }
  function tokenizeStrikethrough(effects, ok3, nok) {
    const previous4 = this.previous;
    const events = this.events;
    let size2 = 0;
    return start;
    function start(code3) {
      ok(code3 === codes.tilde, "expected `~`");
      if (previous4 === codes.tilde && events[events.length - 1][1].type !== types.characterEscape) {
        return nok(code3);
      }
      effects.enter("strikethroughSequenceTemporary");
      return more(code3);
    }
    function more(code3) {
      const before = classifyCharacter(previous4);
      if (code3 === codes.tilde) {
        if (size2 > 1)
          return nok(code3);
        effects.consume(code3);
        size2++;
        return more;
      }
      if (size2 < 2 && !single)
        return nok(code3);
      const token = effects.exit("strikethroughSequenceTemporary");
      const after = classifyCharacter(code3);
      token._open = !after || after === constants2.attentionSideAfter && Boolean(before);
      token._close = !before || before === constants2.attentionSideAfter && Boolean(after);
      return ok3(code3);
    }
  }
}
var init_syntax3 = __esm(() => {
  init_development();
  init_dev();
  init_dev6();
  init_default();
});

// node_modules/micromark-extension-gfm-strikethrough/dev/index.js
var init_dev18 = __esm(() => {
  init_syntax3();
});

// node_modules/micromark-extension-gfm-table/dev/lib/edit-map.js
class EditMap {
  constructor() {
    this.map = [];
  }
  add(index2, remove, add2) {
    addImplementation(this, index2, remove, add2);
  }
  consume(events) {
    this.map.sort(function(a, b) {
      return a[0] - b[0];
    });
    if (this.map.length === 0) {
      return;
    }
    let index2 = this.map.length;
    const vecs = [];
    while (index2 > 0) {
      index2 -= 1;
      vecs.push(events.slice(this.map[index2][0] + this.map[index2][1]), this.map[index2][2]);
      events.length = this.map[index2][0];
    }
    vecs.push(events.slice());
    events.length = 0;
    let slice3 = vecs.pop();
    while (slice3) {
      for (const element of slice3) {
        events.push(element);
      }
      slice3 = vecs.pop();
    }
    this.map.length = 0;
  }
}
function addImplementation(editMap, at, remove, add2) {
  let index2 = 0;
  if (remove === 0 && add2.length === 0) {
    return;
  }
  while (index2 < editMap.map.length) {
    if (editMap.map[index2][0] === at) {
      editMap.map[index2][1] += remove;
      editMap.map[index2][2].push(...add2);
      return;
    }
    index2 += 1;
  }
  editMap.map.push([at, remove, add2]);
}

// node_modules/micromark-extension-gfm-table/dev/lib/infer.js
function gfmTableAlign(events, index2) {
  ok(events[index2][1].type === "table", "expected table");
  let inDelimiterRow = false;
  const align = [];
  while (index2 < events.length) {
    const event = events[index2];
    if (inDelimiterRow) {
      if (event[0] === "enter") {
        if (event[1].type === "tableContent") {
          align.push(events[index2 + 1][1].type === "tableDelimiterMarker" ? "left" : "none");
        }
      } else if (event[1].type === "tableContent") {
        if (events[index2 - 1][1].type === "tableDelimiterMarker") {
          const alignIndex = align.length - 1;
          align[alignIndex] = align[alignIndex] === "left" ? "center" : "right";
        }
      } else if (event[1].type === "tableDelimiterRow") {
        break;
      }
    } else if (event[0] === "enter" && event[1].type === "tableDelimiterRow") {
      inDelimiterRow = true;
    }
    index2 += 1;
  }
  return align;
}
var init_infer = __esm(() => {
  init_development();
});

// node_modules/micromark-extension-gfm-table/dev/lib/syntax.js
function gfmTable() {
  return {
    flow: {
      null: { name: "table", tokenize: tokenizeTable, resolveAll: resolveTable2 }
    }
  };
}
function tokenizeTable(effects, ok3, nok) {
  const self2 = this;
  let size2 = 0;
  let sizeB = 0;
  let seen;
  return start;
  function start(code3) {
    let index2 = self2.events.length - 1;
    while (index2 > -1) {
      const type = self2.events[index2][1].type;
      if (type === types.lineEnding || type === types.linePrefix)
        index2--;
      else
        break;
    }
    const tail = index2 > -1 ? self2.events[index2][1].type : null;
    const next2 = tail === "tableHead" || tail === "tableRow" ? bodyRowStart : headRowBefore;
    if (next2 === bodyRowStart && self2.parser.lazy[self2.now().line]) {
      return nok(code3);
    }
    return next2(code3);
  }
  function headRowBefore(code3) {
    effects.enter("tableHead");
    effects.enter("tableRow");
    return headRowStart(code3);
  }
  function headRowStart(code3) {
    if (code3 === codes.verticalBar) {
      return headRowBreak(code3);
    }
    seen = true;
    sizeB += 1;
    return headRowBreak(code3);
  }
  function headRowBreak(code3) {
    if (code3 === codes.eof) {
      return nok(code3);
    }
    if (markdownLineEnding(code3)) {
      if (sizeB > 1) {
        sizeB = 0;
        self2.interrupt = true;
        effects.exit("tableRow");
        effects.enter(types.lineEnding);
        effects.consume(code3);
        effects.exit(types.lineEnding);
        return headDelimiterStart;
      }
      return nok(code3);
    }
    if (markdownSpace(code3)) {
      return factorySpace(effects, headRowBreak, types.whitespace)(code3);
    }
    sizeB += 1;
    if (seen) {
      seen = false;
      size2 += 1;
    }
    if (code3 === codes.verticalBar) {
      effects.enter("tableCellDivider");
      effects.consume(code3);
      effects.exit("tableCellDivider");
      seen = true;
      return headRowBreak;
    }
    effects.enter(types.data);
    return headRowData(code3);
  }
  function headRowData(code3) {
    if (code3 === codes.eof || code3 === codes.verticalBar || markdownLineEndingOrSpace(code3)) {
      effects.exit(types.data);
      return headRowBreak(code3);
    }
    effects.consume(code3);
    return code3 === codes.backslash ? headRowEscape : headRowData;
  }
  function headRowEscape(code3) {
    if (code3 === codes.backslash || code3 === codes.verticalBar) {
      effects.consume(code3);
      return headRowData;
    }
    return headRowData(code3);
  }
  function headDelimiterStart(code3) {
    self2.interrupt = false;
    if (self2.parser.lazy[self2.now().line]) {
      return nok(code3);
    }
    effects.enter("tableDelimiterRow");
    seen = false;
    if (markdownSpace(code3)) {
      ok(self2.parser.constructs.disable.null, "expected `disabled.null`");
      return factorySpace(effects, headDelimiterBefore, types.linePrefix, self2.parser.constructs.disable.null.includes("codeIndented") ? undefined : constants2.tabSize)(code3);
    }
    return headDelimiterBefore(code3);
  }
  function headDelimiterBefore(code3) {
    if (code3 === codes.dash || code3 === codes.colon) {
      return headDelimiterValueBefore(code3);
    }
    if (code3 === codes.verticalBar) {
      seen = true;
      effects.enter("tableCellDivider");
      effects.consume(code3);
      effects.exit("tableCellDivider");
      return headDelimiterCellBefore;
    }
    return headDelimiterNok(code3);
  }
  function headDelimiterCellBefore(code3) {
    if (markdownSpace(code3)) {
      return factorySpace(effects, headDelimiterValueBefore, types.whitespace)(code3);
    }
    return headDelimiterValueBefore(code3);
  }
  function headDelimiterValueBefore(code3) {
    if (code3 === codes.colon) {
      sizeB += 1;
      seen = true;
      effects.enter("tableDelimiterMarker");
      effects.consume(code3);
      effects.exit("tableDelimiterMarker");
      return headDelimiterLeftAlignmentAfter;
    }
    if (code3 === codes.dash) {
      sizeB += 1;
      return headDelimiterLeftAlignmentAfter(code3);
    }
    if (code3 === codes.eof || markdownLineEnding(code3)) {
      return headDelimiterCellAfter(code3);
    }
    return headDelimiterNok(code3);
  }
  function headDelimiterLeftAlignmentAfter(code3) {
    if (code3 === codes.dash) {
      effects.enter("tableDelimiterFiller");
      return headDelimiterFiller(code3);
    }
    return headDelimiterNok(code3);
  }
  function headDelimiterFiller(code3) {
    if (code3 === codes.dash) {
      effects.consume(code3);
      return headDelimiterFiller;
    }
    if (code3 === codes.colon) {
      seen = true;
      effects.exit("tableDelimiterFiller");
      effects.enter("tableDelimiterMarker");
      effects.consume(code3);
      effects.exit("tableDelimiterMarker");
      return headDelimiterRightAlignmentAfter;
    }
    effects.exit("tableDelimiterFiller");
    return headDelimiterRightAlignmentAfter(code3);
  }
  function headDelimiterRightAlignmentAfter(code3) {
    if (markdownSpace(code3)) {
      return factorySpace(effects, headDelimiterCellAfter, types.whitespace)(code3);
    }
    return headDelimiterCellAfter(code3);
  }
  function headDelimiterCellAfter(code3) {
    if (code3 === codes.verticalBar) {
      return headDelimiterBefore(code3);
    }
    if (code3 === codes.eof || markdownLineEnding(code3)) {
      if (!seen || size2 !== sizeB) {
        return headDelimiterNok(code3);
      }
      effects.exit("tableDelimiterRow");
      effects.exit("tableHead");
      return ok3(code3);
    }
    return headDelimiterNok(code3);
  }
  function headDelimiterNok(code3) {
    return nok(code3);
  }
  function bodyRowStart(code3) {
    effects.enter("tableRow");
    return bodyRowBreak(code3);
  }
  function bodyRowBreak(code3) {
    if (code3 === codes.verticalBar) {
      effects.enter("tableCellDivider");
      effects.consume(code3);
      effects.exit("tableCellDivider");
      return bodyRowBreak;
    }
    if (code3 === codes.eof || markdownLineEnding(code3)) {
      effects.exit("tableRow");
      return ok3(code3);
    }
    if (markdownSpace(code3)) {
      return factorySpace(effects, bodyRowBreak, types.whitespace)(code3);
    }
    effects.enter(types.data);
    return bodyRowData(code3);
  }
  function bodyRowData(code3) {
    if (code3 === codes.eof || code3 === codes.verticalBar || markdownLineEndingOrSpace(code3)) {
      effects.exit(types.data);
      return bodyRowBreak(code3);
    }
    effects.consume(code3);
    return code3 === codes.backslash ? bodyRowEscape : bodyRowData;
  }
  function bodyRowEscape(code3) {
    if (code3 === codes.backslash || code3 === codes.verticalBar) {
      effects.consume(code3);
      return bodyRowData;
    }
    return bodyRowData(code3);
  }
}
function resolveTable2(events, context) {
  let index2 = -1;
  let inFirstCellAwaitingPipe = true;
  let rowKind = 0;
  let lastCell = [0, 0, 0, 0];
  let cell = [0, 0, 0, 0];
  let afterHeadAwaitingFirstBodyRow = false;
  let lastTableEnd = 0;
  let currentTable;
  let currentBody;
  let currentCell;
  const map6 = new EditMap;
  while (++index2 < events.length) {
    const event = events[index2];
    const token = event[1];
    if (event[0] === "enter") {
      if (token.type === "tableHead") {
        afterHeadAwaitingFirstBodyRow = false;
        if (lastTableEnd !== 0) {
          ok(currentTable, "there should be a table opening");
          flushTableEnd(map6, context, lastTableEnd, currentTable, currentBody);
          currentBody = undefined;
          lastTableEnd = 0;
        }
        currentTable = {
          type: "table",
          start: Object.assign({}, token.start),
          end: Object.assign({}, token.end)
        };
        map6.add(index2, 0, [["enter", currentTable, context]]);
      } else if (token.type === "tableRow" || token.type === "tableDelimiterRow") {
        inFirstCellAwaitingPipe = true;
        currentCell = undefined;
        lastCell = [0, 0, 0, 0];
        cell = [0, index2 + 1, 0, 0];
        if (afterHeadAwaitingFirstBodyRow) {
          afterHeadAwaitingFirstBodyRow = false;
          currentBody = {
            type: "tableBody",
            start: Object.assign({}, token.start),
            end: Object.assign({}, token.end)
          };
          map6.add(index2, 0, [["enter", currentBody, context]]);
        }
        rowKind = token.type === "tableDelimiterRow" ? 2 : currentBody ? 3 : 1;
      } else if (rowKind && (token.type === types.data || token.type === "tableDelimiterMarker" || token.type === "tableDelimiterFiller")) {
        inFirstCellAwaitingPipe = false;
        if (cell[2] === 0) {
          if (lastCell[1] !== 0) {
            cell[0] = cell[1];
            currentCell = flushCell(map6, context, lastCell, rowKind, undefined, currentCell);
            lastCell = [0, 0, 0, 0];
          }
          cell[2] = index2;
        }
      } else if (token.type === "tableCellDivider") {
        if (inFirstCellAwaitingPipe) {
          inFirstCellAwaitingPipe = false;
        } else {
          if (lastCell[1] !== 0) {
            cell[0] = cell[1];
            currentCell = flushCell(map6, context, lastCell, rowKind, undefined, currentCell);
          }
          lastCell = cell;
          cell = [lastCell[1], index2, 0, 0];
        }
      }
    } else if (token.type === "tableHead") {
      afterHeadAwaitingFirstBodyRow = true;
      lastTableEnd = index2;
    } else if (token.type === "tableRow" || token.type === "tableDelimiterRow") {
      lastTableEnd = index2;
      if (lastCell[1] !== 0) {
        cell[0] = cell[1];
        currentCell = flushCell(map6, context, lastCell, rowKind, index2, currentCell);
      } else if (cell[1] !== 0) {
        currentCell = flushCell(map6, context, cell, rowKind, index2, currentCell);
      }
      rowKind = 0;
    } else if (rowKind && (token.type === types.data || token.type === "tableDelimiterMarker" || token.type === "tableDelimiterFiller")) {
      cell[3] = index2;
    }
  }
  if (lastTableEnd !== 0) {
    ok(currentTable, "expected table opening");
    flushTableEnd(map6, context, lastTableEnd, currentTable, currentBody);
  }
  map6.consume(context.events);
  index2 = -1;
  while (++index2 < context.events.length) {
    const event = context.events[index2];
    if (event[0] === "enter" && event[1].type === "table") {
      event[1]._align = gfmTableAlign(context.events, index2);
    }
  }
  return events;
}
function flushCell(map6, context, range2, rowKind, rowEnd, previousCell) {
  const groupName = rowKind === 1 ? "tableHeader" : rowKind === 2 ? "tableDelimiter" : "tableData";
  const valueName = "tableContent";
  if (range2[0] !== 0) {
    ok(previousCell, "expected previous cell enter");
    previousCell.end = Object.assign({}, getPoint(context.events, range2[0]));
    map6.add(range2[0], 0, [["exit", previousCell, context]]);
  }
  const now = getPoint(context.events, range2[1]);
  previousCell = {
    type: groupName,
    start: Object.assign({}, now),
    end: Object.assign({}, now)
  };
  map6.add(range2[1], 0, [["enter", previousCell, context]]);
  if (range2[2] !== 0) {
    const relatedStart = getPoint(context.events, range2[2]);
    const relatedEnd = getPoint(context.events, range2[3]);
    const valueToken = {
      type: valueName,
      start: Object.assign({}, relatedStart),
      end: Object.assign({}, relatedEnd)
    };
    map6.add(range2[2], 0, [["enter", valueToken, context]]);
    ok(range2[3] !== 0);
    if (rowKind !== 2) {
      const start = context.events[range2[2]];
      const end = context.events[range2[3]];
      start[1].end = Object.assign({}, end[1].end);
      start[1].type = types.chunkText;
      start[1].contentType = constants2.contentTypeText;
      if (range2[3] > range2[2] + 1) {
        const a = range2[2] + 1;
        const b = range2[3] - range2[2] - 1;
        map6.add(a, b, []);
      }
    }
    map6.add(range2[3] + 1, 0, [["exit", valueToken, context]]);
  }
  if (rowEnd !== undefined) {
    previousCell.end = Object.assign({}, getPoint(context.events, rowEnd));
    map6.add(rowEnd, 0, [["exit", previousCell, context]]);
    previousCell = undefined;
  }
  return previousCell;
}
function flushTableEnd(map6, context, index2, table2, tableBody) {
  const exits = [];
  const related = getPoint(context.events, index2);
  if (tableBody) {
    tableBody.end = Object.assign({}, related);
    exits.push(["exit", tableBody, context]);
  }
  table2.end = Object.assign({}, related);
  exits.push(["exit", table2, context]);
  map6.add(index2 + 1, 0, exits);
}
function getPoint(events, index2) {
  const event = events[index2];
  const side = event[0] === "enter" ? "start" : "end";
  return event[1][side];
}
var init_syntax4 = __esm(() => {
  init_development();
  init_dev5();
  init_dev4();
  init_default();
  init_infer();
});

// node_modules/micromark-extension-gfm-table/dev/index.js
var init_dev19 = __esm(() => {
  init_syntax4();
});

// node_modules/micromark-extension-gfm-task-list-item/dev/lib/syntax.js
function gfmTaskListItem() {
  return {
    text: { [codes.leftSquareBracket]: tasklistCheck }
  };
}
function tokenizeTasklistCheck(effects, ok3, nok) {
  const self2 = this;
  return open;
  function open(code3) {
    ok(code3 === codes.leftSquareBracket, "expected `[`");
    if (self2.previous !== codes.eof || !self2._gfmTasklistFirstContentOfListItem) {
      return nok(code3);
    }
    effects.enter("taskListCheck");
    effects.enter("taskListCheckMarker");
    effects.consume(code3);
    effects.exit("taskListCheckMarker");
    return inside;
  }
  function inside(code3) {
    if (markdownLineEndingOrSpace(code3)) {
      effects.enter("taskListCheckValueUnchecked");
      effects.consume(code3);
      effects.exit("taskListCheckValueUnchecked");
      return close;
    }
    if (code3 === codes.uppercaseX || code3 === codes.lowercaseX) {
      effects.enter("taskListCheckValueChecked");
      effects.consume(code3);
      effects.exit("taskListCheckValueChecked");
      return close;
    }
    return nok(code3);
  }
  function close(code3) {
    if (code3 === codes.rightSquareBracket) {
      effects.enter("taskListCheckMarker");
      effects.consume(code3);
      effects.exit("taskListCheckMarker");
      effects.exit("taskListCheck");
      return after;
    }
    return nok(code3);
  }
  function after(code3) {
    if (markdownLineEnding(code3)) {
      return ok3(code3);
    }
    if (markdownSpace(code3)) {
      return effects.check({ tokenize: spaceThenNonSpace }, ok3, nok)(code3);
    }
    return nok(code3);
  }
}
function spaceThenNonSpace(effects, ok3, nok) {
  return factorySpace(effects, after, types.whitespace);
  function after(code3) {
    return code3 === codes.eof ? nok(code3) : ok3(code3);
  }
}
var tasklistCheck;
var init_syntax5 = __esm(() => {
  init_development();
  init_dev5();
  init_dev4();
  init_default();
  tasklistCheck = { name: "tasklistCheck", tokenize: tokenizeTasklistCheck };
});

// node_modules/micromark-extension-gfm-task-list-item/dev/index.js
var init_dev20 = __esm(() => {
  init_syntax5();
});

// node_modules/micromark-extension-gfm/index.js
function gfm(options) {
  return combineExtensions([
    gfmAutolinkLiteral(),
    gfmFootnote(),
    gfmStrikethrough(options),
    gfmTable(),
    gfmTaskListItem()
  ]);
}
var init_micromark_extension_gfm = __esm(() => {
  init_micromark_util_combine_extensions();
  init_dev16();
  init_dev17();
  init_dev18();
  init_dev19();
  init_dev20();
});

// node_modules/remark-gfm/lib/index.js
function remarkGfm(options) {
  const self2 = this;
  const settings = options || emptyOptions2;
  const data2 = self2.data();
  const micromarkExtensions = data2.micromarkExtensions || (data2.micromarkExtensions = []);
  const fromMarkdownExtensions = data2.fromMarkdownExtensions || (data2.fromMarkdownExtensions = []);
  const toMarkdownExtensions = data2.toMarkdownExtensions || (data2.toMarkdownExtensions = []);
  micromarkExtensions.push(gfm(settings));
  fromMarkdownExtensions.push(gfmFromMarkdown());
  toMarkdownExtensions.push(gfmToMarkdown(settings));
}
var emptyOptions2;
var init_lib17 = __esm(() => {
  init_mdast_util_gfm();
  init_micromark_extension_gfm();
  emptyOptions2 = {};
});

// node_modules/remark-gfm/index.js
var init_remark_gfm = __esm(() => {
  init_lib17();
});

// node_modules/@oai/granola/dist/models/workbook-from-markdown.js
var exports_workbook_from_markdown = {};
__export(exports_workbook_from_markdown, {
  sanitizeSheetName: () => sanitizeSheetName,
  buildTableValuesFromMarkdown: () => buildTableValuesFromMarkdown
});
function sanitizeSheetName(requested) {
  const trimmed = (requested ?? DEFAULT_SHEET_NAME).trim();
  const cleaned = trimmed.replace(INVALID_SHEET_NAME_CHARS, "").trim() || DEFAULT_SHEET_NAME;
  return cleaned.slice(0, EXCEL_MAX_SHEET_NAME_LENGTH);
}
function preprocessMarkdown(markdown) {
  return markdown.replace(BREAK_TAG_PATTERN, BREAK_PLACEHOLDER);
}
function cleanCellValue(value2) {
  return value2.replace(/\u00a0/g, " ").replaceAll(BREAK_PLACEHOLDER, `
`).replace(ZERO_WIDTH_SPACE_PATTERN, "").replace(CONTENT_REFERENCE_DIRECTIVE_PATTERN, "").replace(/\r/g, "").replace(/[ \t]+\n/g, `
`).replace(/\n[ \t]+/g, `
`).trim();
}
function extractTableRows(markdown) {
  const tree = markdownProcessor.parse(preprocessMarkdown(markdown));
  const tableNode = tree.children.find((node2) => node2.type === "table");
  if (!tableNode) {
    throw new Error("Unable to build workbook: no markdown table rows found.");
  }
  const rows = [];
  for (const row2 of tableNode.children) {
    const normalizedRow = row2.children.map((cell) => cleanCellValue(toString(cell)));
    if (normalizedRow.every((cell) => cell.length === 0)) {
      continue;
    }
    rows.push(normalizedRow);
  }
  return rows;
}
function buildTableValuesFromMarkdown(markdown) {
  return extractTableRows(markdown);
}
var DEFAULT_SHEET_NAME = "Markdown table", EXCEL_MAX_SHEET_NAME_LENGTH = 31, INVALID_SHEET_NAME_CHARS, BREAK_TAG_PATTERN, BREAK_PLACEHOLDER = "BPS_TABLE_BR_PLACEHOLDER", CONTENT_REFERENCE_DIRECTIVE_PATTERN, ZERO_WIDTH_SPACE_PATTERN, markdownProcessor;
var init_workbook_from_markdown = __esm(() => {
  init_unified();
  init_remark_parse();
  init_remark_gfm();
  init_mdast_util_to_string();
  INVALID_SHEET_NAME_CHARS = /\\|\/|\?|\*|\[|\]|:/g;
  BREAK_TAG_PATTERN = /<br\s*\/?>/gi;
  CONTENT_REFERENCE_DIRECTIVE_PATTERN = /:{1,3}contentReference\[[^\]]+\](?:\{[^}]*\})?/g;
  ZERO_WIDTH_SPACE_PATTERN = /\u200b/g;
  markdownProcessor = unified().use(remarkParse).use(remarkGfm);
});

// node_modules/@oai/granola/dist/models/workbook-from-csv.js
var exports_workbook_from_csv = {};
__export(exports_workbook_from_csv, {
  sanitizeSheetName: () => sanitizeSheetName2,
  planCsvImport: () => planCsvImport
});
function sanitizeSheetName2(requested) {
  const trimmed = (requested ?? DEFAULT_SHEET_NAME2).trim();
  const cleaned = trimmed.replace(INVALID_SHEET_NAME_CHARS2, "").trim() || DEFAULT_SHEET_NAME2;
  return cleaned.slice(0, EXCEL_MAX_SHEET_NAME_LENGTH2);
}
function planCsvImport(csv, options) {
  const separator = normalizeSeparator(options?.separator);
  const anchor = splitSheetAddress(options?.anchor ?? "A1");
  const anchorSheetName = anchor.sheetName?.trim();
  const requestedSheetName = options?.sheetName?.trim();
  if (anchorSheetName && requestedSheetName && anchorSheetName !== requestedSheetName) {
    throw new Error(`CSV import specifies conflicting sheet names: ` + `"${requestedSheetName}" (options.sheetName) vs "${anchorSheetName}" (anchor).`);
  }
  const sheetName = sanitizeSheetName2(anchorSheetName ?? requestedSheetName);
  const anchorRange = parseRangeAddress(anchor.ref);
  if (!anchorRange) {
    throw new Error(`CSV import anchor must be an A1 cell reference; received "${options?.anchor ?? "A1"}".`);
  }
  const { bounds: anchorBounds } = anchorRange;
  if (anchorBounds.startRow !== anchorBounds.endRow || anchorBounds.startCol !== anchorBounds.endCol) {
    throw new Error(`CSV import anchor must be a single cell reference; received "${options?.anchor ?? "A1"}".`);
  }
  const values2 = buildTableValuesFromCsv(csv, separator);
  const rowCount = values2.length;
  const colCount = rowCount > 0 ? values2[0]?.length ?? 0 : 0;
  if (rowCount === 0 || colCount === 0) {
    return { sheetName, values: [] };
  }
  const bounds = {
    startRow: anchorBounds.startRow,
    startCol: anchorBounds.startCol,
    endRow: anchorBounds.startRow + rowCount - 1,
    endCol: anchorBounds.startCol + colCount - 1
  };
  return {
    sheetName,
    values: values2,
    rangeRef: buildRangeRef(bounds),
    rect: {
      r1: bounds.startRow,
      c1: bounds.startCol,
      r2: bounds.endRow,
      c2: bounds.endCol
    }
  };
}
function normalizeSeparator(separator) {
  const normalized = separator ?? ",";
  if (normalized.length !== 1) {
    throw new Error(`CSV import separator must be a single character; received "${normalized}".`);
  }
  return normalized;
}
function buildTableValuesFromCsv(csv, separator) {
  const trimmed = csv.trim();
  if (!trimmed) {
    return [];
  }
  const rows = parseCsv(csv, separator);
  if (rows.length === 0) {
    return [];
  }
  const columnCount = rows.reduce((max5, row2) => Math.max(max5, row2.length), 0);
  if (columnCount === 0) {
    return [];
  }
  return rows.map((row2) => {
    if (row2.length === columnCount)
      return row2;
    const padded = row2.slice();
    while (padded.length < columnCount) {
      padded.push("");
    }
    return padded;
  });
}
function parseCsv(csv, separator) {
  const rows = [];
  let row2 = [];
  let field = "";
  let inQuotes = false;
  const pushField = () => {
    row2.push(field);
    field = "";
  };
  const pushRow = () => {
    rows.push(row2);
    row2 = [];
  };
  for (let i = 0;i < csv.length; i += 1) {
    const ch = csv[i] ?? "";
    if (inQuotes) {
      if (ch === '"') {
        const next2 = csv[i + 1];
        if (next2 === '"') {
          field += '"';
          i += 1;
          continue;
        }
        inQuotes = false;
        continue;
      }
      field += ch;
      continue;
    }
    if (ch === '"') {
      inQuotes = true;
      continue;
    }
    if (ch === separator) {
      pushField();
      continue;
    }
    if (ch === `
`) {
      pushField();
      pushRow();
      continue;
    }
    if (ch === "\r") {
      const next2 = csv[i + 1];
      if (next2 === `
`) {
        i += 1;
      }
      pushField();
      pushRow();
      continue;
    }
    field += ch;
  }
  pushField();
  pushRow();
  while (rows.length > 0) {
    const last2 = rows[rows.length - 1] ?? [];
    const allEmpty = last2.length > 0 && last2.every((cell) => cell === "");
    if (!allEmpty)
      break;
    rows.pop();
  }
  return rows;
}
var DEFAULT_SHEET_NAME2 = "CSV import", EXCEL_MAX_SHEET_NAME_LENGTH2 = 31, INVALID_SHEET_NAME_CHARS2;
var init_workbook_from_csv = __esm(() => {
  init_address_utils();
  INVALID_SHEET_NAME_CHARS2 = /\\|\/|\?|\*|\[|\]|:/g;
});

// rpc_server/daemon.ts
import net from "node:net";
import fs3 from "node:fs";

// oai_js_artifact_tool/setup/skia-canvas.ts
import {
  Canvas,
  DOMMatrix as SkiaDOMMatrix,
  DOMPoint as SkiaDOMPoint,
  DOMRect as SkiaDOMRect,
  Image as SkiaImage,
  ImageData as SkiaImageData,
  Path2D as SkiaPath2D
} from "skia-canvas";
var DEFAULT_MIME = "image/png";
function normalizeMime(type) {
  if (!type)
    return DEFAULT_MIME;
  const lowered = type.toLowerCase();
  if (lowered === "image/jpeg" || lowered === "image/jpg")
    return "image/jpeg";
  if (lowered === "image/webp")
    return "image/webp";
  if (lowered === "image/png")
    return "image/png";
  return DEFAULT_MIME;
}
function mimeToFormat(mime) {
  switch (mime) {
    case "image/jpeg":
      return "jpg";
    case "image/webp":
      return "webp";
    default:
      return "png";
  }
}

class SkiaOffscreenCanvas {
  #canvas;
  constructor(width = 0, height = 0) {
    this.#canvas = new Canvas(width, height);
  }
  get width() {
    return this.#canvas.width;
  }
  set width(value) {
    this.#canvas.width = value;
  }
  get height() {
    return this.#canvas.height;
  }
  set height(value) {
    this.#canvas.height = value;
  }
  getContext(type = "2d") {
    const ctx = this.#canvas.getContext(type);
    if (ctx && ctx.canvas === this.#canvas) {
      Object.defineProperty(ctx, "canvas", {
        configurable: true,
        value: this,
        writable: false
      });
    }
    return ctx;
  }
  async convertToBlob(options) {
    const mime = normalizeMime(options?.type);
    const format = mimeToFormat(mime);
    const buffer = await this.#canvas.toBuffer(format);
    return new Blob([buffer], { type: mime });
  }
  toBlob(callback, type) {
    this.convertToBlob({ type }).then((blob) => callback(blob)).catch(() => callback(null));
  }
}
async function createImageBitmapFromBlob(blob) {
  const arrayBuffer = await blob.arrayBuffer();
  const buffer = Buffer.from(arrayBuffer);
  return new SkiaImage(buffer);
}
function ensureGlobals() {
  const globalBindings = globalThis;
  const defineGlobal = (key, value) => {
    if (typeof globalBindings[key] === "undefined") {
      globalBindings[key] = value;
    }
  };
  defineGlobal("OffscreenCanvas", SkiaOffscreenCanvas);
  defineGlobal("HTMLCanvasElement", SkiaOffscreenCanvas);
  defineGlobal("Path2D", SkiaPath2D);
  defineGlobal("ImageData", SkiaImageData);
  defineGlobal("Image", SkiaImage);
  defineGlobal("DOMMatrix", SkiaDOMMatrix);
  defineGlobal("DOMPoint", SkiaDOMPoint);
  defineGlobal("DOMRect", SkiaDOMRect);
  const windowValue = globalBindings.window;
  const windowRecord = typeof windowValue === "object" && windowValue !== null ? windowValue : globalBindings.window = {};
  const windowBindings = windowRecord;
  if (typeof windowBindings["devicePixelRatio"] !== "number") {
    windowBindings["devicePixelRatio"] = 1;
  }
  if (typeof globalBindings.devicePixelRatio !== "number") {
    globalBindings.devicePixelRatio = windowBindings["devicePixelRatio"];
  }
  if (typeof globalBindings.createImageBitmap !== "function") {
    globalBindings.createImageBitmap = async (source, options) => {
      const image = source instanceof SkiaImage ? source : await createImageBitmapFromBlob(source);
      const resizeWidth = options?.resizeWidth ?? image.width;
      const resizeHeight = options?.resizeHeight ?? image.height;
      if (resizeWidth === image.width && resizeHeight === image.height) {
        return image;
      }
      const resizeCanvas = new Canvas(resizeWidth, resizeHeight);
      const ctx = resizeCanvas.getContext("2d");
      ctx.drawImage(image, 0, 0, resizeWidth, resizeHeight);
      const resizedBuffer = await resizeCanvas.toBuffer("png");
      return new SkiaImage(resizedBuffer);
    };
  }
  defineGlobal("ImageBitmap", SkiaImage);
}
ensureGlobals();

// oai_js_artifact_tool/setup/walnut.ts
import fs from "node:fs/promises";
import path from "node:path";
import { createRequire as createRequire2 } from "node:module";
import walnutRuntime, { dotnet as dotnetNamed } from "@oai/walnut/wasm/dotnet.js";

// oai_js_artifact_tool/runtime/walnut.ts
var walnutLoader = null;
var walnutPromise = null;
function setWalnutLoader(loader) {
  walnutLoader = loader;
  walnutPromise = null;
}
async function loadWalnut() {
  if (!walnutLoader) {
    throw new Error("Walnut loader is not configured.");
  }
  if (!walnutPromise) {
    walnutPromise = walnutLoader();
  }
  return walnutPromise;
}

// oai_js_artifact_tool/setup/walnut.ts
setWalnutLoader(async () => {
  const dotnet = dotnetNamed || walnutRuntime.dotnet;
  if (!dotnet) {
    throw new Error("Walnut runtime did not export a dotnet factory.");
  }
  const require2 = createRequire2(import.meta.url);
  const wasmEntry = require2.resolve("@oai/walnut/wasm/dotnet.js");
  const wasmDir = path.dirname(wasmEntry);
  const bootJsonPath = path.join(wasmDir, "blazor.boot.json");
  const bootJsonRaw = await fs.readFile(bootJsonPath, "utf8");
  const config = JSON.parse(bootJsonRaw);
  const runtime = await dotnet.withConfig(config).withResourceLoader((_, __, defaultUri) => {
    if (defaultUri.startsWith("file:") || defaultUri.startsWith("http:") || defaultUri.startsWith("https:") || path.isAbsolute(defaultUri)) {
      return defaultUri;
    }
    return path.join(wasmDir, defaultUri);
  }).create();
  const mainAssembly = runtime.getConfig().mainAssemblyName;
  if (!mainAssembly) {
    throw new Error("Walnut runtime did not provide a main assembly name");
  }
  return runtime.getAssemblyExports(mainAssembly);
});

// node_modules/@bufbuild/protobuf/dist/esm/wire/varint.js
function varint64read() {
  let lowBits = 0;
  let highBits = 0;
  for (let shift = 0;shift < 28; shift += 7) {
    let b = this.buf[this.pos++];
    lowBits |= (b & 127) << shift;
    if ((b & 128) == 0) {
      this.assertBounds();
      return [lowBits, highBits];
    }
  }
  let middleByte = this.buf[this.pos++];
  lowBits |= (middleByte & 15) << 28;
  highBits = (middleByte & 112) >> 4;
  if ((middleByte & 128) == 0) {
    this.assertBounds();
    return [lowBits, highBits];
  }
  for (let shift = 3;shift <= 31; shift += 7) {
    let b = this.buf[this.pos++];
    highBits |= (b & 127) << shift;
    if ((b & 128) == 0) {
      this.assertBounds();
      return [lowBits, highBits];
    }
  }
  throw new Error("invalid varint");
}
function varint64write(lo, hi, bytes) {
  for (let i = 0;i < 28; i = i + 7) {
    const shift = lo >>> i;
    const hasNext = !(shift >>> 7 == 0 && hi == 0);
    const byte = (hasNext ? shift | 128 : shift) & 255;
    bytes.push(byte);
    if (!hasNext) {
      return;
    }
  }
  const splitBits = lo >>> 28 & 15 | (hi & 7) << 4;
  const hasMoreBits = !(hi >> 3 == 0);
  bytes.push((hasMoreBits ? splitBits | 128 : splitBits) & 255);
  if (!hasMoreBits) {
    return;
  }
  for (let i = 3;i < 31; i = i + 7) {
    const shift = hi >>> i;
    const hasNext = !(shift >>> 7 == 0);
    const byte = (hasNext ? shift | 128 : shift) & 255;
    bytes.push(byte);
    if (!hasNext) {
      return;
    }
  }
  bytes.push(hi >>> 31 & 1);
}
var TWO_PWR_32_DBL = 4294967296;
function int64FromString(dec) {
  const minus = dec[0] === "-";
  if (minus) {
    dec = dec.slice(1);
  }
  const base = 1e6;
  let lowBits = 0;
  let highBits = 0;
  function add1e6digit(begin, end) {
    const digit1e6 = Number(dec.slice(begin, end));
    highBits *= base;
    lowBits = lowBits * base + digit1e6;
    if (lowBits >= TWO_PWR_32_DBL) {
      highBits = highBits + (lowBits / TWO_PWR_32_DBL | 0);
      lowBits = lowBits % TWO_PWR_32_DBL;
    }
  }
  add1e6digit(-24, -18);
  add1e6digit(-18, -12);
  add1e6digit(-12, -6);
  add1e6digit(-6);
  return minus ? negate(lowBits, highBits) : newBits(lowBits, highBits);
}
function int64ToString(lo, hi) {
  let bits = newBits(lo, hi);
  const negative = bits.hi & 2147483648;
  if (negative) {
    bits = negate(bits.lo, bits.hi);
  }
  const result = uInt64ToString(bits.lo, bits.hi);
  return negative ? "-" + result : result;
}
function uInt64ToString(lo, hi) {
  ({ lo, hi } = toUnsigned(lo, hi));
  if (hi <= 2097151) {
    return String(TWO_PWR_32_DBL * hi + lo);
  }
  const low = lo & 16777215;
  const mid = (lo >>> 24 | hi << 8) & 16777215;
  const high = hi >> 16 & 65535;
  let digitA = low + mid * 6777216 + high * 6710656;
  let digitB = mid + high * 8147497;
  let digitC = high * 2;
  const base = 1e7;
  if (digitA >= base) {
    digitB += Math.floor(digitA / base);
    digitA %= base;
  }
  if (digitB >= base) {
    digitC += Math.floor(digitB / base);
    digitB %= base;
  }
  return digitC.toString() + decimalFrom1e7WithLeadingZeros(digitB) + decimalFrom1e7WithLeadingZeros(digitA);
}
function toUnsigned(lo, hi) {
  return { lo: lo >>> 0, hi: hi >>> 0 };
}
function newBits(lo, hi) {
  return { lo: lo | 0, hi: hi | 0 };
}
function negate(lowBits, highBits) {
  highBits = ~highBits;
  if (lowBits) {
    lowBits = ~lowBits + 1;
  } else {
    highBits += 1;
  }
  return newBits(lowBits, highBits);
}
var decimalFrom1e7WithLeadingZeros = (digit1e7) => {
  const partial = String(digit1e7);
  return "0000000".slice(partial.length) + partial;
};
function varint32write(value, bytes) {
  if (value >= 0) {
    while (value > 127) {
      bytes.push(value & 127 | 128);
      value = value >>> 7;
    }
    bytes.push(value);
  } else {
    for (let i = 0;i < 9; i++) {
      bytes.push(value & 127 | 128);
      value = value >> 7;
    }
    bytes.push(1);
  }
}
function varint32read() {
  let b = this.buf[this.pos++];
  let result = b & 127;
  if ((b & 128) == 0) {
    this.assertBounds();
    return result;
  }
  b = this.buf[this.pos++];
  result |= (b & 127) << 7;
  if ((b & 128) == 0) {
    this.assertBounds();
    return result;
  }
  b = this.buf[this.pos++];
  result |= (b & 127) << 14;
  if ((b & 128) == 0) {
    this.assertBounds();
    return result;
  }
  b = this.buf[this.pos++];
  result |= (b & 127) << 21;
  if ((b & 128) == 0) {
    this.assertBounds();
    return result;
  }
  b = this.buf[this.pos++];
  result |= (b & 15) << 28;
  for (let readBytes = 5;(b & 128) !== 0 && readBytes < 10; readBytes++)
    b = this.buf[this.pos++];
  if ((b & 128) != 0)
    throw new Error("invalid varint");
  this.assertBounds();
  return result >>> 0;
}

// node_modules/@bufbuild/protobuf/dist/esm/proto-int64.js
var protoInt64 = /* @__PURE__ */ makeInt64Support();
function makeInt64Support() {
  const dv = new DataView(new ArrayBuffer(8));
  const ok = typeof BigInt === "function" && typeof dv.getBigInt64 === "function" && typeof dv.getBigUint64 === "function" && typeof dv.setBigInt64 === "function" && typeof dv.setBigUint64 === "function" && (typeof process != "object" || typeof process.env != "object" || process.env.BUF_BIGINT_DISABLE !== "1");
  if (ok) {
    const MIN = BigInt("-9223372036854775808");
    const MAX = BigInt("9223372036854775807");
    const UMIN = BigInt("0");
    const UMAX = BigInt("18446744073709551615");
    return {
      zero: BigInt(0),
      supported: true,
      parse(value) {
        const bi = typeof value == "bigint" ? value : BigInt(value);
        if (bi > MAX || bi < MIN) {
          throw new Error(`invalid int64: ${value}`);
        }
        return bi;
      },
      uParse(value) {
        const bi = typeof value == "bigint" ? value : BigInt(value);
        if (bi > UMAX || bi < UMIN) {
          throw new Error(`invalid uint64: ${value}`);
        }
        return bi;
      },
      enc(value) {
        dv.setBigInt64(0, this.parse(value), true);
        return {
          lo: dv.getInt32(0, true),
          hi: dv.getInt32(4, true)
        };
      },
      uEnc(value) {
        dv.setBigInt64(0, this.uParse(value), true);
        return {
          lo: dv.getInt32(0, true),
          hi: dv.getInt32(4, true)
        };
      },
      dec(lo, hi) {
        dv.setInt32(0, lo, true);
        dv.setInt32(4, hi, true);
        return dv.getBigInt64(0, true);
      },
      uDec(lo, hi) {
        dv.setInt32(0, lo, true);
        dv.setInt32(4, hi, true);
        return dv.getBigUint64(0, true);
      }
    };
  }
  return {
    zero: "0",
    supported: false,
    parse(value) {
      if (typeof value != "string") {
        value = value.toString();
      }
      assertInt64String(value);
      return value;
    },
    uParse(value) {
      if (typeof value != "string") {
        value = value.toString();
      }
      assertUInt64String(value);
      return value;
    },
    enc(value) {
      if (typeof value != "string") {
        value = value.toString();
      }
      assertInt64String(value);
      return int64FromString(value);
    },
    uEnc(value) {
      if (typeof value != "string") {
        value = value.toString();
      }
      assertUInt64String(value);
      return int64FromString(value);
    },
    dec(lo, hi) {
      return int64ToString(lo, hi);
    },
    uDec(lo, hi) {
      return uInt64ToString(lo, hi);
    }
  };
}
function assertInt64String(value) {
  if (!/^-?[0-9]+$/.test(value)) {
    throw new Error("invalid int64: " + value);
  }
}
function assertUInt64String(value) {
  if (!/^[0-9]+$/.test(value)) {
    throw new Error("invalid uint64: " + value);
  }
}

// node_modules/@bufbuild/protobuf/dist/esm/wire/text-encoding.js
var symbol = Symbol.for("@bufbuild/protobuf/text-encoding");
function getTextEncoding() {
  if (globalThis[symbol] == undefined) {
    const te = new globalThis.TextEncoder;
    const td = new globalThis.TextDecoder;
    globalThis[symbol] = {
      encodeUtf8(text) {
        return te.encode(text);
      },
      decodeUtf8(bytes) {
        return td.decode(bytes);
      },
      checkUtf8(text) {
        try {
          encodeURIComponent(text);
          return true;
        } catch (_) {
          return false;
        }
      }
    };
  }
  return globalThis[symbol];
}

// node_modules/@bufbuild/protobuf/dist/esm/wire/binary-encoding.js
var WireType;
(function(WireType2) {
  WireType2[WireType2["Varint"] = 0] = "Varint";
  WireType2[WireType2["Bit64"] = 1] = "Bit64";
  WireType2[WireType2["LengthDelimited"] = 2] = "LengthDelimited";
  WireType2[WireType2["StartGroup"] = 3] = "StartGroup";
  WireType2[WireType2["EndGroup"] = 4] = "EndGroup";
  WireType2[WireType2["Bit32"] = 5] = "Bit32";
})(WireType || (WireType = {}));
var FLOAT32_MAX = 340282346638528860000000000000000000000;
var FLOAT32_MIN = -340282346638528860000000000000000000000;
var UINT32_MAX = 4294967295;
var INT32_MAX = 2147483647;
var INT32_MIN = -2147483648;

class BinaryWriter {
  constructor(encodeUtf8 = getTextEncoding().encodeUtf8) {
    this.encodeUtf8 = encodeUtf8;
    this.stack = [];
    this.chunks = [];
    this.buf = [];
  }
  finish() {
    if (this.buf.length) {
      this.chunks.push(new Uint8Array(this.buf));
      this.buf = [];
    }
    let len = 0;
    for (let i = 0;i < this.chunks.length; i++)
      len += this.chunks[i].length;
    let bytes = new Uint8Array(len);
    let offset = 0;
    for (let i = 0;i < this.chunks.length; i++) {
      bytes.set(this.chunks[i], offset);
      offset += this.chunks[i].length;
    }
    this.chunks = [];
    return bytes;
  }
  fork() {
    this.stack.push({ chunks: this.chunks, buf: this.buf });
    this.chunks = [];
    this.buf = [];
    return this;
  }
  join() {
    let chunk = this.finish();
    let prev = this.stack.pop();
    if (!prev)
      throw new Error("invalid state, fork stack empty");
    this.chunks = prev.chunks;
    this.buf = prev.buf;
    this.uint32(chunk.byteLength);
    return this.raw(chunk);
  }
  tag(fieldNo, type) {
    return this.uint32((fieldNo << 3 | type) >>> 0);
  }
  raw(chunk) {
    if (this.buf.length) {
      this.chunks.push(new Uint8Array(this.buf));
      this.buf = [];
    }
    this.chunks.push(chunk);
    return this;
  }
  uint32(value) {
    assertUInt32(value);
    while (value > 127) {
      this.buf.push(value & 127 | 128);
      value = value >>> 7;
    }
    this.buf.push(value);
    return this;
  }
  int32(value) {
    assertInt32(value);
    varint32write(value, this.buf);
    return this;
  }
  bool(value) {
    this.buf.push(value ? 1 : 0);
    return this;
  }
  bytes(value) {
    this.uint32(value.byteLength);
    return this.raw(value);
  }
  string(value) {
    let chunk = this.encodeUtf8(value);
    this.uint32(chunk.byteLength);
    return this.raw(chunk);
  }
  float(value) {
    assertFloat32(value);
    let chunk = new Uint8Array(4);
    new DataView(chunk.buffer).setFloat32(0, value, true);
    return this.raw(chunk);
  }
  double(value) {
    let chunk = new Uint8Array(8);
    new DataView(chunk.buffer).setFloat64(0, value, true);
    return this.raw(chunk);
  }
  fixed32(value) {
    assertUInt32(value);
    let chunk = new Uint8Array(4);
    new DataView(chunk.buffer).setUint32(0, value, true);
    return this.raw(chunk);
  }
  sfixed32(value) {
    assertInt32(value);
    let chunk = new Uint8Array(4);
    new DataView(chunk.buffer).setInt32(0, value, true);
    return this.raw(chunk);
  }
  sint32(value) {
    assertInt32(value);
    value = (value << 1 ^ value >> 31) >>> 0;
    varint32write(value, this.buf);
    return this;
  }
  sfixed64(value) {
    let chunk = new Uint8Array(8), view = new DataView(chunk.buffer), tc = protoInt64.enc(value);
    view.setInt32(0, tc.lo, true);
    view.setInt32(4, tc.hi, true);
    return this.raw(chunk);
  }
  fixed64(value) {
    let chunk = new Uint8Array(8), view = new DataView(chunk.buffer), tc = protoInt64.uEnc(value);
    view.setInt32(0, tc.lo, true);
    view.setInt32(4, tc.hi, true);
    return this.raw(chunk);
  }
  int64(value) {
    let tc = protoInt64.enc(value);
    varint64write(tc.lo, tc.hi, this.buf);
    return this;
  }
  sint64(value) {
    const tc = protoInt64.enc(value), sign = tc.hi >> 31, lo = tc.lo << 1 ^ sign, hi = (tc.hi << 1 | tc.lo >>> 31) ^ sign;
    varint64write(lo, hi, this.buf);
    return this;
  }
  uint64(value) {
    const tc = protoInt64.uEnc(value);
    varint64write(tc.lo, tc.hi, this.buf);
    return this;
  }
}

class BinaryReader {
  constructor(buf, decodeUtf8 = getTextEncoding().decodeUtf8) {
    this.decodeUtf8 = decodeUtf8;
    this.varint64 = varint64read;
    this.uint32 = varint32read;
    this.buf = buf;
    this.len = buf.length;
    this.pos = 0;
    this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
  }
  tag() {
    let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7;
    if (fieldNo <= 0 || wireType < 0 || wireType > 5)
      throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType);
    return [fieldNo, wireType];
  }
  skip(wireType, fieldNo) {
    let start = this.pos;
    switch (wireType) {
      case WireType.Varint:
        while (this.buf[this.pos++] & 128) {}
        break;
      case WireType.Bit64:
        this.pos += 4;
      case WireType.Bit32:
        this.pos += 4;
        break;
      case WireType.LengthDelimited:
        let len = this.uint32();
        this.pos += len;
        break;
      case WireType.StartGroup:
        for (;; ) {
          const [fn, wt] = this.tag();
          if (wt === WireType.EndGroup) {
            if (fieldNo !== undefined && fn !== fieldNo) {
              throw new Error("invalid end group tag");
            }
            break;
          }
          this.skip(wt, fn);
        }
        break;
      default:
        throw new Error("cant skip wire type " + wireType);
    }
    this.assertBounds();
    return this.buf.subarray(start, this.pos);
  }
  assertBounds() {
    if (this.pos > this.len)
      throw new RangeError("premature EOF");
  }
  int32() {
    return this.uint32() | 0;
  }
  sint32() {
    let zze = this.uint32();
    return zze >>> 1 ^ -(zze & 1);
  }
  int64() {
    return protoInt64.dec(...this.varint64());
  }
  uint64() {
    return protoInt64.uDec(...this.varint64());
  }
  sint64() {
    let [lo, hi] = this.varint64();
    let s = -(lo & 1);
    lo = (lo >>> 1 | (hi & 1) << 31) ^ s;
    hi = hi >>> 1 ^ s;
    return protoInt64.dec(lo, hi);
  }
  bool() {
    let [lo, hi] = this.varint64();
    return lo !== 0 || hi !== 0;
  }
  fixed32() {
    return this.view.getUint32((this.pos += 4) - 4, true);
  }
  sfixed32() {
    return this.view.getInt32((this.pos += 4) - 4, true);
  }
  fixed64() {
    return protoInt64.uDec(this.sfixed32(), this.sfixed32());
  }
  sfixed64() {
    return protoInt64.dec(this.sfixed32(), this.sfixed32());
  }
  float() {
    return this.view.getFloat32((this.pos += 4) - 4, true);
  }
  double() {
    return this.view.getFloat64((this.pos += 8) - 8, true);
  }
  bytes() {
    let len = this.uint32(), start = this.pos;
    this.pos += len;
    this.assertBounds();
    return this.buf.subarray(start, start + len);
  }
  string() {
    return this.decodeUtf8(this.bytes());
  }
}
function assertInt32(arg) {
  if (typeof arg == "string") {
    arg = Number(arg);
  } else if (typeof arg != "number") {
    throw new Error("invalid int32: " + typeof arg);
  }
  if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN)
    throw new Error("invalid int32: " + arg);
}
function assertUInt32(arg) {
  if (typeof arg == "string") {
    arg = Number(arg);
  } else if (typeof arg != "number") {
    throw new Error("invalid uint32: " + typeof arg);
  }
  if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0)
    throw new Error("invalid uint32: " + arg);
}
function assertFloat32(arg) {
  if (typeof arg == "string") {
    const o = arg;
    arg = Number(arg);
    if (Number.isNaN(arg) && o !== "NaN") {
      throw new Error("invalid float32: " + o);
    }
  } else if (typeof arg != "number") {
    throw new Error("invalid float32: " + typeof arg);
  }
  if (Number.isFinite(arg) && (arg > FLOAT32_MAX || arg < FLOAT32_MIN))
    throw new Error("invalid float32: " + arg);
}

// node_modules/@oai/walnut/generated/oaiproto/coworker/pptx/utils.ts
function createBaseBoundingBox() {
  return {
    xEmu: undefined,
    yEmu: undefined,
    widthEmu: undefined,
    heightEmu: undefined,
    rotation: undefined,
    horizontalFlip: undefined,
    verticalFlip: undefined
  };
}
var BoundingBox = {
  encode(message, writer = new BinaryWriter) {
    if (message.xEmu !== undefined) {
      writer.uint32(8).int64(message.xEmu);
    }
    if (message.yEmu !== undefined) {
      writer.uint32(16).int64(message.yEmu);
    }
    if (message.widthEmu !== undefined) {
      writer.uint32(24).int64(message.widthEmu);
    }
    if (message.heightEmu !== undefined) {
      writer.uint32(32).int64(message.heightEmu);
    }
    if (message.rotation !== undefined) {
      writer.uint32(40).int32(message.rotation);
    }
    if (message.horizontalFlip !== undefined) {
      writer.uint32(48).bool(message.horizontalFlip);
    }
    if (message.verticalFlip !== undefined) {
      writer.uint32(56).bool(message.verticalFlip);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseBoundingBox();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.xEmu = longToNumber(reader.int64());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.yEmu = longToNumber(reader.int64());
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.widthEmu = longToNumber(reader.int64());
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.heightEmu = longToNumber(reader.int64());
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.rotation = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.horizontalFlip = reader.bool();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.verticalFlip = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return BoundingBox.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseBoundingBox();
    message.xEmu = object.xEmu ?? undefined;
    message.yEmu = object.yEmu ?? undefined;
    message.widthEmu = object.widthEmu ?? undefined;
    message.heightEmu = object.heightEmu ?? undefined;
    message.rotation = object.rotation ?? undefined;
    message.horizontalFlip = object.horizontalFlip ?? undefined;
    message.verticalFlip = object.verticalFlip ?? undefined;
    return message;
  }
};
function createBaseColorTransform() {
  return {
    tint: undefined,
    shade: undefined,
    lumMod: undefined,
    lumOff: undefined,
    satMod: undefined,
    alpha: undefined
  };
}
var ColorTransform = {
  encode(message, writer = new BinaryWriter) {
    if (message.tint !== undefined) {
      writer.uint32(8).int32(message.tint);
    }
    if (message.shade !== undefined) {
      writer.uint32(16).int32(message.shade);
    }
    if (message.lumMod !== undefined) {
      writer.uint32(24).int32(message.lumMod);
    }
    if (message.lumOff !== undefined) {
      writer.uint32(32).int32(message.lumOff);
    }
    if (message.satMod !== undefined) {
      writer.uint32(40).int32(message.satMod);
    }
    if (message.alpha !== undefined) {
      writer.uint32(48).int32(message.alpha);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseColorTransform();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.tint = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.shade = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.lumMod = reader.int32();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.lumOff = reader.int32();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.satMod = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.alpha = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ColorTransform.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseColorTransform();
    message.tint = object.tint ?? undefined;
    message.shade = object.shade ?? undefined;
    message.lumMod = object.lumMod ?? undefined;
    message.lumOff = object.lumOff ?? undefined;
    message.satMod = object.satMod ?? undefined;
    message.alpha = object.alpha ?? undefined;
    return message;
  }
};
function createBaseColor() {
  return { type: 0, value: "", transform: undefined, lastColor: undefined };
}
var Color = {
  encode(message, writer = new BinaryWriter) {
    if (message.type !== 0) {
      writer.uint32(8).int32(message.type);
    }
    if (message.value !== "") {
      writer.uint32(18).string(message.value);
    }
    if (message.transform !== undefined) {
      ColorTransform.encode(message.transform, writer.uint32(26).fork()).join();
    }
    if (message.lastColor !== undefined) {
      writer.uint32(34).string(message.lastColor);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseColor();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.type = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.value = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.transform = ColorTransform.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.lastColor = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Color.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseColor();
    message.type = object.type ?? 0;
    message.value = object.value ?? "";
    message.transform = object.transform !== undefined && object.transform !== null ? ColorTransform.fromPartial(object.transform) : undefined;
    message.lastColor = object.lastColor ?? undefined;
    return message;
  }
};
function createBaseBackground() {
  return { ref: undefined, fill: undefined };
}
var Background = {
  encode(message, writer = new BinaryWriter) {
    if (message.ref !== undefined) {
      BackgroundRef.encode(message.ref, writer.uint32(18).fork()).join();
    }
    if (message.fill !== undefined) {
      Fill.encode(message.fill, writer.uint32(26).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseBackground();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.ref = BackgroundRef.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.fill = Fill.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Background.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseBackground();
    message.ref = object.ref !== undefined && object.ref !== null ? BackgroundRef.fromPartial(object.ref) : undefined;
    message.fill = object.fill !== undefined && object.fill !== null ? Fill.fromPartial(object.fill) : undefined;
    return message;
  }
};
function createBaseBackgroundRef() {
  return { index: 0, schemeColor: "" };
}
var BackgroundRef = {
  encode(message, writer = new BinaryWriter) {
    if (message.index !== 0) {
      writer.uint32(8).int32(message.index);
    }
    if (message.schemeColor !== "") {
      writer.uint32(18).string(message.schemeColor);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseBackgroundRef();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.index = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.schemeColor = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return BackgroundRef.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseBackgroundRef();
    message.index = object.index ?? 0;
    message.schemeColor = object.schemeColor ?? "";
    return message;
  }
};
function createBaseFill() {
  return {
    id: undefined,
    type: 0,
    color: undefined,
    gradientStops: [],
    relId: undefined,
    gradientKind: undefined,
    angleDeg: undefined,
    isScaled: undefined,
    pathType: undefined,
    fillRect: undefined,
    imageReference: undefined,
    alphaModFix: undefined,
    lum: undefined,
    srcRect: undefined,
    stretchFillRect: undefined,
    tile: undefined,
    duotone: undefined,
    pattern: undefined
  };
}
var Fill = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== undefined) {
      writer.uint32(82).string(message.id);
    }
    if (message.type !== 0) {
      writer.uint32(8).int32(message.type);
    }
    if (message.color !== undefined) {
      Color.encode(message.color, writer.uint32(18).fork()).join();
    }
    for (const v of message.gradientStops) {
      GradientStop.encode(v, writer.uint32(26).fork()).join();
    }
    if (message.relId !== undefined) {
      writer.uint32(34).string(message.relId);
    }
    if (message.gradientKind !== undefined) {
      writer.uint32(40).int32(message.gradientKind);
    }
    if (message.angleDeg !== undefined) {
      writer.uint32(49).double(message.angleDeg);
    }
    if (message.isScaled !== undefined) {
      writer.uint32(56).bool(message.isScaled);
    }
    if (message.pathType !== undefined) {
      writer.uint32(64).int32(message.pathType);
    }
    if (message.fillRect !== undefined) {
      FillToRect.encode(message.fillRect, writer.uint32(74).fork()).join();
    }
    if (message.imageReference !== undefined) {
      ImageReference.encode(message.imageReference, writer.uint32(90).fork()).join();
    }
    if (message.alphaModFix !== undefined) {
      writer.uint32(96).int32(message.alphaModFix);
    }
    if (message.lum !== undefined) {
      writer.uint32(104).bool(message.lum);
    }
    if (message.srcRect !== undefined) {
      FillToRect.encode(message.srcRect, writer.uint32(114).fork()).join();
    }
    if (message.stretchFillRect !== undefined) {
      FillToRect.encode(message.stretchFillRect, writer.uint32(122).fork()).join();
    }
    if (message.tile !== undefined) {
      PictureTile.encode(message.tile, writer.uint32(146).fork()).join();
    }
    if (message.duotone !== undefined) {
      Duotone.encode(message.duotone, writer.uint32(130).fork()).join();
    }
    if (message.pattern !== undefined) {
      PatternFill.encode(message.pattern, writer.uint32(138).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseFill();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.type = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.color = Color.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.gradientStops.push(GradientStop.decode(reader, reader.uint32()));
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.relId = reader.string();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.gradientKind = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 49) {
            break;
          }
          message.angleDeg = reader.double();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.isScaled = reader.bool();
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.pathType = reader.int32();
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.fillRect = FillToRect.decode(reader, reader.uint32());
          continue;
        }
        case 11: {
          if (tag !== 90) {
            break;
          }
          message.imageReference = ImageReference.decode(reader, reader.uint32());
          continue;
        }
        case 12: {
          if (tag !== 96) {
            break;
          }
          message.alphaModFix = reader.int32();
          continue;
        }
        case 13: {
          if (tag !== 104) {
            break;
          }
          message.lum = reader.bool();
          continue;
        }
        case 14: {
          if (tag !== 114) {
            break;
          }
          message.srcRect = FillToRect.decode(reader, reader.uint32());
          continue;
        }
        case 15: {
          if (tag !== 122) {
            break;
          }
          message.stretchFillRect = FillToRect.decode(reader, reader.uint32());
          continue;
        }
        case 18: {
          if (tag !== 146) {
            break;
          }
          message.tile = PictureTile.decode(reader, reader.uint32());
          continue;
        }
        case 16: {
          if (tag !== 130) {
            break;
          }
          message.duotone = Duotone.decode(reader, reader.uint32());
          continue;
        }
        case 17: {
          if (tag !== 138) {
            break;
          }
          message.pattern = PatternFill.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Fill.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseFill();
    message.id = object.id ?? undefined;
    message.type = object.type ?? 0;
    message.color = object.color !== undefined && object.color !== null ? Color.fromPartial(object.color) : undefined;
    message.gradientStops = object.gradientStops?.map((e) => GradientStop.fromPartial(e)) || [];
    message.relId = object.relId ?? undefined;
    message.gradientKind = object.gradientKind ?? undefined;
    message.angleDeg = object.angleDeg ?? undefined;
    message.isScaled = object.isScaled ?? undefined;
    message.pathType = object.pathType ?? undefined;
    message.fillRect = object.fillRect !== undefined && object.fillRect !== null ? FillToRect.fromPartial(object.fillRect) : undefined;
    message.imageReference = object.imageReference !== undefined && object.imageReference !== null ? ImageReference.fromPartial(object.imageReference) : undefined;
    message.alphaModFix = object.alphaModFix ?? undefined;
    message.lum = object.lum ?? undefined;
    message.srcRect = object.srcRect !== undefined && object.srcRect !== null ? FillToRect.fromPartial(object.srcRect) : undefined;
    message.stretchFillRect = object.stretchFillRect !== undefined && object.stretchFillRect !== null ? FillToRect.fromPartial(object.stretchFillRect) : undefined;
    message.tile = object.tile !== undefined && object.tile !== null ? PictureTile.fromPartial(object.tile) : undefined;
    message.duotone = object.duotone !== undefined && object.duotone !== null ? Duotone.fromPartial(object.duotone) : undefined;
    message.pattern = object.pattern !== undefined && object.pattern !== null ? PatternFill.fromPartial(object.pattern) : undefined;
    return message;
  }
};
function createBasePictureTile() {
  return {
    offsetX: undefined,
    offsetY: undefined,
    scaleX: undefined,
    scaleY: undefined,
    flip: undefined,
    alignment: undefined
  };
}
var PictureTile = {
  encode(message, writer = new BinaryWriter) {
    if (message.offsetX !== undefined) {
      writer.uint32(8).int64(message.offsetX);
    }
    if (message.offsetY !== undefined) {
      writer.uint32(16).int64(message.offsetY);
    }
    if (message.scaleX !== undefined) {
      writer.uint32(24).int32(message.scaleX);
    }
    if (message.scaleY !== undefined) {
      writer.uint32(32).int32(message.scaleY);
    }
    if (message.flip !== undefined) {
      writer.uint32(42).string(message.flip);
    }
    if (message.alignment !== undefined) {
      writer.uint32(50).string(message.alignment);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePictureTile();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.offsetX = longToNumber(reader.int64());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.offsetY = longToNumber(reader.int64());
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.scaleX = reader.int32();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.scaleY = reader.int32();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.flip = reader.string();
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.alignment = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PictureTile.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePictureTile();
    message.offsetX = object.offsetX ?? undefined;
    message.offsetY = object.offsetY ?? undefined;
    message.scaleX = object.scaleX ?? undefined;
    message.scaleY = object.scaleY ?? undefined;
    message.flip = object.flip ?? undefined;
    message.alignment = object.alignment ?? undefined;
    return message;
  }
};
function createBasePatternFill() {
  return { patternType: 0, color: undefined };
}
var PatternFill = {
  encode(message, writer = new BinaryWriter) {
    if (message.patternType !== 0) {
      writer.uint32(8).int32(message.patternType);
    }
    if (message.color !== undefined) {
      Color.encode(message.color, writer.uint32(26).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePatternFill();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.patternType = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.color = Color.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PatternFill.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePatternFill();
    message.patternType = object.patternType ?? 0;
    message.color = object.color !== undefined && object.color !== null ? Color.fromPartial(object.color) : undefined;
    return message;
  }
};
function createBaseImageReference() {
  return { id: "" };
}
var ImageReference = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== "") {
      writer.uint32(10).string(message.id);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseImageReference();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.id = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ImageReference.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseImageReference();
    message.id = object.id ?? "";
    return message;
  }
};
function createBaseDuotone() {
  return { darkColor: undefined, lightColor: undefined };
}
var Duotone = {
  encode(message, writer = new BinaryWriter) {
    if (message.darkColor !== undefined) {
      Color.encode(message.darkColor, writer.uint32(10).fork()).join();
    }
    if (message.lightColor !== undefined) {
      Color.encode(message.lightColor, writer.uint32(18).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseDuotone();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.darkColor = Color.decode(reader, reader.uint32());
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.lightColor = Color.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Duotone.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseDuotone();
    message.darkColor = object.darkColor !== undefined && object.darkColor !== null ? Color.fromPartial(object.darkColor) : undefined;
    message.lightColor = object.lightColor !== undefined && object.lightColor !== null ? Color.fromPartial(object.lightColor) : undefined;
    return message;
  }
};
function createBaseGradientStop() {
  return { position: undefined, color: undefined };
}
var GradientStop = {
  encode(message, writer = new BinaryWriter) {
    if (message.position !== undefined) {
      writer.uint32(8).int32(message.position);
    }
    if (message.color !== undefined) {
      Color.encode(message.color, writer.uint32(18).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseGradientStop();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.position = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.color = Color.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return GradientStop.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseGradientStop();
    message.position = object.position ?? undefined;
    message.color = object.color !== undefined && object.color !== null ? Color.fromPartial(object.color) : undefined;
    return message;
  }
};
function createBaseTextAutoFit() {
  return { noAutofit: undefined, normalAutoFit: undefined, shapeAutoFit: undefined };
}
var TextAutoFit = {
  encode(message, writer = new BinaryWriter) {
    if (message.noAutofit !== undefined) {
      TextAutoFit_NoAutoFit.encode(message.noAutofit, writer.uint32(10).fork()).join();
    }
    if (message.normalAutoFit !== undefined) {
      TextAutoFit_NormalAutoFit.encode(message.normalAutoFit, writer.uint32(18).fork()).join();
    }
    if (message.shapeAutoFit !== undefined) {
      TextAutoFit_ShapeAutoFit.encode(message.shapeAutoFit, writer.uint32(26).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTextAutoFit();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.noAutofit = TextAutoFit_NoAutoFit.decode(reader, reader.uint32());
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.normalAutoFit = TextAutoFit_NormalAutoFit.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.shapeAutoFit = TextAutoFit_ShapeAutoFit.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TextAutoFit.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTextAutoFit();
    message.noAutofit = object.noAutofit !== undefined && object.noAutofit !== null ? TextAutoFit_NoAutoFit.fromPartial(object.noAutofit) : undefined;
    message.normalAutoFit = object.normalAutoFit !== undefined && object.normalAutoFit !== null ? TextAutoFit_NormalAutoFit.fromPartial(object.normalAutoFit) : undefined;
    message.shapeAutoFit = object.shapeAutoFit !== undefined && object.shapeAutoFit !== null ? TextAutoFit_ShapeAutoFit.fromPartial(object.shapeAutoFit) : undefined;
    return message;
  }
};
function createBaseTextAutoFit_NoAutoFit() {
  return {};
}
var TextAutoFit_NoAutoFit = {
  encode(_, writer = new BinaryWriter) {
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTextAutoFit_NoAutoFit();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TextAutoFit_NoAutoFit.fromPartial(base ?? {});
  },
  fromPartial(_) {
    const message = createBaseTextAutoFit_NoAutoFit();
    return message;
  }
};
function createBaseTextAutoFit_ShapeAutoFit() {
  return {};
}
var TextAutoFit_ShapeAutoFit = {
  encode(_, writer = new BinaryWriter) {
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTextAutoFit_ShapeAutoFit();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TextAutoFit_ShapeAutoFit.fromPartial(base ?? {});
  },
  fromPartial(_) {
    const message = createBaseTextAutoFit_ShapeAutoFit();
    return message;
  }
};
function createBaseTextAutoFit_NormalAutoFit() {
  return { fontScale: undefined, lineSpaceReduction: undefined };
}
var TextAutoFit_NormalAutoFit = {
  encode(message, writer = new BinaryWriter) {
    if (message.fontScale !== undefined) {
      writer.uint32(8).int32(message.fontScale);
    }
    if (message.lineSpaceReduction !== undefined) {
      writer.uint32(16).int32(message.lineSpaceReduction);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTextAutoFit_NormalAutoFit();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.fontScale = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.lineSpaceReduction = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TextAutoFit_NormalAutoFit.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTextAutoFit_NormalAutoFit();
    message.fontScale = object.fontScale ?? undefined;
    message.lineSpaceReduction = object.lineSpaceReduction ?? undefined;
    return message;
  }
};
function createBaseTextStyle() {
  return {
    anchor: undefined,
    vertical: undefined,
    rotation: undefined,
    bold: undefined,
    italic: undefined,
    fontSize: undefined,
    fill: undefined,
    alignment: undefined,
    underline: undefined,
    bottomInset: undefined,
    leftInset: undefined,
    rightInset: undefined,
    topInset: undefined,
    useParagraphSpacing: undefined,
    name: undefined,
    family: undefined,
    scheme: undefined,
    typeface: undefined,
    characterSpacing: undefined,
    wrap: undefined,
    autoFit: undefined
  };
}
var TextStyle = {
  encode(message, writer = new BinaryWriter) {
    if (message.anchor !== undefined) {
      writer.uint32(8).int32(message.anchor);
    }
    if (message.vertical !== undefined) {
      writer.uint32(16).int32(message.vertical);
    }
    if (message.rotation !== undefined) {
      writer.uint32(24).int32(message.rotation);
    }
    if (message.bold !== undefined) {
      writer.uint32(32).bool(message.bold);
    }
    if (message.italic !== undefined) {
      writer.uint32(40).bool(message.italic);
    }
    if (message.fontSize !== undefined) {
      writer.uint32(48).int32(message.fontSize);
    }
    if (message.fill !== undefined) {
      Fill.encode(message.fill, writer.uint32(58).fork()).join();
    }
    if (message.alignment !== undefined) {
      writer.uint32(64).int32(message.alignment);
    }
    if (message.underline !== undefined) {
      writer.uint32(74).string(message.underline);
    }
    if (message.bottomInset !== undefined) {
      writer.uint32(80).int32(message.bottomInset);
    }
    if (message.leftInset !== undefined) {
      writer.uint32(88).int32(message.leftInset);
    }
    if (message.rightInset !== undefined) {
      writer.uint32(96).int32(message.rightInset);
    }
    if (message.topInset !== undefined) {
      writer.uint32(104).int32(message.topInset);
    }
    if (message.useParagraphSpacing !== undefined) {
      writer.uint32(112).bool(message.useParagraphSpacing);
    }
    if (message.name !== undefined) {
      writer.uint32(122).string(message.name);
    }
    if (message.family !== undefined) {
      writer.uint32(128).int32(message.family);
    }
    if (message.scheme !== undefined) {
      writer.uint32(138).string(message.scheme);
    }
    if (message.typeface !== undefined) {
      writer.uint32(146).string(message.typeface);
    }
    if (message.characterSpacing !== undefined) {
      writer.uint32(152).int32(message.characterSpacing);
    }
    if (message.wrap !== undefined) {
      writer.uint32(160).int32(message.wrap);
    }
    if (message.autoFit !== undefined) {
      TextAutoFit.encode(message.autoFit, writer.uint32(170).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTextStyle();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.anchor = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.vertical = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.rotation = reader.int32();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.bold = reader.bool();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.italic = reader.bool();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.fontSize = reader.int32();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.fill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.alignment = reader.int32();
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.underline = reader.string();
          continue;
        }
        case 10: {
          if (tag !== 80) {
            break;
          }
          message.bottomInset = reader.int32();
          continue;
        }
        case 11: {
          if (tag !== 88) {
            break;
          }
          message.leftInset = reader.int32();
          continue;
        }
        case 12: {
          if (tag !== 96) {
            break;
          }
          message.rightInset = reader.int32();
          continue;
        }
        case 13: {
          if (tag !== 104) {
            break;
          }
          message.topInset = reader.int32();
          continue;
        }
        case 14: {
          if (tag !== 112) {
            break;
          }
          message.useParagraphSpacing = reader.bool();
          continue;
        }
        case 15: {
          if (tag !== 122) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 16: {
          if (tag !== 128) {
            break;
          }
          message.family = reader.int32();
          continue;
        }
        case 17: {
          if (tag !== 138) {
            break;
          }
          message.scheme = reader.string();
          continue;
        }
        case 18: {
          if (tag !== 146) {
            break;
          }
          message.typeface = reader.string();
          continue;
        }
        case 19: {
          if (tag !== 152) {
            break;
          }
          message.characterSpacing = reader.int32();
          continue;
        }
        case 20: {
          if (tag !== 160) {
            break;
          }
          message.wrap = reader.int32();
          continue;
        }
        case 21: {
          if (tag !== 170) {
            break;
          }
          message.autoFit = TextAutoFit.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TextStyle.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTextStyle();
    message.anchor = object.anchor ?? undefined;
    message.vertical = object.vertical ?? undefined;
    message.rotation = object.rotation ?? undefined;
    message.bold = object.bold ?? undefined;
    message.italic = object.italic ?? undefined;
    message.fontSize = object.fontSize ?? undefined;
    message.fill = object.fill !== undefined && object.fill !== null ? Fill.fromPartial(object.fill) : undefined;
    message.alignment = object.alignment ?? undefined;
    message.underline = object.underline ?? undefined;
    message.bottomInset = object.bottomInset ?? undefined;
    message.leftInset = object.leftInset ?? undefined;
    message.rightInset = object.rightInset ?? undefined;
    message.topInset = object.topInset ?? undefined;
    message.useParagraphSpacing = object.useParagraphSpacing ?? undefined;
    message.name = object.name ?? undefined;
    message.family = object.family ?? undefined;
    message.scheme = object.scheme ?? undefined;
    message.typeface = object.typeface ?? undefined;
    message.characterSpacing = object.characterSpacing ?? undefined;
    message.wrap = object.wrap ?? undefined;
    message.autoFit = object.autoFit !== undefined && object.autoFit !== null ? TextAutoFit.fromPartial(object.autoFit) : undefined;
    return message;
  }
};
function createBaseParagraphStyle() {
  return {
    bulletCharacter: undefined,
    marginLeft: undefined,
    indent: undefined,
    lineSpacingPercent: undefined,
    lineSpacingPoints: undefined,
    autoNumberType: undefined,
    autoNumberStartAt: undefined,
    outlineLevel: undefined
  };
}
var ParagraphStyle = {
  encode(message, writer = new BinaryWriter) {
    if (message.bulletCharacter !== undefined) {
      writer.uint32(10).string(message.bulletCharacter);
    }
    if (message.marginLeft !== undefined) {
      writer.uint32(16).int32(message.marginLeft);
    }
    if (message.indent !== undefined) {
      writer.uint32(24).int32(message.indent);
    }
    if (message.lineSpacingPercent !== undefined) {
      writer.uint32(32).int32(message.lineSpacingPercent);
    }
    if (message.lineSpacingPoints !== undefined) {
      writer.uint32(40).int32(message.lineSpacingPoints);
    }
    if (message.autoNumberType !== undefined) {
      writer.uint32(50).string(message.autoNumberType);
    }
    if (message.autoNumberStartAt !== undefined) {
      writer.uint32(56).int32(message.autoNumberStartAt);
    }
    if (message.outlineLevel !== undefined) {
      writer.uint32(64).int32(message.outlineLevel);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseParagraphStyle();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.bulletCharacter = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.marginLeft = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.indent = reader.int32();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.lineSpacingPercent = reader.int32();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.lineSpacingPoints = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.autoNumberType = reader.string();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.autoNumberStartAt = reader.int32();
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.outlineLevel = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ParagraphStyle.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseParagraphStyle();
    message.bulletCharacter = object.bulletCharacter ?? undefined;
    message.marginLeft = object.marginLeft ?? undefined;
    message.indent = object.indent ?? undefined;
    message.lineSpacingPercent = object.lineSpacingPercent ?? undefined;
    message.lineSpacingPoints = object.lineSpacingPoints ?? undefined;
    message.autoNumberType = object.autoNumberType ?? undefined;
    message.autoNumberStartAt = object.autoNumberStartAt ?? undefined;
    message.outlineLevel = object.outlineLevel ?? undefined;
    return message;
  }
};
function createBaseTextStyleDefinition() {
  return {
    id: "",
    name: "",
    description: undefined,
    textStyle: undefined,
    paragraphStyle: undefined,
    basedOn: undefined,
    tags: [],
    nextId: undefined,
    spaceBefore: undefined,
    spaceAfter: undefined
  };
}
var TextStyleDefinition = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== "") {
      writer.uint32(10).string(message.id);
    }
    if (message.name !== "") {
      writer.uint32(18).string(message.name);
    }
    if (message.description !== undefined) {
      writer.uint32(26).string(message.description);
    }
    if (message.textStyle !== undefined) {
      TextStyle.encode(message.textStyle, writer.uint32(34).fork()).join();
    }
    if (message.paragraphStyle !== undefined) {
      ParagraphStyle.encode(message.paragraphStyle, writer.uint32(42).fork()).join();
    }
    if (message.basedOn !== undefined) {
      writer.uint32(50).string(message.basedOn);
    }
    for (const v of message.tags) {
      writer.uint32(58).string(v);
    }
    if (message.nextId !== undefined) {
      writer.uint32(66).string(message.nextId);
    }
    if (message.spaceBefore !== undefined) {
      writer.uint32(72).int32(message.spaceBefore);
    }
    if (message.spaceAfter !== undefined) {
      writer.uint32(80).int32(message.spaceAfter);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTextStyleDefinition();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.description = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.textStyle = TextStyle.decode(reader, reader.uint32());
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.paragraphStyle = ParagraphStyle.decode(reader, reader.uint32());
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.basedOn = reader.string();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.tags.push(reader.string());
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.nextId = reader.string();
          continue;
        }
        case 9: {
          if (tag !== 72) {
            break;
          }
          message.spaceBefore = reader.int32();
          continue;
        }
        case 10: {
          if (tag !== 80) {
            break;
          }
          message.spaceAfter = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TextStyleDefinition.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTextStyleDefinition();
    message.id = object.id ?? "";
    message.name = object.name ?? "";
    message.description = object.description ?? undefined;
    message.textStyle = object.textStyle !== undefined && object.textStyle !== null ? TextStyle.fromPartial(object.textStyle) : undefined;
    message.paragraphStyle = object.paragraphStyle !== undefined && object.paragraphStyle !== null ? ParagraphStyle.fromPartial(object.paragraphStyle) : undefined;
    message.basedOn = object.basedOn ?? undefined;
    message.tags = object.tags?.map((e) => e) || [];
    message.nextId = object.nextId ?? undefined;
    message.spaceBefore = object.spaceBefore ?? undefined;
    message.spaceAfter = object.spaceAfter ?? undefined;
    return message;
  }
};
function createBaseLevelStyle() {
  return {
    id: undefined,
    level: 0,
    textStyle: undefined,
    paragraphStyle: undefined,
    spaceBefore: undefined,
    spaceAfter: undefined
  };
}
var LevelStyle = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== undefined) {
      writer.uint32(10).string(message.id);
    }
    if (message.level !== 0) {
      writer.uint32(16).int32(message.level);
    }
    if (message.textStyle !== undefined) {
      TextStyle.encode(message.textStyle, writer.uint32(26).fork()).join();
    }
    if (message.paragraphStyle !== undefined) {
      ParagraphStyle.encode(message.paragraphStyle, writer.uint32(34).fork()).join();
    }
    if (message.spaceBefore !== undefined) {
      writer.uint32(40).int32(message.spaceBefore);
    }
    if (message.spaceAfter !== undefined) {
      writer.uint32(48).int32(message.spaceAfter);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseLevelStyle();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.level = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.textStyle = TextStyle.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.paragraphStyle = ParagraphStyle.decode(reader, reader.uint32());
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.spaceBefore = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.spaceAfter = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return LevelStyle.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseLevelStyle();
    message.id = object.id ?? undefined;
    message.level = object.level ?? 0;
    message.textStyle = object.textStyle !== undefined && object.textStyle !== null ? TextStyle.fromPartial(object.textStyle) : undefined;
    message.paragraphStyle = object.paragraphStyle !== undefined && object.paragraphStyle !== null ? ParagraphStyle.fromPartial(object.paragraphStyle) : undefined;
    message.spaceBefore = object.spaceBefore ?? undefined;
    message.spaceAfter = object.spaceAfter ?? undefined;
    return message;
  }
};
function createBaseLine() {
  return {
    style: 0,
    widthEmu: undefined,
    fill: undefined,
    compound: undefined,
    sketch: undefined,
    cap: undefined,
    join: undefined
  };
}
var Line = {
  encode(message, writer = new BinaryWriter) {
    if (message.style !== 0) {
      writer.uint32(8).int32(message.style);
    }
    if (message.widthEmu !== undefined) {
      writer.uint32(16).int32(message.widthEmu);
    }
    if (message.fill !== undefined) {
      Fill.encode(message.fill, writer.uint32(26).fork()).join();
    }
    if (message.compound !== undefined) {
      writer.uint32(32).int32(message.compound);
    }
    if (message.sketch !== undefined) {
      Line_LineSketch.encode(message.sketch, writer.uint32(42).fork()).join();
    }
    if (message.cap !== undefined) {
      writer.uint32(48).int32(message.cap);
    }
    if (message.join !== undefined) {
      writer.uint32(56).int32(message.join);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseLine();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.style = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.widthEmu = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.fill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.compound = reader.int32();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.sketch = Line_LineSketch.decode(reader, reader.uint32());
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.cap = reader.int32();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.join = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Line.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseLine();
    message.style = object.style ?? 0;
    message.widthEmu = object.widthEmu ?? undefined;
    message.fill = object.fill !== undefined && object.fill !== null ? Fill.fromPartial(object.fill) : undefined;
    message.compound = object.compound ?? undefined;
    message.sketch = object.sketch !== undefined && object.sketch !== null ? Line_LineSketch.fromPartial(object.sketch) : undefined;
    message.cap = object.cap ?? undefined;
    message.join = object.join ?? undefined;
    return message;
  }
};
function createBaseLine_LineSketch() {
  return { type: 0, presetGeometry: "", seed: undefined };
}
var Line_LineSketch = {
  encode(message, writer = new BinaryWriter) {
    if (message.type !== 0) {
      writer.uint32(8).int32(message.type);
    }
    if (message.presetGeometry !== "") {
      writer.uint32(18).string(message.presetGeometry);
    }
    if (message.seed !== undefined) {
      writer.uint32(24).uint32(message.seed);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseLine_LineSketch();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.type = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.presetGeometry = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.seed = reader.uint32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Line_LineSketch.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseLine_LineSketch();
    message.type = object.type ?? 0;
    message.presetGeometry = object.presetGeometry ?? "";
    message.seed = object.seed ?? undefined;
    return message;
  }
};
function createBaseFillToRect() {
  return { l: undefined, t: undefined, r: undefined, b: undefined };
}
var FillToRect = {
  encode(message, writer = new BinaryWriter) {
    if (message.l !== undefined) {
      writer.uint32(8).int32(message.l);
    }
    if (message.t !== undefined) {
      writer.uint32(16).int32(message.t);
    }
    if (message.r !== undefined) {
      writer.uint32(24).int32(message.r);
    }
    if (message.b !== undefined) {
      writer.uint32(32).int32(message.b);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseFillToRect();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.l = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.t = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.r = reader.int32();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.b = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return FillToRect.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseFillToRect();
    message.l = object.l ?? undefined;
    message.t = object.t ?? undefined;
    message.r = object.r ?? undefined;
    message.b = object.b ?? undefined;
    return message;
  }
};
function createBaseImage() {
  return { contentType: "", data: new Uint8Array(0), id: "", prompt: undefined, uri: undefined };
}
var Image = {
  encode(message, writer = new BinaryWriter) {
    if (message.contentType !== "") {
      writer.uint32(10).string(message.contentType);
    }
    if (message.data.length !== 0) {
      writer.uint32(18).bytes(message.data);
    }
    if (message.id !== "") {
      writer.uint32(26).string(message.id);
    }
    if (message.prompt !== undefined) {
      writer.uint32(34).string(message.prompt);
    }
    if (message.uri !== undefined) {
      writer.uint32(42).string(message.uri);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseImage();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.contentType = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.data = reader.bytes();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.prompt = reader.string();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.uri = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Image.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseImage();
    message.contentType = object.contentType ?? "";
    message.data = object.data ?? new Uint8Array(0);
    message.id = object.id ?? "";
    message.prompt = object.prompt ?? undefined;
    message.uri = object.uri ?? undefined;
    return message;
  }
};
function createBaseContentReference() {
  return {
    id: "",
    tetherId: "",
    uri: undefined,
    title: undefined,
    type: 0,
    sourceType: undefined,
    targetId: "",
    contentLineRange: undefined,
    contentId: undefined
  };
}
var ContentReference = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== "") {
      writer.uint32(10).string(message.id);
    }
    if (message.tetherId !== "") {
      writer.uint32(18).string(message.tetherId);
    }
    if (message.uri !== undefined) {
      writer.uint32(26).string(message.uri);
    }
    if (message.title !== undefined) {
      writer.uint32(34).string(message.title);
    }
    if (message.type !== 0) {
      writer.uint32(40).int32(message.type);
    }
    if (message.sourceType !== undefined) {
      writer.uint32(48).int32(message.sourceType);
    }
    if (message.targetId !== "") {
      writer.uint32(58).string(message.targetId);
    }
    if (message.contentLineRange !== undefined) {
      LineRange.encode(message.contentLineRange, writer.uint32(66).fork()).join();
    }
    if (message.contentId !== undefined) {
      writer.uint32(74).string(message.contentId);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseContentReference();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.tetherId = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.uri = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.title = reader.string();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.type = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.sourceType = reader.int32();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.targetId = reader.string();
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.contentLineRange = LineRange.decode(reader, reader.uint32());
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.contentId = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ContentReference.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseContentReference();
    message.id = object.id ?? "";
    message.tetherId = object.tetherId ?? "";
    message.uri = object.uri ?? undefined;
    message.title = object.title ?? undefined;
    message.type = object.type ?? 0;
    message.sourceType = object.sourceType ?? undefined;
    message.targetId = object.targetId ?? "";
    message.contentLineRange = object.contentLineRange !== undefined && object.contentLineRange !== null ? LineRange.fromPartial(object.contentLineRange) : undefined;
    message.contentId = object.contentId ?? undefined;
    return message;
  }
};
function createBaseLineRange() {
  return { startLineNum: 0, endLineNum: undefined };
}
var LineRange = {
  encode(message, writer = new BinaryWriter) {
    if (message.startLineNum !== 0) {
      writer.uint32(8).uint64(message.startLineNum);
    }
    if (message.endLineNum !== undefined) {
      writer.uint32(16).uint64(message.endLineNum);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseLineRange();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.startLineNum = longToNumber(reader.uint64());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.endLineNum = longToNumber(reader.uint64());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return LineRange.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseLineRange();
    message.startLineNum = object.startLineNum ?? 0;
    message.endLineNum = object.endLineNum ?? undefined;
    return message;
  }
};
function createBasePerson() {
  return {
    id: "",
    displayName: "",
    initials: undefined,
    email: undefined,
    avatarUrl: undefined,
    userId: undefined,
    providerId: undefined
  };
}
var Person = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== "") {
      writer.uint32(10).string(message.id);
    }
    if (message.displayName !== "") {
      writer.uint32(18).string(message.displayName);
    }
    if (message.initials !== undefined) {
      writer.uint32(26).string(message.initials);
    }
    if (message.email !== undefined) {
      writer.uint32(34).string(message.email);
    }
    if (message.avatarUrl !== undefined) {
      writer.uint32(42).string(message.avatarUrl);
    }
    if (message.userId !== undefined) {
      writer.uint32(50).string(message.userId);
    }
    if (message.providerId !== undefined) {
      writer.uint32(58).string(message.providerId);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePerson();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.displayName = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.initials = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.email = reader.string();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.avatarUrl = reader.string();
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.userId = reader.string();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.providerId = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Person.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePerson();
    message.id = object.id ?? "";
    message.displayName = object.displayName ?? "";
    message.initials = object.initials ?? undefined;
    message.email = object.email ?? undefined;
    message.avatarUrl = object.avatarUrl ?? undefined;
    message.userId = object.userId ?? undefined;
    message.providerId = object.providerId ?? undefined;
    return message;
  }
};
function createBaseTextBody() {
  return { plainText: "" };
}
var TextBody = {
  encode(message, writer = new BinaryWriter) {
    if (message.plainText !== "") {
      writer.uint32(10).string(message.plainText);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTextBody();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.plainText = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TextBody.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTextBody();
    message.plainText = object.plainText ?? "";
    return message;
  }
};
function createBaseSpreadsheetCellTarget() {
  return { sheetName: "", sheetId: undefined, address: "" };
}
var SpreadsheetCellTarget = {
  encode(message, writer = new BinaryWriter) {
    if (message.sheetName !== "") {
      writer.uint32(10).string(message.sheetName);
    }
    if (message.sheetId !== undefined) {
      writer.uint32(18).string(message.sheetId);
    }
    if (message.address !== "") {
      writer.uint32(26).string(message.address);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseSpreadsheetCellTarget();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.sheetName = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.sheetId = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.address = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return SpreadsheetCellTarget.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseSpreadsheetCellTarget();
    message.sheetName = object.sheetName ?? "";
    message.sheetId = object.sheetId ?? undefined;
    message.address = object.address ?? "";
    return message;
  }
};
function createBaseSpreadsheetRangeTarget() {
  return { sheetName: "", sheetId: undefined, startAddress: "", endAddress: "" };
}
var SpreadsheetRangeTarget = {
  encode(message, writer = new BinaryWriter) {
    if (message.sheetName !== "") {
      writer.uint32(10).string(message.sheetName);
    }
    if (message.sheetId !== undefined) {
      writer.uint32(18).string(message.sheetId);
    }
    if (message.startAddress !== "") {
      writer.uint32(26).string(message.startAddress);
    }
    if (message.endAddress !== "") {
      writer.uint32(34).string(message.endAddress);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseSpreadsheetRangeTarget();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.sheetName = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.sheetId = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.startAddress = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.endAddress = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return SpreadsheetRangeTarget.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseSpreadsheetRangeTarget();
    message.sheetName = object.sheetName ?? "";
    message.sheetId = object.sheetId ?? undefined;
    message.startAddress = object.startAddress ?? "";
    message.endAddress = object.endAddress ?? "";
    return message;
  }
};
function createBaseSlideTarget() {
  return { slideId: "" };
}
var SlideTarget = {
  encode(message, writer = new BinaryWriter) {
    if (message.slideId !== "") {
      writer.uint32(10).string(message.slideId);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseSlideTarget();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.slideId = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return SlideTarget.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseSlideTarget();
    message.slideId = object.slideId ?? "";
    return message;
  }
};
function createBaseElementTarget() {
  return { slideId: "", elementId: "" };
}
var ElementTarget = {
  encode(message, writer = new BinaryWriter) {
    if (message.slideId !== "") {
      writer.uint32(10).string(message.slideId);
    }
    if (message.elementId !== "") {
      writer.uint32(18).string(message.elementId);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseElementTarget();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.slideId = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.elementId = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ElementTarget.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseElementTarget();
    message.slideId = object.slideId ?? "";
    message.elementId = object.elementId ?? "";
    return message;
  }
};
function createBaseTextRangeContext() {
  return { contextLength: undefined, contextHash: undefined };
}
var TextRangeContext = {
  encode(message, writer = new BinaryWriter) {
    if (message.contextLength !== undefined) {
      writer.uint32(8).uint32(message.contextLength);
    }
    if (message.contextHash !== undefined) {
      writer.uint32(16).uint32(message.contextHash);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTextRangeContext();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.contextLength = reader.uint32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.contextHash = reader.uint32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TextRangeContext.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTextRangeContext();
    message.contextLength = object.contextLength ?? undefined;
    message.contextHash = object.contextHash ?? undefined;
    return message;
  }
};
function createBaseTextRangeTarget() {
  return { slideId: "", elementId: "", startCp: 0, length: 0, context: undefined };
}
var TextRangeTarget = {
  encode(message, writer = new BinaryWriter) {
    if (message.slideId !== "") {
      writer.uint32(10).string(message.slideId);
    }
    if (message.elementId !== "") {
      writer.uint32(18).string(message.elementId);
    }
    if (message.startCp !== 0) {
      writer.uint32(24).uint32(message.startCp);
    }
    if (message.length !== 0) {
      writer.uint32(32).uint32(message.length);
    }
    if (message.context !== undefined) {
      TextRangeContext.encode(message.context, writer.uint32(42).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTextRangeTarget();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.slideId = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.elementId = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.startCp = reader.uint32();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.length = reader.uint32();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.context = TextRangeContext.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TextRangeTarget.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTextRangeTarget();
    message.slideId = object.slideId ?? "";
    message.elementId = object.elementId ?? "";
    message.startCp = object.startCp ?? 0;
    message.length = object.length ?? 0;
    message.context = object.context !== undefined && object.context !== null ? TextRangeContext.fromPartial(object.context) : undefined;
    return message;
  }
};
function createBaseAnnotationTarget() {
  return {
    spreadsheetCell: undefined,
    spreadsheetRange: undefined,
    slide: undefined,
    element: undefined,
    textRange: undefined
  };
}
var AnnotationTarget = {
  encode(message, writer = new BinaryWriter) {
    if (message.spreadsheetCell !== undefined) {
      SpreadsheetCellTarget.encode(message.spreadsheetCell, writer.uint32(10).fork()).join();
    }
    if (message.spreadsheetRange !== undefined) {
      SpreadsheetRangeTarget.encode(message.spreadsheetRange, writer.uint32(18).fork()).join();
    }
    if (message.slide !== undefined) {
      SlideTarget.encode(message.slide, writer.uint32(26).fork()).join();
    }
    if (message.element !== undefined) {
      ElementTarget.encode(message.element, writer.uint32(34).fork()).join();
    }
    if (message.textRange !== undefined) {
      TextRangeTarget.encode(message.textRange, writer.uint32(42).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseAnnotationTarget();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.spreadsheetCell = SpreadsheetCellTarget.decode(reader, reader.uint32());
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.spreadsheetRange = SpreadsheetRangeTarget.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.slide = SlideTarget.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.element = ElementTarget.decode(reader, reader.uint32());
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.textRange = TextRangeTarget.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return AnnotationTarget.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseAnnotationTarget();
    message.spreadsheetCell = object.spreadsheetCell !== undefined && object.spreadsheetCell !== null ? SpreadsheetCellTarget.fromPartial(object.spreadsheetCell) : undefined;
    message.spreadsheetRange = object.spreadsheetRange !== undefined && object.spreadsheetRange !== null ? SpreadsheetRangeTarget.fromPartial(object.spreadsheetRange) : undefined;
    message.slide = object.slide !== undefined && object.slide !== null ? SlideTarget.fromPartial(object.slide) : undefined;
    message.element = object.element !== undefined && object.element !== null ? ElementTarget.fromPartial(object.element) : undefined;
    message.textRange = object.textRange !== undefined && object.textRange !== null ? TextRangeTarget.fromPartial(object.textRange) : undefined;
    return message;
  }
};
function createBaseReactionInstance() {
  return { authorId: "", time: "" };
}
var ReactionInstance = {
  encode(message, writer = new BinaryWriter) {
    if (message.authorId !== "") {
      writer.uint32(10).string(message.authorId);
    }
    if (message.time !== "") {
      writer.uint32(18).string(message.time);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseReactionInstance();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.authorId = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.time = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ReactionInstance.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseReactionInstance();
    message.authorId = object.authorId ?? "";
    message.time = object.time ?? "";
    return message;
  }
};
function createBaseCommentReaction() {
  return { type: "", instances: [] };
}
var CommentReaction = {
  encode(message, writer = new BinaryWriter) {
    if (message.type !== "") {
      writer.uint32(10).string(message.type);
    }
    for (const v of message.instances) {
      ReactionInstance.encode(v, writer.uint32(18).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCommentReaction();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.type = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.instances.push(ReactionInstance.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CommentReaction.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCommentReaction();
    message.type = object.type ?? "";
    message.instances = object.instances?.map((e) => ReactionInstance.fromPartial(e)) || [];
    return message;
  }
};
function createBaseCommentPosition() {
  return { xEmu: 0, yEmu: 0 };
}
var CommentPosition = {
  encode(message, writer = new BinaryWriter) {
    if (message.xEmu !== 0) {
      writer.uint32(8).int64(message.xEmu);
    }
    if (message.yEmu !== 0) {
      writer.uint32(16).int64(message.yEmu);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCommentPosition();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.xEmu = longToNumber(reader.int64());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.yEmu = longToNumber(reader.int64());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CommentPosition.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCommentPosition();
    message.xEmu = object.xEmu ?? 0;
    message.yEmu = object.yEmu ?? 0;
    return message;
  }
};
function createBaseComment() {
  return {
    id: "",
    parentId: undefined,
    authorId: "",
    createdAt: "",
    editedAt: undefined,
    body: undefined,
    isDeleted: false,
    reactions: [],
    citations: [],
    position: undefined
  };
}
var Comment = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== "") {
      writer.uint32(10).string(message.id);
    }
    if (message.parentId !== undefined) {
      writer.uint32(18).string(message.parentId);
    }
    if (message.authorId !== "") {
      writer.uint32(26).string(message.authorId);
    }
    if (message.createdAt !== "") {
      writer.uint32(34).string(message.createdAt);
    }
    if (message.editedAt !== undefined) {
      writer.uint32(42).string(message.editedAt);
    }
    if (message.body !== undefined) {
      TextBody.encode(message.body, writer.uint32(50).fork()).join();
    }
    if (message.isDeleted !== false) {
      writer.uint32(56).bool(message.isDeleted);
    }
    for (const v of message.reactions) {
      CommentReaction.encode(v, writer.uint32(66).fork()).join();
    }
    for (const v of message.citations) {
      writer.uint32(74).string(v);
    }
    if (message.position !== undefined) {
      CommentPosition.encode(message.position, writer.uint32(82).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseComment();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.parentId = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.authorId = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.createdAt = reader.string();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.editedAt = reader.string();
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.body = TextBody.decode(reader, reader.uint32());
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.isDeleted = reader.bool();
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.reactions.push(CommentReaction.decode(reader, reader.uint32()));
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.citations.push(reader.string());
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.position = CommentPosition.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Comment.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseComment();
    message.id = object.id ?? "";
    message.parentId = object.parentId ?? undefined;
    message.authorId = object.authorId ?? "";
    message.createdAt = object.createdAt ?? "";
    message.editedAt = object.editedAt ?? undefined;
    message.body = object.body !== undefined && object.body !== null ? TextBody.fromPartial(object.body) : undefined;
    message.isDeleted = object.isDeleted ?? false;
    message.reactions = object.reactions?.map((e) => CommentReaction.fromPartial(e)) || [];
    message.citations = object.citations?.map((e) => e) || [];
    message.position = object.position !== undefined && object.position !== null ? CommentPosition.fromPartial(object.position) : undefined;
    return message;
  }
};
function createBaseThread() {
  return { id: "", target: undefined, comments: [], status: 0, resolvedBy: undefined, resolvedAt: undefined };
}
var Thread = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== "") {
      writer.uint32(10).string(message.id);
    }
    if (message.target !== undefined) {
      AnnotationTarget.encode(message.target, writer.uint32(18).fork()).join();
    }
    for (const v of message.comments) {
      Comment.encode(v, writer.uint32(26).fork()).join();
    }
    if (message.status !== 0) {
      writer.uint32(32).int32(message.status);
    }
    if (message.resolvedBy !== undefined) {
      writer.uint32(42).string(message.resolvedBy);
    }
    if (message.resolvedAt !== undefined) {
      writer.uint32(50).string(message.resolvedAt);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseThread();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.target = AnnotationTarget.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.comments.push(Comment.decode(reader, reader.uint32()));
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.status = reader.int32();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.resolvedBy = reader.string();
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.resolvedAt = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Thread.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseThread();
    message.id = object.id ?? "";
    message.target = object.target !== undefined && object.target !== null ? AnnotationTarget.fromPartial(object.target) : undefined;
    message.comments = object.comments?.map((e) => Comment.fromPartial(e)) || [];
    message.status = object.status ?? 0;
    message.resolvedBy = object.resolvedBy ?? undefined;
    message.resolvedAt = object.resolvedAt ?? undefined;
    return message;
  }
};
var gt = (() => {
  if (typeof globalThis !== "undefined") {
    return globalThis;
  }
  if (typeof self !== "undefined") {
    return self;
  }
  if (typeof window !== "undefined") {
    return window;
  }
  if (typeof global !== "undefined") {
    return global;
  }
  throw "Unable to locate global object";
})();
function longToNumber(int64) {
  const num = gt.Number(int64.toString());
  if (num > gt.Number.MAX_SAFE_INTEGER) {
    throw new gt.Error("Value is larger than Number.MAX_SAFE_INTEGER");
  }
  if (num < gt.Number.MIN_SAFE_INTEGER) {
    throw new gt.Error("Value is smaller than Number.MIN_SAFE_INTEGER");
  }
  return num;
}

// node_modules/@oai/walnut/generated/oaiproto/coworker/pptx/chart.ts
function createBaseChart() {
  return {
    title: "",
    categories: [],
    series: [],
    bbox: undefined,
    type: 0,
    styleIndex: 0,
    id: "",
    xAxis: undefined,
    yAxis: undefined,
    barDirection: 0,
    hasLegend: false,
    legend: undefined,
    titleTextStyle: undefined,
    dataLabels: undefined,
    chartFill: undefined,
    chartLine: undefined,
    chartSpaceFill: undefined,
    chartSpaceLine: undefined,
    roundedCorners: undefined,
    plotAreaFill: undefined,
    plotAreaLine: undefined,
    pivot: undefined,
    pivotOptions: undefined,
    pivotFormats: [],
    mapOptions: undefined,
    style: undefined,
    displayBlanksAs: undefined,
    showDlblsOverMax: undefined,
    view3d: undefined,
    barOptions: undefined,
    lineOptions: undefined,
    areaOptions: undefined,
    pieOptions: undefined,
    ofPieOptions: undefined,
    doughnutOptions: undefined,
    scatterOptions: undefined,
    bubbleOptions: undefined,
    radarOptions: undefined,
    surfaceOptions: undefined,
    treemapOptions: undefined,
    boxWhiskerOptions: undefined,
    histogramOptions: undefined,
    waterfallOptions: undefined,
    funnelOptions: undefined
  };
}
var Chart = {
  encode(message, writer = new BinaryWriter) {
    if (message.title !== "") {
      writer.uint32(10).string(message.title);
    }
    for (const v of message.categories) {
      writer.uint32(18).string(v);
    }
    for (const v of message.series) {
      Series.encode(v, writer.uint32(26).fork()).join();
    }
    if (message.bbox !== undefined) {
      BoundingBox.encode(message.bbox, writer.uint32(34).fork()).join();
    }
    if (message.type !== 0) {
      writer.uint32(40).int32(message.type);
    }
    if (message.styleIndex !== 0) {
      writer.uint32(48).int32(message.styleIndex);
    }
    if (message.id !== "") {
      writer.uint32(58).string(message.id);
    }
    if (message.xAxis !== undefined) {
      Axis.encode(message.xAxis, writer.uint32(66).fork()).join();
    }
    if (message.yAxis !== undefined) {
      Axis.encode(message.yAxis, writer.uint32(74).fork()).join();
    }
    if (message.barDirection !== 0) {
      writer.uint32(80).int32(message.barDirection);
    }
    if (message.hasLegend !== false) {
      writer.uint32(88).bool(message.hasLegend);
    }
    if (message.legend !== undefined) {
      Legend.encode(message.legend, writer.uint32(98).fork()).join();
    }
    if (message.titleTextStyle !== undefined) {
      TextStyle.encode(message.titleTextStyle, writer.uint32(106).fork()).join();
    }
    if (message.dataLabels !== undefined) {
      DataLabels.encode(message.dataLabels, writer.uint32(114).fork()).join();
    }
    if (message.chartFill !== undefined) {
      Fill.encode(message.chartFill, writer.uint32(122).fork()).join();
    }
    if (message.chartLine !== undefined) {
      Line.encode(message.chartLine, writer.uint32(130).fork()).join();
    }
    if (message.chartSpaceFill !== undefined) {
      Fill.encode(message.chartSpaceFill, writer.uint32(194).fork()).join();
    }
    if (message.chartSpaceLine !== undefined) {
      Line.encode(message.chartSpaceLine, writer.uint32(202).fork()).join();
    }
    if (message.roundedCorners !== undefined) {
      writer.uint32(208).bool(message.roundedCorners);
    }
    if (message.plotAreaFill !== undefined) {
      Fill.encode(message.plotAreaFill, writer.uint32(138).fork()).join();
    }
    if (message.plotAreaLine !== undefined) {
      Line.encode(message.plotAreaLine, writer.uint32(146).fork()).join();
    }
    if (message.pivot !== undefined) {
      PivotChartBinding.encode(message.pivot, writer.uint32(154).fork()).join();
    }
    if (message.pivotOptions !== undefined) {
      PivotChartOptions.encode(message.pivotOptions, writer.uint32(162).fork()).join();
    }
    for (const v of message.pivotFormats) {
      PivotChartFormat.encode(v, writer.uint32(170).fork()).join();
    }
    if (message.mapOptions !== undefined) {
      MapChartOptions.encode(message.mapOptions, writer.uint32(178).fork()).join();
    }
    if (message.style !== undefined) {
      ChartStyleRef.encode(message.style, writer.uint32(186).fork()).join();
    }
    if (message.displayBlanksAs !== undefined) {
      writer.uint32(224).int32(message.displayBlanksAs);
    }
    if (message.showDlblsOverMax !== undefined) {
      writer.uint32(232).bool(message.showDlblsOverMax);
    }
    if (message.view3d !== undefined) {
      View3D.encode(message.view3d, writer.uint32(330).fork()).join();
    }
    if (message.barOptions !== undefined) {
      BarOptions.encode(message.barOptions, writer.uint32(402).fork()).join();
    }
    if (message.lineOptions !== undefined) {
      LineOptions.encode(message.lineOptions, writer.uint32(410).fork()).join();
    }
    if (message.areaOptions !== undefined) {
      AreaOptions.encode(message.areaOptions, writer.uint32(418).fork()).join();
    }
    if (message.pieOptions !== undefined) {
      PieOptions.encode(message.pieOptions, writer.uint32(426).fork()).join();
    }
    if (message.ofPieOptions !== undefined) {
      OfPieOptions.encode(message.ofPieOptions, writer.uint32(474).fork()).join();
    }
    if (message.doughnutOptions !== undefined) {
      DoughnutOptions.encode(message.doughnutOptions, writer.uint32(434).fork()).join();
    }
    if (message.scatterOptions !== undefined) {
      ScatterOptions.encode(message.scatterOptions, writer.uint32(442).fork()).join();
    }
    if (message.bubbleOptions !== undefined) {
      BubbleOptions.encode(message.bubbleOptions, writer.uint32(450).fork()).join();
    }
    if (message.radarOptions !== undefined) {
      RadarOptions.encode(message.radarOptions, writer.uint32(458).fork()).join();
    }
    if (message.surfaceOptions !== undefined) {
      SurfaceOptions.encode(message.surfaceOptions, writer.uint32(466).fork()).join();
    }
    if (message.treemapOptions !== undefined) {
      TreemapOptions.encode(message.treemapOptions, writer.uint32(354).fork()).join();
    }
    if (message.boxWhiskerOptions !== undefined) {
      BoxWhiskerOptions.encode(message.boxWhiskerOptions, writer.uint32(362).fork()).join();
    }
    if (message.histogramOptions !== undefined) {
      HistogramOptions.encode(message.histogramOptions, writer.uint32(370).fork()).join();
    }
    if (message.waterfallOptions !== undefined) {
      WaterfallOptions.encode(message.waterfallOptions, writer.uint32(378).fork()).join();
    }
    if (message.funnelOptions !== undefined) {
      FunnelOptions.encode(message.funnelOptions, writer.uint32(386).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseChart();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.title = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.categories.push(reader.string());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.series.push(Series.decode(reader, reader.uint32()));
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.bbox = BoundingBox.decode(reader, reader.uint32());
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.type = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.styleIndex = reader.int32();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.xAxis = Axis.decode(reader, reader.uint32());
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.yAxis = Axis.decode(reader, reader.uint32());
          continue;
        }
        case 10: {
          if (tag !== 80) {
            break;
          }
          message.barDirection = reader.int32();
          continue;
        }
        case 11: {
          if (tag !== 88) {
            break;
          }
          message.hasLegend = reader.bool();
          continue;
        }
        case 12: {
          if (tag !== 98) {
            break;
          }
          message.legend = Legend.decode(reader, reader.uint32());
          continue;
        }
        case 13: {
          if (tag !== 106) {
            break;
          }
          message.titleTextStyle = TextStyle.decode(reader, reader.uint32());
          continue;
        }
        case 14: {
          if (tag !== 114) {
            break;
          }
          message.dataLabels = DataLabels.decode(reader, reader.uint32());
          continue;
        }
        case 15: {
          if (tag !== 122) {
            break;
          }
          message.chartFill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 16: {
          if (tag !== 130) {
            break;
          }
          message.chartLine = Line.decode(reader, reader.uint32());
          continue;
        }
        case 24: {
          if (tag !== 194) {
            break;
          }
          message.chartSpaceFill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 25: {
          if (tag !== 202) {
            break;
          }
          message.chartSpaceLine = Line.decode(reader, reader.uint32());
          continue;
        }
        case 26: {
          if (tag !== 208) {
            break;
          }
          message.roundedCorners = reader.bool();
          continue;
        }
        case 17: {
          if (tag !== 138) {
            break;
          }
          message.plotAreaFill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 18: {
          if (tag !== 146) {
            break;
          }
          message.plotAreaLine = Line.decode(reader, reader.uint32());
          continue;
        }
        case 19: {
          if (tag !== 154) {
            break;
          }
          message.pivot = PivotChartBinding.decode(reader, reader.uint32());
          continue;
        }
        case 20: {
          if (tag !== 162) {
            break;
          }
          message.pivotOptions = PivotChartOptions.decode(reader, reader.uint32());
          continue;
        }
        case 21: {
          if (tag !== 170) {
            break;
          }
          message.pivotFormats.push(PivotChartFormat.decode(reader, reader.uint32()));
          continue;
        }
        case 22: {
          if (tag !== 178) {
            break;
          }
          message.mapOptions = MapChartOptions.decode(reader, reader.uint32());
          continue;
        }
        case 23: {
          if (tag !== 186) {
            break;
          }
          message.style = ChartStyleRef.decode(reader, reader.uint32());
          continue;
        }
        case 28: {
          if (tag !== 224) {
            break;
          }
          message.displayBlanksAs = reader.int32();
          continue;
        }
        case 29: {
          if (tag !== 232) {
            break;
          }
          message.showDlblsOverMax = reader.bool();
          continue;
        }
        case 41: {
          if (tag !== 330) {
            break;
          }
          message.view3d = View3D.decode(reader, reader.uint32());
          continue;
        }
        case 50: {
          if (tag !== 402) {
            break;
          }
          message.barOptions = BarOptions.decode(reader, reader.uint32());
          continue;
        }
        case 51: {
          if (tag !== 410) {
            break;
          }
          message.lineOptions = LineOptions.decode(reader, reader.uint32());
          continue;
        }
        case 52: {
          if (tag !== 418) {
            break;
          }
          message.areaOptions = AreaOptions.decode(reader, reader.uint32());
          continue;
        }
        case 53: {
          if (tag !== 426) {
            break;
          }
          message.pieOptions = PieOptions.decode(reader, reader.uint32());
          continue;
        }
        case 59: {
          if (tag !== 474) {
            break;
          }
          message.ofPieOptions = OfPieOptions.decode(reader, reader.uint32());
          continue;
        }
        case 54: {
          if (tag !== 434) {
            break;
          }
          message.doughnutOptions = DoughnutOptions.decode(reader, reader.uint32());
          continue;
        }
        case 55: {
          if (tag !== 442) {
            break;
          }
          message.scatterOptions = ScatterOptions.decode(reader, reader.uint32());
          continue;
        }
        case 56: {
          if (tag !== 450) {
            break;
          }
          message.bubbleOptions = BubbleOptions.decode(reader, reader.uint32());
          continue;
        }
        case 57: {
          if (tag !== 458) {
            break;
          }
          message.radarOptions = RadarOptions.decode(reader, reader.uint32());
          continue;
        }
        case 58: {
          if (tag !== 466) {
            break;
          }
          message.surfaceOptions = SurfaceOptions.decode(reader, reader.uint32());
          continue;
        }
        case 44: {
          if (tag !== 354) {
            break;
          }
          message.treemapOptions = TreemapOptions.decode(reader, reader.uint32());
          continue;
        }
        case 45: {
          if (tag !== 362) {
            break;
          }
          message.boxWhiskerOptions = BoxWhiskerOptions.decode(reader, reader.uint32());
          continue;
        }
        case 46: {
          if (tag !== 370) {
            break;
          }
          message.histogramOptions = HistogramOptions.decode(reader, reader.uint32());
          continue;
        }
        case 47: {
          if (tag !== 378) {
            break;
          }
          message.waterfallOptions = WaterfallOptions.decode(reader, reader.uint32());
          continue;
        }
        case 48: {
          if (tag !== 386) {
            break;
          }
          message.funnelOptions = FunnelOptions.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Chart.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseChart();
    message.title = object.title ?? "";
    message.categories = object.categories?.map((e) => e) || [];
    message.series = object.series?.map((e) => Series.fromPartial(e)) || [];
    message.bbox = object.bbox !== undefined && object.bbox !== null ? BoundingBox.fromPartial(object.bbox) : undefined;
    message.type = object.type ?? 0;
    message.styleIndex = object.styleIndex ?? 0;
    message.id = object.id ?? "";
    message.xAxis = object.xAxis !== undefined && object.xAxis !== null ? Axis.fromPartial(object.xAxis) : undefined;
    message.yAxis = object.yAxis !== undefined && object.yAxis !== null ? Axis.fromPartial(object.yAxis) : undefined;
    message.barDirection = object.barDirection ?? 0;
    message.hasLegend = object.hasLegend ?? false;
    message.legend = object.legend !== undefined && object.legend !== null ? Legend.fromPartial(object.legend) : undefined;
    message.titleTextStyle = object.titleTextStyle !== undefined && object.titleTextStyle !== null ? TextStyle.fromPartial(object.titleTextStyle) : undefined;
    message.dataLabels = object.dataLabels !== undefined && object.dataLabels !== null ? DataLabels.fromPartial(object.dataLabels) : undefined;
    message.chartFill = object.chartFill !== undefined && object.chartFill !== null ? Fill.fromPartial(object.chartFill) : undefined;
    message.chartLine = object.chartLine !== undefined && object.chartLine !== null ? Line.fromPartial(object.chartLine) : undefined;
    message.chartSpaceFill = object.chartSpaceFill !== undefined && object.chartSpaceFill !== null ? Fill.fromPartial(object.chartSpaceFill) : undefined;
    message.chartSpaceLine = object.chartSpaceLine !== undefined && object.chartSpaceLine !== null ? Line.fromPartial(object.chartSpaceLine) : undefined;
    message.roundedCorners = object.roundedCorners ?? undefined;
    message.plotAreaFill = object.plotAreaFill !== undefined && object.plotAreaFill !== null ? Fill.fromPartial(object.plotAreaFill) : undefined;
    message.plotAreaLine = object.plotAreaLine !== undefined && object.plotAreaLine !== null ? Line.fromPartial(object.plotAreaLine) : undefined;
    message.pivot = object.pivot !== undefined && object.pivot !== null ? PivotChartBinding.fromPartial(object.pivot) : undefined;
    message.pivotOptions = object.pivotOptions !== undefined && object.pivotOptions !== null ? PivotChartOptions.fromPartial(object.pivotOptions) : undefined;
    message.pivotFormats = object.pivotFormats?.map((e) => PivotChartFormat.fromPartial(e)) || [];
    message.mapOptions = object.mapOptions !== undefined && object.mapOptions !== null ? MapChartOptions.fromPartial(object.mapOptions) : undefined;
    message.style = object.style !== undefined && object.style !== null ? ChartStyleRef.fromPartial(object.style) : undefined;
    message.displayBlanksAs = object.displayBlanksAs ?? undefined;
    message.showDlblsOverMax = object.showDlblsOverMax ?? undefined;
    message.view3d = object.view3d !== undefined && object.view3d !== null ? View3D.fromPartial(object.view3d) : undefined;
    message.barOptions = object.barOptions !== undefined && object.barOptions !== null ? BarOptions.fromPartial(object.barOptions) : undefined;
    message.lineOptions = object.lineOptions !== undefined && object.lineOptions !== null ? LineOptions.fromPartial(object.lineOptions) : undefined;
    message.areaOptions = object.areaOptions !== undefined && object.areaOptions !== null ? AreaOptions.fromPartial(object.areaOptions) : undefined;
    message.pieOptions = object.pieOptions !== undefined && object.pieOptions !== null ? PieOptions.fromPartial(object.pieOptions) : undefined;
    message.ofPieOptions = object.ofPieOptions !== undefined && object.ofPieOptions !== null ? OfPieOptions.fromPartial(object.ofPieOptions) : undefined;
    message.doughnutOptions = object.doughnutOptions !== undefined && object.doughnutOptions !== null ? DoughnutOptions.fromPartial(object.doughnutOptions) : undefined;
    message.scatterOptions = object.scatterOptions !== undefined && object.scatterOptions !== null ? ScatterOptions.fromPartial(object.scatterOptions) : undefined;
    message.bubbleOptions = object.bubbleOptions !== undefined && object.bubbleOptions !== null ? BubbleOptions.fromPartial(object.bubbleOptions) : undefined;
    message.radarOptions = object.radarOptions !== undefined && object.radarOptions !== null ? RadarOptions.fromPartial(object.radarOptions) : undefined;
    message.surfaceOptions = object.surfaceOptions !== undefined && object.surfaceOptions !== null ? SurfaceOptions.fromPartial(object.surfaceOptions) : undefined;
    message.treemapOptions = object.treemapOptions !== undefined && object.treemapOptions !== null ? TreemapOptions.fromPartial(object.treemapOptions) : undefined;
    message.boxWhiskerOptions = object.boxWhiskerOptions !== undefined && object.boxWhiskerOptions !== null ? BoxWhiskerOptions.fromPartial(object.boxWhiskerOptions) : undefined;
    message.histogramOptions = object.histogramOptions !== undefined && object.histogramOptions !== null ? HistogramOptions.fromPartial(object.histogramOptions) : undefined;
    message.waterfallOptions = object.waterfallOptions !== undefined && object.waterfallOptions !== null ? WaterfallOptions.fromPartial(object.waterfallOptions) : undefined;
    message.funnelOptions = object.funnelOptions !== undefined && object.funnelOptions !== null ? FunnelOptions.fromPartial(object.funnelOptions) : undefined;
    return message;
  }
};
function createBaseLegend() {
  return { position: 0, overlay: undefined, textStyle: undefined, fill: undefined, stroke: undefined };
}
var Legend = {
  encode(message, writer = new BinaryWriter) {
    if (message.position !== 0) {
      writer.uint32(8).int32(message.position);
    }
    if (message.overlay !== undefined) {
      writer.uint32(16).bool(message.overlay);
    }
    if (message.textStyle !== undefined) {
      TextStyle.encode(message.textStyle, writer.uint32(26).fork()).join();
    }
    if (message.fill !== undefined) {
      Fill.encode(message.fill, writer.uint32(34).fork()).join();
    }
    if (message.stroke !== undefined) {
      Line.encode(message.stroke, writer.uint32(42).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseLegend();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.position = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.overlay = reader.bool();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.textStyle = TextStyle.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.fill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.stroke = Line.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Legend.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseLegend();
    message.position = object.position ?? 0;
    message.overlay = object.overlay ?? undefined;
    message.textStyle = object.textStyle !== undefined && object.textStyle !== null ? TextStyle.fromPartial(object.textStyle) : undefined;
    message.fill = object.fill !== undefined && object.fill !== null ? Fill.fromPartial(object.fill) : undefined;
    message.stroke = object.stroke !== undefined && object.stroke !== null ? Line.fromPartial(object.stroke) : undefined;
    return message;
  }
};
function createBaseBarOptions() {
  return {
    direction: undefined,
    grouping: undefined,
    varyColors: undefined,
    gapWidth: undefined,
    overlap: undefined,
    gapDepth: undefined,
    bar3dShape: undefined
  };
}
var BarOptions = {
  encode(message, writer = new BinaryWriter) {
    if (message.direction !== undefined) {
      writer.uint32(8).int32(message.direction);
    }
    if (message.grouping !== undefined) {
      writer.uint32(16).int32(message.grouping);
    }
    if (message.varyColors !== undefined) {
      writer.uint32(24).bool(message.varyColors);
    }
    if (message.gapWidth !== undefined) {
      writer.uint32(32).uint32(message.gapWidth);
    }
    if (message.overlap !== undefined) {
      writer.uint32(40).sint32(message.overlap);
    }
    if (message.gapDepth !== undefined) {
      writer.uint32(48).uint32(message.gapDepth);
    }
    if (message.bar3dShape !== undefined) {
      writer.uint32(56).int32(message.bar3dShape);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseBarOptions();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.direction = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.grouping = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.varyColors = reader.bool();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.gapWidth = reader.uint32();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.overlap = reader.sint32();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.gapDepth = reader.uint32();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.bar3dShape = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return BarOptions.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseBarOptions();
    message.direction = object.direction ?? undefined;
    message.grouping = object.grouping ?? undefined;
    message.varyColors = object.varyColors ?? undefined;
    message.gapWidth = object.gapWidth ?? undefined;
    message.overlap = object.overlap ?? undefined;
    message.gapDepth = object.gapDepth ?? undefined;
    message.bar3dShape = object.bar3dShape ?? undefined;
    return message;
  }
};
function createBaseSeries() {
  return {
    id: undefined,
    name: "",
    values: [],
    formula: "",
    stringCache: "",
    categories: [],
    categoryFormula: "",
    fill: undefined,
    stroke: undefined,
    points: [],
    valuesFormatCode: undefined,
    categoryFormatCode: undefined,
    invertIfNegative: undefined,
    uniqueId: undefined,
    explosion: undefined,
    marker: undefined,
    xValues: [],
    xFormula: "",
    xValuesFormatCode: undefined,
    bubbleSizes: [],
    bubbleSizeFormula: "",
    categoryPaths: [],
    dataLabels: undefined,
    dataLabelOverrides: [],
    trendlines: []
  };
}
var Series = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== undefined) {
      writer.uint32(66).string(message.id);
    }
    if (message.name !== "") {
      writer.uint32(10).string(message.name);
    }
    writer.uint32(18).fork();
    for (const v of message.values) {
      writer.double(v);
    }
    writer.join();
    if (message.formula !== "") {
      writer.uint32(26).string(message.formula);
    }
    if (message.stringCache !== "") {
      writer.uint32(34).string(message.stringCache);
    }
    for (const v of message.categories) {
      writer.uint32(42).string(v);
    }
    if (message.categoryFormula !== "") {
      writer.uint32(50).string(message.categoryFormula);
    }
    if (message.fill !== undefined) {
      Fill.encode(message.fill, writer.uint32(58).fork()).join();
    }
    if (message.stroke !== undefined) {
      Line.encode(message.stroke, writer.uint32(74).fork()).join();
    }
    for (const v of message.points) {
      DataPoint.encode(v, writer.uint32(82).fork()).join();
    }
    if (message.valuesFormatCode !== undefined) {
      writer.uint32(90).string(message.valuesFormatCode);
    }
    if (message.categoryFormatCode !== undefined) {
      writer.uint32(98).string(message.categoryFormatCode);
    }
    if (message.invertIfNegative !== undefined) {
      writer.uint32(104).bool(message.invertIfNegative);
    }
    if (message.uniqueId !== undefined) {
      writer.uint32(114).string(message.uniqueId);
    }
    if (message.explosion !== undefined) {
      writer.uint32(120).uint32(message.explosion);
    }
    if (message.marker !== undefined) {
      Marker.encode(message.marker, writer.uint32(130).fork()).join();
    }
    writer.uint32(138).fork();
    for (const v of message.xValues) {
      writer.double(v);
    }
    writer.join();
    if (message.xFormula !== "") {
      writer.uint32(146).string(message.xFormula);
    }
    if (message.xValuesFormatCode !== undefined) {
      writer.uint32(154).string(message.xValuesFormatCode);
    }
    writer.uint32(162).fork();
    for (const v of message.bubbleSizes) {
      writer.double(v);
    }
    writer.join();
    if (message.bubbleSizeFormula !== "") {
      writer.uint32(170).string(message.bubbleSizeFormula);
    }
    for (const v of message.categoryPaths) {
      CategoryPath.encode(v, writer.uint32(178).fork()).join();
    }
    if (message.dataLabels !== undefined) {
      DataLabels.encode(message.dataLabels, writer.uint32(186).fork()).join();
    }
    for (const v of message.dataLabelOverrides) {
      DataLabel.encode(v, writer.uint32(194).fork()).join();
    }
    for (const v of message.trendlines) {
      Trendline.encode(v, writer.uint32(202).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseSeries();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 2: {
          if (tag === 17) {
            message.values.push(reader.double());
            continue;
          }
          if (tag === 18) {
            const end2 = reader.uint32() + reader.pos;
            while (reader.pos < end2) {
              message.values.push(reader.double());
            }
            continue;
          }
          break;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.formula = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.stringCache = reader.string();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.categories.push(reader.string());
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.categoryFormula = reader.string();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.fill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.stroke = Line.decode(reader, reader.uint32());
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.points.push(DataPoint.decode(reader, reader.uint32()));
          continue;
        }
        case 11: {
          if (tag !== 90) {
            break;
          }
          message.valuesFormatCode = reader.string();
          continue;
        }
        case 12: {
          if (tag !== 98) {
            break;
          }
          message.categoryFormatCode = reader.string();
          continue;
        }
        case 13: {
          if (tag !== 104) {
            break;
          }
          message.invertIfNegative = reader.bool();
          continue;
        }
        case 14: {
          if (tag !== 114) {
            break;
          }
          message.uniqueId = reader.string();
          continue;
        }
        case 15: {
          if (tag !== 120) {
            break;
          }
          message.explosion = reader.uint32();
          continue;
        }
        case 16: {
          if (tag !== 130) {
            break;
          }
          message.marker = Marker.decode(reader, reader.uint32());
          continue;
        }
        case 17: {
          if (tag === 137) {
            message.xValues.push(reader.double());
            continue;
          }
          if (tag === 138) {
            const end2 = reader.uint32() + reader.pos;
            while (reader.pos < end2) {
              message.xValues.push(reader.double());
            }
            continue;
          }
          break;
        }
        case 18: {
          if (tag !== 146) {
            break;
          }
          message.xFormula = reader.string();
          continue;
        }
        case 19: {
          if (tag !== 154) {
            break;
          }
          message.xValuesFormatCode = reader.string();
          continue;
        }
        case 20: {
          if (tag === 161) {
            message.bubbleSizes.push(reader.double());
            continue;
          }
          if (tag === 162) {
            const end2 = reader.uint32() + reader.pos;
            while (reader.pos < end2) {
              message.bubbleSizes.push(reader.double());
            }
            continue;
          }
          break;
        }
        case 21: {
          if (tag !== 170) {
            break;
          }
          message.bubbleSizeFormula = reader.string();
          continue;
        }
        case 22: {
          if (tag !== 178) {
            break;
          }
          message.categoryPaths.push(CategoryPath.decode(reader, reader.uint32()));
          continue;
        }
        case 23: {
          if (tag !== 186) {
            break;
          }
          message.dataLabels = DataLabels.decode(reader, reader.uint32());
          continue;
        }
        case 24: {
          if (tag !== 194) {
            break;
          }
          message.dataLabelOverrides.push(DataLabel.decode(reader, reader.uint32()));
          continue;
        }
        case 25: {
          if (tag !== 202) {
            break;
          }
          message.trendlines.push(Trendline.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Series.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseSeries();
    message.id = object.id ?? undefined;
    message.name = object.name ?? "";
    message.values = object.values?.map((e) => e) || [];
    message.formula = object.formula ?? "";
    message.stringCache = object.stringCache ?? "";
    message.categories = object.categories?.map((e) => e) || [];
    message.categoryFormula = object.categoryFormula ?? "";
    message.fill = object.fill !== undefined && object.fill !== null ? Fill.fromPartial(object.fill) : undefined;
    message.stroke = object.stroke !== undefined && object.stroke !== null ? Line.fromPartial(object.stroke) : undefined;
    message.points = object.points?.map((e) => DataPoint.fromPartial(e)) || [];
    message.valuesFormatCode = object.valuesFormatCode ?? undefined;
    message.categoryFormatCode = object.categoryFormatCode ?? undefined;
    message.invertIfNegative = object.invertIfNegative ?? undefined;
    message.uniqueId = object.uniqueId ?? undefined;
    message.explosion = object.explosion ?? undefined;
    message.marker = object.marker !== undefined && object.marker !== null ? Marker.fromPartial(object.marker) : undefined;
    message.xValues = object.xValues?.map((e) => e) || [];
    message.xFormula = object.xFormula ?? "";
    message.xValuesFormatCode = object.xValuesFormatCode ?? undefined;
    message.bubbleSizes = object.bubbleSizes?.map((e) => e) || [];
    message.bubbleSizeFormula = object.bubbleSizeFormula ?? "";
    message.categoryPaths = object.categoryPaths?.map((e) => CategoryPath.fromPartial(e)) || [];
    message.dataLabels = object.dataLabels !== undefined && object.dataLabels !== null ? DataLabels.fromPartial(object.dataLabels) : undefined;
    message.dataLabelOverrides = object.dataLabelOverrides?.map((e) => DataLabel.fromPartial(e)) || [];
    message.trendlines = object.trendlines?.map((e) => Trendline.fromPartial(e)) || [];
    return message;
  }
};
function createBaseManualLayout() {
  return { x: undefined, y: undefined, w: undefined, h: undefined };
}
var ManualLayout = {
  encode(message, writer = new BinaryWriter) {
    if (message.x !== undefined) {
      writer.uint32(9).double(message.x);
    }
    if (message.y !== undefined) {
      writer.uint32(17).double(message.y);
    }
    if (message.w !== undefined) {
      writer.uint32(25).double(message.w);
    }
    if (message.h !== undefined) {
      writer.uint32(33).double(message.h);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseManualLayout();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 9) {
            break;
          }
          message.x = reader.double();
          continue;
        }
        case 2: {
          if (tag !== 17) {
            break;
          }
          message.y = reader.double();
          continue;
        }
        case 3: {
          if (tag !== 25) {
            break;
          }
          message.w = reader.double();
          continue;
        }
        case 4: {
          if (tag !== 33) {
            break;
          }
          message.h = reader.double();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ManualLayout.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseManualLayout();
    message.x = object.x ?? undefined;
    message.y = object.y ?? undefined;
    message.w = object.w ?? undefined;
    message.h = object.h ?? undefined;
    return message;
  }
};
function createBaseTrendlineLabel() {
  return {
    text: undefined,
    numberFormatCode: undefined,
    numberFormatSourceLinked: undefined,
    manualLayout: undefined,
    textStyle: undefined,
    fill: undefined,
    stroke: undefined,
    textRuns: []
  };
}
var TrendlineLabel = {
  encode(message, writer = new BinaryWriter) {
    if (message.text !== undefined) {
      writer.uint32(10).string(message.text);
    }
    if (message.numberFormatCode !== undefined) {
      writer.uint32(18).string(message.numberFormatCode);
    }
    if (message.numberFormatSourceLinked !== undefined) {
      writer.uint32(24).bool(message.numberFormatSourceLinked);
    }
    if (message.manualLayout !== undefined) {
      ManualLayout.encode(message.manualLayout, writer.uint32(34).fork()).join();
    }
    if (message.textStyle !== undefined) {
      TextStyle.encode(message.textStyle, writer.uint32(42).fork()).join();
    }
    if (message.fill !== undefined) {
      Fill.encode(message.fill, writer.uint32(50).fork()).join();
    }
    if (message.stroke !== undefined) {
      Line.encode(message.stroke, writer.uint32(58).fork()).join();
    }
    for (const v of message.textRuns) {
      TrendlineLabelRun.encode(v, writer.uint32(66).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTrendlineLabel();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.text = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.numberFormatCode = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.numberFormatSourceLinked = reader.bool();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.manualLayout = ManualLayout.decode(reader, reader.uint32());
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.textStyle = TextStyle.decode(reader, reader.uint32());
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.fill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.stroke = Line.decode(reader, reader.uint32());
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.textRuns.push(TrendlineLabelRun.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TrendlineLabel.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTrendlineLabel();
    message.text = object.text ?? undefined;
    message.numberFormatCode = object.numberFormatCode ?? undefined;
    message.numberFormatSourceLinked = object.numberFormatSourceLinked ?? undefined;
    message.manualLayout = object.manualLayout !== undefined && object.manualLayout !== null ? ManualLayout.fromPartial(object.manualLayout) : undefined;
    message.textStyle = object.textStyle !== undefined && object.textStyle !== null ? TextStyle.fromPartial(object.textStyle) : undefined;
    message.fill = object.fill !== undefined && object.fill !== null ? Fill.fromPartial(object.fill) : undefined;
    message.stroke = object.stroke !== undefined && object.stroke !== null ? Line.fromPartial(object.stroke) : undefined;
    message.textRuns = object.textRuns?.map((e) => TrendlineLabelRun.fromPartial(e)) || [];
    return message;
  }
};
function createBaseTrendlineLabelRun() {
  return { text: "", textStyle: undefined };
}
var TrendlineLabelRun = {
  encode(message, writer = new BinaryWriter) {
    if (message.text !== "") {
      writer.uint32(10).string(message.text);
    }
    if (message.textStyle !== undefined) {
      TextStyle.encode(message.textStyle, writer.uint32(18).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTrendlineLabelRun();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.text = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.textStyle = TextStyle.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TrendlineLabelRun.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTrendlineLabelRun();
    message.text = object.text ?? "";
    message.textStyle = object.textStyle !== undefined && object.textStyle !== null ? TextStyle.fromPartial(object.textStyle) : undefined;
    return message;
  }
};
function createBaseTrendline() {
  return {
    type: 0,
    name: undefined,
    order: undefined,
    period: undefined,
    forward: undefined,
    backward: undefined,
    intercept: undefined,
    displayEquation: undefined,
    displayRSquared: undefined,
    stroke: undefined,
    label: undefined
  };
}
var Trendline = {
  encode(message, writer = new BinaryWriter) {
    if (message.type !== 0) {
      writer.uint32(8).int32(message.type);
    }
    if (message.name !== undefined) {
      writer.uint32(18).string(message.name);
    }
    if (message.order !== undefined) {
      writer.uint32(24).uint32(message.order);
    }
    if (message.period !== undefined) {
      writer.uint32(32).uint32(message.period);
    }
    if (message.forward !== undefined) {
      writer.uint32(41).double(message.forward);
    }
    if (message.backward !== undefined) {
      writer.uint32(49).double(message.backward);
    }
    if (message.intercept !== undefined) {
      writer.uint32(57).double(message.intercept);
    }
    if (message.displayEquation !== undefined) {
      writer.uint32(64).bool(message.displayEquation);
    }
    if (message.displayRSquared !== undefined) {
      writer.uint32(72).bool(message.displayRSquared);
    }
    if (message.stroke !== undefined) {
      Line.encode(message.stroke, writer.uint32(82).fork()).join();
    }
    if (message.label !== undefined) {
      TrendlineLabel.encode(message.label, writer.uint32(90).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTrendline();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.type = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.order = reader.uint32();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.period = reader.uint32();
          continue;
        }
        case 5: {
          if (tag !== 41) {
            break;
          }
          message.forward = reader.double();
          continue;
        }
        case 6: {
          if (tag !== 49) {
            break;
          }
          message.backward = reader.double();
          continue;
        }
        case 7: {
          if (tag !== 57) {
            break;
          }
          message.intercept = reader.double();
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.displayEquation = reader.bool();
          continue;
        }
        case 9: {
          if (tag !== 72) {
            break;
          }
          message.displayRSquared = reader.bool();
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.stroke = Line.decode(reader, reader.uint32());
          continue;
        }
        case 11: {
          if (tag !== 90) {
            break;
          }
          message.label = TrendlineLabel.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Trendline.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTrendline();
    message.type = object.type ?? 0;
    message.name = object.name ?? undefined;
    message.order = object.order ?? undefined;
    message.period = object.period ?? undefined;
    message.forward = object.forward ?? undefined;
    message.backward = object.backward ?? undefined;
    message.intercept = object.intercept ?? undefined;
    message.displayEquation = object.displayEquation ?? undefined;
    message.displayRSquared = object.displayRSquared ?? undefined;
    message.stroke = object.stroke !== undefined && object.stroke !== null ? Line.fromPartial(object.stroke) : undefined;
    message.label = object.label !== undefined && object.label !== null ? TrendlineLabel.fromPartial(object.label) : undefined;
    return message;
  }
};
function createBaseLineOptions() {
  return { grouping: undefined, smooth: undefined, varyColors: undefined };
}
var LineOptions = {
  encode(message, writer = new BinaryWriter) {
    if (message.grouping !== undefined) {
      writer.uint32(8).int32(message.grouping);
    }
    if (message.smooth !== undefined) {
      writer.uint32(16).bool(message.smooth);
    }
    if (message.varyColors !== undefined) {
      writer.uint32(24).bool(message.varyColors);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseLineOptions();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.grouping = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.smooth = reader.bool();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.varyColors = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return LineOptions.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseLineOptions();
    message.grouping = object.grouping ?? undefined;
    message.smooth = object.smooth ?? undefined;
    message.varyColors = object.varyColors ?? undefined;
    return message;
  }
};
function createBaseAreaOptions() {
  return { grouping: undefined, varyColors: undefined };
}
var AreaOptions = {
  encode(message, writer = new BinaryWriter) {
    if (message.grouping !== undefined) {
      writer.uint32(8).int32(message.grouping);
    }
    if (message.varyColors !== undefined) {
      writer.uint32(16).bool(message.varyColors);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseAreaOptions();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.grouping = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.varyColors = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return AreaOptions.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseAreaOptions();
    message.grouping = object.grouping ?? undefined;
    message.varyColors = object.varyColors ?? undefined;
    return message;
  }
};
function createBasePieOptions() {
  return { firstSliceAngle: undefined, varyColors: undefined };
}
var PieOptions = {
  encode(message, writer = new BinaryWriter) {
    if (message.firstSliceAngle !== undefined) {
      writer.uint32(8).uint32(message.firstSliceAngle);
    }
    if (message.varyColors !== undefined) {
      writer.uint32(16).bool(message.varyColors);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePieOptions();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.firstSliceAngle = reader.uint32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.varyColors = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PieOptions.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePieOptions();
    message.firstSliceAngle = object.firstSliceAngle ?? undefined;
    message.varyColors = object.varyColors ?? undefined;
    return message;
  }
};
function createBaseOfPieOptions() {
  return {
    ofPieType: undefined,
    splitType: undefined,
    splitPosition: undefined,
    gapWidth: undefined,
    secondPieSize: undefined,
    secondaryIndices: [],
    varyColors: undefined,
    serLines: []
  };
}
var OfPieOptions = {
  encode(message, writer = new BinaryWriter) {
    if (message.ofPieType !== undefined) {
      writer.uint32(8).int32(message.ofPieType);
    }
    if (message.splitType !== undefined) {
      writer.uint32(16).int32(message.splitType);
    }
    if (message.splitPosition !== undefined) {
      writer.uint32(25).double(message.splitPosition);
    }
    if (message.gapWidth !== undefined) {
      writer.uint32(32).uint32(message.gapWidth);
    }
    if (message.secondPieSize !== undefined) {
      writer.uint32(40).uint32(message.secondPieSize);
    }
    writer.uint32(50).fork();
    for (const v of message.secondaryIndices) {
      writer.uint32(v);
    }
    writer.join();
    if (message.varyColors !== undefined) {
      writer.uint32(56).bool(message.varyColors);
    }
    for (const v of message.serLines) {
      Line.encode(v, writer.uint32(66).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseOfPieOptions();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.ofPieType = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.splitType = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 25) {
            break;
          }
          message.splitPosition = reader.double();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.gapWidth = reader.uint32();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.secondPieSize = reader.uint32();
          continue;
        }
        case 6: {
          if (tag === 48) {
            message.secondaryIndices.push(reader.uint32());
            continue;
          }
          if (tag === 50) {
            const end2 = reader.uint32() + reader.pos;
            while (reader.pos < end2) {
              message.secondaryIndices.push(reader.uint32());
            }
            continue;
          }
          break;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.varyColors = reader.bool();
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.serLines.push(Line.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return OfPieOptions.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseOfPieOptions();
    message.ofPieType = object.ofPieType ?? undefined;
    message.splitType = object.splitType ?? undefined;
    message.splitPosition = object.splitPosition ?? undefined;
    message.gapWidth = object.gapWidth ?? undefined;
    message.secondPieSize = object.secondPieSize ?? undefined;
    message.secondaryIndices = object.secondaryIndices?.map((e) => e) || [];
    message.varyColors = object.varyColors ?? undefined;
    message.serLines = object.serLines?.map((e) => Line.fromPartial(e)) || [];
    return message;
  }
};
function createBaseDoughnutOptions() {
  return { holeSize: undefined, firstSliceAngle: undefined, varyColors: undefined };
}
var DoughnutOptions = {
  encode(message, writer = new BinaryWriter) {
    if (message.holeSize !== undefined) {
      writer.uint32(8).uint32(message.holeSize);
    }
    if (message.firstSliceAngle !== undefined) {
      writer.uint32(16).uint32(message.firstSliceAngle);
    }
    if (message.varyColors !== undefined) {
      writer.uint32(24).bool(message.varyColors);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseDoughnutOptions();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.holeSize = reader.uint32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.firstSliceAngle = reader.uint32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.varyColors = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return DoughnutOptions.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseDoughnutOptions();
    message.holeSize = object.holeSize ?? undefined;
    message.firstSliceAngle = object.firstSliceAngle ?? undefined;
    message.varyColors = object.varyColors ?? undefined;
    return message;
  }
};
function createBaseScatterOptions() {
  return { style: undefined, varyColors: undefined };
}
var ScatterOptions = {
  encode(message, writer = new BinaryWriter) {
    if (message.style !== undefined) {
      writer.uint32(8).int32(message.style);
    }
    if (message.varyColors !== undefined) {
      writer.uint32(16).bool(message.varyColors);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseScatterOptions();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.style = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.varyColors = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ScatterOptions.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseScatterOptions();
    message.style = object.style ?? undefined;
    message.varyColors = object.varyColors ?? undefined;
    return message;
  }
};
function createBaseBubbleOptions() {
  return { is3d: undefined, scale: undefined, showNegative: undefined, varyColors: undefined };
}
var BubbleOptions = {
  encode(message, writer = new BinaryWriter) {
    if (message.is3d !== undefined) {
      writer.uint32(8).bool(message.is3d);
    }
    if (message.scale !== undefined) {
      writer.uint32(16).uint32(message.scale);
    }
    if (message.showNegative !== undefined) {
      writer.uint32(24).bool(message.showNegative);
    }
    if (message.varyColors !== undefined) {
      writer.uint32(32).bool(message.varyColors);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseBubbleOptions();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.is3d = reader.bool();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.scale = reader.uint32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.showNegative = reader.bool();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.varyColors = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return BubbleOptions.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseBubbleOptions();
    message.is3d = object.is3d ?? undefined;
    message.scale = object.scale ?? undefined;
    message.showNegative = object.showNegative ?? undefined;
    message.varyColors = object.varyColors ?? undefined;
    return message;
  }
};
function createBaseRadarOptions() {
  return { style: undefined, varyColors: undefined };
}
var RadarOptions = {
  encode(message, writer = new BinaryWriter) {
    if (message.style !== undefined) {
      writer.uint32(8).int32(message.style);
    }
    if (message.varyColors !== undefined) {
      writer.uint32(16).bool(message.varyColors);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseRadarOptions();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.style = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.varyColors = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return RadarOptions.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseRadarOptions();
    message.style = object.style ?? undefined;
    message.varyColors = object.varyColors ?? undefined;
    return message;
  }
};
function createBaseSurfaceOptions() {
  return { wireframe: undefined };
}
var SurfaceOptions = {
  encode(message, writer = new BinaryWriter) {
    if (message.wireframe !== undefined) {
      writer.uint32(8).bool(message.wireframe);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseSurfaceOptions();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.wireframe = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return SurfaceOptions.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseSurfaceOptions();
    message.wireframe = object.wireframe ?? undefined;
    return message;
  }
};
function createBaseDataPoint() {
  return { idx: 0, fill: undefined, stroke: undefined, explosion: undefined };
}
var DataPoint = {
  encode(message, writer = new BinaryWriter) {
    if (message.idx !== 0) {
      writer.uint32(8).int32(message.idx);
    }
    if (message.fill !== undefined) {
      Fill.encode(message.fill, writer.uint32(18).fork()).join();
    }
    if (message.stroke !== undefined) {
      Line.encode(message.stroke, writer.uint32(26).fork()).join();
    }
    if (message.explosion !== undefined) {
      writer.uint32(32).uint32(message.explosion);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseDataPoint();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.idx = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.fill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.stroke = Line.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.explosion = reader.uint32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return DataPoint.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseDataPoint();
    message.idx = object.idx ?? 0;
    message.fill = object.fill !== undefined && object.fill !== null ? Fill.fromPartial(object.fill) : undefined;
    message.stroke = object.stroke !== undefined && object.stroke !== null ? Line.fromPartial(object.stroke) : undefined;
    message.explosion = object.explosion ?? undefined;
    return message;
  }
};
function createBaseAxis() {
  return {
    textStyle: undefined,
    line: undefined,
    min: undefined,
    max: undefined,
    majorGridlines: undefined,
    minorGridlines: undefined,
    numberFormatCode: undefined,
    numberFormatSourceLinked: undefined,
    majorUnit: undefined,
    minorUnit: undefined,
    position: undefined,
    orientation: undefined,
    majorTickMark: undefined,
    minorTickMark: undefined,
    tickLabelPosition: undefined,
    crossBetween: undefined,
    crosses: undefined,
    crossValue: undefined,
    deleted: undefined,
    title: undefined,
    titleTextStyle: undefined
  };
}
var Axis = {
  encode(message, writer = new BinaryWriter) {
    if (message.textStyle !== undefined) {
      TextStyle.encode(message.textStyle, writer.uint32(10).fork()).join();
    }
    if (message.line !== undefined) {
      Line.encode(message.line, writer.uint32(18).fork()).join();
    }
    if (message.min !== undefined) {
      writer.uint32(25).double(message.min);
    }
    if (message.max !== undefined) {
      writer.uint32(33).double(message.max);
    }
    if (message.majorGridlines !== undefined) {
      Line.encode(message.majorGridlines, writer.uint32(42).fork()).join();
    }
    if (message.minorGridlines !== undefined) {
      Line.encode(message.minorGridlines, writer.uint32(50).fork()).join();
    }
    if (message.numberFormatCode !== undefined) {
      writer.uint32(58).string(message.numberFormatCode);
    }
    if (message.numberFormatSourceLinked !== undefined) {
      writer.uint32(168).bool(message.numberFormatSourceLinked);
    }
    if (message.majorUnit !== undefined) {
      writer.uint32(65).double(message.majorUnit);
    }
    if (message.minorUnit !== undefined) {
      writer.uint32(73).double(message.minorUnit);
    }
    if (message.position !== undefined) {
      writer.uint32(80).int32(message.position);
    }
    if (message.orientation !== undefined) {
      writer.uint32(88).int32(message.orientation);
    }
    if (message.majorTickMark !== undefined) {
      writer.uint32(96).int32(message.majorTickMark);
    }
    if (message.minorTickMark !== undefined) {
      writer.uint32(104).int32(message.minorTickMark);
    }
    if (message.tickLabelPosition !== undefined) {
      writer.uint32(112).int32(message.tickLabelPosition);
    }
    if (message.crossBetween !== undefined) {
      writer.uint32(120).int32(message.crossBetween);
    }
    if (message.crosses !== undefined) {
      writer.uint32(128).int32(message.crosses);
    }
    if (message.crossValue !== undefined) {
      writer.uint32(137).double(message.crossValue);
    }
    if (message.deleted !== undefined) {
      writer.uint32(144).bool(message.deleted);
    }
    if (message.title !== undefined) {
      writer.uint32(154).string(message.title);
    }
    if (message.titleTextStyle !== undefined) {
      TextStyle.encode(message.titleTextStyle, writer.uint32(162).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseAxis();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.textStyle = TextStyle.decode(reader, reader.uint32());
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.line = Line.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 25) {
            break;
          }
          message.min = reader.double();
          continue;
        }
        case 4: {
          if (tag !== 33) {
            break;
          }
          message.max = reader.double();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.majorGridlines = Line.decode(reader, reader.uint32());
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.minorGridlines = Line.decode(reader, reader.uint32());
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.numberFormatCode = reader.string();
          continue;
        }
        case 21: {
          if (tag !== 168) {
            break;
          }
          message.numberFormatSourceLinked = reader.bool();
          continue;
        }
        case 8: {
          if (tag !== 65) {
            break;
          }
          message.majorUnit = reader.double();
          continue;
        }
        case 9: {
          if (tag !== 73) {
            break;
          }
          message.minorUnit = reader.double();
          continue;
        }
        case 10: {
          if (tag !== 80) {
            break;
          }
          message.position = reader.int32();
          continue;
        }
        case 11: {
          if (tag !== 88) {
            break;
          }
          message.orientation = reader.int32();
          continue;
        }
        case 12: {
          if (tag !== 96) {
            break;
          }
          message.majorTickMark = reader.int32();
          continue;
        }
        case 13: {
          if (tag !== 104) {
            break;
          }
          message.minorTickMark = reader.int32();
          continue;
        }
        case 14: {
          if (tag !== 112) {
            break;
          }
          message.tickLabelPosition = reader.int32();
          continue;
        }
        case 15: {
          if (tag !== 120) {
            break;
          }
          message.crossBetween = reader.int32();
          continue;
        }
        case 16: {
          if (tag !== 128) {
            break;
          }
          message.crosses = reader.int32();
          continue;
        }
        case 17: {
          if (tag !== 137) {
            break;
          }
          message.crossValue = reader.double();
          continue;
        }
        case 18: {
          if (tag !== 144) {
            break;
          }
          message.deleted = reader.bool();
          continue;
        }
        case 19: {
          if (tag !== 154) {
            break;
          }
          message.title = reader.string();
          continue;
        }
        case 20: {
          if (tag !== 162) {
            break;
          }
          message.titleTextStyle = TextStyle.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Axis.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseAxis();
    message.textStyle = object.textStyle !== undefined && object.textStyle !== null ? TextStyle.fromPartial(object.textStyle) : undefined;
    message.line = object.line !== undefined && object.line !== null ? Line.fromPartial(object.line) : undefined;
    message.min = object.min ?? undefined;
    message.max = object.max ?? undefined;
    message.majorGridlines = object.majorGridlines !== undefined && object.majorGridlines !== null ? Line.fromPartial(object.majorGridlines) : undefined;
    message.minorGridlines = object.minorGridlines !== undefined && object.minorGridlines !== null ? Line.fromPartial(object.minorGridlines) : undefined;
    message.numberFormatCode = object.numberFormatCode ?? undefined;
    message.numberFormatSourceLinked = object.numberFormatSourceLinked ?? undefined;
    message.majorUnit = object.majorUnit ?? undefined;
    message.minorUnit = object.minorUnit ?? undefined;
    message.position = object.position ?? undefined;
    message.orientation = object.orientation ?? undefined;
    message.majorTickMark = object.majorTickMark ?? undefined;
    message.minorTickMark = object.minorTickMark ?? undefined;
    message.tickLabelPosition = object.tickLabelPosition ?? undefined;
    message.crossBetween = object.crossBetween ?? undefined;
    message.crosses = object.crosses ?? undefined;
    message.crossValue = object.crossValue ?? undefined;
    message.deleted = object.deleted ?? undefined;
    message.title = object.title ?? undefined;
    message.titleTextStyle = object.titleTextStyle !== undefined && object.titleTextStyle !== null ? TextStyle.fromPartial(object.titleTextStyle) : undefined;
    return message;
  }
};
function createBaseDataLabels() {
  return {
    showValue: false,
    position: 0,
    textStyle: undefined,
    leaderLine: undefined,
    fill: undefined,
    stroke: undefined,
    showCategoryName: false,
    showSeriesName: false,
    showLegendKey: false,
    showPercent: false,
    showBubbleSize: false,
    showLeaderLines: false,
    showFlagsPresentMask: undefined,
    showDataLabelsRange: undefined,
    dataLabelsRangeFormula: undefined
  };
}
var DataLabels = {
  encode(message, writer = new BinaryWriter) {
    if (message.showValue !== false) {
      writer.uint32(8).bool(message.showValue);
    }
    if (message.position !== 0) {
      writer.uint32(16).int32(message.position);
    }
    if (message.textStyle !== undefined) {
      TextStyle.encode(message.textStyle, writer.uint32(26).fork()).join();
    }
    if (message.leaderLine !== undefined) {
      Line.encode(message.leaderLine, writer.uint32(34).fork()).join();
    }
    if (message.fill !== undefined) {
      Fill.encode(message.fill, writer.uint32(42).fork()).join();
    }
    if (message.stroke !== undefined) {
      Line.encode(message.stroke, writer.uint32(50).fork()).join();
    }
    if (message.showCategoryName !== false) {
      writer.uint32(56).bool(message.showCategoryName);
    }
    if (message.showSeriesName !== false) {
      writer.uint32(64).bool(message.showSeriesName);
    }
    if (message.showLegendKey !== false) {
      writer.uint32(72).bool(message.showLegendKey);
    }
    if (message.showPercent !== false) {
      writer.uint32(80).bool(message.showPercent);
    }
    if (message.showBubbleSize !== false) {
      writer.uint32(88).bool(message.showBubbleSize);
    }
    if (message.showLeaderLines !== false) {
      writer.uint32(96).bool(message.showLeaderLines);
    }
    if (message.showFlagsPresentMask !== undefined) {
      writer.uint32(120).uint32(message.showFlagsPresentMask);
    }
    if (message.showDataLabelsRange !== undefined) {
      writer.uint32(104).bool(message.showDataLabelsRange);
    }
    if (message.dataLabelsRangeFormula !== undefined) {
      writer.uint32(114).string(message.dataLabelsRangeFormula);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseDataLabels();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.showValue = reader.bool();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.position = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.textStyle = TextStyle.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.leaderLine = Line.decode(reader, reader.uint32());
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.fill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.stroke = Line.decode(reader, reader.uint32());
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.showCategoryName = reader.bool();
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.showSeriesName = reader.bool();
          continue;
        }
        case 9: {
          if (tag !== 72) {
            break;
          }
          message.showLegendKey = reader.bool();
          continue;
        }
        case 10: {
          if (tag !== 80) {
            break;
          }
          message.showPercent = reader.bool();
          continue;
        }
        case 11: {
          if (tag !== 88) {
            break;
          }
          message.showBubbleSize = reader.bool();
          continue;
        }
        case 12: {
          if (tag !== 96) {
            break;
          }
          message.showLeaderLines = reader.bool();
          continue;
        }
        case 15: {
          if (tag !== 120) {
            break;
          }
          message.showFlagsPresentMask = reader.uint32();
          continue;
        }
        case 13: {
          if (tag !== 104) {
            break;
          }
          message.showDataLabelsRange = reader.bool();
          continue;
        }
        case 14: {
          if (tag !== 114) {
            break;
          }
          message.dataLabelsRangeFormula = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return DataLabels.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseDataLabels();
    message.showValue = object.showValue ?? false;
    message.position = object.position ?? 0;
    message.textStyle = object.textStyle !== undefined && object.textStyle !== null ? TextStyle.fromPartial(object.textStyle) : undefined;
    message.leaderLine = object.leaderLine !== undefined && object.leaderLine !== null ? Line.fromPartial(object.leaderLine) : undefined;
    message.fill = object.fill !== undefined && object.fill !== null ? Fill.fromPartial(object.fill) : undefined;
    message.stroke = object.stroke !== undefined && object.stroke !== null ? Line.fromPartial(object.stroke) : undefined;
    message.showCategoryName = object.showCategoryName ?? false;
    message.showSeriesName = object.showSeriesName ?? false;
    message.showLegendKey = object.showLegendKey ?? false;
    message.showPercent = object.showPercent ?? false;
    message.showBubbleSize = object.showBubbleSize ?? false;
    message.showLeaderLines = object.showLeaderLines ?? false;
    message.showFlagsPresentMask = object.showFlagsPresentMask ?? undefined;
    message.showDataLabelsRange = object.showDataLabelsRange ?? undefined;
    message.dataLabelsRangeFormula = object.dataLabelsRangeFormula ?? undefined;
    return message;
  }
};
function createBaseDataLabel() {
  return {
    idx: 0,
    text: undefined,
    position: undefined,
    textStyle: undefined,
    fill: undefined,
    stroke: undefined,
    showValue: undefined,
    showCategoryName: undefined,
    showSeriesName: undefined,
    showLegendKey: undefined,
    showPercent: undefined,
    showBubbleSize: undefined
  };
}
var DataLabel = {
  encode(message, writer = new BinaryWriter) {
    if (message.idx !== 0) {
      writer.uint32(8).int32(message.idx);
    }
    if (message.text !== undefined) {
      writer.uint32(18).string(message.text);
    }
    if (message.position !== undefined) {
      writer.uint32(24).int32(message.position);
    }
    if (message.textStyle !== undefined) {
      TextStyle.encode(message.textStyle, writer.uint32(34).fork()).join();
    }
    if (message.fill !== undefined) {
      Fill.encode(message.fill, writer.uint32(42).fork()).join();
    }
    if (message.stroke !== undefined) {
      Line.encode(message.stroke, writer.uint32(50).fork()).join();
    }
    if (message.showValue !== undefined) {
      writer.uint32(56).bool(message.showValue);
    }
    if (message.showCategoryName !== undefined) {
      writer.uint32(64).bool(message.showCategoryName);
    }
    if (message.showSeriesName !== undefined) {
      writer.uint32(72).bool(message.showSeriesName);
    }
    if (message.showLegendKey !== undefined) {
      writer.uint32(80).bool(message.showLegendKey);
    }
    if (message.showPercent !== undefined) {
      writer.uint32(88).bool(message.showPercent);
    }
    if (message.showBubbleSize !== undefined) {
      writer.uint32(96).bool(message.showBubbleSize);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseDataLabel();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.idx = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.text = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.position = reader.int32();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.textStyle = TextStyle.decode(reader, reader.uint32());
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.fill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.stroke = Line.decode(reader, reader.uint32());
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.showValue = reader.bool();
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.showCategoryName = reader.bool();
          continue;
        }
        case 9: {
          if (tag !== 72) {
            break;
          }
          message.showSeriesName = reader.bool();
          continue;
        }
        case 10: {
          if (tag !== 80) {
            break;
          }
          message.showLegendKey = reader.bool();
          continue;
        }
        case 11: {
          if (tag !== 88) {
            break;
          }
          message.showPercent = reader.bool();
          continue;
        }
        case 12: {
          if (tag !== 96) {
            break;
          }
          message.showBubbleSize = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return DataLabel.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseDataLabel();
    message.idx = object.idx ?? 0;
    message.text = object.text ?? undefined;
    message.position = object.position ?? undefined;
    message.textStyle = object.textStyle !== undefined && object.textStyle !== null ? TextStyle.fromPartial(object.textStyle) : undefined;
    message.fill = object.fill !== undefined && object.fill !== null ? Fill.fromPartial(object.fill) : undefined;
    message.stroke = object.stroke !== undefined && object.stroke !== null ? Line.fromPartial(object.stroke) : undefined;
    message.showValue = object.showValue ?? undefined;
    message.showCategoryName = object.showCategoryName ?? undefined;
    message.showSeriesName = object.showSeriesName ?? undefined;
    message.showLegendKey = object.showLegendKey ?? undefined;
    message.showPercent = object.showPercent ?? undefined;
    message.showBubbleSize = object.showBubbleSize ?? undefined;
    return message;
  }
};
function createBaseMapChartOptions() {
  return {
    mapArea: undefined,
    projection: undefined,
    labelLayout: undefined,
    dataLevel: undefined,
    showUnknown: undefined,
    onlyRegionsWithData: undefined,
    regionFilter: undefined,
    colorScale: [],
    buckets: undefined,
    classification: undefined,
    colorScaleEx: undefined
  };
}
var MapChartOptions = {
  encode(message, writer = new BinaryWriter) {
    if (message.mapArea !== undefined) {
      writer.uint32(8).int32(message.mapArea);
    }
    if (message.projection !== undefined) {
      writer.uint32(16).int32(message.projection);
    }
    if (message.labelLayout !== undefined) {
      writer.uint32(24).int32(message.labelLayout);
    }
    if (message.dataLevel !== undefined) {
      writer.uint32(32).int32(message.dataLevel);
    }
    if (message.showUnknown !== undefined) {
      writer.uint32(40).bool(message.showUnknown);
    }
    if (message.onlyRegionsWithData !== undefined) {
      writer.uint32(48).bool(message.onlyRegionsWithData);
    }
    if (message.regionFilter !== undefined) {
      writer.uint32(58).string(message.regionFilter);
    }
    for (const v of message.colorScale) {
      Color.encode(v, writer.uint32(66).fork()).join();
    }
    if (message.buckets !== undefined) {
      writer.uint32(72).int32(message.buckets);
    }
    if (message.classification !== undefined) {
      writer.uint32(80).int32(message.classification);
    }
    if (message.colorScaleEx !== undefined) {
      ColorScale.encode(message.colorScaleEx, writer.uint32(90).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseMapChartOptions();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.mapArea = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.projection = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.labelLayout = reader.int32();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.dataLevel = reader.int32();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.showUnknown = reader.bool();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.onlyRegionsWithData = reader.bool();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.regionFilter = reader.string();
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.colorScale.push(Color.decode(reader, reader.uint32()));
          continue;
        }
        case 9: {
          if (tag !== 72) {
            break;
          }
          message.buckets = reader.int32();
          continue;
        }
        case 10: {
          if (tag !== 80) {
            break;
          }
          message.classification = reader.int32();
          continue;
        }
        case 11: {
          if (tag !== 90) {
            break;
          }
          message.colorScaleEx = ColorScale.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return MapChartOptions.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseMapChartOptions();
    message.mapArea = object.mapArea ?? undefined;
    message.projection = object.projection ?? undefined;
    message.labelLayout = object.labelLayout ?? undefined;
    message.dataLevel = object.dataLevel ?? undefined;
    message.showUnknown = object.showUnknown ?? undefined;
    message.onlyRegionsWithData = object.onlyRegionsWithData ?? undefined;
    message.regionFilter = object.regionFilter ?? undefined;
    message.colorScale = object.colorScale?.map((e) => Color.fromPartial(e)) || [];
    message.buckets = object.buckets ?? undefined;
    message.classification = object.classification ?? undefined;
    message.colorScaleEx = object.colorScaleEx !== undefined && object.colorScaleEx !== null ? ColorScale.fromPartial(object.colorScaleEx) : undefined;
    return message;
  }
};
function createBaseCategoryPath() {
  return { levels: [] };
}
var CategoryPath = {
  encode(message, writer = new BinaryWriter) {
    for (const v of message.levels) {
      writer.uint32(10).string(v);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCategoryPath();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.levels.push(reader.string());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CategoryPath.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCategoryPath();
    message.levels = object.levels?.map((e) => e) || [];
    return message;
  }
};
function createBaseTreemapOptions() {
  return { parentLabelLayout: undefined };
}
var TreemapOptions = {
  encode(message, writer = new BinaryWriter) {
    if (message.parentLabelLayout !== undefined) {
      writer.uint32(8).int32(message.parentLabelLayout);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTreemapOptions();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.parentLabelLayout = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TreemapOptions.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTreemapOptions();
    message.parentLabelLayout = object.parentLabelLayout ?? undefined;
    return message;
  }
};
function createBaseBoxWhiskerOptions() {
  return {
    showMeanLine: undefined,
    showMeanMarker: undefined,
    showNonOutliers: undefined,
    showOutliers: undefined,
    quartileMethod: undefined
  };
}
var BoxWhiskerOptions = {
  encode(message, writer = new BinaryWriter) {
    if (message.showMeanLine !== undefined) {
      writer.uint32(8).bool(message.showMeanLine);
    }
    if (message.showMeanMarker !== undefined) {
      writer.uint32(16).bool(message.showMeanMarker);
    }
    if (message.showNonOutliers !== undefined) {
      writer.uint32(24).bool(message.showNonOutliers);
    }
    if (message.showOutliers !== undefined) {
      writer.uint32(32).bool(message.showOutliers);
    }
    if (message.quartileMethod !== undefined) {
      writer.uint32(40).int32(message.quartileMethod);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseBoxWhiskerOptions();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.showMeanLine = reader.bool();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.showMeanMarker = reader.bool();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.showNonOutliers = reader.bool();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.showOutliers = reader.bool();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.quartileMethod = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return BoxWhiskerOptions.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseBoxWhiskerOptions();
    message.showMeanLine = object.showMeanLine ?? undefined;
    message.showMeanMarker = object.showMeanMarker ?? undefined;
    message.showNonOutliers = object.showNonOutliers ?? undefined;
    message.showOutliers = object.showOutliers ?? undefined;
    message.quartileMethod = object.quartileMethod ?? undefined;
    return message;
  }
};
function createBaseHistogramOptions() {
  return {
    intervalClosed: undefined,
    binWidth: undefined,
    binCount: undefined,
    underflow: undefined,
    overflow: undefined,
    aggregated: undefined
  };
}
var HistogramOptions = {
  encode(message, writer = new BinaryWriter) {
    if (message.intervalClosed !== undefined) {
      writer.uint32(8).int32(message.intervalClosed);
    }
    if (message.binWidth !== undefined) {
      writer.uint32(17).double(message.binWidth);
    }
    if (message.binCount !== undefined) {
      writer.uint32(24).uint32(message.binCount);
    }
    if (message.underflow !== undefined) {
      writer.uint32(33).double(message.underflow);
    }
    if (message.overflow !== undefined) {
      writer.uint32(41).double(message.overflow);
    }
    if (message.aggregated !== undefined) {
      writer.uint32(48).bool(message.aggregated);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseHistogramOptions();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.intervalClosed = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 17) {
            break;
          }
          message.binWidth = reader.double();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.binCount = reader.uint32();
          continue;
        }
        case 4: {
          if (tag !== 33) {
            break;
          }
          message.underflow = reader.double();
          continue;
        }
        case 5: {
          if (tag !== 41) {
            break;
          }
          message.overflow = reader.double();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.aggregated = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return HistogramOptions.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseHistogramOptions();
    message.intervalClosed = object.intervalClosed ?? undefined;
    message.binWidth = object.binWidth ?? undefined;
    message.binCount = object.binCount ?? undefined;
    message.underflow = object.underflow ?? undefined;
    message.overflow = object.overflow ?? undefined;
    message.aggregated = object.aggregated ?? undefined;
    return message;
  }
};
function createBaseWaterfallOptions() {
  return { subtotalIndices: [] };
}
var WaterfallOptions = {
  encode(message, writer = new BinaryWriter) {
    writer.uint32(10).fork();
    for (const v of message.subtotalIndices) {
      writer.uint32(v);
    }
    writer.join();
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseWaterfallOptions();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag === 8) {
            message.subtotalIndices.push(reader.uint32());
            continue;
          }
          if (tag === 10) {
            const end2 = reader.uint32() + reader.pos;
            while (reader.pos < end2) {
              message.subtotalIndices.push(reader.uint32());
            }
            continue;
          }
          break;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return WaterfallOptions.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseWaterfallOptions();
    message.subtotalIndices = object.subtotalIndices?.map((e) => e) || [];
    return message;
  }
};
function createBaseFunnelOptions() {
  return { gapWidth: undefined };
}
var FunnelOptions = {
  encode(message, writer = new BinaryWriter) {
    if (message.gapWidth !== undefined) {
      writer.uint32(9).double(message.gapWidth);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseFunnelOptions();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 9) {
            break;
          }
          message.gapWidth = reader.double();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return FunnelOptions.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseFunnelOptions();
    message.gapWidth = object.gapWidth ?? undefined;
    return message;
  }
};
function createBaseChartStyleRef() {
  return { styleId: undefined, colorStyleId: undefined, palette: [], themeName: undefined };
}
var ChartStyleRef = {
  encode(message, writer = new BinaryWriter) {
    if (message.styleId !== undefined) {
      writer.uint32(8).int32(message.styleId);
    }
    if (message.colorStyleId !== undefined) {
      writer.uint32(16).int32(message.colorStyleId);
    }
    for (const v of message.palette) {
      Color.encode(v, writer.uint32(26).fork()).join();
    }
    if (message.themeName !== undefined) {
      writer.uint32(34).string(message.themeName);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseChartStyleRef();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.styleId = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.colorStyleId = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.palette.push(Color.decode(reader, reader.uint32()));
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.themeName = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ChartStyleRef.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseChartStyleRef();
    message.styleId = object.styleId ?? undefined;
    message.colorStyleId = object.colorStyleId ?? undefined;
    message.palette = object.palette?.map((e) => Color.fromPartial(e)) || [];
    message.themeName = object.themeName ?? undefined;
    return message;
  }
};
function createBaseColorScale() {
  return { type: undefined, colors: [] };
}
var ColorScale = {
  encode(message, writer = new BinaryWriter) {
    if (message.type !== undefined) {
      writer.uint32(8).int32(message.type);
    }
    for (const v of message.colors) {
      Color.encode(v, writer.uint32(18).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseColorScale();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.type = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.colors.push(Color.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ColorScale.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseColorScale();
    message.type = object.type ?? undefined;
    message.colors = object.colors?.map((e) => Color.fromPartial(e)) || [];
    return message;
  }
};
function createBasePivotChartBinding() {
  return {
    pivotTableQualifiedName: "",
    pivotTableName: undefined,
    pivotCacheId: undefined,
    fmtId: undefined,
    pivotTableId: undefined
  };
}
var PivotChartBinding = {
  encode(message, writer = new BinaryWriter) {
    if (message.pivotTableQualifiedName !== "") {
      writer.uint32(10).string(message.pivotTableQualifiedName);
    }
    if (message.pivotTableName !== undefined) {
      writer.uint32(18).string(message.pivotTableName);
    }
    if (message.pivotCacheId !== undefined) {
      writer.uint32(24).uint32(message.pivotCacheId);
    }
    if (message.fmtId !== undefined) {
      writer.uint32(32).uint32(message.fmtId);
    }
    if (message.pivotTableId !== undefined) {
      writer.uint32(42).string(message.pivotTableId);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePivotChartBinding();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.pivotTableQualifiedName = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.pivotTableName = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.pivotCacheId = reader.uint32();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.fmtId = reader.uint32();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.pivotTableId = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PivotChartBinding.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePivotChartBinding();
    message.pivotTableQualifiedName = object.pivotTableQualifiedName ?? "";
    message.pivotTableName = object.pivotTableName ?? undefined;
    message.pivotCacheId = object.pivotCacheId ?? undefined;
    message.fmtId = object.fmtId ?? undefined;
    message.pivotTableId = object.pivotTableId ?? undefined;
    return message;
  }
};
function createBasePivotChartOptions() {
  return {
    dropZonesVisible: undefined,
    showFilterButtons: undefined,
    showCategoryButtons: undefined,
    showDataButtons: undefined,
    showSeriesButtons: undefined
  };
}
var PivotChartOptions = {
  encode(message, writer = new BinaryWriter) {
    if (message.dropZonesVisible !== undefined) {
      writer.uint32(8).bool(message.dropZonesVisible);
    }
    if (message.showFilterButtons !== undefined) {
      writer.uint32(16).bool(message.showFilterButtons);
    }
    if (message.showCategoryButtons !== undefined) {
      writer.uint32(24).bool(message.showCategoryButtons);
    }
    if (message.showDataButtons !== undefined) {
      writer.uint32(32).bool(message.showDataButtons);
    }
    if (message.showSeriesButtons !== undefined) {
      writer.uint32(40).bool(message.showSeriesButtons);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePivotChartOptions();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.dropZonesVisible = reader.bool();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.showFilterButtons = reader.bool();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.showCategoryButtons = reader.bool();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.showDataButtons = reader.bool();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.showSeriesButtons = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PivotChartOptions.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePivotChartOptions();
    message.dropZonesVisible = object.dropZonesVisible ?? undefined;
    message.showFilterButtons = object.showFilterButtons ?? undefined;
    message.showCategoryButtons = object.showCategoryButtons ?? undefined;
    message.showDataButtons = object.showDataButtons ?? undefined;
    message.showSeriesButtons = object.showSeriesButtons ?? undefined;
    return message;
  }
};
function createBasePivotChartFormat() {
  return { idx: 0, fill: undefined, stroke: undefined, text: undefined };
}
var PivotChartFormat = {
  encode(message, writer = new BinaryWriter) {
    if (message.idx !== 0) {
      writer.uint32(8).uint32(message.idx);
    }
    if (message.fill !== undefined) {
      Fill.encode(message.fill, writer.uint32(18).fork()).join();
    }
    if (message.stroke !== undefined) {
      Line.encode(message.stroke, writer.uint32(26).fork()).join();
    }
    if (message.text !== undefined) {
      TextStyle.encode(message.text, writer.uint32(34).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePivotChartFormat();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.idx = reader.uint32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.fill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.stroke = Line.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.text = TextStyle.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PivotChartFormat.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePivotChartFormat();
    message.idx = object.idx ?? 0;
    message.fill = object.fill !== undefined && object.fill !== null ? Fill.fromPartial(object.fill) : undefined;
    message.stroke = object.stroke !== undefined && object.stroke !== null ? Line.fromPartial(object.stroke) : undefined;
    message.text = object.text !== undefined && object.text !== null ? TextStyle.fromPartial(object.text) : undefined;
    return message;
  }
};
function createBaseMarker() {
  return { symbol: undefined, size: undefined };
}
var Marker = {
  encode(message, writer = new BinaryWriter) {
    if (message.symbol !== undefined) {
      writer.uint32(8).int32(message.symbol);
    }
    if (message.size !== undefined) {
      writer.uint32(16).uint32(message.size);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseMarker();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.symbol = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.size = reader.uint32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Marker.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseMarker();
    message.symbol = object.symbol ?? undefined;
    message.size = object.size ?? undefined;
    return message;
  }
};
function createBaseView3D() {
  return { rotX: undefined, rotY: undefined, rightAngleAxes: undefined, perspective: undefined };
}
var View3D = {
  encode(message, writer = new BinaryWriter) {
    if (message.rotX !== undefined) {
      writer.uint32(8).int32(message.rotX);
    }
    if (message.rotY !== undefined) {
      writer.uint32(16).int32(message.rotY);
    }
    if (message.rightAngleAxes !== undefined) {
      writer.uint32(24).bool(message.rightAngleAxes);
    }
    if (message.perspective !== undefined) {
      writer.uint32(32).uint32(message.perspective);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseView3D();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.rotX = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.rotY = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.rightAngleAxes = reader.bool();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.perspective = reader.uint32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return View3D.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseView3D();
    message.rotX = object.rotX ?? undefined;
    message.rotY = object.rotY ?? undefined;
    message.rightAngleAxes = object.rightAngleAxes ?? undefined;
    message.perspective = object.perspective ?? undefined;
    return message;
  }
};

// node_modules/@oai/walnut/generated/oaiproto/coworker/pptx/presentation.ts
function createBasePresentation() {
  return {
    id: undefined,
    slides: [],
    theme: undefined,
    layouts: [],
    charts: [],
    images: [],
    contentReferences: [],
    people: [],
    threads: [],
    textStyles: [],
    tableStyles: undefined
  };
}
var Presentation = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== undefined) {
      writer.uint32(82).string(message.id);
    }
    for (const v of message.slides) {
      Slide.encode(v, writer.uint32(10).fork()).join();
    }
    if (message.theme !== undefined) {
      Theme.encode(message.theme, writer.uint32(18).fork()).join();
    }
    for (const v of message.layouts) {
      Layout.encode(v, writer.uint32(26).fork()).join();
    }
    for (const v of message.charts) {
      Chart.encode(v, writer.uint32(74).fork()).join();
    }
    for (const v of message.images) {
      Image.encode(v, writer.uint32(34).fork()).join();
    }
    for (const v of message.contentReferences) {
      ContentReference.encode(v, writer.uint32(42).fork()).join();
    }
    for (const v of message.people) {
      Person.encode(v, writer.uint32(90).fork()).join();
    }
    for (const v of message.threads) {
      Thread.encode(v, writer.uint32(98).fork()).join();
    }
    for (const v of message.textStyles) {
      TextStyleDefinition.encode(v, writer.uint32(50).fork()).join();
    }
    if (message.tableStyles !== undefined) {
      TableStyles.encode(message.tableStyles, writer.uint32(58).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePresentation();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.slides.push(Slide.decode(reader, reader.uint32()));
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.theme = Theme.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.layouts.push(Layout.decode(reader, reader.uint32()));
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.charts.push(Chart.decode(reader, reader.uint32()));
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.images.push(Image.decode(reader, reader.uint32()));
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.contentReferences.push(ContentReference.decode(reader, reader.uint32()));
          continue;
        }
        case 11: {
          if (tag !== 90) {
            break;
          }
          message.people.push(Person.decode(reader, reader.uint32()));
          continue;
        }
        case 12: {
          if (tag !== 98) {
            break;
          }
          message.threads.push(Thread.decode(reader, reader.uint32()));
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.textStyles.push(TextStyleDefinition.decode(reader, reader.uint32()));
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.tableStyles = TableStyles.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Presentation.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePresentation();
    message.id = object.id ?? undefined;
    message.slides = object.slides?.map((e) => Slide.fromPartial(e)) || [];
    message.theme = object.theme !== undefined && object.theme !== null ? Theme.fromPartial(object.theme) : undefined;
    message.layouts = object.layouts?.map((e) => Layout.fromPartial(e)) || [];
    message.charts = object.charts?.map((e) => Chart.fromPartial(e)) || [];
    message.images = object.images?.map((e) => Image.fromPartial(e)) || [];
    message.contentReferences = object.contentReferences?.map((e) => ContentReference.fromPartial(e)) || [];
    message.people = object.people?.map((e) => Person.fromPartial(e)) || [];
    message.threads = object.threads?.map((e) => Thread.fromPartial(e)) || [];
    message.textStyles = object.textStyles?.map((e) => TextStyleDefinition.fromPartial(e)) || [];
    message.tableStyles = object.tableStyles !== undefined && object.tableStyles !== null ? TableStyles.fromPartial(object.tableStyles) : undefined;
    return message;
  }
};
function createBaseTheme() {
  return { colorScheme: undefined, backgroundFillStyleList: [], lineStyleList: [], effectStyleList: [] };
}
var Theme = {
  encode(message, writer = new BinaryWriter) {
    if (message.colorScheme !== undefined) {
      ColorScheme.encode(message.colorScheme, writer.uint32(10).fork()).join();
    }
    for (const v of message.backgroundFillStyleList) {
      Fill.encode(v, writer.uint32(18).fork()).join();
    }
    for (const v of message.lineStyleList) {
      Line.encode(v, writer.uint32(26).fork()).join();
    }
    for (const v of message.effectStyleList) {
      EffectStyle.encode(v, writer.uint32(34).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTheme();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.colorScheme = ColorScheme.decode(reader, reader.uint32());
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.backgroundFillStyleList.push(Fill.decode(reader, reader.uint32()));
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.lineStyleList.push(Line.decode(reader, reader.uint32()));
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.effectStyleList.push(EffectStyle.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Theme.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTheme();
    message.colorScheme = object.colorScheme !== undefined && object.colorScheme !== null ? ColorScheme.fromPartial(object.colorScheme) : undefined;
    message.backgroundFillStyleList = object.backgroundFillStyleList?.map((e) => Fill.fromPartial(e)) || [];
    message.lineStyleList = object.lineStyleList?.map((e) => Line.fromPartial(e)) || [];
    message.effectStyleList = object.effectStyleList?.map((e) => EffectStyle.fromPartial(e)) || [];
    return message;
  }
};
function createBaseColorScheme() {
  return { name: "", colors: [] };
}
var ColorScheme = {
  encode(message, writer = new BinaryWriter) {
    if (message.name !== "") {
      writer.uint32(10).string(message.name);
    }
    for (const v of message.colors) {
      ThemeColor.encode(v, writer.uint32(18).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseColorScheme();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.colors.push(ThemeColor.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ColorScheme.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseColorScheme();
    message.name = object.name ?? "";
    message.colors = object.colors?.map((e) => ThemeColor.fromPartial(e)) || [];
    return message;
  }
};
function createBaseThemeColor() {
  return { name: "", color: undefined };
}
var ThemeColor = {
  encode(message, writer = new BinaryWriter) {
    if (message.name !== "") {
      writer.uint32(10).string(message.name);
    }
    if (message.color !== undefined) {
      Color.encode(message.color, writer.uint32(18).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseThemeColor();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.color = Color.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ThemeColor.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseThemeColor();
    message.name = object.name ?? "";
    message.color = object.color !== undefined && object.color !== null ? Color.fromPartial(object.color) : undefined;
    return message;
  }
};
function createBaseTableStyles() {
  return { defaultStyleId: undefined, outerXml: undefined };
}
var TableStyles = {
  encode(message, writer = new BinaryWriter) {
    if (message.defaultStyleId !== undefined) {
      writer.uint32(10).string(message.defaultStyleId);
    }
    if (message.outerXml !== undefined) {
      writer.uint32(18).string(message.outerXml);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTableStyles();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.defaultStyleId = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.outerXml = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TableStyles.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTableStyles();
    message.defaultStyleId = object.defaultStyleId ?? undefined;
    message.outerXml = object.outerXml ?? undefined;
    return message;
  }
};
function createBaseLayout() {
  return {
    id: "",
    innerXml: undefined,
    outerXml: undefined,
    name: "",
    type: "",
    background: undefined,
    elements: [],
    bodyLevelStyles: [],
    titleLevelStyles: [],
    otherLevelStyles: [],
    parentLayoutId: "",
    colorMap: undefined
  };
}
var Layout = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== "") {
      writer.uint32(10).string(message.id);
    }
    if (message.innerXml !== undefined) {
      writer.uint32(50).string(message.innerXml);
    }
    if (message.outerXml !== undefined) {
      writer.uint32(58).string(message.outerXml);
    }
    if (message.name !== "") {
      writer.uint32(66).string(message.name);
    }
    if (message.type !== "") {
      writer.uint32(74).string(message.type);
    }
    if (message.background !== undefined) {
      Background.encode(message.background, writer.uint32(82).fork()).join();
    }
    for (const v of message.elements) {
      Element.encode(v, writer.uint32(90).fork()).join();
    }
    for (const v of message.bodyLevelStyles) {
      LevelStyle.encode(v, writer.uint32(98).fork()).join();
    }
    for (const v of message.titleLevelStyles) {
      LevelStyle.encode(v, writer.uint32(106).fork()).join();
    }
    for (const v of message.otherLevelStyles) {
      LevelStyle.encode(v, writer.uint32(114).fork()).join();
    }
    if (message.parentLayoutId !== "") {
      writer.uint32(122).string(message.parentLayoutId);
    }
    if (message.colorMap !== undefined) {
      ColorMap.encode(message.colorMap, writer.uint32(130).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseLayout();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.innerXml = reader.string();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.outerXml = reader.string();
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.type = reader.string();
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.background = Background.decode(reader, reader.uint32());
          continue;
        }
        case 11: {
          if (tag !== 90) {
            break;
          }
          message.elements.push(Element.decode(reader, reader.uint32()));
          continue;
        }
        case 12: {
          if (tag !== 98) {
            break;
          }
          message.bodyLevelStyles.push(LevelStyle.decode(reader, reader.uint32()));
          continue;
        }
        case 13: {
          if (tag !== 106) {
            break;
          }
          message.titleLevelStyles.push(LevelStyle.decode(reader, reader.uint32()));
          continue;
        }
        case 14: {
          if (tag !== 114) {
            break;
          }
          message.otherLevelStyles.push(LevelStyle.decode(reader, reader.uint32()));
          continue;
        }
        case 15: {
          if (tag !== 122) {
            break;
          }
          message.parentLayoutId = reader.string();
          continue;
        }
        case 16: {
          if (tag !== 130) {
            break;
          }
          message.colorMap = ColorMap.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Layout.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseLayout();
    message.id = object.id ?? "";
    message.innerXml = object.innerXml ?? undefined;
    message.outerXml = object.outerXml ?? undefined;
    message.name = object.name ?? "";
    message.type = object.type ?? "";
    message.background = object.background !== undefined && object.background !== null ? Background.fromPartial(object.background) : undefined;
    message.elements = object.elements?.map((e) => Element.fromPartial(e)) || [];
    message.bodyLevelStyles = object.bodyLevelStyles?.map((e) => LevelStyle.fromPartial(e)) || [];
    message.titleLevelStyles = object.titleLevelStyles?.map((e) => LevelStyle.fromPartial(e)) || [];
    message.otherLevelStyles = object.otherLevelStyles?.map((e) => LevelStyle.fromPartial(e)) || [];
    message.parentLayoutId = object.parentLayoutId ?? "";
    message.colorMap = object.colorMap !== undefined && object.colorMap !== null ? ColorMap.fromPartial(object.colorMap) : undefined;
    return message;
  }
};
function createBaseSlide() {
  return {
    index: 0,
    useLayoutId: "",
    elements: [],
    widthEmu: 0,
    heightEmu: 0,
    innerXml: undefined,
    outerXml: undefined,
    background: undefined,
    id: "",
    notesSlide: undefined,
    creationId: undefined
  };
}
var Slide = {
  encode(message, writer = new BinaryWriter) {
    if (message.index !== 0) {
      writer.uint32(8).int32(message.index);
    }
    if (message.useLayoutId !== "") {
      writer.uint32(18).string(message.useLayoutId);
    }
    for (const v of message.elements) {
      Element.encode(v, writer.uint32(26).fork()).join();
    }
    if (message.widthEmu !== 0) {
      writer.uint32(40).int64(message.widthEmu);
    }
    if (message.heightEmu !== 0) {
      writer.uint32(48).int64(message.heightEmu);
    }
    if (message.innerXml !== undefined) {
      writer.uint32(58).string(message.innerXml);
    }
    if (message.outerXml !== undefined) {
      writer.uint32(66).string(message.outerXml);
    }
    if (message.background !== undefined) {
      Background.encode(message.background, writer.uint32(82).fork()).join();
    }
    if (message.id !== "") {
      writer.uint32(90).string(message.id);
    }
    if (message.notesSlide !== undefined) {
      Slide.encode(message.notesSlide, writer.uint32(98).fork()).join();
    }
    if (message.creationId !== undefined) {
      writer.uint32(106).string(message.creationId);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseSlide();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.index = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.useLayoutId = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.elements.push(Element.decode(reader, reader.uint32()));
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.widthEmu = longToNumber2(reader.int64());
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.heightEmu = longToNumber2(reader.int64());
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.innerXml = reader.string();
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.outerXml = reader.string();
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.background = Background.decode(reader, reader.uint32());
          continue;
        }
        case 11: {
          if (tag !== 90) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 12: {
          if (tag !== 98) {
            break;
          }
          message.notesSlide = Slide.decode(reader, reader.uint32());
          continue;
        }
        case 13: {
          if (tag !== 106) {
            break;
          }
          message.creationId = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Slide.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseSlide();
    message.index = object.index ?? 0;
    message.useLayoutId = object.useLayoutId ?? "";
    message.elements = object.elements?.map((e) => Element.fromPartial(e)) || [];
    message.widthEmu = object.widthEmu ?? 0;
    message.heightEmu = object.heightEmu ?? 0;
    message.innerXml = object.innerXml ?? undefined;
    message.outerXml = object.outerXml ?? undefined;
    message.background = object.background !== undefined && object.background !== null ? Background.fromPartial(object.background) : undefined;
    message.id = object.id ?? "";
    message.notesSlide = object.notesSlide !== undefined && object.notesSlide !== null ? Slide.fromPartial(object.notesSlide) : undefined;
    message.creationId = object.creationId ?? undefined;
    return message;
  }
};
function createBaseElement() {
  return {
    bbox: undefined,
    zIndex: undefined,
    innerXml: undefined,
    outerXml: undefined,
    shape: undefined,
    image: undefined,
    chartReference: undefined,
    video: undefined,
    table: undefined,
    imageReference: undefined,
    codeBlock: undefined,
    paragraphs: [],
    name: undefined,
    type: 0,
    placeholderIndex: undefined,
    placeholderType: undefined,
    textStyle: undefined,
    effects: [],
    children: [],
    levelsStyles: [],
    fill: undefined,
    line: undefined,
    scene3d: undefined,
    shape3d: undefined,
    imageMask: undefined,
    lineReference: undefined,
    fillReference: undefined,
    effectReference: undefined,
    fontReference: undefined,
    hyperlink: undefined,
    id: "",
    creationId: undefined,
    connector: undefined,
    citations: []
  };
}
var Element = {
  encode(message, writer = new BinaryWriter) {
    if (message.bbox !== undefined) {
      BoundingBox.encode(message.bbox, writer.uint32(10).fork()).join();
    }
    if (message.zIndex !== undefined) {
      writer.uint32(16).int32(message.zIndex);
    }
    if (message.innerXml !== undefined) {
      writer.uint32(58).string(message.innerXml);
    }
    if (message.outerXml !== undefined) {
      writer.uint32(66).string(message.outerXml);
    }
    if (message.shape !== undefined) {
      ShapeElement.encode(message.shape, writer.uint32(34).fork()).join();
    }
    if (message.image !== undefined) {
      ImageElement.encode(message.image, writer.uint32(42).fork()).join();
    }
    if (message.chartReference !== undefined) {
      ChartReference.encode(message.chartReference, writer.uint32(146).fork()).join();
    }
    if (message.video !== undefined) {
      VideoElement.encode(message.video, writer.uint32(162).fork()).join();
    }
    if (message.table !== undefined) {
      TableElement.encode(message.table, writer.uint32(170).fork()).join();
    }
    if (message.imageReference !== undefined) {
      ImageReference.encode(message.imageReference, writer.uint32(26).fork()).join();
    }
    if (message.codeBlock !== undefined) {
      CodeBlockElement.encode(message.codeBlock, writer.uint32(74).fork()).join();
    }
    for (const v of message.paragraphs) {
      Paragraph.encode(v, writer.uint32(50).fork()).join();
    }
    if (message.name !== undefined) {
      writer.uint32(82).string(message.name);
    }
    if (message.type !== 0) {
      writer.uint32(88).int32(message.type);
    }
    if (message.placeholderIndex !== undefined) {
      writer.uint32(96).int32(message.placeholderIndex);
    }
    if (message.placeholderType !== undefined) {
      writer.uint32(106).string(message.placeholderType);
    }
    if (message.textStyle !== undefined) {
      TextStyle.encode(message.textStyle, writer.uint32(114).fork()).join();
    }
    for (const v of message.effects) {
      Effect.encode(v, writer.uint32(122).fork()).join();
    }
    for (const v of message.children) {
      Element.encode(v, writer.uint32(138).fork()).join();
    }
    for (const v of message.levelsStyles) {
      LevelStyle.encode(v, writer.uint32(130).fork()).join();
    }
    if (message.fill !== undefined) {
      Fill.encode(message.fill, writer.uint32(154).fork()).join();
    }
    if (message.line !== undefined) {
      Line.encode(message.line, writer.uint32(242).fork()).join();
    }
    if (message.scene3d !== undefined) {
      Scene3D.encode(message.scene3d, writer.uint32(250).fork()).join();
    }
    if (message.shape3d !== undefined) {
      Shape3D.encode(message.shape3d, writer.uint32(258).fork()).join();
    }
    if (message.imageMask !== undefined) {
      ImageMask.encode(message.imageMask, writer.uint32(266).fork()).join();
    }
    if (message.lineReference !== undefined) {
      StyleReference.encode(message.lineReference, writer.uint32(178).fork()).join();
    }
    if (message.fillReference !== undefined) {
      StyleReference.encode(message.fillReference, writer.uint32(186).fork()).join();
    }
    if (message.effectReference !== undefined) {
      StyleReference.encode(message.effectReference, writer.uint32(194).fork()).join();
    }
    if (message.fontReference !== undefined) {
      StyleReference.encode(message.fontReference, writer.uint32(202).fork()).join();
    }
    if (message.hyperlink !== undefined) {
      Hyperlink.encode(message.hyperlink, writer.uint32(210).fork()).join();
    }
    if (message.id !== "") {
      writer.uint32(218).string(message.id);
    }
    if (message.creationId !== undefined) {
      writer.uint32(274).string(message.creationId);
    }
    if (message.connector !== undefined) {
      Connector.encode(message.connector, writer.uint32(226).fork()).join();
    }
    for (const v of message.citations) {
      writer.uint32(234).string(v);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseElement();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.bbox = BoundingBox.decode(reader, reader.uint32());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.zIndex = reader.int32();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.innerXml = reader.string();
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.outerXml = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.shape = ShapeElement.decode(reader, reader.uint32());
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.image = ImageElement.decode(reader, reader.uint32());
          continue;
        }
        case 18: {
          if (tag !== 146) {
            break;
          }
          message.chartReference = ChartReference.decode(reader, reader.uint32());
          continue;
        }
        case 20: {
          if (tag !== 162) {
            break;
          }
          message.video = VideoElement.decode(reader, reader.uint32());
          continue;
        }
        case 21: {
          if (tag !== 170) {
            break;
          }
          message.table = TableElement.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.imageReference = ImageReference.decode(reader, reader.uint32());
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.codeBlock = CodeBlockElement.decode(reader, reader.uint32());
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.paragraphs.push(Paragraph.decode(reader, reader.uint32()));
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 11: {
          if (tag !== 88) {
            break;
          }
          message.type = reader.int32();
          continue;
        }
        case 12: {
          if (tag !== 96) {
            break;
          }
          message.placeholderIndex = reader.int32();
          continue;
        }
        case 13: {
          if (tag !== 106) {
            break;
          }
          message.placeholderType = reader.string();
          continue;
        }
        case 14: {
          if (tag !== 114) {
            break;
          }
          message.textStyle = TextStyle.decode(reader, reader.uint32());
          continue;
        }
        case 15: {
          if (tag !== 122) {
            break;
          }
          message.effects.push(Effect.decode(reader, reader.uint32()));
          continue;
        }
        case 17: {
          if (tag !== 138) {
            break;
          }
          message.children.push(Element.decode(reader, reader.uint32()));
          continue;
        }
        case 16: {
          if (tag !== 130) {
            break;
          }
          message.levelsStyles.push(LevelStyle.decode(reader, reader.uint32()));
          continue;
        }
        case 19: {
          if (tag !== 154) {
            break;
          }
          message.fill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 30: {
          if (tag !== 242) {
            break;
          }
          message.line = Line.decode(reader, reader.uint32());
          continue;
        }
        case 31: {
          if (tag !== 250) {
            break;
          }
          message.scene3d = Scene3D.decode(reader, reader.uint32());
          continue;
        }
        case 32: {
          if (tag !== 258) {
            break;
          }
          message.shape3d = Shape3D.decode(reader, reader.uint32());
          continue;
        }
        case 33: {
          if (tag !== 266) {
            break;
          }
          message.imageMask = ImageMask.decode(reader, reader.uint32());
          continue;
        }
        case 22: {
          if (tag !== 178) {
            break;
          }
          message.lineReference = StyleReference.decode(reader, reader.uint32());
          continue;
        }
        case 23: {
          if (tag !== 186) {
            break;
          }
          message.fillReference = StyleReference.decode(reader, reader.uint32());
          continue;
        }
        case 24: {
          if (tag !== 194) {
            break;
          }
          message.effectReference = StyleReference.decode(reader, reader.uint32());
          continue;
        }
        case 25: {
          if (tag !== 202) {
            break;
          }
          message.fontReference = StyleReference.decode(reader, reader.uint32());
          continue;
        }
        case 26: {
          if (tag !== 210) {
            break;
          }
          message.hyperlink = Hyperlink.decode(reader, reader.uint32());
          continue;
        }
        case 27: {
          if (tag !== 218) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 34: {
          if (tag !== 274) {
            break;
          }
          message.creationId = reader.string();
          continue;
        }
        case 28: {
          if (tag !== 226) {
            break;
          }
          message.connector = Connector.decode(reader, reader.uint32());
          continue;
        }
        case 29: {
          if (tag !== 234) {
            break;
          }
          message.citations.push(reader.string());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Element.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseElement();
    message.bbox = object.bbox !== undefined && object.bbox !== null ? BoundingBox.fromPartial(object.bbox) : undefined;
    message.zIndex = object.zIndex ?? undefined;
    message.innerXml = object.innerXml ?? undefined;
    message.outerXml = object.outerXml ?? undefined;
    message.shape = object.shape !== undefined && object.shape !== null ? ShapeElement.fromPartial(object.shape) : undefined;
    message.image = object.image !== undefined && object.image !== null ? ImageElement.fromPartial(object.image) : undefined;
    message.chartReference = object.chartReference !== undefined && object.chartReference !== null ? ChartReference.fromPartial(object.chartReference) : undefined;
    message.video = object.video !== undefined && object.video !== null ? VideoElement.fromPartial(object.video) : undefined;
    message.table = object.table !== undefined && object.table !== null ? TableElement.fromPartial(object.table) : undefined;
    message.imageReference = object.imageReference !== undefined && object.imageReference !== null ? ImageReference.fromPartial(object.imageReference) : undefined;
    message.codeBlock = object.codeBlock !== undefined && object.codeBlock !== null ? CodeBlockElement.fromPartial(object.codeBlock) : undefined;
    message.paragraphs = object.paragraphs?.map((e) => Paragraph.fromPartial(e)) || [];
    message.name = object.name ?? undefined;
    message.type = object.type ?? 0;
    message.placeholderIndex = object.placeholderIndex ?? undefined;
    message.placeholderType = object.placeholderType ?? undefined;
    message.textStyle = object.textStyle !== undefined && object.textStyle !== null ? TextStyle.fromPartial(object.textStyle) : undefined;
    message.effects = object.effects?.map((e) => Effect.fromPartial(e)) || [];
    message.children = object.children?.map((e) => Element.fromPartial(e)) || [];
    message.levelsStyles = object.levelsStyles?.map((e) => LevelStyle.fromPartial(e)) || [];
    message.fill = object.fill !== undefined && object.fill !== null ? Fill.fromPartial(object.fill) : undefined;
    message.line = object.line !== undefined && object.line !== null ? Line.fromPartial(object.line) : undefined;
    message.scene3d = object.scene3d !== undefined && object.scene3d !== null ? Scene3D.fromPartial(object.scene3d) : undefined;
    message.shape3d = object.shape3d !== undefined && object.shape3d !== null ? Shape3D.fromPartial(object.shape3d) : undefined;
    message.imageMask = object.imageMask !== undefined && object.imageMask !== null ? ImageMask.fromPartial(object.imageMask) : undefined;
    message.lineReference = object.lineReference !== undefined && object.lineReference !== null ? StyleReference.fromPartial(object.lineReference) : undefined;
    message.fillReference = object.fillReference !== undefined && object.fillReference !== null ? StyleReference.fromPartial(object.fillReference) : undefined;
    message.effectReference = object.effectReference !== undefined && object.effectReference !== null ? StyleReference.fromPartial(object.effectReference) : undefined;
    message.fontReference = object.fontReference !== undefined && object.fontReference !== null ? StyleReference.fromPartial(object.fontReference) : undefined;
    message.hyperlink = object.hyperlink !== undefined && object.hyperlink !== null ? Hyperlink.fromPartial(object.hyperlink) : undefined;
    message.id = object.id ?? "";
    message.creationId = object.creationId ?? undefined;
    message.connector = object.connector !== undefined && object.connector !== null ? Connector.fromPartial(object.connector) : undefined;
    message.citations = object.citations?.map((e) => e) || [];
    return message;
  }
};
function createBaseStyleReference() {
  return { index: "", color: undefined };
}
var StyleReference = {
  encode(message, writer = new BinaryWriter) {
    if (message.index !== "") {
      writer.uint32(10).string(message.index);
    }
    if (message.color !== undefined) {
      Color.encode(message.color, writer.uint32(18).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseStyleReference();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.index = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.color = Color.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return StyleReference.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseStyleReference();
    message.index = object.index ?? "";
    message.color = object.color !== undefined && object.color !== null ? Color.fromPartial(object.color) : undefined;
    return message;
  }
};
function createBaseScene3D() {
  return { camera: undefined, lightRig: undefined };
}
var Scene3D = {
  encode(message, writer = new BinaryWriter) {
    if (message.camera !== undefined) {
      Camera3D.encode(message.camera, writer.uint32(10).fork()).join();
    }
    if (message.lightRig !== undefined) {
      LightRig3D.encode(message.lightRig, writer.uint32(18).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseScene3D();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.camera = Camera3D.decode(reader, reader.uint32());
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.lightRig = LightRig3D.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Scene3D.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseScene3D();
    message.camera = object.camera !== undefined && object.camera !== null ? Camera3D.fromPartial(object.camera) : undefined;
    message.lightRig = object.lightRig !== undefined && object.lightRig !== null ? LightRig3D.fromPartial(object.lightRig) : undefined;
    return message;
  }
};
function createBaseShape3D() {
  return {
    zEmu: undefined,
    extrusionHeightEmu: undefined,
    contourWidthEmu: undefined,
    presetMaterial: undefined,
    bevelTop: undefined,
    bevelBottom: undefined,
    extrusionColor: undefined,
    contourColor: undefined
  };
}
var Shape3D = {
  encode(message, writer = new BinaryWriter) {
    if (message.zEmu !== undefined) {
      writer.uint32(8).int64(message.zEmu);
    }
    if (message.extrusionHeightEmu !== undefined) {
      writer.uint32(16).int64(message.extrusionHeightEmu);
    }
    if (message.contourWidthEmu !== undefined) {
      writer.uint32(24).int64(message.contourWidthEmu);
    }
    if (message.presetMaterial !== undefined) {
      writer.uint32(34).string(message.presetMaterial);
    }
    if (message.bevelTop !== undefined) {
      Shape3D_Bevel.encode(message.bevelTop, writer.uint32(42).fork()).join();
    }
    if (message.bevelBottom !== undefined) {
      Shape3D_Bevel.encode(message.bevelBottom, writer.uint32(50).fork()).join();
    }
    if (message.extrusionColor !== undefined) {
      Color.encode(message.extrusionColor, writer.uint32(58).fork()).join();
    }
    if (message.contourColor !== undefined) {
      Color.encode(message.contourColor, writer.uint32(66).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseShape3D();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.zEmu = longToNumber2(reader.int64());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.extrusionHeightEmu = longToNumber2(reader.int64());
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.contourWidthEmu = longToNumber2(reader.int64());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.presetMaterial = reader.string();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.bevelTop = Shape3D_Bevel.decode(reader, reader.uint32());
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.bevelBottom = Shape3D_Bevel.decode(reader, reader.uint32());
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.extrusionColor = Color.decode(reader, reader.uint32());
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.contourColor = Color.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Shape3D.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseShape3D();
    message.zEmu = object.zEmu ?? undefined;
    message.extrusionHeightEmu = object.extrusionHeightEmu ?? undefined;
    message.contourWidthEmu = object.contourWidthEmu ?? undefined;
    message.presetMaterial = object.presetMaterial ?? undefined;
    message.bevelTop = object.bevelTop !== undefined && object.bevelTop !== null ? Shape3D_Bevel.fromPartial(object.bevelTop) : undefined;
    message.bevelBottom = object.bevelBottom !== undefined && object.bevelBottom !== null ? Shape3D_Bevel.fromPartial(object.bevelBottom) : undefined;
    message.extrusionColor = object.extrusionColor !== undefined && object.extrusionColor !== null ? Color.fromPartial(object.extrusionColor) : undefined;
    message.contourColor = object.contourColor !== undefined && object.contourColor !== null ? Color.fromPartial(object.contourColor) : undefined;
    return message;
  }
};
function createBaseShape3D_Bevel() {
  return { widthEmu: undefined, heightEmu: undefined, preset: undefined };
}
var Shape3D_Bevel = {
  encode(message, writer = new BinaryWriter) {
    if (message.widthEmu !== undefined) {
      writer.uint32(8).int64(message.widthEmu);
    }
    if (message.heightEmu !== undefined) {
      writer.uint32(16).int64(message.heightEmu);
    }
    if (message.preset !== undefined) {
      writer.uint32(26).string(message.preset);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseShape3D_Bevel();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.widthEmu = longToNumber2(reader.int64());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.heightEmu = longToNumber2(reader.int64());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.preset = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Shape3D_Bevel.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseShape3D_Bevel();
    message.widthEmu = object.widthEmu ?? undefined;
    message.heightEmu = object.heightEmu ?? undefined;
    message.preset = object.preset ?? undefined;
    return message;
  }
};
function createBaseCamera3D() {
  return { preset: "", rotation: undefined };
}
var Camera3D = {
  encode(message, writer = new BinaryWriter) {
    if (message.preset !== "") {
      writer.uint32(10).string(message.preset);
    }
    if (message.rotation !== undefined) {
      Rotation3D.encode(message.rotation, writer.uint32(18).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCamera3D();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.preset = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.rotation = Rotation3D.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Camera3D.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCamera3D();
    message.preset = object.preset ?? "";
    message.rotation = object.rotation !== undefined && object.rotation !== null ? Rotation3D.fromPartial(object.rotation) : undefined;
    return message;
  }
};
function createBaseLightRig3D() {
  return { rig: "", direction: "", rotation: undefined };
}
var LightRig3D = {
  encode(message, writer = new BinaryWriter) {
    if (message.rig !== "") {
      writer.uint32(10).string(message.rig);
    }
    if (message.direction !== "") {
      writer.uint32(18).string(message.direction);
    }
    if (message.rotation !== undefined) {
      Rotation3D.encode(message.rotation, writer.uint32(26).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseLightRig3D();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.rig = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.direction = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.rotation = Rotation3D.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return LightRig3D.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseLightRig3D();
    message.rig = object.rig ?? "";
    message.direction = object.direction ?? "";
    message.rotation = object.rotation !== undefined && object.rotation !== null ? Rotation3D.fromPartial(object.rotation) : undefined;
    return message;
  }
};
function createBaseRotation3D() {
  return { latitude: undefined, longitude: undefined, revolution: undefined };
}
var Rotation3D = {
  encode(message, writer = new BinaryWriter) {
    if (message.latitude !== undefined) {
      writer.uint32(8).int32(message.latitude);
    }
    if (message.longitude !== undefined) {
      writer.uint32(16).int32(message.longitude);
    }
    if (message.revolution !== undefined) {
      writer.uint32(24).int32(message.revolution);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseRotation3D();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.latitude = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.longitude = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.revolution = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Rotation3D.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseRotation3D();
    message.latitude = object.latitude ?? undefined;
    message.longitude = object.longitude ?? undefined;
    message.revolution = object.revolution ?? undefined;
    return message;
  }
};
function createBaseChartReference() {
  return { id: "" };
}
var ChartReference = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== "") {
      writer.uint32(10).string(message.id);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseChartReference();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.id = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ChartReference.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseChartReference();
    message.id = object.id ?? "";
    return message;
  }
};
function createBaseConnector() {
  return { fromElementId: "", fromIdx: 0, toElementId: "", toIdx: 0, lineStyle: undefined };
}
var Connector = {
  encode(message, writer = new BinaryWriter) {
    if (message.fromElementId !== "") {
      writer.uint32(10).string(message.fromElementId);
    }
    if (message.fromIdx !== 0) {
      writer.uint32(16).int32(message.fromIdx);
    }
    if (message.toElementId !== "") {
      writer.uint32(26).string(message.toElementId);
    }
    if (message.toIdx !== 0) {
      writer.uint32(32).int32(message.toIdx);
    }
    if (message.lineStyle !== undefined) {
      ConnectorLineStyle.encode(message.lineStyle, writer.uint32(42).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseConnector();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.fromElementId = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.fromIdx = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.toElementId = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.toIdx = reader.int32();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.lineStyle = ConnectorLineStyle.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Connector.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseConnector();
    message.fromElementId = object.fromElementId ?? "";
    message.fromIdx = object.fromIdx ?? 0;
    message.toElementId = object.toElementId ?? "";
    message.toIdx = object.toIdx ?? 0;
    message.lineStyle = object.lineStyle !== undefined && object.lineStyle !== null ? ConnectorLineStyle.fromPartial(object.lineStyle) : undefined;
    return message;
  }
};
function createBaseTableElement() {
  return { rows: [], columnWidths: [], properties: undefined };
}
var TableElement = {
  encode(message, writer = new BinaryWriter) {
    for (const v of message.rows) {
      TableRow.encode(v, writer.uint32(10).fork()).join();
    }
    writer.uint32(18).fork();
    for (const v of message.columnWidths) {
      writer.int32(v);
    }
    writer.join();
    if (message.properties !== undefined) {
      TableProperties.encode(message.properties, writer.uint32(26).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTableElement();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.rows.push(TableRow.decode(reader, reader.uint32()));
          continue;
        }
        case 2: {
          if (tag === 16) {
            message.columnWidths.push(reader.int32());
            continue;
          }
          if (tag === 18) {
            const end2 = reader.uint32() + reader.pos;
            while (reader.pos < end2) {
              message.columnWidths.push(reader.int32());
            }
            continue;
          }
          break;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.properties = TableProperties.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TableElement.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTableElement();
    message.rows = object.rows?.map((e) => TableRow.fromPartial(e)) || [];
    message.columnWidths = object.columnWidths?.map((e) => e) || [];
    message.properties = object.properties !== undefined && object.properties !== null ? TableProperties.fromPartial(object.properties) : undefined;
    return message;
  }
};
function createBaseTableProperties() {
  return {
    fill: undefined,
    rightToLeft: undefined,
    firstRow: undefined,
    firstColumn: undefined,
    lastRow: undefined,
    lastColumn: undefined,
    bandedRows: undefined,
    bandedColumns: undefined,
    styleId: undefined,
    effects: [],
    styleXml: undefined
  };
}
var TableProperties = {
  encode(message, writer = new BinaryWriter) {
    if (message.fill !== undefined) {
      Fill.encode(message.fill, writer.uint32(10).fork()).join();
    }
    if (message.rightToLeft !== undefined) {
      writer.uint32(16).bool(message.rightToLeft);
    }
    if (message.firstRow !== undefined) {
      writer.uint32(24).bool(message.firstRow);
    }
    if (message.firstColumn !== undefined) {
      writer.uint32(32).bool(message.firstColumn);
    }
    if (message.lastRow !== undefined) {
      writer.uint32(40).bool(message.lastRow);
    }
    if (message.lastColumn !== undefined) {
      writer.uint32(48).bool(message.lastColumn);
    }
    if (message.bandedRows !== undefined) {
      writer.uint32(56).bool(message.bandedRows);
    }
    if (message.bandedColumns !== undefined) {
      writer.uint32(64).bool(message.bandedColumns);
    }
    if (message.styleId !== undefined) {
      writer.uint32(74).string(message.styleId);
    }
    for (const v of message.effects) {
      Effect.encode(v, writer.uint32(82).fork()).join();
    }
    if (message.styleXml !== undefined) {
      writer.uint32(90).string(message.styleXml);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTableProperties();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.fill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.rightToLeft = reader.bool();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.firstRow = reader.bool();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.firstColumn = reader.bool();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.lastRow = reader.bool();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.lastColumn = reader.bool();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.bandedRows = reader.bool();
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.bandedColumns = reader.bool();
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.styleId = reader.string();
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.effects.push(Effect.decode(reader, reader.uint32()));
          continue;
        }
        case 11: {
          if (tag !== 90) {
            break;
          }
          message.styleXml = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TableProperties.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTableProperties();
    message.fill = object.fill !== undefined && object.fill !== null ? Fill.fromPartial(object.fill) : undefined;
    message.rightToLeft = object.rightToLeft ?? undefined;
    message.firstRow = object.firstRow ?? undefined;
    message.firstColumn = object.firstColumn ?? undefined;
    message.lastRow = object.lastRow ?? undefined;
    message.lastColumn = object.lastColumn ?? undefined;
    message.bandedRows = object.bandedRows ?? undefined;
    message.bandedColumns = object.bandedColumns ?? undefined;
    message.styleId = object.styleId ?? undefined;
    message.effects = object.effects?.map((e) => Effect.fromPartial(e)) || [];
    message.styleXml = object.styleXml ?? undefined;
    return message;
  }
};
function createBaseTableCell() {
  return {
    id: undefined,
    text: "",
    textStyle: undefined,
    paragraphs: [],
    levelsStyles: [],
    fill: undefined,
    lines: undefined,
    gridSpan: undefined,
    rowSpan: undefined,
    horizontalMerge: undefined,
    verticalMerge: undefined,
    textDirection: undefined,
    marginLeft: undefined,
    marginRight: undefined,
    marginTop: undefined,
    marginBottom: undefined,
    anchor: undefined,
    anchorCenter: undefined,
    horizontalOverflow: undefined
  };
}
var TableCell = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== undefined) {
      writer.uint32(58).string(message.id);
    }
    if (message.text !== "") {
      writer.uint32(10).string(message.text);
    }
    if (message.textStyle !== undefined) {
      TextStyle.encode(message.textStyle, writer.uint32(18).fork()).join();
    }
    for (const v of message.paragraphs) {
      Paragraph.encode(v, writer.uint32(26).fork()).join();
    }
    for (const v of message.levelsStyles) {
      LevelStyle.encode(v, writer.uint32(34).fork()).join();
    }
    if (message.fill !== undefined) {
      Fill.encode(message.fill, writer.uint32(42).fork()).join();
    }
    if (message.lines !== undefined) {
      TableCell_Lines.encode(message.lines, writer.uint32(50).fork()).join();
    }
    if (message.gridSpan !== undefined) {
      writer.uint32(64).int32(message.gridSpan);
    }
    if (message.rowSpan !== undefined) {
      writer.uint32(72).int32(message.rowSpan);
    }
    if (message.horizontalMerge !== undefined) {
      writer.uint32(80).bool(message.horizontalMerge);
    }
    if (message.verticalMerge !== undefined) {
      writer.uint32(88).bool(message.verticalMerge);
    }
    if (message.textDirection !== undefined) {
      writer.uint32(98).string(message.textDirection);
    }
    if (message.marginLeft !== undefined) {
      writer.uint32(104).int32(message.marginLeft);
    }
    if (message.marginRight !== undefined) {
      writer.uint32(112).int32(message.marginRight);
    }
    if (message.marginTop !== undefined) {
      writer.uint32(120).int32(message.marginTop);
    }
    if (message.marginBottom !== undefined) {
      writer.uint32(128).int32(message.marginBottom);
    }
    if (message.anchor !== undefined) {
      writer.uint32(138).string(message.anchor);
    }
    if (message.anchorCenter !== undefined) {
      writer.uint32(144).bool(message.anchorCenter);
    }
    if (message.horizontalOverflow !== undefined) {
      writer.uint32(154).string(message.horizontalOverflow);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTableCell();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.text = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.textStyle = TextStyle.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.paragraphs.push(Paragraph.decode(reader, reader.uint32()));
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.levelsStyles.push(LevelStyle.decode(reader, reader.uint32()));
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.fill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.lines = TableCell_Lines.decode(reader, reader.uint32());
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.gridSpan = reader.int32();
          continue;
        }
        case 9: {
          if (tag !== 72) {
            break;
          }
          message.rowSpan = reader.int32();
          continue;
        }
        case 10: {
          if (tag !== 80) {
            break;
          }
          message.horizontalMerge = reader.bool();
          continue;
        }
        case 11: {
          if (tag !== 88) {
            break;
          }
          message.verticalMerge = reader.bool();
          continue;
        }
        case 12: {
          if (tag !== 98) {
            break;
          }
          message.textDirection = reader.string();
          continue;
        }
        case 13: {
          if (tag !== 104) {
            break;
          }
          message.marginLeft = reader.int32();
          continue;
        }
        case 14: {
          if (tag !== 112) {
            break;
          }
          message.marginRight = reader.int32();
          continue;
        }
        case 15: {
          if (tag !== 120) {
            break;
          }
          message.marginTop = reader.int32();
          continue;
        }
        case 16: {
          if (tag !== 128) {
            break;
          }
          message.marginBottom = reader.int32();
          continue;
        }
        case 17: {
          if (tag !== 138) {
            break;
          }
          message.anchor = reader.string();
          continue;
        }
        case 18: {
          if (tag !== 144) {
            break;
          }
          message.anchorCenter = reader.bool();
          continue;
        }
        case 19: {
          if (tag !== 154) {
            break;
          }
          message.horizontalOverflow = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TableCell.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTableCell();
    message.id = object.id ?? undefined;
    message.text = object.text ?? "";
    message.textStyle = object.textStyle !== undefined && object.textStyle !== null ? TextStyle.fromPartial(object.textStyle) : undefined;
    message.paragraphs = object.paragraphs?.map((e) => Paragraph.fromPartial(e)) || [];
    message.levelsStyles = object.levelsStyles?.map((e) => LevelStyle.fromPartial(e)) || [];
    message.fill = object.fill !== undefined && object.fill !== null ? Fill.fromPartial(object.fill) : undefined;
    message.lines = object.lines !== undefined && object.lines !== null ? TableCell_Lines.fromPartial(object.lines) : undefined;
    message.gridSpan = object.gridSpan ?? undefined;
    message.rowSpan = object.rowSpan ?? undefined;
    message.horizontalMerge = object.horizontalMerge ?? undefined;
    message.verticalMerge = object.verticalMerge ?? undefined;
    message.textDirection = object.textDirection ?? undefined;
    message.marginLeft = object.marginLeft ?? undefined;
    message.marginRight = object.marginRight ?? undefined;
    message.marginTop = object.marginTop ?? undefined;
    message.marginBottom = object.marginBottom ?? undefined;
    message.anchor = object.anchor ?? undefined;
    message.anchorCenter = object.anchorCenter ?? undefined;
    message.horizontalOverflow = object.horizontalOverflow ?? undefined;
    return message;
  }
};
function createBaseTableCell_Lines() {
  return {
    top: undefined,
    right: undefined,
    bottom: undefined,
    left: undefined,
    diagonalDown: undefined,
    diagonalUp: undefined
  };
}
var TableCell_Lines = {
  encode(message, writer = new BinaryWriter) {
    if (message.top !== undefined) {
      Line.encode(message.top, writer.uint32(10).fork()).join();
    }
    if (message.right !== undefined) {
      Line.encode(message.right, writer.uint32(18).fork()).join();
    }
    if (message.bottom !== undefined) {
      Line.encode(message.bottom, writer.uint32(26).fork()).join();
    }
    if (message.left !== undefined) {
      Line.encode(message.left, writer.uint32(34).fork()).join();
    }
    if (message.diagonalDown !== undefined) {
      Line.encode(message.diagonalDown, writer.uint32(42).fork()).join();
    }
    if (message.diagonalUp !== undefined) {
      Line.encode(message.diagonalUp, writer.uint32(50).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTableCell_Lines();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.top = Line.decode(reader, reader.uint32());
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.right = Line.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.bottom = Line.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.left = Line.decode(reader, reader.uint32());
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.diagonalDown = Line.decode(reader, reader.uint32());
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.diagonalUp = Line.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TableCell_Lines.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTableCell_Lines();
    message.top = object.top !== undefined && object.top !== null ? Line.fromPartial(object.top) : undefined;
    message.right = object.right !== undefined && object.right !== null ? Line.fromPartial(object.right) : undefined;
    message.bottom = object.bottom !== undefined && object.bottom !== null ? Line.fromPartial(object.bottom) : undefined;
    message.left = object.left !== undefined && object.left !== null ? Line.fromPartial(object.left) : undefined;
    message.diagonalDown = object.diagonalDown !== undefined && object.diagonalDown !== null ? Line.fromPartial(object.diagonalDown) : undefined;
    message.diagonalUp = object.diagonalUp !== undefined && object.diagonalUp !== null ? Line.fromPartial(object.diagonalUp) : undefined;
    return message;
  }
};
function createBaseTableRow() {
  return { id: undefined, cells: [], heightEmu: undefined };
}
var TableRow = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== undefined) {
      writer.uint32(26).string(message.id);
    }
    for (const v of message.cells) {
      TableCell.encode(v, writer.uint32(10).fork()).join();
    }
    if (message.heightEmu !== undefined) {
      writer.uint32(16).int32(message.heightEmu);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTableRow();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.cells.push(TableCell.decode(reader, reader.uint32()));
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.heightEmu = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TableRow.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTableRow();
    message.id = object.id ?? undefined;
    message.cells = object.cells?.map((e) => TableCell.fromPartial(e)) || [];
    message.heightEmu = object.heightEmu ?? undefined;
    return message;
  }
};
function createBaseParagraph() {
  return {
    id: undefined,
    runs: [],
    textStyle: undefined,
    bulletCharacter: undefined,
    marginLeft: undefined,
    indent: undefined,
    spaceAfter: undefined,
    spaceBefore: undefined,
    styleId: undefined,
    paragraphStyle: undefined,
    docxSectionBreakCarrier: undefined
  };
}
var Paragraph = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== undefined) {
      writer.uint32(74).string(message.id);
    }
    for (const v of message.runs) {
      TextRun.encode(v, writer.uint32(10).fork()).join();
    }
    if (message.textStyle !== undefined) {
      TextStyle.encode(message.textStyle, writer.uint32(18).fork()).join();
    }
    if (message.bulletCharacter !== undefined) {
      writer.uint32(26).string(message.bulletCharacter);
    }
    if (message.marginLeft !== undefined) {
      writer.uint32(32).int32(message.marginLeft);
    }
    if (message.indent !== undefined) {
      writer.uint32(40).int32(message.indent);
    }
    if (message.spaceAfter !== undefined) {
      writer.uint32(48).int32(message.spaceAfter);
    }
    if (message.spaceBefore !== undefined) {
      writer.uint32(56).int32(message.spaceBefore);
    }
    if (message.styleId !== undefined) {
      writer.uint32(66).string(message.styleId);
    }
    if (message.paragraphStyle !== undefined) {
      ParagraphStyle.encode(message.paragraphStyle, writer.uint32(82).fork()).join();
    }
    if (message.docxSectionBreakCarrier !== undefined) {
      writer.uint32(88).bool(message.docxSectionBreakCarrier);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseParagraph();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.runs.push(TextRun.decode(reader, reader.uint32()));
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.textStyle = TextStyle.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.bulletCharacter = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.marginLeft = reader.int32();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.indent = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.spaceAfter = reader.int32();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.spaceBefore = reader.int32();
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.styleId = reader.string();
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.paragraphStyle = ParagraphStyle.decode(reader, reader.uint32());
          continue;
        }
        case 11: {
          if (tag !== 88) {
            break;
          }
          message.docxSectionBreakCarrier = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Paragraph.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseParagraph();
    message.id = object.id ?? undefined;
    message.runs = object.runs?.map((e) => TextRun.fromPartial(e)) || [];
    message.textStyle = object.textStyle !== undefined && object.textStyle !== null ? TextStyle.fromPartial(object.textStyle) : undefined;
    message.bulletCharacter = object.bulletCharacter ?? undefined;
    message.marginLeft = object.marginLeft ?? undefined;
    message.indent = object.indent ?? undefined;
    message.spaceAfter = object.spaceAfter ?? undefined;
    message.spaceBefore = object.spaceBefore ?? undefined;
    message.styleId = object.styleId ?? undefined;
    message.paragraphStyle = object.paragraphStyle !== undefined && object.paragraphStyle !== null ? ParagraphStyle.fromPartial(object.paragraphStyle) : undefined;
    message.docxSectionBreakCarrier = object.docxSectionBreakCarrier ?? undefined;
    return message;
  }
};
function createBaseTextRun() {
  return { id: undefined, text: "", textStyle: undefined, hyperlink: undefined, citations: [], reviewMarkIds: [] };
}
var TextRun = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== undefined) {
      writer.uint32(34).string(message.id);
    }
    if (message.text !== "") {
      writer.uint32(10).string(message.text);
    }
    if (message.textStyle !== undefined) {
      TextStyle.encode(message.textStyle, writer.uint32(18).fork()).join();
    }
    if (message.hyperlink !== undefined) {
      Hyperlink.encode(message.hyperlink, writer.uint32(26).fork()).join();
    }
    for (const v of message.citations) {
      writer.uint32(42).string(v);
    }
    for (const v of message.reviewMarkIds) {
      writer.uint32(50).string(v);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTextRun();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.text = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.textStyle = TextStyle.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.hyperlink = Hyperlink.decode(reader, reader.uint32());
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.citations.push(reader.string());
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.reviewMarkIds.push(reader.string());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TextRun.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTextRun();
    message.id = object.id ?? undefined;
    message.text = object.text ?? "";
    message.textStyle = object.textStyle !== undefined && object.textStyle !== null ? TextStyle.fromPartial(object.textStyle) : undefined;
    message.hyperlink = object.hyperlink !== undefined && object.hyperlink !== null ? Hyperlink.fromPartial(object.hyperlink) : undefined;
    message.citations = object.citations?.map((e) => e) || [];
    message.reviewMarkIds = object.reviewMarkIds?.map((e) => e) || [];
    return message;
  }
};
function createBaseHyperlink() {
  return { uri: "", isExternal: false, action: "" };
}
var Hyperlink = {
  encode(message, writer = new BinaryWriter) {
    if (message.uri !== "") {
      writer.uint32(10).string(message.uri);
    }
    if (message.isExternal !== false) {
      writer.uint32(16).bool(message.isExternal);
    }
    if (message.action !== "") {
      writer.uint32(26).string(message.action);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseHyperlink();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.uri = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.isExternal = reader.bool();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.action = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Hyperlink.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseHyperlink();
    message.uri = object.uri ?? "";
    message.isExternal = object.isExternal ?? false;
    message.action = object.action ?? "";
    return message;
  }
};
function createBaseEffectStyle() {
  return { effects: [] };
}
var EffectStyle = {
  encode(message, writer = new BinaryWriter) {
    for (const v of message.effects) {
      Effect.encode(v, writer.uint32(10).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseEffectStyle();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.effects.push(Effect.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return EffectStyle.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseEffectStyle();
    message.effects = object.effects?.map((e) => Effect.fromPartial(e)) || [];
    return message;
  }
};
function createBaseEffect() {
  return { type: 0, shadow: undefined, glow: undefined, reflection: undefined, softEdges: undefined };
}
var Effect = {
  encode(message, writer = new BinaryWriter) {
    if (message.type !== 0) {
      writer.uint32(8).int32(message.type);
    }
    if (message.shadow !== undefined) {
      ShadowEffect.encode(message.shadow, writer.uint32(18).fork()).join();
    }
    if (message.glow !== undefined) {
      GlowEffect.encode(message.glow, writer.uint32(26).fork()).join();
    }
    if (message.reflection !== undefined) {
      ReflectionEffect.encode(message.reflection, writer.uint32(34).fork()).join();
    }
    if (message.softEdges !== undefined) {
      SoftEdgesEffect.encode(message.softEdges, writer.uint32(42).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseEffect();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.type = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.shadow = ShadowEffect.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.glow = GlowEffect.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.reflection = ReflectionEffect.decode(reader, reader.uint32());
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.softEdges = SoftEdgesEffect.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Effect.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseEffect();
    message.type = object.type ?? 0;
    message.shadow = object.shadow !== undefined && object.shadow !== null ? ShadowEffect.fromPartial(object.shadow) : undefined;
    message.glow = object.glow !== undefined && object.glow !== null ? GlowEffect.fromPartial(object.glow) : undefined;
    message.reflection = object.reflection !== undefined && object.reflection !== null ? ReflectionEffect.fromPartial(object.reflection) : undefined;
    message.softEdges = object.softEdges !== undefined && object.softEdges !== null ? SoftEdgesEffect.fromPartial(object.softEdges) : undefined;
    return message;
  }
};
function createBaseGlowEffect() {
  return { color: undefined, radiusEmu: undefined };
}
var GlowEffect = {
  encode(message, writer = new BinaryWriter) {
    if (message.color !== undefined) {
      Color.encode(message.color, writer.uint32(10).fork()).join();
    }
    if (message.radiusEmu !== undefined) {
      writer.uint32(16).int64(message.radiusEmu);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseGlowEffect();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.color = Color.decode(reader, reader.uint32());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.radiusEmu = longToNumber2(reader.int64());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return GlowEffect.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseGlowEffect();
    message.color = object.color !== undefined && object.color !== null ? Color.fromPartial(object.color) : undefined;
    message.radiusEmu = object.radiusEmu ?? undefined;
    return message;
  }
};
function createBaseSoftEdgesEffect() {
  return { radiusEmu: undefined };
}
var SoftEdgesEffect = {
  encode(message, writer = new BinaryWriter) {
    if (message.radiusEmu !== undefined) {
      writer.uint32(8).int64(message.radiusEmu);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseSoftEdgesEffect();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.radiusEmu = longToNumber2(reader.int64());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return SoftEdgesEffect.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseSoftEdgesEffect();
    message.radiusEmu = object.radiusEmu ?? undefined;
    return message;
  }
};
function createBaseReflectionEffect() {
  return {
    blurRadiusEmu: undefined,
    startAlpha: undefined,
    startPosition: undefined,
    endAlpha: undefined,
    endPosition: undefined,
    distanceEmu: undefined,
    direction: undefined,
    fadeDirection: undefined,
    horizontalScale: undefined,
    verticalScale: undefined,
    horizontalSkew: undefined,
    verticalSkew: undefined,
    alignment: undefined,
    rotateWithShape: undefined
  };
}
var ReflectionEffect = {
  encode(message, writer = new BinaryWriter) {
    if (message.blurRadiusEmu !== undefined) {
      writer.uint32(8).int64(message.blurRadiusEmu);
    }
    if (message.startAlpha !== undefined) {
      writer.uint32(16).int32(message.startAlpha);
    }
    if (message.startPosition !== undefined) {
      writer.uint32(24).int32(message.startPosition);
    }
    if (message.endAlpha !== undefined) {
      writer.uint32(32).int32(message.endAlpha);
    }
    if (message.endPosition !== undefined) {
      writer.uint32(40).int32(message.endPosition);
    }
    if (message.distanceEmu !== undefined) {
      writer.uint32(48).int64(message.distanceEmu);
    }
    if (message.direction !== undefined) {
      writer.uint32(56).int32(message.direction);
    }
    if (message.fadeDirection !== undefined) {
      writer.uint32(64).int32(message.fadeDirection);
    }
    if (message.horizontalScale !== undefined) {
      writer.uint32(72).int32(message.horizontalScale);
    }
    if (message.verticalScale !== undefined) {
      writer.uint32(80).int32(message.verticalScale);
    }
    if (message.horizontalSkew !== undefined) {
      writer.uint32(88).int32(message.horizontalSkew);
    }
    if (message.verticalSkew !== undefined) {
      writer.uint32(96).int32(message.verticalSkew);
    }
    if (message.alignment !== undefined) {
      writer.uint32(106).string(message.alignment);
    }
    if (message.rotateWithShape !== undefined) {
      writer.uint32(112).bool(message.rotateWithShape);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseReflectionEffect();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.blurRadiusEmu = longToNumber2(reader.int64());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.startAlpha = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.startPosition = reader.int32();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.endAlpha = reader.int32();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.endPosition = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.distanceEmu = longToNumber2(reader.int64());
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.direction = reader.int32();
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.fadeDirection = reader.int32();
          continue;
        }
        case 9: {
          if (tag !== 72) {
            break;
          }
          message.horizontalScale = reader.int32();
          continue;
        }
        case 10: {
          if (tag !== 80) {
            break;
          }
          message.verticalScale = reader.int32();
          continue;
        }
        case 11: {
          if (tag !== 88) {
            break;
          }
          message.horizontalSkew = reader.int32();
          continue;
        }
        case 12: {
          if (tag !== 96) {
            break;
          }
          message.verticalSkew = reader.int32();
          continue;
        }
        case 13: {
          if (tag !== 106) {
            break;
          }
          message.alignment = reader.string();
          continue;
        }
        case 14: {
          if (tag !== 112) {
            break;
          }
          message.rotateWithShape = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ReflectionEffect.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseReflectionEffect();
    message.blurRadiusEmu = object.blurRadiusEmu ?? undefined;
    message.startAlpha = object.startAlpha ?? undefined;
    message.startPosition = object.startPosition ?? undefined;
    message.endAlpha = object.endAlpha ?? undefined;
    message.endPosition = object.endPosition ?? undefined;
    message.distanceEmu = object.distanceEmu ?? undefined;
    message.direction = object.direction ?? undefined;
    message.fadeDirection = object.fadeDirection ?? undefined;
    message.horizontalScale = object.horizontalScale ?? undefined;
    message.verticalScale = object.verticalScale ?? undefined;
    message.horizontalSkew = object.horizontalSkew ?? undefined;
    message.verticalSkew = object.verticalSkew ?? undefined;
    message.alignment = object.alignment ?? undefined;
    message.rotateWithShape = object.rotateWithShape ?? undefined;
    return message;
  }
};
function createBaseShadowEffect() {
  return {
    color: undefined,
    blurRadius: undefined,
    distance: undefined,
    direction: undefined,
    alignment: undefined,
    rotateWithShape: undefined
  };
}
var ShadowEffect = {
  encode(message, writer = new BinaryWriter) {
    if (message.color !== undefined) {
      Color.encode(message.color, writer.uint32(18).fork()).join();
    }
    if (message.blurRadius !== undefined) {
      writer.uint32(24).int32(message.blurRadius);
    }
    if (message.distance !== undefined) {
      writer.uint32(32).int32(message.distance);
    }
    if (message.direction !== undefined) {
      writer.uint32(40).int32(message.direction);
    }
    if (message.alignment !== undefined) {
      writer.uint32(50).string(message.alignment);
    }
    if (message.rotateWithShape !== undefined) {
      writer.uint32(56).bool(message.rotateWithShape);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseShadowEffect();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.color = Color.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.blurRadius = reader.int32();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.distance = reader.int32();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.direction = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.alignment = reader.string();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.rotateWithShape = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ShadowEffect.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseShadowEffect();
    message.color = object.color !== undefined && object.color !== null ? Color.fromPartial(object.color) : undefined;
    message.blurRadius = object.blurRadius ?? undefined;
    message.distance = object.distance ?? undefined;
    message.direction = object.direction ?? undefined;
    message.alignment = object.alignment ?? undefined;
    message.rotateWithShape = object.rotateWithShape ?? undefined;
    return message;
  }
};
function createBaseShapeElement() {
  return { geometry: 0, fill: undefined, line: undefined, adjustmentList: [], rectFormula: undefined, customPaths: [] };
}
var ShapeElement = {
  encode(message, writer = new BinaryWriter) {
    if (message.geometry !== 0) {
      writer.uint32(8).int32(message.geometry);
    }
    if (message.fill !== undefined) {
      Fill.encode(message.fill, writer.uint32(42).fork()).join();
    }
    if (message.line !== undefined) {
      Line.encode(message.line, writer.uint32(50).fork()).join();
    }
    for (const v of message.adjustmentList) {
      AvLst.encode(v, writer.uint32(58).fork()).join();
    }
    if (message.rectFormula !== undefined) {
      RectFormula.encode(message.rectFormula, writer.uint32(66).fork()).join();
    }
    for (const v of message.customPaths) {
      CustomPath.encode(v, writer.uint32(74).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseShapeElement();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.geometry = reader.int32();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.fill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.line = Line.decode(reader, reader.uint32());
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.adjustmentList.push(AvLst.decode(reader, reader.uint32()));
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.rectFormula = RectFormula.decode(reader, reader.uint32());
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.customPaths.push(CustomPath.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ShapeElement.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseShapeElement();
    message.geometry = object.geometry ?? 0;
    message.fill = object.fill !== undefined && object.fill !== null ? Fill.fromPartial(object.fill) : undefined;
    message.line = object.line !== undefined && object.line !== null ? Line.fromPartial(object.line) : undefined;
    message.adjustmentList = object.adjustmentList?.map((e) => AvLst.fromPartial(e)) || [];
    message.rectFormula = object.rectFormula !== undefined && object.rectFormula !== null ? RectFormula.fromPartial(object.rectFormula) : undefined;
    message.customPaths = object.customPaths?.map((e) => CustomPath.fromPartial(e)) || [];
    return message;
  }
};
function createBaseAvLst() {
  return { name: "", formula: "" };
}
var AvLst = {
  encode(message, writer = new BinaryWriter) {
    if (message.name !== "") {
      writer.uint32(10).string(message.name);
    }
    if (message.formula !== "") {
      writer.uint32(18).string(message.formula);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseAvLst();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.formula = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return AvLst.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseAvLst();
    message.name = object.name ?? "";
    message.formula = object.formula ?? "";
    return message;
  }
};
function createBaseImageMask() {
  return { geometry: "", cropLeft: 0, cropTop: 0, cropRight: 0, cropBottom: 0, adjustmentList: [] };
}
var ImageMask = {
  encode(message, writer = new BinaryWriter) {
    if (message.geometry !== "") {
      writer.uint32(10).string(message.geometry);
    }
    if (message.cropLeft !== 0) {
      writer.uint32(16).uint32(message.cropLeft);
    }
    if (message.cropTop !== 0) {
      writer.uint32(24).uint32(message.cropTop);
    }
    if (message.cropRight !== 0) {
      writer.uint32(32).uint32(message.cropRight);
    }
    if (message.cropBottom !== 0) {
      writer.uint32(40).uint32(message.cropBottom);
    }
    for (const v of message.adjustmentList) {
      AvLst.encode(v, writer.uint32(50).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseImageMask();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.geometry = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.cropLeft = reader.uint32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.cropTop = reader.uint32();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.cropRight = reader.uint32();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.cropBottom = reader.uint32();
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.adjustmentList.push(AvLst.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ImageMask.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseImageMask();
    message.geometry = object.geometry ?? "";
    message.cropLeft = object.cropLeft ?? 0;
    message.cropTop = object.cropTop ?? 0;
    message.cropRight = object.cropRight ?? 0;
    message.cropBottom = object.cropBottom ?? 0;
    message.adjustmentList = object.adjustmentList?.map((e) => AvLst.fromPartial(e)) || [];
    return message;
  }
};
function createBaseImageElement() {
  return { contentType: "", data: new Uint8Array(0), mask: undefined, alt: "" };
}
var ImageElement = {
  encode(message, writer = new BinaryWriter) {
    if (message.contentType !== "") {
      writer.uint32(10).string(message.contentType);
    }
    if (message.data.length !== 0) {
      writer.uint32(18).bytes(message.data);
    }
    if (message.mask !== undefined) {
      ImageMask.encode(message.mask, writer.uint32(26).fork()).join();
    }
    if (message.alt !== "") {
      writer.uint32(34).string(message.alt);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseImageElement();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.contentType = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.data = reader.bytes();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.mask = ImageMask.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.alt = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ImageElement.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseImageElement();
    message.contentType = object.contentType ?? "";
    message.data = object.data ?? new Uint8Array(0);
    message.mask = object.mask !== undefined && object.mask !== null ? ImageMask.fromPartial(object.mask) : undefined;
    message.alt = object.alt ?? "";
    return message;
  }
};
function createBaseVideoElement() {
  return { contentType: "", data: new Uint8Array(0), mask: undefined, alt: "" };
}
var VideoElement = {
  encode(message, writer = new BinaryWriter) {
    if (message.contentType !== "") {
      writer.uint32(10).string(message.contentType);
    }
    if (message.data.length !== 0) {
      writer.uint32(18).bytes(message.data);
    }
    if (message.mask !== undefined) {
      ImageMask.encode(message.mask, writer.uint32(26).fork()).join();
    }
    if (message.alt !== "") {
      writer.uint32(34).string(message.alt);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseVideoElement();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.contentType = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.data = reader.bytes();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.mask = ImageMask.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.alt = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return VideoElement.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseVideoElement();
    message.contentType = object.contentType ?? "";
    message.data = object.data ?? new Uint8Array(0);
    message.mask = object.mask !== undefined && object.mask !== null ? ImageMask.fromPartial(object.mask) : undefined;
    message.alt = object.alt ?? "";
    return message;
  }
};
function createBaseColorMap() {
  return {
    accent1: "",
    accent2: "",
    accent3: "",
    accent4: "",
    accent5: "",
    accent6: "",
    bg1: "",
    bg2: "",
    tx1: "",
    tx2: "",
    hlink: "",
    folHlink: ""
  };
}
var ColorMap = {
  encode(message, writer = new BinaryWriter) {
    if (message.accent1 !== "") {
      writer.uint32(10).string(message.accent1);
    }
    if (message.accent2 !== "") {
      writer.uint32(18).string(message.accent2);
    }
    if (message.accent3 !== "") {
      writer.uint32(26).string(message.accent3);
    }
    if (message.accent4 !== "") {
      writer.uint32(34).string(message.accent4);
    }
    if (message.accent5 !== "") {
      writer.uint32(42).string(message.accent5);
    }
    if (message.accent6 !== "") {
      writer.uint32(50).string(message.accent6);
    }
    if (message.bg1 !== "") {
      writer.uint32(58).string(message.bg1);
    }
    if (message.bg2 !== "") {
      writer.uint32(66).string(message.bg2);
    }
    if (message.tx1 !== "") {
      writer.uint32(74).string(message.tx1);
    }
    if (message.tx2 !== "") {
      writer.uint32(82).string(message.tx2);
    }
    if (message.hlink !== "") {
      writer.uint32(90).string(message.hlink);
    }
    if (message.folHlink !== "") {
      writer.uint32(98).string(message.folHlink);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseColorMap();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.accent1 = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.accent2 = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.accent3 = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.accent4 = reader.string();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.accent5 = reader.string();
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.accent6 = reader.string();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.bg1 = reader.string();
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.bg2 = reader.string();
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.tx1 = reader.string();
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.tx2 = reader.string();
          continue;
        }
        case 11: {
          if (tag !== 90) {
            break;
          }
          message.hlink = reader.string();
          continue;
        }
        case 12: {
          if (tag !== 98) {
            break;
          }
          message.folHlink = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ColorMap.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseColorMap();
    message.accent1 = object.accent1 ?? "";
    message.accent2 = object.accent2 ?? "";
    message.accent3 = object.accent3 ?? "";
    message.accent4 = object.accent4 ?? "";
    message.accent5 = object.accent5 ?? "";
    message.accent6 = object.accent6 ?? "";
    message.bg1 = object.bg1 ?? "";
    message.bg2 = object.bg2 ?? "";
    message.tx1 = object.tx1 ?? "";
    message.tx2 = object.tx2 ?? "";
    message.hlink = object.hlink ?? "";
    message.folHlink = object.folHlink ?? "";
    return message;
  }
};
function createBaseRectFormula() {
  return { t: "", l: "", r: "", b: "" };
}
var RectFormula = {
  encode(message, writer = new BinaryWriter) {
    if (message.t !== "") {
      writer.uint32(10).string(message.t);
    }
    if (message.l !== "") {
      writer.uint32(18).string(message.l);
    }
    if (message.r !== "") {
      writer.uint32(26).string(message.r);
    }
    if (message.b !== "") {
      writer.uint32(34).string(message.b);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseRectFormula();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.t = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.l = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.r = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.b = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return RectFormula.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseRectFormula();
    message.t = object.t ?? "";
    message.l = object.l ?? "";
    message.r = object.r ?? "";
    message.b = object.b ?? "";
    return message;
  }
};
function createBasePathMoveTo() {
  return { x: 0, y: 0 };
}
var PathMoveTo = {
  encode(message, writer = new BinaryWriter) {
    if (message.x !== 0) {
      writer.uint32(8).int64(message.x);
    }
    if (message.y !== 0) {
      writer.uint32(16).int64(message.y);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePathMoveTo();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.x = longToNumber2(reader.int64());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.y = longToNumber2(reader.int64());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PathMoveTo.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePathMoveTo();
    message.x = object.x ?? 0;
    message.y = object.y ?? 0;
    return message;
  }
};
function createBasePathLineTo() {
  return { x: 0, y: 0 };
}
var PathLineTo = {
  encode(message, writer = new BinaryWriter) {
    if (message.x !== 0) {
      writer.uint32(8).int64(message.x);
    }
    if (message.y !== 0) {
      writer.uint32(16).int64(message.y);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePathLineTo();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.x = longToNumber2(reader.int64());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.y = longToNumber2(reader.int64());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PathLineTo.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePathLineTo();
    message.x = object.x ?? 0;
    message.y = object.y ?? 0;
    return message;
  }
};
function createBasePathClose() {
  return {};
}
var PathClose = {
  encode(_, writer = new BinaryWriter) {
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePathClose();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PathClose.fromPartial(base ?? {});
  },
  fromPartial(_) {
    const message = createBasePathClose();
    return message;
  }
};
function createBasePathQuadBezierTo() {
  return { x1: 0, y1: 0, x: 0, y: 0 };
}
var PathQuadBezierTo = {
  encode(message, writer = new BinaryWriter) {
    if (message.x1 !== 0) {
      writer.uint32(8).int64(message.x1);
    }
    if (message.y1 !== 0) {
      writer.uint32(16).int64(message.y1);
    }
    if (message.x !== 0) {
      writer.uint32(24).int64(message.x);
    }
    if (message.y !== 0) {
      writer.uint32(32).int64(message.y);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePathQuadBezierTo();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.x1 = longToNumber2(reader.int64());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.y1 = longToNumber2(reader.int64());
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.x = longToNumber2(reader.int64());
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.y = longToNumber2(reader.int64());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PathQuadBezierTo.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePathQuadBezierTo();
    message.x1 = object.x1 ?? 0;
    message.y1 = object.y1 ?? 0;
    message.x = object.x ?? 0;
    message.y = object.y ?? 0;
    return message;
  }
};
function createBasePathCubicBezierTo() {
  return { x1: 0, y1: 0, x2: 0, y2: 0, x: 0, y: 0 };
}
var PathCubicBezierTo = {
  encode(message, writer = new BinaryWriter) {
    if (message.x1 !== 0) {
      writer.uint32(8).int64(message.x1);
    }
    if (message.y1 !== 0) {
      writer.uint32(16).int64(message.y1);
    }
    if (message.x2 !== 0) {
      writer.uint32(24).int64(message.x2);
    }
    if (message.y2 !== 0) {
      writer.uint32(32).int64(message.y2);
    }
    if (message.x !== 0) {
      writer.uint32(40).int64(message.x);
    }
    if (message.y !== 0) {
      writer.uint32(48).int64(message.y);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePathCubicBezierTo();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.x1 = longToNumber2(reader.int64());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.y1 = longToNumber2(reader.int64());
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.x2 = longToNumber2(reader.int64());
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.y2 = longToNumber2(reader.int64());
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.x = longToNumber2(reader.int64());
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.y = longToNumber2(reader.int64());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PathCubicBezierTo.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePathCubicBezierTo();
    message.x1 = object.x1 ?? 0;
    message.y1 = object.y1 ?? 0;
    message.x2 = object.x2 ?? 0;
    message.y2 = object.y2 ?? 0;
    message.x = object.x ?? 0;
    message.y = object.y ?? 0;
    return message;
  }
};
function createBasePathArcTo() {
  return { widthRadius: 0, heightRadius: 0, startAngle: 0, swingAngle: 0 };
}
var PathArcTo = {
  encode(message, writer = new BinaryWriter) {
    if (message.widthRadius !== 0) {
      writer.uint32(8).int64(message.widthRadius);
    }
    if (message.heightRadius !== 0) {
      writer.uint32(16).int64(message.heightRadius);
    }
    if (message.startAngle !== 0) {
      writer.uint32(24).int64(message.startAngle);
    }
    if (message.swingAngle !== 0) {
      writer.uint32(32).int64(message.swingAngle);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePathArcTo();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.widthRadius = longToNumber2(reader.int64());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.heightRadius = longToNumber2(reader.int64());
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.startAngle = longToNumber2(reader.int64());
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.swingAngle = longToNumber2(reader.int64());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PathArcTo.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePathArcTo();
    message.widthRadius = object.widthRadius ?? 0;
    message.heightRadius = object.heightRadius ?? 0;
    message.startAngle = object.startAngle ?? 0;
    message.swingAngle = object.swingAngle ?? 0;
    return message;
  }
};
function createBasePathCommand() {
  return {
    moveTo: undefined,
    lineTo: undefined,
    close: undefined,
    quadBezTo: undefined,
    cubicBezTo: undefined,
    arcTo: undefined
  };
}
var PathCommand = {
  encode(message, writer = new BinaryWriter) {
    if (message.moveTo !== undefined) {
      PathMoveTo.encode(message.moveTo, writer.uint32(10).fork()).join();
    }
    if (message.lineTo !== undefined) {
      PathLineTo.encode(message.lineTo, writer.uint32(18).fork()).join();
    }
    if (message.close !== undefined) {
      PathClose.encode(message.close, writer.uint32(26).fork()).join();
    }
    if (message.quadBezTo !== undefined) {
      PathQuadBezierTo.encode(message.quadBezTo, writer.uint32(34).fork()).join();
    }
    if (message.cubicBezTo !== undefined) {
      PathCubicBezierTo.encode(message.cubicBezTo, writer.uint32(42).fork()).join();
    }
    if (message.arcTo !== undefined) {
      PathArcTo.encode(message.arcTo, writer.uint32(50).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePathCommand();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.moveTo = PathMoveTo.decode(reader, reader.uint32());
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.lineTo = PathLineTo.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.close = PathClose.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.quadBezTo = PathQuadBezierTo.decode(reader, reader.uint32());
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.cubicBezTo = PathCubicBezierTo.decode(reader, reader.uint32());
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.arcTo = PathArcTo.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PathCommand.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePathCommand();
    message.moveTo = object.moveTo !== undefined && object.moveTo !== null ? PathMoveTo.fromPartial(object.moveTo) : undefined;
    message.lineTo = object.lineTo !== undefined && object.lineTo !== null ? PathLineTo.fromPartial(object.lineTo) : undefined;
    message.close = object.close !== undefined && object.close !== null ? PathClose.fromPartial(object.close) : undefined;
    message.quadBezTo = object.quadBezTo !== undefined && object.quadBezTo !== null ? PathQuadBezierTo.fromPartial(object.quadBezTo) : undefined;
    message.cubicBezTo = object.cubicBezTo !== undefined && object.cubicBezTo !== null ? PathCubicBezierTo.fromPartial(object.cubicBezTo) : undefined;
    message.arcTo = object.arcTo !== undefined && object.arcTo !== null ? PathArcTo.fromPartial(object.arcTo) : undefined;
    return message;
  }
};
function createBaseCustomPath() {
  return { id: undefined, widthEmu: 0, heightEmu: 0, commands: [] };
}
var CustomPath = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== undefined) {
      writer.uint32(34).string(message.id);
    }
    if (message.widthEmu !== 0) {
      writer.uint32(8).int64(message.widthEmu);
    }
    if (message.heightEmu !== 0) {
      writer.uint32(16).int64(message.heightEmu);
    }
    for (const v of message.commands) {
      PathCommand.encode(v, writer.uint32(26).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCustomPath();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.widthEmu = longToNumber2(reader.int64());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.heightEmu = longToNumber2(reader.int64());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.commands.push(PathCommand.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CustomPath.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCustomPath();
    message.id = object.id ?? undefined;
    message.widthEmu = object.widthEmu ?? 0;
    message.heightEmu = object.heightEmu ?? 0;
    message.commands = object.commands?.map((e) => PathCommand.fromPartial(e)) || [];
    return message;
  }
};
function createBaseCodeThemeRef() {
  return { themeId: "" };
}
var CodeThemeRef = {
  encode(message, writer = new BinaryWriter) {
    if (message.themeId !== "") {
      writer.uint32(10).string(message.themeId);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCodeThemeRef();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.themeId = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CodeThemeRef.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCodeThemeRef();
    message.themeId = object.themeId ?? "";
    return message;
  }
};
function createBaseCodeExecutionMeta() {
  return { runtime: "", exitCode: 0, durationMs: 0, timestampIso8601: "" };
}
var CodeExecutionMeta = {
  encode(message, writer = new BinaryWriter) {
    if (message.runtime !== "") {
      writer.uint32(10).string(message.runtime);
    }
    if (message.exitCode !== 0) {
      writer.uint32(16).int32(message.exitCode);
    }
    if (message.durationMs !== 0) {
      writer.uint32(25).double(message.durationMs);
    }
    if (message.timestampIso8601 !== "") {
      writer.uint32(34).string(message.timestampIso8601);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCodeExecutionMeta();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.runtime = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.exitCode = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 25) {
            break;
          }
          message.durationMs = reader.double();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.timestampIso8601 = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CodeExecutionMeta.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCodeExecutionMeta();
    message.runtime = object.runtime ?? "";
    message.exitCode = object.exitCode ?? 0;
    message.durationMs = object.durationMs ?? 0;
    message.timestampIso8601 = object.timestampIso8601 ?? "";
    return message;
  }
};
function createBaseCodeBlockElement() {
  return { id: "", kind: 0, theme: undefined, script: undefined };
}
var CodeBlockElement = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== "") {
      writer.uint32(10).string(message.id);
    }
    if (message.kind !== 0) {
      writer.uint32(16).int32(message.kind);
    }
    if (message.theme !== undefined) {
      CodeThemeRef.encode(message.theme, writer.uint32(26).fork()).join();
    }
    if (message.script !== undefined) {
      Script.encode(message.script, writer.uint32(58).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCodeBlockElement();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.kind = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.theme = CodeThemeRef.decode(reader, reader.uint32());
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.script = Script.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CodeBlockElement.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCodeBlockElement();
    message.id = object.id ?? "";
    message.kind = object.kind ?? 0;
    message.theme = object.theme !== undefined && object.theme !== null ? CodeThemeRef.fromPartial(object.theme) : undefined;
    message.script = object.script !== undefined && object.script !== null ? Script.fromPartial(object.script) : undefined;
    return message;
  }
};
function createBaseCodeEnvironment() {
  return { id: "", language: "", initSource: "" };
}
var CodeEnvironment = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== "") {
      writer.uint32(10).string(message.id);
    }
    if (message.language !== "") {
      writer.uint32(18).string(message.language);
    }
    if (message.initSource !== "") {
      writer.uint32(26).string(message.initSource);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCodeEnvironment();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.language = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.initSource = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CodeEnvironment.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCodeEnvironment();
    message.id = object.id ?? "";
    message.language = object.language ?? "";
    message.initSource = object.initSource ?? "";
    return message;
  }
};
function createBaseScript() {
  return { language: "", source: "", returnMode: 0, environmentId: "", result: undefined, execution: undefined };
}
var Script = {
  encode(message, writer = new BinaryWriter) {
    if (message.language !== "") {
      writer.uint32(10).string(message.language);
    }
    if (message.source !== "") {
      writer.uint32(18).string(message.source);
    }
    if (message.returnMode !== 0) {
      writer.uint32(32).int32(message.returnMode);
    }
    if (message.environmentId !== "") {
      writer.uint32(42).string(message.environmentId);
    }
    if (message.result !== undefined) {
      CodeResult.encode(message.result, writer.uint32(50).fork()).join();
    }
    if (message.execution !== undefined) {
      CodeExecutionMeta.encode(message.execution, writer.uint32(58).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseScript();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.language = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.source = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.returnMode = reader.int32();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.environmentId = reader.string();
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.result = CodeResult.decode(reader, reader.uint32());
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.execution = CodeExecutionMeta.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Script.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseScript();
    message.language = object.language ?? "";
    message.source = object.source ?? "";
    message.returnMode = object.returnMode ?? 0;
    message.environmentId = object.environmentId ?? "";
    message.result = object.result !== undefined && object.result !== null ? CodeResult.fromPartial(object.result) : undefined;
    message.execution = object.execution !== undefined && object.execution !== null ? CodeExecutionMeta.fromPartial(object.execution) : undefined;
    return message;
  }
};
function createBaseCodeResult() {
  return { json: undefined, stdout: undefined, refs: [], error: undefined };
}
var CodeResult = {
  encode(message, writer = new BinaryWriter) {
    if (message.json !== undefined) {
      writer.uint32(18).string(message.json);
    }
    if (message.stdout !== undefined) {
      writer.uint32(26).string(message.stdout);
    }
    for (const v of message.refs) {
      writer.uint32(34).string(v);
    }
    if (message.error !== undefined) {
      writer.uint32(42).string(message.error);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCodeResult();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.json = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.stdout = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.refs.push(reader.string());
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.error = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CodeResult.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCodeResult();
    message.json = object.json ?? undefined;
    message.stdout = object.stdout ?? undefined;
    message.refs = object.refs?.map((e) => e) || [];
    message.error = object.error ?? undefined;
    return message;
  }
};
function createBaseConnectorLineStyle() {
  return { cap: undefined, join: undefined, head: undefined, tail: undefined };
}
var ConnectorLineStyle = {
  encode(message, writer = new BinaryWriter) {
    if (message.cap !== undefined) {
      writer.uint32(40).int32(message.cap);
    }
    if (message.join !== undefined) {
      writer.uint32(48).int32(message.join);
    }
    if (message.head !== undefined) {
      ConnectorLineStyle_LineEnd.encode(message.head, writer.uint32(58).fork()).join();
    }
    if (message.tail !== undefined) {
      ConnectorLineStyle_LineEnd.encode(message.tail, writer.uint32(66).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseConnectorLineStyle();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.cap = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.join = reader.int32();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.head = ConnectorLineStyle_LineEnd.decode(reader, reader.uint32());
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.tail = ConnectorLineStyle_LineEnd.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ConnectorLineStyle.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseConnectorLineStyle();
    message.cap = object.cap ?? undefined;
    message.join = object.join ?? undefined;
    message.head = object.head !== undefined && object.head !== null ? ConnectorLineStyle_LineEnd.fromPartial(object.head) : undefined;
    message.tail = object.tail !== undefined && object.tail !== null ? ConnectorLineStyle_LineEnd.fromPartial(object.tail) : undefined;
    return message;
  }
};
function createBaseConnectorLineStyle_LineEnd() {
  return { type: 0, width: 0, length: 0 };
}
var ConnectorLineStyle_LineEnd = {
  encode(message, writer = new BinaryWriter) {
    if (message.type !== 0) {
      writer.uint32(8).int32(message.type);
    }
    if (message.width !== 0) {
      writer.uint32(16).int32(message.width);
    }
    if (message.length !== 0) {
      writer.uint32(24).int32(message.length);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseConnectorLineStyle_LineEnd();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.type = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.width = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.length = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ConnectorLineStyle_LineEnd.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseConnectorLineStyle_LineEnd();
    message.type = object.type ?? 0;
    message.width = object.width ?? 0;
    message.length = object.length ?? 0;
    return message;
  }
};
var gt2 = (() => {
  if (typeof globalThis !== "undefined") {
    return globalThis;
  }
  if (typeof self !== "undefined") {
    return self;
  }
  if (typeof window !== "undefined") {
    return window;
  }
  if (typeof global !== "undefined") {
    return global;
  }
  throw "Unable to locate global object";
})();
function longToNumber2(int64) {
  const num = gt2.Number(int64.toString());
  if (num > gt2.Number.MAX_SAFE_INTEGER) {
    throw new gt2.Error("Value is larger than Number.MAX_SAFE_INTEGER");
  }
  if (num < gt2.Number.MIN_SAFE_INTEGER) {
    throw new gt2.Error("Value is smaller than Number.MIN_SAFE_INTEGER");
  }
  return num;
}

// node_modules/@oai/granola/dist/style-map.js
function mapPlaceholderToTxStyle(phType) {
  switch (phType) {
    case "title":
    case "ctrTitle":
      return "titleStyle";
    case "body":
    case undefined:
    case "obj":
    case "content":
    case "subTitle":
    case "":
      return "bodyStyle";
    default:
      return "otherStyle";
  }
}

// node_modules/@oai/granola/dist/models/presentation/placeholder-utils.js
var RAW_TO_PLACEHOLDER_TYPE = new Map([
  ["title", "title"],
  ["ctrTitle", "title"],
  ["ctrtitle", "title"],
  ["subtitle", "subtitle"],
  ["subTitle", "subtitle"],
  ["body", "body"],
  ["content", "content"],
  ["obj", "content"],
  ["picture", "picture"],
  ["pic", "picture"],
  ["chart", "chart"],
  ["tbl", "table"],
  ["table", "table"]
]);
function mapProtoPlaceholderType(raw) {
  if (!raw) {
    return;
  }
  const exact = RAW_TO_PLACEHOLDER_TYPE.get(raw);
  if (exact) {
    return exact;
  }
  const normalised = raw.trim();
  if (!normalised) {
    return;
  }
  const lower = normalised.toLowerCase();
  return RAW_TO_PLACEHOLDER_TYPE.get(lower) ?? undefined;
}
function normalizePlaceholderKey(name) {
  return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, " ").trim().replace(/\s+/g, " ");
}
function derivePlaceholderKey(options) {
  const type = mapProtoPlaceholderType(options.rawType ?? undefined);
  if (type) {
    return normalizePlaceholderKey(type);
  }
  if (!options.name) {
    return;
  }
  const trimmed = options.name.trim();
  if (trimmed.length === 0) {
    return;
  }
  return normalizePlaceholderKey(trimmed);
}

// node_modules/@oai/granola/dist/draw-utils/utils.js
var EMU_TO_PX = 1 / 9525;
function isValidBBox(bbox) {
  return bbox.xEmu !== 0 || bbox.yEmu !== 0 || bbox.widthEmu !== 0 || bbox.heightEmu !== 0;
}
function isPlainObject(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}
function cloneMergeValue(value) {
  if (Array.isArray(value)) {
    return value.map((item) => cloneMergeValue(item));
  }
  if (!isPlainObject(value)) {
    return value;
  }
  const cloned = {};
  for (const [key, child] of Object.entries(value)) {
    cloned[key] = cloneMergeValue(child);
  }
  return cloned;
}
function mergeKeepingDefined(target, source) {
  if (!source) {
    return target;
  }
  for (const [key, sourceValue] of Object.entries(source)) {
    const targetValue = target[key];
    if (targetValue === undefined || targetValue === null) {
      target[key] = cloneMergeValue(sourceValue);
      continue;
    }
    if (isPlainObject(targetValue) && isPlainObject(sourceValue)) {
      mergeKeepingDefined(targetValue, sourceValue);
    }
  }
  return target;
}
var mergeStylesLodash = (mostSpecific, ...fallbacks) => {
  const merged = mergeKeepingDefined({}, cloneMergeValue(mostSpecific) ?? {});
  for (const fallback of fallbacks) {
    mergeKeepingDefined(merged, fallback);
  }
  return merged;
};
function resolveStyles(el, pres, slide) {
  const levelIndex = 0;
  const placeholderIdx = el.placeholderIndex ?? 0;
  const fallbackTypesFor = (t) => {
    switch (t) {
      case "subTitle":
        return ["subTitle", "body"];
      case "ctrTitle":
      case "centeredTitle":
        return ["ctrTitle", "title"];
      default:
        return [t ?? "other"];
    }
  };
  function buildPlaceholderSearchTypes(rawType) {
    const seen = new Set;
    const add = (value) => {
      if (!value)
        return;
      const normalized = mapProtoPlaceholderType(value);
      if (normalized) {
        seen.add(normalized);
        return;
      }
      seen.add(value);
    };
    add(rawType);
    for (const candidate of fallbackTypesFor(rawType)) {
      add(candidate);
    }
    return [...seen];
  }
  const isPlaceholder = el.placeholderType !== undefined || el.placeholderIndex !== undefined;
  let styleGroup = isPlaceholder ? mapPlaceholderToTxStyle(el.placeholderType) : "otherStyle";
  if (el.placeholderType === "subTitle" && styleGroup === "titleStyle") {
    styleGroup = "bodyStyle";
  }
  const layoutId = slide.useLayoutId;
  const layout = pres.layouts.getById(layoutId);
  const textStyle = el.textStyle ?? {
    anchor: 0 /* ANCHOR_TYPE_UNSPECIFIED */,
    vertical: 0 /* VERTICAL_TYPE_UNSPECIFIED */,
    bold: false,
    italic: false,
    fontSize: 1400,
    fill: undefined,
    alignment: 0 /* ALIGNMENT_TYPE_UNSPECIFIED */,
    underline: "none",
    bottomInset: 0,
    leftInset: 0,
    rightInset: 0,
    topInset: 0,
    useParagraphSpacing: false
  };
  const levelStyle = el.levelsStyles?.[levelIndex]?.textStyle;
  let placeholderStyle;
  let placeholderLevelStyle;
  let masterPlaceholderStyle;
  let masterPlaceholderLevelStyle;
  let masterStyle;
  const layoutTypes = buildPlaceholderSearchTypes(el.placeholderType);
  const ph = layout?.findPlaceholder(layoutTypes, placeholderIdx);
  if (ph?.textStyle)
    placeholderStyle = ph.textStyle.toProto();
  if (ph?.levelsStyles?.[levelIndex]?.textStyle) {
    placeholderLevelStyle = ph.levelsStyles[levelIndex].textStyle;
  }
  const masterLayout = (() => {
    if (layout?.parentLayoutId) {
      const explicitParent = pres.layouts.getById(layout.parentLayoutId);
      if (explicitParent)
        return explicitParent;
    }
    const directMaster = pres.layouts.getByName("master");
    if (directMaster)
      return directMaster;
    const masterLike = pres.layouts.items.find((candidate) => {
      const name = candidate.name?.toLowerCase() ?? "";
      const id = candidate.id?.toLowerCase() ?? "";
      return candidate.type === "master" || name.includes("master") || id.includes("slidemaster");
    });
    return masterLike;
  })();
  if (masterLayout) {
    const masterTypes = buildPlaceholderSearchTypes(el.placeholderType);
    const mph = masterLayout.findPlaceholder(masterTypes, placeholderIdx);
    if (mph?.textStyle)
      masterPlaceholderStyle = mph.textStyle.toProto();
    if (mph?.levelsStyles?.[levelIndex]?.textStyle) {
      masterPlaceholderLevelStyle = mph.levelsStyles[levelIndex].textStyle;
    }
    if (styleGroup === "titleStyle" && masterLayout?.titleLevelStyles?.[levelIndex]?.textStyle) {
      masterStyle = masterLayout.titleLevelStyles[levelIndex].textStyle;
    } else if (styleGroup === "bodyStyle" && masterLayout?.bodyLevelStyles?.[levelIndex]?.textStyle) {
      masterStyle = masterLayout.bodyLevelStyles[levelIndex].textStyle;
    } else if (masterLayout?.otherLevelStyles?.[levelIndex]?.textStyle) {
      masterStyle = masterLayout.otherLevelStyles[levelIndex].textStyle;
    }
  }
  const fontRefStyle = el.fontReference?.color ? {
    fill: {
      type: 1 /* FILL_TYPE_SOLID */,
      color: el.fontReference.color,
      gradientStops: []
    }
  } : undefined;
  return mergeStylesLodash(textStyle, fontRefStyle, levelStyle, placeholderStyle, placeholderLevelStyle, masterPlaceholderStyle, masterPlaceholderLevelStyle, masterStyle);
}
function normalizeFamilyName(name) {
  if (!name)
    return;
  const trimmed = String(name).trim();
  if (!trimmed)
    return;
  if (/[^A-Za-z0-9_-]/.test(trimmed)) {
    const escaped = trimmed.replace(/'/g, "\\'");
    return `'${escaped}'`;
  }
  return trimmed;
}

// node_modules/@oai/granola/dist/draw-utils/font-metrics.js
var METRICS_FONT_SIZE = 100;
var ASCENT_SAMPLE = "H";
var DESCENT_SAMPLE = "g";
var sharedMeasurementCtx;
var fontCacheListeners = new Set;
var fontEventsHooked = false;
function createMeasurementContext() {
  if (typeof OffscreenCanvas !== "undefined") {
    const canvas = new OffscreenCanvas(1, 1);
    const ctx = canvas.getContext("2d");
    if (ctx)
      return ctx;
  }
  throw new Error("[font-metrics] OffscreenCanvas API is not available for measurements.");
}
function getSharedMeasurementContext() {
  if (!sharedMeasurementCtx) {
    sharedMeasurementCtx = createMeasurementContext();
    sharedMeasurementCtx.textBaseline = "alphabetic";
  }
  return sharedMeasurementCtx;
}
function notifyFontCacheInvalidation() {
  fontCacheListeners.forEach((listener) => listener());
}
function attachFontLoadListeners() {
  if (fontEventsHooked)
    return;
  const docFonts = globalThis.fonts;
  if (!docFonts || typeof docFonts.addEventListener !== "function")
    return;
  const handler = () => notifyFontCacheInvalidation();
  docFonts.addEventListener("loadingdone", handler);
  docFonts.addEventListener("loadingerror", handler);
  fontEventsHooked = true;
}
function onFontCacheInvalidation(listener) {
  fontCacheListeners.add(listener);
  attachFontLoadListeners();
  return () => {
    fontCacheListeners.delete(listener);
  };
}
function buildFontShorthand(descriptor, sizePx) {
  const style = descriptor.style && descriptor.style !== "normal" ? `${descriptor.style} ` : "";
  const weight = descriptor.weight && descriptor.weight !== "normal" ? `${descriptor.weight} ` : "";
  const stretch = descriptor.stretch && descriptor.stretch !== "normal" ? `${descriptor.stretch} ` : "";
  return `${style}${weight}${stretch}${sizePx}px ${descriptor.family}`.trim();
}
function getFontIdentityKey(descriptor) {
  const style = descriptor.style?.trim().toLowerCase() || "normal";
  const weight = descriptor.weight?.trim().toLowerCase() || "normal";
  const stretch = descriptor.stretch?.trim().toLowerCase() || "normal";
  return `${style}|${weight}|${stretch}|${descriptor.family}`;
}
function sanitizeMetric(value, fallback) {
  if (typeof value === "number" && Number.isFinite(value) && value > 0) {
    return value;
  }
  return fallback;
}
function resolveFontMetricsRatiosFromTextMetrics(ascentSample, descentSample, measuredAtPx = METRICS_FONT_SIZE) {
  const actualAscent = sanitizeMetric(ascentSample.actualBoundingBoxAscent, measuredAtPx * 0.8);
  const actualDescent = sanitizeMetric(descentSample.actualBoundingBoxDescent, measuredAtPx * 0.2);
  const fontBoxAscent = sanitizeMetric(ascentSample.fontBoundingBoxAscent, actualAscent);
  const fontBoxDescent = sanitizeMetric(descentSample.fontBoundingBoxDescent, actualDescent);
  const fontBoxTotal = fontBoxAscent + fontBoxDescent;
  const actualTotal = actualAscent + actualDescent;
  const lineGap = Math.max(0, fontBoxTotal - actualTotal);
  return {
    ascentEm: fontBoxAscent / measuredAtPx,
    descentEm: fontBoxDescent / measuredAtPx,
    lineGapEm: lineGap / measuredAtPx,
    measuredAtPx
  };
}

class FontMetricsProvider {
  #cache = new Map;
  #unsubscribe;
  constructor() {
    this.#unsubscribe = onFontCacheInvalidation(() => this.reset());
  }
  getFontKey(descriptor) {
    return getFontIdentityKey(descriptor);
  }
  getMetrics(descriptor) {
    const key = this.getFontKey(descriptor);
    const cached = this.#cache.get(key);
    if (cached)
      return cached;
    const measured = this.measure(descriptor);
    this.#cache.set(key, measured);
    return measured;
  }
  getMetricsForSize(descriptor, fontPx) {
    const ratios = this.getMetrics(descriptor);
    const ascentPx = ratios.ascentEm * fontPx;
    const descentPx = ratios.descentEm * fontPx;
    const lineGapPx = ratios.lineGapEm * fontPx;
    return {
      ascentPx,
      descentPx,
      lineGapPx
    };
  }
  reset() {
    this.#cache.clear();
  }
  dispose() {
    this.reset();
    this.#unsubscribe?.();
    this.#unsubscribe = undefined;
  }
  measure(descriptor) {
    const ctx = getSharedMeasurementContext();
    ctx.font = buildFontShorthand(descriptor, METRICS_FONT_SIZE);
    const ascentSample = ctx.measureText(ASCENT_SAMPLE);
    const descentSample = ctx.measureText(DESCENT_SAMPLE);
    return resolveFontMetricsRatiosFromTextMetrics(ascentSample, descentSample, METRICS_FONT_SIZE);
  }
}
var defaultFontMetricsProvider = new FontMetricsProvider;

// node_modules/@oai/granola/dist/draw-utils/text-segmentation.js
var intlWithSegmenter = typeof Intl !== "undefined" ? Intl : undefined;
var segmenter = typeof intlWithSegmenter?.Segmenter === "function" ? new intlWithSegmenter.Segmenter : undefined;
var MAX_GRAPHEME_CACHE_ENTRIES = 1024;
var graphemeCache = new Map;
function splitGraphemes(text) {
  if (!text) {
    return [];
  }
  const cached = graphemeCache.get(text);
  if (cached) {
    return cached;
  }
  if (segmenter) {
    const out = [];
    for (const entry of segmenter.segment(text)) {
      if (entry.segment) {
        out.push(entry.segment);
      }
    }
    if (graphemeCache.size >= MAX_GRAPHEME_CACHE_ENTRIES) {
      graphemeCache.clear();
    }
    graphemeCache.set(text, out);
    return out;
  }
  const fallback = Array.from(text);
  if (graphemeCache.size >= MAX_GRAPHEME_CACHE_ENTRIES) {
    graphemeCache.clear();
  }
  graphemeCache.set(text, fallback);
  return fallback;
}

// node_modules/@oai/granola/dist/draw-utils/text-measure-cache.js
var WIDTH_CACHE_LIMIT = 2000;
var KERNING_EPSILON = 0.01;
var SIZE_KEY_PRECISION = 1000;

class TextMeasureCache {
  #ctx;
  #widthCache = new Map;
  #inkBoundsCache = new Map;
  #glyphWidthCache = new Map;
  #kerningCache = new Map;
  #unsubscribe;
  constructor() {
    this.#unsubscribe = onFontCacheInvalidation(() => this.reset());
  }
  measureTokenWidth(font, text) {
    const key = `${font}__${text}`;
    const cached = this.#widthCache.get(key);
    if (cached !== undefined) {
      return cached;
    }
    const ctx = this.#getCtx();
    ctx.font = font;
    ctx.textBaseline = "alphabetic";
    const width = ctx.measureText(text).width;
    this.#widthCache.set(key, width);
    if (this.#widthCache.size > WIDTH_CACHE_LIMIT) {
      const oldestKey = this.#widthCache.keys().next().value;
      if (oldestKey) {
        this.#widthCache.delete(oldestKey);
      }
    }
    return width;
  }
  buildAdvance(fontKey, font, fontPx, text, graphemes) {
    const glyphs = graphemes ?? splitGraphemes(text);
    const advances = new Float32Array(glyphs.length + 1);
    advances[0] = 0;
    if (glyphs.length === 0) {
      return advances;
    }
    let acc = 0;
    let prevGlyph;
    for (let i = 0;i < glyphs.length; i++) {
      const glyph = glyphs[i];
      if (!glyph) {
        continue;
      }
      const glyphWidth = this.getGlyphWidth(fontKey, fontPx, font, glyph);
      const kerning = prevGlyph !== undefined ? this.getKerningAdjustment(fontKey, font, fontPx, prevGlyph, glyph) : 0;
      acc += glyphWidth + kerning;
      advances[i + 1] = acc;
      prevGlyph = glyph;
    }
    return advances;
  }
  measureInkBounds(font, text) {
    const key = `${font}__ink__${text}`;
    const cached = this.#inkBoundsCache.get(key);
    if (cached) {
      return cached;
    }
    const ctx = this.#getCtx();
    ctx.font = font;
    ctx.textBaseline = "alphabetic";
    const metrics = ctx.measureText(text);
    const next = {
      leftPx: typeof metrics.actualBoundingBoxLeft === "number" && Number.isFinite(metrics.actualBoundingBoxLeft) ? Math.max(0, metrics.actualBoundingBoxLeft) : 0,
      rightPx: typeof metrics.actualBoundingBoxRight === "number" && Number.isFinite(metrics.actualBoundingBoxRight) ? Math.max(0, metrics.actualBoundingBoxRight) : Math.max(0, metrics.width),
      ascentPx: typeof metrics.actualBoundingBoxAscent === "number" && Number.isFinite(metrics.actualBoundingBoxAscent) ? Math.max(0, metrics.actualBoundingBoxAscent) : 0,
      descentPx: typeof metrics.actualBoundingBoxDescent === "number" && Number.isFinite(metrics.actualBoundingBoxDescent) ? Math.max(0, metrics.actualBoundingBoxDescent) : 0
    };
    this.#inkBoundsCache.set(key, next);
    return next;
  }
  reset() {
    this.#widthCache.clear();
    this.#inkBoundsCache.clear();
    this.#glyphWidthCache.clear();
    this.#kerningCache.clear();
  }
  dispose() {
    this.reset();
    this.#unsubscribe?.();
    this.#unsubscribe = undefined;
    this.#ctx = undefined;
  }
  #getCtx() {
    if (!this.#ctx) {
      this.#ctx = getSharedMeasurementContext();
    }
    return this.#ctx;
  }
  getGlyphWidth(fontKey, fontPx, font, glyph) {
    const bucketKey = this.getSizeBucketKey(fontKey, fontPx);
    const bucket = this.#glyphWidthCache.get(bucketKey) ?? this.#glyphWidthCache.set(bucketKey, new Map).get(bucketKey);
    const cached = bucket.get(glyph);
    if (cached !== undefined) {
      return cached;
    }
    const width = this.measureDirect(font, glyph);
    bucket.set(glyph, width);
    return width;
  }
  getKerningAdjustment(fontKey, font, fontPx, left, right) {
    if (!left || !right) {
      return 0;
    }
    const pairKey = `${this.getSizeBucketKey(fontKey, fontPx)}__${left}${right}`;
    const cached = this.#kerningCache.get(pairKey);
    if (cached !== undefined) {
      return cached;
    }
    const pairWidth = this.measureDirect(font, left + right);
    const leftWidth = this.getGlyphWidth(fontKey, fontPx, font, left);
    const rightWidth = this.getGlyphWidth(fontKey, fontPx, font, right);
    const kerning = pairWidth - (leftWidth + rightWidth);
    const normalized = Math.abs(kerning) < KERNING_EPSILON ? 0 : kerning;
    this.#kerningCache.set(pairKey, normalized);
    return normalized;
  }
  measureDirect(font, text) {
    const ctx = this.#getCtx();
    ctx.font = font;
    ctx.textBaseline = "alphabetic";
    return ctx.measureText(text).width;
  }
  getSizeBucketKey(fontKey, fontPx) {
    const scaled = Math.round(fontPx * SIZE_KEY_PRECISION);
    return `${fontKey}@${scaled}`;
  }
}

// node_modules/@oai/granola/dist/openxml/color-transform.js
function clamp(value, min, max) {
  if (Number.isNaN(value)) {
    return min;
  }
  return Math.min(Math.max(value, min), max);
}
function hexToRgb(hex) {
  const clean = hex.replace("#", "");
  return {
    r: parseInt(clean.slice(0, 2), 16),
    g: parseInt(clean.slice(2, 4), 16),
    b: parseInt(clean.slice(4, 6), 16)
  };
}
function rgbToHex(rgb) {
  const to2 = (value) => clamp(Math.round(value), 0, 255).toString(16).padStart(2, "0");
  return `#${to2(rgb.r)}${to2(rgb.g)}${to2(rgb.b)}`.toUpperCase();
}
function rgbToHsl(r, g, b) {
  r /= 255;
  g /= 255;
  b /= 255;
  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  let h = 0;
  let s = 0;
  const l = (max + min) / 2;
  if (max !== min) {
    const d = max - min;
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
    switch (max) {
      case r:
        h = (g - b) / d + (g < b ? 6 : 0);
        break;
      case g:
        h = (b - r) / d + 2;
        break;
      default:
        h = (r - g) / d + 4;
        break;
    }
    h /= 6;
  }
  return { h, s, l };
}
function hslToRgb(h, s, l) {
  let r;
  let g;
  let b;
  if (s === 0) {
    r = g = b = l;
  } else {
    const hue2rgb = (p2, q2, t) => {
      if (t < 0)
        t += 1;
      if (t > 1)
        t -= 1;
      if (t < 1 / 6)
        return p2 + (q2 - p2) * 6 * t;
      if (t < 1 / 2)
        return q2;
      if (t < 2 / 3)
        return p2 + (q2 - p2) * (2 / 3 - t) * 6;
      return p2;
    };
    const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
    const p = 2 * l - q;
    r = hue2rgb(p, q, h + 1 / 3);
    g = hue2rgb(p, q, h);
    b = hue2rgb(p, q, h - 1 / 3);
  }
  return {
    r: Math.round(r * 255),
    g: Math.round(g * 255),
    b: Math.round(b * 255)
  };
}
function applyLumAndSaturationTransforms(rgb, transform) {
  const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b);
  if (typeof transform.satMod === "number") {
    hsl.s = clamp(hsl.s * (transform.satMod / 1e5), 0, 1);
  }
  if (typeof transform.lumMod === "number") {
    hsl.l = clamp(hsl.l * (transform.lumMod / 1e5), 0, 1);
  }
  if (typeof transform.lumOff === "number") {
    hsl.l = clamp(hsl.l + transform.lumOff / 1e5, 0, 1);
  }
  return hslToRgb(hsl.h, hsl.s, hsl.l);
}
function applyDrawingTint(rgb, tint) {
  const k = clamp(tint / 1e5, -1, 1);
  const apply = (channel) => k >= 0 ? channel + (255 - channel) * k : channel * (1 + k);
  return {
    r: apply(rgb.r),
    g: apply(rgb.g),
    b: apply(rgb.b)
  };
}
function applySpreadsheetTint(rgb, tint) {
  const k = clamp(tint / 1e5, -1, 1);
  const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b);
  let lum = Math.round(hsl.l * 255);
  if (k < 0) {
    lum = Math.round(lum * (1 + k));
  } else {
    lum = Math.round(lum * (1 - k) + (255 - Math.floor(255 * (1 - k))));
  }
  hsl.l = clamp(lum / 255, 0, 1);
  return hslToRgb(hsl.h, hsl.s, hsl.l);
}
function applyShade(rgb, shade) {
  const factor = clamp(1 - shade / 1e5, 0, 1);
  return {
    r: rgb.r * factor,
    g: rgb.g * factor,
    b: rgb.b * factor
  };
}
function applyOpenXmlColorTransform(rgb, transform, colorSpace = "drawingml") {
  if (!transform) {
    return {
      r: clamp(Math.round(rgb.r), 0, 255),
      g: clamp(Math.round(rgb.g), 0, 255),
      b: clamp(Math.round(rgb.b), 0, 255)
    };
  }
  let next = { ...rgb };
  if (typeof transform.satMod === "number" || typeof transform.lumMod === "number" || typeof transform.lumOff === "number") {
    next = applyLumAndSaturationTransforms(next, transform);
  }
  if (typeof transform.tint === "number") {
    next = colorSpace === "spreadsheetml" ? applySpreadsheetTint(next, transform.tint) : applyDrawingTint(next, transform.tint);
  }
  if (typeof transform.shade === "number") {
    next = applyShade(next, transform.shade);
  }
  return {
    r: clamp(Math.round(next.r), 0, 255),
    g: clamp(Math.round(next.g), 0, 255),
    b: clamp(Math.round(next.b), 0, 255)
  };
}

// node_modules/@oai/granola/dist/draw-utils/color-utils.js
function clamp2(val, min, max) {
  return Math.min(Math.max(val, min), max);
}
function colorToRgba(color, themeMap, options) {
  if (!color)
    return "rgba(0,0,0,1)";
  let baseHex = "#000000";
  let a = 1;
  if (color.type === 1 /* COLOR_TYPE_RGB */) {
    const raw = String(color.value).replace(/^#/, "");
    if (raw.length === 8) {
      baseHex = `#${raw.slice(2)}`;
    } else if (raw.length === 6) {
      baseHex = `#${raw}`;
    } else {
      baseHex = "#000000";
    }
  } else if (color.type === 2 /* COLOR_TYPE_SCHEME */) {
    const raw = String(color.value);
    let hex = themeMap.colorMap[raw];
    if (!hex && raw.startsWith("theme:")) {
      const n = parseInt(raw.split(":")[1] ?? "", 10);
      if (!Number.isNaN(n)) {
        const schemeKeys = [
          "lt1",
          "dk1",
          "lt2",
          "dk2",
          "accent1",
          "accent2",
          "accent3",
          "accent4",
          "accent5",
          "accent6",
          "hlink",
          "folHlink"
        ];
        const key = schemeKeys[n];
        if (key)
          hex = themeMap.colorMap[key];
      }
    }
    baseHex = hex || "#000000";
  } else {
    baseHex = "#000000";
  }
  let { r, g, b } = hexToRgb(baseHex);
  const t = color.transform;
  if (t) {
    if (t.alpha !== undefined) {
      a = clamp2(t.alpha / 1e5, 0, 1);
    }
    ({ r, g, b } = applyOpenXmlColorTransform({ r, g, b }, t, options?.colorSpace ?? "drawingml"));
  }
  return `rgba(${r},${g},${b},${a})`;
}
function resolveColor(color, themeMap, defaultFillOrOptions) {
  const options = typeof defaultFillOrOptions === "string" ? { defaultFill: defaultFillOrOptions } : defaultFillOrOptions;
  const defaultFill = options?.defaultFill;
  if (!color)
    return defaultFill ?? "transparent";
  return colorToRgba(color, themeMap, options) ?? defaultFill ?? "transparent";
}

// node_modules/@oai/granola/dist/draw-utils/build-theme-map.js
function buildThemeMap(theme, schemeRemap) {
  if (!theme)
    return { colorMap: {}, lineStyleMap: {}, effectMap: {} };
  const lineStyleMap = {};
  const lineStyles = theme.lineStyleList ?? [];
  for (const [index, l] of lineStyles.entries()) {
    lineStyleMap[index + 1] = l;
  }
  const effectMap = {};
  const effectStyles = theme.effectStyleList ?? [];
  for (const [index, e] of effectStyles.entries()) {
    effectMap[index + 1] = e;
  }
  const baseColorMap = theme.hexColorMap;
  const resolvedColorMap = { ...baseColorMap };
  if (schemeRemap) {
    for (const [from, to] of Object.entries(schemeRemap)) {
      const hex = baseColorMap[to];
      if (hex) {
        resolvedColorMap[from] = hex;
      }
    }
  }
  return {
    colorMap: resolvedColorMap,
    lineStyleMap,
    effectMap
  };
}
function isNumber(value) {
  return typeof value === "number" && !Number.isNaN(value);
}
function pickDefined(preferred, fallback) {
  return preferred !== undefined && preferred !== null ? preferred : fallback !== undefined && fallback !== null ? fallback : undefined;
}
function resolveLevelStyleForParagraph(el, para) {
  if (!el || !el.levelsStyles?.length)
    return;
  const levels = el.levelsStyles;
  const paraML = para?.paragraphStyle?.marginLeft;
  if (isNumber(paraML)) {
    let best;
    let bestDiff = Number.POSITIVE_INFINITY;
    for (const ls of levels) {
      const ml = ls.paragraphStyle?.marginLeft;
      if (!isNumber(ml))
        continue;
      const diff = Math.abs(ml - paraML);
      if (diff < bestDiff) {
        best = ls;
        bestDiff = diff;
      }
    }
    if (best)
      return best;
  }
  return levels.find((ls) => ls.level === 1) ?? levels[0];
}
function mergeParagraphStyles(levelStyle, paragraphStyle) {
  const lvl = levelStyle?.paragraphStyle ?? {};
  return {
    bulletCharacter: pickDefined(paragraphStyle?.bulletCharacter, lvl.bulletCharacter),
    marginLeft: pickDefined(paragraphStyle?.marginLeft, lvl.marginLeft),
    indent: pickDefined(paragraphStyle?.indent, lvl.indent),
    lineSpacingPercent: pickDefined(paragraphStyle?.lineSpacingPercent, lvl.lineSpacingPercent),
    lineSpacingPoints: pickDefined(paragraphStyle?.lineSpacingPoints, lvl.lineSpacingPoints),
    autoNumberType: pickDefined(paragraphStyle?.autoNumberType, lvl.autoNumberType),
    autoNumberStartAt: pickDefined(paragraphStyle?.autoNumberStartAt, lvl.autoNumberStartAt)
  };
}
function resolveParagraphSpacing(el, para) {
  const lvl = resolveLevelStyleForParagraph(el, para);
  const paraBefore = para?.spaceBefore;
  const paraAfter = para?.spaceAfter;
  return {
    spaceBefore: paraBefore !== undefined ? paraBefore : lvl?.spaceBefore,
    spaceAfter: paraAfter !== undefined ? paraAfter : lvl?.spaceAfter
  };
}

// node_modules/@oai/granola/dist/draw-utils/text-math.js
var PX_PER_POINT = 96 / 72;
var TWIPS_PER_POINT = 20;
function fontSizeToPx(fontSizePtHundred, scale = 1) {
  return (fontSizePtHundred ?? 0) / 100 * PX_PER_POINT * scale;
}
function ptToPx(ptHundred) {
  return ptHundred ? ptHundred / 100 * PX_PER_POINT : 0;
}
function twipsToPx(twips) {
  return twips ? twips / TWIPS_PER_POINT * PX_PER_POINT : 0;
}

// node_modules/@oai/granola/dist/draw-utils/paragraph-spacing.js
function paragraphSpacingToPx(value, unit) {
  if (value === undefined) {
    return 0;
  }
  if (unit === "twips") {
    return twipsToPx(value);
  }
  return ptToPx(value);
}
function resolveParagraphSpacingConfig({ element, paragraph, defaults }) {
  const resolvedSpacing = resolveParagraphSpacing(element, paragraph);
  return {
    spaceBefore: resolvedSpacing.spaceBefore !== undefined ? resolvedSpacing.spaceBefore : defaults?.spaceBefore,
    spaceAfter: resolvedSpacing.spaceAfter !== undefined ? resolvedSpacing.spaceAfter : defaults?.spaceAfter
  };
}
function resolveParagraphSpacingPx({ element, paragraph, unit, defaults }) {
  const spacing = resolveParagraphSpacingConfig({
    element,
    paragraph,
    defaults
  });
  return {
    spaceBeforePx: paragraphSpacingToPx(spacing.spaceBefore, unit),
    spaceAfterPx: paragraphSpacingToPx(spacing.spaceAfter, unit)
  };
}
function getParagraphSpacingOverlapPx(previousSpaceAfterPx, nextSpaceBeforePx) {
  const previous = Math.max(0, previousSpaceAfterPx);
  const next = Math.max(0, nextSpaceBeforePx);
  return Math.min(previous, next);
}
function getCollapsedParagraphSpaceBeforePx(previousSpaceAfterPx, nextSpaceBeforePx) {
  const overlap = getParagraphSpacingOverlapPx(previousSpaceAfterPx, nextSpaceBeforePx);
  return Math.max(0, nextSpaceBeforePx - overlap);
}

// node_modules/@oai/granola/dist/models/document/style-cascade.js
var DOCX_CONTEXTUAL_SPACING_TAG = "docx:contextualSpacing";
var DOCX_CONTEXTUAL_SPACING_SCHEME_PREFIX = "__docxContextualSpacing:";
var DOCX_CONTEXTUAL_SPACING_SCHEME_TOKEN = `${DOCX_CONTEXTUAL_SPACING_SCHEME_PREFIX}true`;
function mergeStyleWithFallback(specific, fallback) {
  if (!specific && !fallback) {
    return;
  }
  const merged = {
    ...fallback ?? {}
  };
  for (const [key, value] of Object.entries(specific ?? {})) {
    if (value !== undefined) {
      merged[key] = value;
    }
  }
  return merged;
}
function schemeTokenKey(token) {
  const delimiterIndex = token.indexOf(":");
  return delimiterIndex >= 0 ? token.slice(0, delimiterIndex + 1) : token;
}
function normalizeSchemeTokenValue(value) {
  const normalized = value?.trim().toLowerCase();
  return normalized ? normalized : undefined;
}
function mergeTextStyleSchemeTokens(...schemes) {
  const order = [];
  const values = new Map;
  for (const scheme of schemes) {
    if (!scheme) {
      continue;
    }
    for (const rawToken of scheme.split(";")) {
      const token = rawToken.trim();
      if (!token) {
        continue;
      }
      const key = schemeTokenKey(token).toLowerCase();
      if (!values.has(key)) {
        order.push(key);
      }
      values.set(key, token);
    }
  }
  if (order.length === 0) {
    return;
  }
  return order.map((key) => values.get(key)).join(";");
}
function resolveSchemeValue(scheme, prefix) {
  if (!scheme) {
    return;
  }
  const normalizedPrefix = prefix.toLowerCase();
  for (const rawToken of scheme.split(";")) {
    const token = rawToken.trim();
    if (!token || !token.toLowerCase().startsWith(normalizedPrefix)) {
      continue;
    }
    const value = token.slice(prefix.length).trim();
    if (value) {
      return value;
    }
  }
  return;
}
function hasDocxContextualSpacing(textStyle) {
  const token = resolveSchemeValue(textStyle?.scheme, DOCX_CONTEXTUAL_SPACING_SCHEME_PREFIX);
  const normalized = normalizeSchemeTokenValue(token);
  return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
}
function hasDocxContextualSpacingTag(tags) {
  return (tags ?? []).some((tag) => normalizeSchemeTokenValue(tag) === normalizeSchemeTokenValue(DOCX_CONTEXTUAL_SPACING_TAG));
}
function mergeDocumentTextStyle(specific, fallback) {
  const merged = mergeStyleWithFallback(specific, fallback);
  if (!merged) {
    return;
  }
  const mergedScheme = mergeTextStyleSchemeTokens(fallback?.scheme, specific?.scheme);
  if (mergedScheme) {
    merged.scheme = mergedScheme;
  }
  return merged;
}
function resolveDefaultParagraphStyleId(textStyles) {
  for (const style of textStyles) {
    if (style.id?.toLowerCase() === "normal") {
      return style.id;
    }
  }
  for (const style of textStyles) {
    if (style.name?.toLowerCase() === "normal" && style.id) {
      return style.id;
    }
  }
  for (const style of textStyles) {
    if (style.id) {
      return style.id;
    }
  }
  return;
}
function normalizeStyleKey(value) {
  const normalized = value?.trim().toLowerCase();
  return normalized ? normalized : undefined;
}

class ParagraphStyleDefinitionResolver {
  #defaultStyleId;
  #styleById = new Map;
  #styleIdByName = new Map;
  #resolvedStyleById = new Map;
  #resolvingStyleIds = new Set;
  constructor(textStyles = []) {
    this.#defaultStyleId = resolveDefaultParagraphStyleId(textStyles);
    for (const style of textStyles) {
      if (style.id) {
        this.#styleById.set(style.id, style);
        const normalizedId = normalizeStyleKey(style.id);
        if (normalizedId) {
          this.#styleIdByName.set(normalizedId, style.id);
        }
      }
      const normalizedName = normalizeStyleKey(style.name);
      if (normalizedName && style.id) {
        this.#styleIdByName.set(normalizedName, style.id);
      }
    }
  }
  resolve(styleId) {
    return this.resolveExplicit(styleId ?? this.#defaultStyleId);
  }
  resolveStyleIdByName(name) {
    const normalizedName = normalizeStyleKey(name);
    if (!normalizedName) {
      return;
    }
    return this.#styleIdByName.get(normalizedName);
  }
  resolveByName(name) {
    const styleId = this.resolveStyleIdByName(name);
    if (!styleId) {
      return;
    }
    return this.resolveExplicit(styleId);
  }
  resolveExplicit(styleId) {
    if (!styleId) {
      return;
    }
    if (this.#resolvedStyleById.has(styleId)) {
      return this.#resolvedStyleById.get(styleId) ?? undefined;
    }
    if (this.#resolvingStyleIds.has(styleId)) {
      return;
    }
    const style = this.#styleById.get(styleId);
    if (!style) {
      this.#resolvedStyleById.set(styleId, null);
      return;
    }
    this.#resolvingStyleIds.add(styleId);
    const inherited = this.resolveExplicit(style.basedOn);
    this.#resolvingStyleIds.delete(styleId);
    const resolved = {
      textStyle: mergeDocumentTextStyle(style.textStyle, inherited?.textStyle),
      paragraphStyle: mergeStyleWithFallback(style.paragraphStyle, inherited?.paragraphStyle),
      spaceBefore: style.spaceBefore ?? inherited?.spaceBefore,
      spaceAfter: style.spaceAfter ?? inherited?.spaceAfter,
      contextualSpacing: hasDocxContextualSpacingTag(style.tags) || inherited?.contextualSpacing === true
    };
    this.#resolvedStyleById.set(styleId, resolved);
    return resolved;
  }
}

// node_modules/@oai/granola/dist/draw-utils/text-layout.js
var DEFAULT_FONT_SIZE_PT = 14;
var DEFAULT_FONT_SIZE_PT_HUNDRED = DEFAULT_FONT_SIZE_PT * 100;
var DEFAULT_LINE_MULTIPLE = 1;
var NO_WRAP_WIDTH = 1e9;
var FALLBACK_ASCENT_RATIO = 0.8;
var FALLBACK_DESCENT_RATIO = 0.2;
var WHITESPACE_REGEX = /\s/;
var MAX_TOKEN_CACHE_ENTRIES = 1024;
var TWIP_TO_PX = 96 / 1440;
var DOCX_TWIP_PARAGRAPH_DISTANCE_THRESHOLD = 20000;
var DOCX_HIGHLIGHT_SCHEME_PREFIX = "__docxHighlight:";
var DOCX_ALIGNMENT_SCHEME_PREFIX = "__docxAlign:";
var DOCX_CAPS_SCHEME_PREFIX = "__docxCaps:";
var DOCX_PARAGRAPH_RIGHT_INDENT_SCHEME_PREFIX = "__docxParagraphRightIndent:";
var DOCX_COMPLEX_SCRIPT_FONT_SIZE_SCHEME_PREFIX = "__docxComplexScriptFontSize:";
var DOCX_COMPLEX_SCRIPT_TYPEFACE_SCHEME_PREFIX = "__docxComplexScriptTypeface:";
var DOCX_EAST_ASIA_TYPEFACE_SCHEME_PREFIX = "__docxEastAsiaTypeface:";
var DOCX_RENDERED_FLOW_BREAK_TOKEN = "__docxBreak:rendered__";
var DEFAULT_HYPERLINK_COLOR = "#0563c1";
var DEFAULT_HYPERLINK_UNDERLINE = "single";
var runTextTokenCache = new Map;
var DOCX_HIGHLIGHT_COLORS = {
  yellow: "#fff200",
  darkyellow: "#c9a000",
  green: "#00b050",
  darkgreen: "#006100",
  cyan: "#00b0f0",
  magenta: "#c000c0",
  blue: "#4472c4",
  darkblue: "#1f3864",
  red: "#ff0000",
  darkred: "#9c0006",
  gray: "#808080",
  darkgray: "#404040",
  lightgray: "#d9d9d9",
  black: "#111111"
};
function emuToPx(emu) {
  return emu ? emu * EMU_TO_PX : 0;
}
function twipsToPx2(twips) {
  return twips ? twips * TWIP_TO_PX : 0;
}
function paragraphDistanceToPx(value) {
  if (value === undefined) {
    return 0;
  }
  return Math.abs(value) <= DOCX_TWIP_PARAGRAPH_DISTANCE_THRESHOLD ? twipsToPx2(value) : emuToPx(value);
}
function styleIdsMatch(leftStyleId, rightStyleId) {
  const left = leftStyleId?.trim().toLowerCase();
  const right = rightStyleId?.trim().toLowerCase();
  return !!left && left === right;
}
function shouldSuppressDocxContextualSpacing(previousParagraph, currentParagraph) {
  return styleIdsMatch(previousParagraph?.styleId, currentParagraph?.styleId) && hasDocxContextualSpacing(currentParagraph?.textStyle);
}
function normalizeHighlightKey(value) {
  return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "");
}
function resolveSchemeValue2(scheme, prefix) {
  if (!scheme) {
    return;
  }
  const tokens = scheme.split(";").map((token) => token.trim()).filter((token) => token.length > 0);
  const normalizedPrefix = prefix.toLowerCase();
  for (const token of tokens) {
    if (!token.toLowerCase().startsWith(normalizedPrefix)) {
      continue;
    }
    const value = token.slice(prefix.length).trim();
    if (value.length > 0) {
      return value;
    }
  }
  return;
}
function schemeTokenKey2(token) {
  const delimiterIndex = token.indexOf(":");
  return delimiterIndex >= 0 ? token.slice(0, delimiterIndex + 1) : token;
}
function mergeSchemeTokens(...schemes) {
  const order = [];
  const values = new Map;
  for (const scheme of schemes) {
    if (!scheme) {
      continue;
    }
    for (const rawToken of scheme.split(";")) {
      const token = rawToken.trim();
      if (!token) {
        continue;
      }
      const key = schemeTokenKey2(token).toLowerCase();
      if (!values.has(key)) {
        order.push(key);
      }
      values.set(key, token);
    }
  }
  if (order.length === 0) {
    return;
  }
  return order.map((key) => values.get(key)).join(";");
}
function resolveHighlightSchemeColor(scheme) {
  const token = resolveSchemeValue2(scheme, DOCX_HIGHLIGHT_SCHEME_PREFIX);
  if (!token) {
    return;
  }
  if (token.startsWith("#")) {
    return token;
  }
  return DOCX_HIGHLIGHT_COLORS[normalizeHighlightKey(token)];
}
function resolveAlignmentFromScheme(scheme) {
  const token = resolveSchemeValue2(scheme, DOCX_ALIGNMENT_SCHEME_PREFIX);
  if (!token) {
    return;
  }
  const normalized = token.toLowerCase();
  if (normalized === "justify" || normalized === "justified") {
    return "justify";
  }
  if (normalized === "center") {
    return "center";
  }
  if (normalized === "right") {
    return "right";
  }
  return "left";
}
function hasDocxCaps(scheme) {
  const token = resolveSchemeValue2(scheme, DOCX_CAPS_SCHEME_PREFIX);
  if (!token) {
    return false;
  }
  const normalized = token.toLowerCase();
  return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
}
function applyDocxTextTransforms(text, scheme) {
  return hasDocxCaps(scheme) ? text.toUpperCase() : text;
}
function resolveDocxSchemeFontSize(scheme) {
  const token = resolveSchemeValue2(scheme, DOCX_COMPLEX_SCRIPT_FONT_SIZE_SCHEME_PREFIX);
  if (!token) {
    return;
  }
  const parsed = Number.parseInt(token, 10);
  return Number.isFinite(parsed) && parsed > 0 ? parsed * 50 : undefined;
}
function resolveDocxSchemeTwips(scheme, prefix) {
  const token = resolveSchemeValue2(scheme, prefix);
  if (!token) {
    return;
  }
  const parsed = Number.parseInt(token, 10);
  return Number.isFinite(parsed) ? parsed : undefined;
}
function resolveDocxSchemeTypeface(scheme) {
  return resolveSchemeValue2(scheme, DOCX_COMPLEX_SCRIPT_TYPEFACE_SCHEME_PREFIX) ?? resolveSchemeValue2(scheme, DOCX_EAST_ASIA_TYPEFACE_SCHEME_PREFIX);
}
function resolveTextStyleFontSize(style) {
  return style?.fontSize ?? resolveDocxSchemeFontSize(style?.scheme);
}
function resolveTextStyleTypeface(style) {
  return style?.typeface ?? style?.name ?? resolveDocxSchemeTypeface(style?.scheme);
}
function resolveTextStyleUnderline(style, isHyperlink) {
  if (isHyperlink && (!style?.underline || style.underline === "none")) {
    return DEFAULT_HYPERLINK_UNDERLINE;
  }
  return style?.underline;
}
function toAlpha(num, upper) {
  let n = Math.max(1, Math.floor(num));
  let s = "";
  while (n > 0) {
    n--;
    s = String.fromCharCode(97 + n % 26) + s;
    n = Math.floor(n / 26);
  }
  return upper ? s.toUpperCase() : s;
}
function toRoman(num, upper) {
  let n = Math.max(1, Math.min(3999, Math.floor(num)));
  const map = [
    [1000, "M"],
    [900, "CM"],
    [500, "D"],
    [400, "CD"],
    [100, "C"],
    [90, "XC"],
    [50, "L"],
    [40, "XL"],
    [10, "X"],
    [9, "IX"],
    [5, "V"],
    [4, "IV"],
    [1, "I"]
  ];
  let out = "";
  for (const [val, sym] of map) {
    while (n >= val) {
      out += sym;
      n -= val;
    }
  }
  const result = upper ? out : out.toLowerCase();
  return result;
}
function formatListNumber(index, scheme) {
  switch (scheme) {
    case "arabicBracketBoth":
      return `[${index}]`;
    case "arabicPeriod":
      return `${index}.`;
    case "arabicPlain":
      return `${index}`;
    case "alphaLcPeriod":
      return `${toAlpha(index, false)}.`;
    case "alphaUcPeriod":
      return `${toAlpha(index, true)}.`;
    case "alphaLcParenR":
      return `${toAlpha(index, false)})`;
    case "alphaUcParenR":
      return `${toAlpha(index, true)})`;
    case "romanLcPeriod":
      return `${toRoman(index, false)}.`;
    case "romanUcPeriod":
      return `${toRoman(index, true)}.`;
    default:
      return `${index}.`;
  }
}
function tokenizeRunText(text) {
  function tokenizePlainTextChunk(chunk) {
    const graphemes = splitGraphemes(chunk);
    const chunkTokens = [];
    let buffer = [];
    let bufferType = null;
    const flushBuffer = () => {
      if (!buffer.length || !bufferType) {
        return;
      }
      chunkTokens.push({
        type: bufferType,
        text: buffer.join(""),
        graphemes: buffer.slice()
      });
      buffer = [];
      bufferType = null;
    };
    for (let i = 0;i < graphemes.length; i++) {
      const unit = graphemes[i];
      if (!unit) {
        continue;
      }
      const nextUnit = graphemes[i + 1];
      if (unit === "\r" && nextUnit === `
`) {
        flushBuffer();
        chunkTokens.push({ type: "newline", text: `\r
` });
        i++;
        continue;
      }
      if (unit === `
` || unit === "\r") {
        flushBuffer();
        chunkTokens.push({ type: "newline", text: unit });
        continue;
      }
      const tokenType = WHITESPACE_REGEX.test(unit) ? "whitespace" : "word";
      if (tokenType !== bufferType) {
        flushBuffer();
        bufferType = tokenType;
      }
      buffer.push(unit);
    }
    flushBuffer();
    return chunkTokens;
  }
  if (!text) {
    return [];
  }
  const cached = runTextTokenCache.get(text);
  if (cached) {
    return cached;
  }
  const tokens = [];
  let searchStart = 0;
  while (searchStart < text.length) {
    const flowBreakIndex = text.indexOf(DOCX_RENDERED_FLOW_BREAK_TOKEN, searchStart);
    const chunkEnd = flowBreakIndex >= 0 ? flowBreakIndex : text.length;
    if (chunkEnd > searchStart) {
      tokens.push(...tokenizePlainTextChunk(text.slice(searchStart, chunkEnd)));
    }
    if (flowBreakIndex < 0) {
      break;
    }
    searchStart = flowBreakIndex + DOCX_RENDERED_FLOW_BREAK_TOKEN.length;
  }
  if (runTextTokenCache.size >= MAX_TOKEN_CACHE_ENTRIES) {
    runTextTokenCache.clear();
  }
  runTextTokenCache.set(text, tokens);
  return tokens;
}
function sliceAdvance(advances, start, end) {
  const length = end - start;
  const out = new Float32Array(length + 1);
  const base = getAdvanceValue(advances, start);
  for (let i = 0;i <= length; i++) {
    out[i] = getAdvanceValue(advances, start + i) - base;
  }
  return out;
}
function findFittingGraphemeEnd(advances, startIndex, maxWidth) {
  let low = startIndex + 1;
  let high = advances.length - 1;
  let best = startIndex;
  const base = getAdvanceValue(advances, startIndex);
  while (low <= high) {
    const mid = Math.floor((low + high) / 2);
    const width = getAdvanceValue(advances, mid) - base;
    if (width <= maxWidth) {
      best = mid;
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }
  return best;
}
function getAdvanceValue(array, index) {
  if (array.length === 0) {
    return 0;
  }
  if (index <= 0) {
    return array[0] ?? 0;
  }
  if (index >= array.length) {
    return array[array.length - 1] ?? 0;
  }
  return array[index] ?? 0;
}

class TextLayoutEngine {
  fontMetrics;
  measureCache;
  constructor(fontMetrics, measureCache) {
    this.fontMetrics = fontMetrics;
    this.measureCache = measureCache;
  }
  layout(request) {
    const { element } = request;
    if (!element.paragraphs || element.paragraphs.length === 0) {
      return { lines: [], contentHeightPx: 0 };
    }
    const lines = [];
    const textScale = request.textScale ?? 1;
    const effectiveBoxW = request.wrap ? request.boxWidthPx : NO_WRAP_WIDTH;
    const defaultFontPx = fontSizeToPx(DEFAULT_FONT_SIZE_PT_HUNDRED, textScale);
    const listCounters = {};
    let previousParagraphSpaceAfterPx = 0;
    for (let paraIndex = 0;paraIndex < element.paragraphs.length; paraIndex++) {
      const paragraph = element.paragraphs[paraIndex];
      if (!paragraph)
        continue;
      previousParagraphSpaceAfterPx = this.layoutParagraph({
        element,
        paragraph,
        paraIndex,
        request,
        defaultFontPx,
        effectiveBoxW,
        listCounters,
        lines,
        previousParagraphSpaceAfterPx
      });
    }
    if (!request.wrap) {
      lines.forEach((line) => {
        applyInkBoundsToNoWrapLine(line);
      });
    }
    const nextContentHeightPx = lines.reduce((sum, line) => sum + line.heightPx, 0);
    return { lines, contentHeightPx: nextContentHeightPx };
  }
  layoutParagraph({ element, paragraph, paraIndex, request, defaultFontPx, effectiveBoxW, listCounters, lines, previousParagraphSpaceAfterPx }) {
    const paragraphTextStyle = paragraph.textStyle;
    const levelStyle = resolveLevelStyleForParagraph(element, paragraph);
    const mergedParaStyle = mergeParagraphStyles(levelStyle, paragraph.paragraphStyle);
    const { spaceBeforePx, spaceAfterPx } = resolveParagraphSpacingPx({
      element,
      paragraph,
      unit: request.paragraphSpacingUnit,
      defaults: request.masterDefaults
    });
    const previousParagraph = element.paragraphs?.[paraIndex - 1];
    const nextParagraph = element.paragraphs?.[paraIndex + 1];
    const suppressLeadingContextualSpacing = shouldSuppressDocxContextualSpacing(previousParagraph, paragraph);
    const suppressTrailingContextualSpacing = shouldSuppressDocxContextualSpacing(paragraph, nextParagraph);
    const effectiveSpaceBeforePx = suppressLeadingContextualSpacing ? 0 : spaceBeforePx;
    const effectiveSpaceAfterPx = suppressTrailingContextualSpacing ? 0 : spaceAfterPx;
    const paragraphMarginLeftPx = paragraph.marginLeft !== undefined ? paragraphDistanceToPx(paragraph.marginLeft) : emuToPx(mergedParaStyle.marginLeft ?? 0);
    const paragraphIndentPx = paragraph.indent !== undefined ? paragraphDistanceToPx(paragraph.indent) : emuToPx(mergedParaStyle.indent ?? 0);
    const paragraphRightIndentPx = twipsToPx2(resolveDocxSchemeTwips(paragraphTextStyle?.scheme, DOCX_PARAGRAPH_RIGHT_INDENT_SCHEME_PREFIX));
    const hasBullet = !!mergedParaStyle.bulletCharacter;
    const isNumbered = !!mergedParaStyle.autoNumberType;
    const hasListMarker = hasBullet || isNumbered;
    const firstLineOffsetPx = paragraphMarginLeftPx + paragraphIndentPx;
    const hangingOffsetPx = paragraphMarginLeftPx;
    const lineMultipleRaw = (mergedParaStyle.lineSpacingPercent ?? request.masterDefaults?.lineSpacingPercent ?? Math.round(DEFAULT_LINE_MULTIPLE * 1e5)) / 1e5;
    const lineMultiple = lineMultipleRaw > 0 ? lineMultipleRaw : 1;
    const lineSpacingPx = mergedParaStyle.lineSpacingPoints !== undefined && mergedParaStyle.lineSpacingPoints > 0 ? ptToPx(mergedParaStyle.lineSpacingPoints) : undefined;
    const collapsedSpaceBeforePx = getCollapsedParagraphSpaceBeforePx(previousParagraphSpaceAfterPx, effectiveSpaceBeforePx);
    if (collapsedSpaceBeforePx > 0) {
      lines.push({
        segments: [],
        widthPx: 0,
        heightPx: collapsedSpaceBeforePx,
        contentHeightPx: 0,
        align: "left",
        offsetPx: 0,
        availableWidthPx: request.boxWidthPx,
        baselineOffsetPx: 0,
        maxAscentPx: 0,
        maxDescentPx: 0,
        maxPx: 0
      });
    }
    const segs = [];
    let lineWidth = 0;
    let lineAlign = "left";
    let lineMaxAscentPx = 0;
    let lineMaxDescentPx = 0;
    let isFirstLineOfParagraph = true;
    let bulletInserted = false;
    const resolveCurrentLineOffsetPx = () => isFirstLineOfParagraph ? firstLineOffsetPx : hangingOffsetPx;
    const resolveCurrentLineAvailableWidthPx = () => Math.max(1, effectiveBoxW - resolveCurrentLineOffsetPx() - paragraphRightIndentPx);
    const paragraphAlignmentStyle = mergeStylesLodash({}, paragraphTextStyle, request.elementStyle);
    const paragraphAlignmentScheme = mergeSchemeTokens(request.elementStyle?.scheme, paragraphTextStyle?.scheme);
    const paragraphAlignment = resolveAlignmentFromScheme(paragraphAlignmentScheme);
    lineAlign = paragraphAlignment ?? (Number(paragraphAlignmentStyle.alignment) === 4 ? "justify" : paragraphAlignmentStyle.alignment === 2 /* ALIGNMENT_TYPE_CENTER */ ? "center" : paragraphAlignmentStyle.alignment === 3 /* ALIGNMENT_TYPE_RIGHT */ ? "right" : "left");
    const trimTrailingWhitespaceSegments = () => {
      if (!segs.some((segment) => segment.text.length > 0 && segment.text.trim().length > 0)) {
        return;
      }
      let removedWidthPx = 0;
      while (segs.length > 0) {
        const trailingSegment = segs[segs.length - 1];
        if (!trailingSegment || trailingSegment.text.length === 0 || trailingSegment.text.trim().length > 0 || !WHITESPACE_REGEX.test(trailingSegment.text)) {
          break;
        }
        removedWidthPx += trailingSegment.widthPx;
        segs.pop();
      }
      if (removedWidthPx === 0) {
        return;
      }
      lineWidth = Math.max(0, lineWidth - removedWidthPx);
      lineMaxAscentPx = segs.reduce((max, segment) => Math.max(max, segment.ascentPx), 0);
      lineMaxDescentPx = segs.reduce((max, segment) => Math.max(max, segment.descentPx), 0);
    };
    const markLastCommittedLineFlowBreak = () => {
      const lastLine = lines[lines.length - 1];
      if (!lastLine) {
        return;
      }
      if (!lastLine.segments.some((segment) => segment.paraIndex === paraIndex)) {
        return;
      }
      lastLine.flowBreakAfter = true;
    };
    const flushLine = (addAfterPx = 0, options) => {
      if (segs.length === 0)
        return;
      trimTrailingWhitespaceSegments();
      const baseAscent = lineMaxAscentPx > 0 ? lineMaxAscentPx : defaultFontPx * FALLBACK_ASCENT_RATIO;
      const baseDescent = lineMaxDescentPx > 0 ? lineMaxDescentPx : defaultFontPx * FALLBACK_DESCENT_RATIO;
      const naturalHeightPx = baseAscent + baseDescent;
      const lineHeightBasisPx = segs.reduce((maxPx, segment) => Math.max(maxPx, segment.px), 0) || defaultFontPx;
      const contentHeight = lineSpacingPx !== undefined ? lineSpacingPx : lineHeightBasisPx * lineMultiple;
      const leadingPx = contentHeight - naturalHeightPx;
      const leadingBeforePx = leadingPx / 2;
      const leadingAfterPx = leadingPx - leadingBeforePx;
      const offsetPx = resolveCurrentLineOffsetPx();
      const availableWidthPx = resolveCurrentLineAvailableWidthPx();
      lines.push({
        segments: segs.slice(),
        widthPx: lineWidth,
        heightPx: contentHeight + addAfterPx,
        contentHeightPx: contentHeight,
        naturalHeightPx,
        leadingBeforePx,
        leadingAfterPx,
        align: lineAlign,
        offsetPx,
        availableWidthPx,
        baselineOffsetPx: leadingBeforePx + baseAscent,
        maxAscentPx: baseAscent,
        maxDescentPx: baseDescent,
        maxPx: baseAscent + baseDescent,
        flowBreakAfter: options?.flowBreakAfter ?? false
      });
      segs.length = 0;
      lineWidth = 0;
      lineMaxAscentPx = 0;
      lineMaxDescentPx = 0;
      isFirstLineOfParagraph = false;
    };
    const listKey = isNumbered ? `${mergedParaStyle.autoNumberType}|${paragraphMarginLeftPx}|${paragraphIndentPx}` : "";
    let listIndex = 0;
    if (isNumbered) {
      const startAt = mergedParaStyle.autoNumberStartAt;
      if (listCounters[listKey] === undefined) {
        listCounters[listKey] = typeof startAt === "number" && startAt > 0 ? startAt : 1;
      }
      listIndex = listCounters[listKey];
    }
    const paragraphRuns = paragraph.runs ?? [];
    for (let runIndex = 0;runIndex < paragraphRuns.length; runIndex++) {
      const run = paragraphRuns[runIndex];
      if (!run)
        continue;
      const style = mergeStylesLodash({}, run.textStyle, paragraphTextStyle, request.elementStyle);
      const mergedScheme = mergeSchemeTokens(request.elementStyle?.scheme, paragraphTextStyle?.scheme, run.textStyle?.scheme);
      if (mergedScheme) {
        style.scheme = mergedScheme;
      }
      const resolvedFontSize = resolveTextStyleFontSize(style);
      const px = resolvedFontSize ? fontSizeToPx(resolvedFontSize, request.textScale) : defaultFontPx;
      const explicitFamily = normalizeFamilyName(resolveTextStyleTypeface(style));
      const family = explicitFamily ? `${explicitFamily}, Calibri, Carlito, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif` : "Calibri, Carlito, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif";
      const fontDescriptor = {
        style: style?.italic ? "italic" : "normal",
        weight: style?.bold ? "700" : "normal",
        family
      };
      const font = buildFontShorthand(fontDescriptor, px);
      const fontKey = this.fontMetrics.getFontKey(fontDescriptor);
      const metrics = this.fontMetrics.getMetricsForSize(fontDescriptor, px);
      const isHyperlink = Boolean(run.hyperlink?.uri);
      const fill = isHyperlink && !style?.fill ? DEFAULT_HYPERLINK_COLOR : resolveColor(style?.fill?.color, request.themeMap, request.defaultTextFill);
      const highlight = resolveHighlightSchemeColor(style?.scheme);
      const underline = resolveTextStyleUnderline(style, isHyperlink);
      if (hasListMarker && !bulletInserted) {
        const marker = isNumbered ? `${formatListNumber(listIndex, mergedParaStyle.autoNumberType)} ` : `${mergedParaStyle.bulletCharacter} `;
        const markerAdvance = this.measureCache.buildAdvance(fontKey, font, px, marker);
        const markerInk = this.measureCache.measureInkBounds(font, marker);
        const markerWidth = markerAdvance[marker.length] ?? 0;
        segs.push({
          text: marker,
          widthPx: markerWidth,
          font,
          fontKey,
          fill,
          highlight,
          underline,
          px,
          ascentPx: metrics.ascentPx,
          descentPx: metrics.descentPx,
          run,
          paraIndex,
          runIndex,
          charStart: 0,
          charEnd: marker.length,
          advance: markerAdvance,
          inkLeftPx: markerInk.leftPx,
          inkRightPx: markerInk.rightPx,
          inkAscentPx: markerInk.ascentPx,
          inkDescentPx: markerInk.descentPx
        });
        lineWidth += markerWidth;
        lineMaxAscentPx = Math.max(lineMaxAscentPx, metrics.ascentPx);
        lineMaxDescentPx = Math.max(lineMaxDescentPx, metrics.descentPx);
        if (isFirstLineOfParagraph) {
          const markerGapPx = hangingOffsetPx - firstLineOffsetPx - markerWidth;
          if (markerGapPx > 0.5) {
            segs.push({
              text: "",
              widthPx: markerGapPx,
              font,
              fontKey,
              fill,
              highlight,
              underline,
              px,
              ascentPx: metrics.ascentPx,
              descentPx: metrics.descentPx,
              run,
              paraIndex,
              runIndex,
              charStart: marker.length,
              charEnd: marker.length,
              advance: new Float32Array(1),
              inkLeftPx: 0,
              inkRightPx: 0,
              inkAscentPx: 0,
              inkDescentPx: 0
            });
            lineWidth += markerGapPx;
          }
        }
        bulletInserted = true;
        if (isNumbered) {
          listCounters[listKey] = listIndex + 1;
        }
      }
      const displayText = run.text ? applyDocxTextTransforms(run.text, style?.scheme) : "";
      const tokens = displayText ? tokenizeRunText(displayText) : [];
      if (!tokens.length) {
        segs.push({
          text: "",
          widthPx: 0,
          font,
          fontKey,
          fill,
          highlight,
          underline,
          px,
          ascentPx: metrics.ascentPx,
          descentPx: metrics.descentPx,
          run,
          paraIndex,
          runIndex,
          charStart: 0,
          charEnd: 0,
          advance: new Float32Array(1),
          inkLeftPx: 0,
          inkRightPx: 0,
          inkAscentPx: 0,
          inkDescentPx: 0
        });
        lineMaxAscentPx = Math.max(lineMaxAscentPx, metrics.ascentPx);
        lineMaxDescentPx = Math.max(lineMaxDescentPx, metrics.descentPx);
        continue;
      }
      let runCharOffset = 0;
      for (const token of tokens) {
        if (token.type === "flowBreak") {
          if (segs.length > 0) {
            flushLine(0, { flowBreakAfter: true });
          } else {
            markLastCommittedLineFlowBreak();
          }
          runCharOffset += token.text.length;
          continue;
        }
        if (token.type === "newline") {
          if (segs.length === 0) {
            segs.push({
              text: "",
              widthPx: 0,
              font,
              fontKey,
              fill,
              highlight,
              underline,
              px,
              ascentPx: metrics.ascentPx,
              descentPx: metrics.descentPx,
              run,
              paraIndex,
              runIndex,
              charStart: runCharOffset,
              charEnd: runCharOffset,
              advance: new Float32Array(1),
              inkLeftPx: 0,
              inkRightPx: 0,
              inkAscentPx: 0,
              inkDescentPx: 0
            });
            lineMaxAscentPx = Math.max(lineMaxAscentPx, metrics.ascentPx);
            lineMaxDescentPx = Math.max(lineMaxDescentPx, metrics.descentPx);
          }
          flushLine();
          continue;
        }
        const graphemes = token.graphemes ?? splitGraphemes(token.text);
        if (!graphemes.length)
          continue;
        const tokenAdvances = this.measureCache.buildAdvance(fontKey, font, px, token.text, graphemes);
        const emitSlice = (sliceStart2, sliceEnd) => {
          if (sliceStart2 >= sliceEnd) {
            return sliceEnd;
          }
          const textSlice = sliceStart2 === 0 && sliceEnd === graphemes.length ? token.text : graphemes.slice(sliceStart2, sliceEnd).join("");
          const widthPx = getAdvanceValue(tokenAdvances, sliceEnd) - getAdvanceValue(tokenAdvances, sliceStart2);
          const advance = sliceAdvance(tokenAdvances, sliceStart2, sliceEnd);
          const ink = this.measureCache.measureInkBounds(font, textSlice);
          const charStart = runCharOffset;
          const charEnd = charStart + textSlice.length;
          segs.push({
            text: textSlice,
            widthPx,
            font,
            fontKey,
            fill,
            highlight,
            underline,
            px,
            ascentPx: metrics.ascentPx,
            descentPx: metrics.descentPx,
            run,
            paraIndex,
            runIndex,
            charStart,
            charEnd,
            advance,
            inkLeftPx: ink.leftPx,
            inkRightPx: ink.rightPx,
            inkAscentPx: ink.ascentPx,
            inkDescentPx: ink.descentPx
          });
          lineWidth += widthPx;
          lineMaxAscentPx = Math.max(lineMaxAscentPx, metrics.ascentPx);
          lineMaxDescentPx = Math.max(lineMaxDescentPx, metrics.descentPx);
          runCharOffset = charEnd;
          return sliceEnd;
        };
        let sliceStart = 0;
        while (sliceStart < graphemes.length) {
          const remainingW = resolveCurrentLineAvailableWidthPx() - lineWidth;
          if (request.wrap && remainingW <= 0 && segs.length) {
            flushLine();
            continue;
          }
          const remainingWidth = getAdvanceValue(tokenAdvances, graphemes.length) - getAdvanceValue(tokenAdvances, sliceStart);
          if (!request.wrap || remainingWidth <= remainingW) {
            sliceStart = emitSlice(sliceStart, graphemes.length);
            break;
          }
          if (token.type === "word" && lineWidth > 0) {
            flushLine();
            continue;
          }
          const sliceEnd = findFittingGraphemeEnd(tokenAdvances, sliceStart, remainingW);
          const nextEnd = sliceEnd > sliceStart ? sliceEnd : sliceStart + 1;
          sliceStart = emitSlice(sliceStart, nextEnd);
          if (sliceStart < graphemes.length) {
            flushLine();
          }
        }
      }
    }
    if (segs.length === 0) {
      const placeholderStyle = mergeStylesLodash({}, paragraphTextStyle, request.elementStyle);
      const placeholderScheme = mergeSchemeTokens(request.elementStyle?.scheme, paragraphTextStyle?.scheme);
      if (placeholderScheme) {
        placeholderStyle.scheme = placeholderScheme;
      }
      const resolvedPlaceholderFontSize = resolveTextStyleFontSize(placeholderStyle);
      const placeholderFamily = normalizeFamilyName(resolveTextStyleTypeface(placeholderStyle));
      const family = placeholderFamily ? `${placeholderFamily}, Calibri, Carlito, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif` : "Calibri, Carlito, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif";
      const fontDescriptor = {
        style: placeholderStyle.italic ? "italic" : "normal",
        weight: placeholderStyle.bold ? "700" : "normal",
        family
      };
      const px = resolvedPlaceholderFontSize ? fontSizeToPx(resolvedPlaceholderFontSize, request.textScale) : defaultFontPx;
      const font = buildFontShorthand(fontDescriptor, px);
      const fontKey = this.fontMetrics.getFontKey(fontDescriptor);
      const metrics = this.fontMetrics.getMetricsForSize(fontDescriptor, px);
      const placeholderRun = {
        text: "",
        citations: [],
        reviewMarkIds: []
      };
      segs.push({
        text: "",
        widthPx: 0,
        font,
        fontKey,
        fill: request.defaultTextFill,
        highlight: undefined,
        underline: undefined,
        px,
        ascentPx: metrics.ascentPx,
        descentPx: metrics.descentPx,
        run: placeholderRun,
        paraIndex,
        runIndex: 0,
        charStart: 0,
        charEnd: 0,
        advance: new Float32Array(1),
        inkLeftPx: 0,
        inkRightPx: 0,
        inkAscentPx: 0,
        inkDescentPx: 0
      });
      lineMaxAscentPx = Math.max(lineMaxAscentPx, metrics.ascentPx);
      lineMaxDescentPx = Math.max(lineMaxDescentPx, metrics.descentPx);
    }
    flushLine(effectiveSpaceAfterPx);
    return effectiveSpaceAfterPx;
  }
}
function applyInkBoundsToNoWrapLine(line) {
  if (line.segments.length === 0) {
    return;
  }
  let cursorX = 0;
  let minLeft = Number.POSITIVE_INFINITY;
  let maxRight = Number.NEGATIVE_INFINITY;
  let maxAscent = 0;
  let maxDescent = 0;
  line.segments.forEach((segment) => {
    const hasInk = segment.inkRightPx > 0 || segment.inkAscentPx > 0 || segment.inkDescentPx > 0;
    if (hasInk) {
      minLeft = Math.min(minLeft, cursorX - segment.inkLeftPx);
      maxRight = Math.max(maxRight, cursorX + segment.inkRightPx);
      maxAscent = Math.max(maxAscent, segment.inkAscentPx);
      maxDescent = Math.max(maxDescent, segment.inkDescentPx);
    }
    cursorX += segment.widthPx;
  });
  if (!Number.isFinite(minLeft) || !Number.isFinite(maxRight)) {
    return;
  }
  const inkWidth = Math.max(0, maxRight - minLeft);
  if (inkWidth <= 0) {
    return;
  }
  line.inkLeftPx = minLeft;
  line.inkRightPx = maxRight;
  line.inkAscentPx = maxAscent;
  line.inkDescentPx = maxDescent;
}

// node_modules/@oai/granola/dist/draw-utils/text-renderer.js
class TextRenderer {
  render(request) {
    const { lines } = request;
    if (!lines.length)
      return;
    const blockHeight = lines.reduce((sum, line) => sum + line.heightPx, 0);
    const contentTopY = this.resolveTopY(request, blockHeight);
    const rotationRad = request.rotationDeg * Math.PI / 180;
    const shouldDraw = request.draw;
    const needsRotation = shouldDraw && rotationRad !== 0;
    const ctx = request.ctx;
    if (shouldDraw) {
      ctx.textAlign = "left";
      ctx.textBaseline = "alphabetic";
      if (needsRotation) {
        ctx.save();
        ctx.translate(request.box.x, contentTopY);
        ctx.rotate(rotationRad);
      }
    }
    const outLinkRects = [];
    let cursorY = contentTopY;
    for (let lineIndex = 0;lineIndex < lines.length; lineIndex += 1) {
      const line = lines[lineIndex];
      if (!line)
        continue;
      const lineTopY = cursorY;
      const lineX = this.resolveLineX(request.box, line);
      const baselineY = this.resolveBaselineY(line, lineTopY);
      line.x = lineX;
      line.topY = lineTopY;
      line.baselineY = baselineY;
      const availableWidthPx = this.resolveAvailableWidthPx(request.box.width, line);
      const shouldJustify = this.shouldJustifyLine(lines, lineIndex, line, request.box.width);
      const stretchableSegmentCount = shouldJustify ? line.segments.reduce((count, segment) => {
        return /\s/.test(segment.text) ? count + 1 : count;
      }, 0) : 0;
      const extraWidthPx = shouldJustify ? Math.max(0, availableWidthPx - line.widthPx) : 0;
      const extraPerStretchableSegmentPx = stretchableSegmentCount > 0 ? extraWidthPx / stretchableSegmentCount : 0;
      const segmentLayouts = [];
      let cursorX = lineX;
      for (let segIndex = 0;segIndex < line.segments.length; segIndex += 1) {
        const seg = line.segments[segIndex];
        if (!seg) {
          continue;
        }
        const justificationAdvancePx = shouldJustify && extraPerStretchableSegmentPx > 0 && /\s/.test(seg.text) ? extraPerStretchableSegmentPx : 0;
        segmentLayouts.push({
          seg,
          xPx: cursorX,
          advancePx: seg.widthPx + justificationAdvancePx,
          highlight: this.resolveSegmentHighlight(line.segments, segIndex)
        });
        cursorX += seg.widthPx + justificationAdvancePx;
      }
      if (shouldDraw) {
        this.drawSegmentHighlights(ctx, segmentLayouts, baselineY, needsRotation, request.box.x, contentTopY);
      }
      for (const { seg, xPx } of segmentLayouts) {
        seg.xPx = xPx;
        if (shouldDraw) {
          ctx.font = seg.font;
          ctx.fillStyle = seg.fill;
          if (needsRotation) {
            ctx.fillText(seg.text, xPx - request.box.x, baselineY - contentTopY);
          } else {
            ctx.fillText(seg.text, xPx, baselineY);
          }
          if (seg.underline && seg.underline !== "none" && seg.widthPx > 0) {
            const underlineYPx = baselineY + Math.max(1, seg.descentPx * 0.35);
            const underlineThicknessPx = Math.max(1, seg.px * 0.05);
            ctx.strokeStyle = seg.fill;
            ctx.lineWidth = underlineThicknessPx;
            ctx.beginPath();
            if (needsRotation) {
              ctx.moveTo(xPx - request.box.x, underlineYPx - contentTopY);
              ctx.lineTo(xPx - request.box.x + seg.widthPx, underlineYPx - contentTopY);
            } else {
              ctx.moveTo(xPx, underlineYPx);
              ctx.lineTo(xPx + seg.widthPx, underlineYPx);
            }
            ctx.stroke();
          }
          if (seg.run?.hyperlink?.uri) {
            const rect = {
              x: xPx,
              y: baselineY - seg.ascentPx,
              width: seg.widthPx,
              height: seg.ascentPx + seg.descentPx,
              url: seg.run.hyperlink.uri
            };
            outLinkRects.push(rect);
            request.linkRects?.push(rect);
          }
        }
      }
      cursorY += line.heightPx;
    }
    if (shouldDraw && needsRotation) {
      ctx.restore();
    }
    const rotatedWidth = rotationRad !== 0 ? Math.abs(request.box.width * Math.cos(rotationRad)) + Math.abs(blockHeight * Math.sin(rotationRad)) : request.box.width;
    const rotatedHeight = rotationRad !== 0 ? Math.abs(request.box.width * Math.sin(rotationRad)) + Math.abs(blockHeight * Math.cos(rotationRad)) : blockHeight;
    return {
      x: request.box.x,
      y: contentTopY,
      width: rotatedWidth,
      height: rotatedHeight,
      unrotatedWidth: request.box.width,
      unrotatedHeight: blockHeight,
      lines: lines.map((line) => ({
        segments: line.segments,
        x: line.x,
        widthPx: line.widthPx,
        heightPx: line.heightPx,
        contentHeightPx: line.contentHeightPx,
        naturalHeightPx: line.naturalHeightPx,
        leadingBeforePx: line.leadingBeforePx,
        leadingAfterPx: line.leadingAfterPx,
        align: line.align,
        offsetPx: line.offsetPx,
        availableWidthPx: line.availableWidthPx,
        baselineOffsetPx: line.baselineOffsetPx,
        topY: line.topY,
        baselineY: line.baselineY,
        maxAscentPx: line.maxAscentPx,
        maxDescentPx: line.maxDescentPx,
        maxPx: line.maxPx,
        inkLeftPx: line.inkLeftPx,
        inkRightPx: line.inkRightPx,
        inkAscentPx: line.inkAscentPx,
        inkDescentPx: line.inkDescentPx
      })),
      linkRects: outLinkRects
    };
  }
  resolveTopY(request, blockHeight) {
    const { anchor } = request;
    const box = request.box;
    switch (anchor) {
      case 3 /* ANCHOR_TYPE_BOTTOM */:
        return box.y + (box.height - blockHeight);
      case 2 /* ANCHOR_TYPE_MIDDLE */:
        return box.y + (box.height - blockHeight) / 2;
      case 1 /* ANCHOR_TYPE_TOP */:
      default:
        return box.y;
    }
  }
  resolveLineX(box, line) {
    const availableWidthPx = this.resolveAvailableWidthPx(box.width, line);
    if (line.align === "center") {
      return box.x + line.offsetPx + (availableWidthPx - line.widthPx) / 2;
    }
    if (line.align === "right") {
      return box.x + line.offsetPx + availableWidthPx - line.widthPx;
    }
    return box.x + line.offsetPx;
  }
  resolveBaselineY(line, cursorY) {
    return cursorY + line.baselineOffsetPx;
  }
  shouldJustifyLine(lines, lineIndex, line, boxWidthPx) {
    if (line.align !== "justify" || line.segments.length === 0) {
      return false;
    }
    const availableWidthPx = this.resolveAvailableWidthPx(boxWidthPx, line);
    const remainingWidth = availableWidthPx - line.widthPx;
    if (remainingWidth <= 0.5) {
      return false;
    }
    const paraIndex = line.segments[0]?.paraIndex;
    if (paraIndex === undefined) {
      return false;
    }
    for (let nextIndex = lineIndex + 1;nextIndex < lines.length; nextIndex += 1) {
      const nextLine = lines[nextIndex];
      if (!nextLine || nextLine.segments.length === 0) {
        continue;
      }
      return nextLine.segments[0]?.paraIndex === paraIndex;
    }
    return false;
  }
  resolveAvailableWidthPx(boxWidthPx, line) {
    const boxAvailableWidthPx = Math.max(0, boxWidthPx - line.offsetPx);
    if (line.availableWidthPx === undefined) {
      return boxAvailableWidthPx;
    }
    return Math.min(line.availableWidthPx, boxAvailableWidthPx);
  }
  resolveSegmentHighlight(segments, segIndex) {
    const segment = segments[segIndex];
    if (!segment) {
      return;
    }
    if (segment.highlight) {
      return segment.highlight;
    }
    if (!segment.text.trim()) {
      const previousHighlight = segments[segIndex - 1]?.highlight;
      const nextHighlight = segments[segIndex + 1]?.highlight;
      if (previousHighlight && previousHighlight === nextHighlight) {
        return previousHighlight;
      }
    }
    return;
  }
  drawSegmentHighlights(ctx, segmentLayouts, baselineY, needsRotation, boxX, contentTopY) {
    let currentGroup;
    const flushGroup = () => {
      if (!currentGroup) {
        return;
      }
      const highlightY = baselineY - currentGroup.maxAscentPx;
      const highlightHeight = currentGroup.maxAscentPx + currentGroup.maxDescentPx;
      ctx.fillStyle = currentGroup.color;
      if (needsRotation) {
        ctx.fillRect(currentGroup.startXPx - boxX, highlightY - contentTopY, currentGroup.endXPx - currentGroup.startXPx, highlightHeight);
      } else {
        ctx.fillRect(currentGroup.startXPx, highlightY, currentGroup.endXPx - currentGroup.startXPx, highlightHeight);
      }
      currentGroup = undefined;
    };
    for (const { seg, xPx, advancePx, highlight } of segmentLayouts) {
      if (!highlight) {
        flushGroup();
        continue;
      }
      const endXPx = xPx + advancePx;
      if (currentGroup && currentGroup.color === highlight && Math.abs(currentGroup.endXPx - xPx) <= 0.5) {
        currentGroup.endXPx = endXPx;
        currentGroup.maxAscentPx = Math.max(currentGroup.maxAscentPx, seg.ascentPx);
        currentGroup.maxDescentPx = Math.max(currentGroup.maxDescentPx, seg.descentPx);
        continue;
      }
      flushGroup();
      currentGroup = {
        color: highlight,
        startXPx: xPx,
        endXPx,
        maxAscentPx: seg.ascentPx,
        maxDescentPx: seg.descentPx
      };
    }
    flushGroup();
  }
}

// node_modules/@oai/granola/dist/draw-utils/draw-text.js
function getMasterLevelDefaults(el, pres, slide) {
  const layoutId = slide.useLayoutId;
  const layout = pres.layouts.getById(layoutId);
  const masterLayout = layout?.parentLayoutId ? pres.layouts.getById(layout.parentLayoutId) ?? pres.layouts.getByName("master") : pres.layouts.getByName("master");
  if (!masterLayout)
    return {};
  const isPlaceholder = el.placeholderType !== undefined || el.placeholderIndex !== undefined;
  const styleGroup = isPlaceholder ? mapPlaceholderToTxStyle(el.placeholderType) : "otherStyle";
  const levelIndex = 0;
  const lvl = styleGroup === "titleStyle" ? masterLayout.titleLevelStyles?.[levelIndex] : styleGroup === "bodyStyle" ? masterLayout.bodyLevelStyles?.[levelIndex] : masterLayout.otherLevelStyles?.[levelIndex];
  return {
    lineSpacingPercent: lvl?.paragraphStyle?.lineSpacingPercent,
    spaceBefore: lvl?.spaceBefore,
    spaceAfter: lvl?.spaceAfter
  };
}
var PAD_LR = 0.1 * 96;
var PAD_TB = 0.05 * 96;
var DEFAULT_TEXT_PADDING_PX = {
  left: PAD_LR,
  right: PAD_LR,
  top: PAD_TB,
  bottom: PAD_TB
};
function resolveTextPaddingPx(textStyle) {
  const leftInset = textStyle?.leftInset;
  const rightInset = textStyle?.rightInset;
  const topInset = textStyle?.topInset;
  const bottomInset = textStyle?.bottomInset;
  return {
    left: leftInset === undefined ? DEFAULT_TEXT_PADDING_PX.left : leftInset * EMU_TO_PX,
    right: rightInset === undefined ? DEFAULT_TEXT_PADDING_PX.right : rightInset * EMU_TO_PX,
    top: topInset === undefined ? DEFAULT_TEXT_PADDING_PX.top : topInset * EMU_TO_PX,
    bottom: bottomInset === undefined ? DEFAULT_TEXT_PADDING_PX.bottom : bottomInset * EMU_TO_PX
  };
}
var fontMetricsProvider = defaultFontMetricsProvider;
var textMeasureCache = new TextMeasureCache;
var textLayoutEngine = new TextLayoutEngine(fontMetricsProvider, textMeasureCache);
var textRenderer = new TextRenderer;
function resolveTextBox(el, options) {
  let x = 0;
  let y = 0;
  let boxW = 0;
  let boxH = 0;
  if (options?.bboxPx) {
    ({ x, y, width: boxW, height: boxH } = options.bboxPx);
  } else if (el.bbox) {
    const xEmu = el.bbox.xEmu ?? 0;
    const yEmu = el.bbox.yEmu ?? 0;
    const wEmu = el.bbox.widthEmu ?? 0;
    const hEmu = el.bbox.heightEmu ?? 0;
    x = xEmu * EMU_TO_PX;
    y = yEmu * EMU_TO_PX;
    boxW = wEmu * EMU_TO_PX;
    boxH = hEmu * EMU_TO_PX;
  }
  const elementStyle = options?.resolvedStyle ?? el.textStyle;
  const padding = options?.paddingPx ?? resolveTextPaddingPx(elementStyle);
  const padLeft = padding?.left ?? 0;
  const padRight = padding?.right ?? 0;
  const padTop = padding?.top ?? 0;
  const padBottom = padding?.bottom ?? 0;
  return {
    elementStyle,
    box: {
      x: x + padLeft,
      y: y + padTop,
      width: Math.max(0, boxW - (padLeft + padRight)),
      height: Math.max(0, boxH - (padTop + padBottom))
    }
  };
}
function layoutTextBlock(el, themeMap, options) {
  if (!el.paragraphs || el.paragraphs.length === 0) {
    return;
  }
  const { elementStyle, box } = resolveTextBox(el, options);
  const defaultTextFillGlobal = themeMap.colorMap?.["tx1"] ?? "#000000";
  const layoutResult = textLayoutEngine.layout({
    element: el,
    elementStyle,
    themeMap,
    defaultTextFill: defaultTextFillGlobal,
    textScale: options?.textScale ?? 1,
    wrap: options?.wrap ?? true,
    boxWidthPx: box.width,
    masterDefaults: options?.masterDefaults,
    paragraphSpacingUnit: options?.paragraphSpacingUnit
  });
  if (!layoutResult.lines.length) {
    return;
  }
  return { lines: layoutResult.lines };
}
function renderTextBlock(el, layout, ctx, linkRects, options) {
  if (!layout.lines.length) {
    return;
  }
  const { elementStyle, box } = resolveTextBox(el, options);
  return textRenderer.render({
    ctx,
    lines: layout.lines,
    box,
    anchor: elementStyle?.anchor ?? 1 /* ANCHOR_TYPE_TOP */,
    rotationDeg: elementStyle?.rotation ?? 0,
    draw: options?.mode !== "layout",
    linkRects
  });
}
function drawText(el, ctx, themeMap, linkRects, options) {
  const layout = layoutTextBlock(el, themeMap, options);
  if (!layout) {
    return;
  }
  return renderTextBlock(el, layout, ctx, linkRects, options);
}

// node_modules/@oai/granola/dist/draw-utils/get-master-scheme-remap.js
function getMasterSchemeRemap(pres, slide) {
  const layout = pres.layouts.getById(slide.useLayoutId);
  const master = layout?.parentLayoutId ? pres.layouts.getById(layout.parentLayoutId) : pres.layouts.items.find((candidate) => candidate.type === "master");
  return master?.colorMap ?? undefined;
}

// node_modules/@oai/granola/dist/draw-utils/get-bbox.js
function getBBox(el, pres, slide) {
  const layoutId = slide.useLayoutId;
  if (el.bbox && isValidBBox(el.bbox) && pres) {
    const { xEmu, yEmu, widthEmu, heightEmu } = el.bbox;
    return {
      x: (xEmu ?? 0) * EMU_TO_PX,
      y: (yEmu ?? 0) * EMU_TO_PX,
      width: (widthEmu ?? 0) * EMU_TO_PX,
      height: (heightEmu ?? 0) * EMU_TO_PX
    };
  }
  const placeholderIndex = el.placeholderIndex;
  const rawPlaceholderType = el.placeholderType;
  const normalizedPlaceholderType = mapProtoPlaceholderType(rawPlaceholderType) ?? rawPlaceholderType;
  const placeholderTypeCandidates = new Set;
  if (rawPlaceholderType) {
    placeholderTypeCandidates.add(rawPlaceholderType);
  }
  if (normalizedPlaceholderType) {
    placeholderTypeCandidates.add(normalizedPlaceholderType);
  }
  const findPlaceholder = (layout) => {
    if (!layout) {
      return;
    }
    if (placeholderIndex !== undefined) {
      const byIndex = layout.elements.find((p) => p.placeholderIndex === placeholderIndex);
      if (byIndex) {
        return byIndex;
      }
    }
    if (placeholderTypeCandidates.size > 0) {
      const byType = layout.elements.find((p) => {
        const protoType = p.toProto().placeholderType;
        if (protoType && placeholderTypeCandidates.has(protoType)) {
          return true;
        }
        const facadeType = p.placeholderType;
        return typeof facadeType === "string" && placeholderTypeCandidates.has(facadeType);
      });
      if (byType) {
        return byType;
      }
    }
    return;
  };
  const rectFromFrame = (frame) => {
    if (!frame) {
      return;
    }
    const { left, top, width, height } = frame;
    if (left === undefined || top === undefined || width === undefined || height === undefined || width <= 0 || height <= 0) {
      return;
    }
    return { x: left, y: top, width, height };
  };
  if (placeholderIndex !== undefined || normalizedPlaceholderType !== undefined) {
    const layout = pres.layouts.getById(layoutId);
    const layoutPlaceholder = findPlaceholder(layout);
    const layoutRect = rectFromFrame(layoutPlaceholder?.frame);
    if (layoutRect) {
      return layoutRect;
    }
    const masterLayout = (layout?.parentLayoutId ? pres.layouts.getById(layout.parentLayoutId) : undefined) ?? pres.layouts.items.find((candidate) => candidate.type === "master");
    const masterPlaceholder = findPlaceholder(masterLayout);
    const masterRect = rectFromFrame(masterPlaceholder?.frame);
    if (masterRect) {
      return masterRect;
    }
  }
  return { x: 0, y: 0, width: 0, height: 0 };
}

// node_modules/d3-format/src/formatDecimal.js
function formatDecimal_default(x) {
  return Math.abs(x = Math.round(x)) >= 1000000000000000000000 ? x.toLocaleString("en").replace(/,/g, "") : x.toString(10);
}
function formatDecimalParts(x, p) {
  if (!isFinite(x) || x === 0)
    return null;
  var i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e"), coefficient = x.slice(0, i);
  return [
    coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
    +x.slice(i + 1)
  ];
}

// node_modules/d3-format/src/exponent.js
function exponent_default(x) {
  return x = formatDecimalParts(Math.abs(x)), x ? x[1] : NaN;
}

// node_modules/d3-format/src/formatGroup.js
function formatGroup_default(grouping, thousands) {
  return function(value, width) {
    var i = value.length, t = [], j = 0, g = grouping[0], length = 0;
    while (i > 0 && g > 0) {
      if (length + g + 1 > width)
        g = Math.max(1, width - length);
      t.push(value.substring(i -= g, i + g));
      if ((length += g + 1) > width)
        break;
      g = grouping[j = (j + 1) % grouping.length];
    }
    return t.reverse().join(thousands);
  };
}

// node_modules/d3-format/src/formatNumerals.js
function formatNumerals_default(numerals) {
  return function(value) {
    return value.replace(/[0-9]/g, function(i) {
      return numerals[+i];
    });
  };
}

// node_modules/d3-format/src/formatSpecifier.js
var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;
function formatSpecifier(specifier) {
  if (!(match = re.exec(specifier)))
    throw new Error("invalid format: " + specifier);
  var match;
  return new FormatSpecifier({
    fill: match[1],
    align: match[2],
    sign: match[3],
    symbol: match[4],
    zero: match[5],
    width: match[6],
    comma: match[7],
    precision: match[8] && match[8].slice(1),
    trim: match[9],
    type: match[10]
  });
}
formatSpecifier.prototype = FormatSpecifier.prototype;
function FormatSpecifier(specifier) {
  this.fill = specifier.fill === undefined ? " " : specifier.fill + "";
  this.align = specifier.align === undefined ? ">" : specifier.align + "";
  this.sign = specifier.sign === undefined ? "-" : specifier.sign + "";
  this.symbol = specifier.symbol === undefined ? "" : specifier.symbol + "";
  this.zero = !!specifier.zero;
  this.width = specifier.width === undefined ? undefined : +specifier.width;
  this.comma = !!specifier.comma;
  this.precision = specifier.precision === undefined ? undefined : +specifier.precision;
  this.trim = !!specifier.trim;
  this.type = specifier.type === undefined ? "" : specifier.type + "";
}
FormatSpecifier.prototype.toString = function() {
  return this.fill + this.align + this.sign + this.symbol + (this.zero ? "0" : "") + (this.width === undefined ? "" : Math.max(1, this.width | 0)) + (this.comma ? "," : "") + (this.precision === undefined ? "" : "." + Math.max(0, this.precision | 0)) + (this.trim ? "~" : "") + this.type;
};

// node_modules/d3-format/src/formatTrim.js
function formatTrim_default(s) {
  out:
    for (var n = s.length, i = 1, i0 = -1, i1;i < n; ++i) {
      switch (s[i]) {
        case ".":
          i0 = i1 = i;
          break;
        case "0":
          if (i0 === 0)
            i0 = i;
          i1 = i;
          break;
        default:
          if (!+s[i])
            break out;
          if (i0 > 0)
            i0 = 0;
          break;
      }
    }
  return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
}

// node_modules/d3-format/src/formatPrefixAuto.js
var prefixExponent;
function formatPrefixAuto_default(x, p) {
  var d = formatDecimalParts(x, p);
  if (!d)
    return prefixExponent = undefined, x.toPrecision(p);
  var coefficient = d[0], exponent = d[1], i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1, n = coefficient.length;
  return i === n ? coefficient : i > n ? coefficient + new Array(i - n + 1).join("0") : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i) : "0." + new Array(1 - i).join("0") + formatDecimalParts(x, Math.max(0, p + i - 1))[0];
}

// node_modules/d3-format/src/formatRounded.js
function formatRounded_default(x, p) {
  var d = formatDecimalParts(x, p);
  if (!d)
    return x + "";
  var coefficient = d[0], exponent = d[1];
  return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1) : coefficient + new Array(exponent - coefficient.length + 2).join("0");
}

// node_modules/d3-format/src/formatTypes.js
var formatTypes_default = {
  "%": (x, p) => (x * 100).toFixed(p),
  b: (x) => Math.round(x).toString(2),
  c: (x) => x + "",
  d: formatDecimal_default,
  e: (x, p) => x.toExponential(p),
  f: (x, p) => x.toFixed(p),
  g: (x, p) => x.toPrecision(p),
  o: (x) => Math.round(x).toString(8),
  p: (x, p) => formatRounded_default(x * 100, p),
  r: formatRounded_default,
  s: formatPrefixAuto_default,
  X: (x) => Math.round(x).toString(16).toUpperCase(),
  x: (x) => Math.round(x).toString(16)
};

// node_modules/d3-format/src/identity.js
function identity_default(x) {
  return x;
}

// node_modules/d3-format/src/locale.js
var map = Array.prototype.map;
var prefixes = ["y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y"];
function locale_default(locale) {
  var group = locale.grouping === undefined || locale.thousands === undefined ? identity_default : formatGroup_default(map.call(locale.grouping, Number), locale.thousands + ""), currencyPrefix = locale.currency === undefined ? "" : locale.currency[0] + "", currencySuffix = locale.currency === undefined ? "" : locale.currency[1] + "", decimal = locale.decimal === undefined ? "." : locale.decimal + "", numerals = locale.numerals === undefined ? identity_default : formatNumerals_default(map.call(locale.numerals, String)), percent = locale.percent === undefined ? "%" : locale.percent + "", minus = locale.minus === undefined ? "−" : locale.minus + "", nan = locale.nan === undefined ? "NaN" : locale.nan + "";
  function newFormat(specifier, options) {
    specifier = formatSpecifier(specifier);
    var { fill, align, sign, symbol: symbol2, zero, width, comma, precision, trim, type } = specifier;
    if (type === "n")
      comma = true, type = "g";
    else if (!formatTypes_default[type])
      precision === undefined && (precision = 12), trim = true, type = "g";
    if (zero || fill === "0" && align === "=")
      zero = true, fill = "0", align = "=";
    var prefix = (options && options.prefix !== undefined ? options.prefix : "") + (symbol2 === "$" ? currencyPrefix : symbol2 === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : ""), suffix = (symbol2 === "$" ? currencySuffix : /[%p]/.test(type) ? percent : "") + (options && options.suffix !== undefined ? options.suffix : "");
    var formatType = formatTypes_default[type], maybeSuffix = /[defgprs%]/.test(type);
    precision = precision === undefined ? 6 : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision)) : Math.max(0, Math.min(20, precision));
    function format(value) {
      var valuePrefix = prefix, valueSuffix = suffix, i, n, c;
      if (type === "c") {
        valueSuffix = formatType(value) + valueSuffix;
        value = "";
      } else {
        value = +value;
        var valueNegative = value < 0 || 1 / value < 0;
        value = isNaN(value) ? nan : formatType(Math.abs(value), precision);
        if (trim)
          value = formatTrim_default(value);
        if (valueNegative && +value === 0 && sign !== "+")
          valueNegative = false;
        valuePrefix = (valueNegative ? sign === "(" ? sign : minus : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
        valueSuffix = (type === "s" && !isNaN(value) && prefixExponent !== undefined ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");
        if (maybeSuffix) {
          i = -1, n = value.length;
          while (++i < n) {
            if (c = value.charCodeAt(i), 48 > c || c > 57) {
              valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
              value = value.slice(0, i);
              break;
            }
          }
        }
      }
      if (comma && !zero)
        value = group(value, Infinity);
      var length = valuePrefix.length + value.length + valueSuffix.length, padding = length < width ? new Array(width - length + 1).join(fill) : "";
      if (comma && zero)
        value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";
      switch (align) {
        case "<":
          value = valuePrefix + value + valueSuffix + padding;
          break;
        case "=":
          value = valuePrefix + padding + value + valueSuffix;
          break;
        case "^":
          value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length);
          break;
        default:
          value = padding + valuePrefix + value + valueSuffix;
          break;
      }
      return numerals(value);
    }
    format.toString = function() {
      return specifier + "";
    };
    return format;
  }
  function formatPrefix(specifier, value) {
    var e = Math.max(-8, Math.min(8, Math.floor(exponent_default(value) / 3))) * 3, k = Math.pow(10, -e), f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier), { suffix: prefixes[8 + e / 3] });
    return function(value2) {
      return f(k * value2);
    };
  }
  return {
    format: newFormat,
    formatPrefix
  };
}

// node_modules/d3-format/src/defaultLocale.js
var locale;
var format;
var formatPrefix;
defaultLocale({
  thousands: ",",
  grouping: [3],
  currency: ["$", ""]
});
function defaultLocale(definition) {
  locale = locale_default(definition);
  format = locale.format;
  formatPrefix = locale.formatPrefix;
  return locale;
}
// node_modules/d3-format/src/precisionFixed.js
function precisionFixed_default(step) {
  return Math.max(0, -exponent_default(Math.abs(step)));
}
// node_modules/d3-format/src/precisionPrefix.js
function precisionPrefix_default(step, value) {
  return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent_default(value) / 3))) * 3 - exponent_default(Math.abs(step)));
}
// node_modules/d3-format/src/precisionRound.js
function precisionRound_default(step, max) {
  step = Math.abs(step), max = Math.abs(max) - step;
  return Math.max(0, exponent_default(max) - exponent_default(step)) + 1;
}
// node_modules/d3-scale-chromatic/src/colors.js
function colors_default(specifier) {
  var n = specifier.length / 6 | 0, colors = new Array(n), i = 0;
  while (i < n)
    colors[i] = "#" + specifier.slice(i * 6, ++i * 6);
  return colors;
}

// node_modules/d3-scale-chromatic/src/categorical/Tableau10.js
var Tableau10_default = colors_default("4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab");
// node_modules/d3-color/src/define.js
function define_default(constructor, factory, prototype) {
  constructor.prototype = factory.prototype = prototype;
  prototype.constructor = constructor;
}
function extend(parent, definition) {
  var prototype = Object.create(parent.prototype);
  for (var key in definition)
    prototype[key] = definition[key];
  return prototype;
}

// node_modules/d3-color/src/color.js
function Color2() {}
var darker = 0.7;
var brighter = 1 / darker;
var reI = "\\s*([+-]?\\d+)\\s*";
var reN = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*";
var reP = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*";
var reHex = /^#([0-9a-f]{3,8})$/;
var reRgbInteger = new RegExp(`^rgb\\(${reI},${reI},${reI}\\)$`);
var reRgbPercent = new RegExp(`^rgb\\(${reP},${reP},${reP}\\)$`);
var reRgbaInteger = new RegExp(`^rgba\\(${reI},${reI},${reI},${reN}\\)$`);
var reRgbaPercent = new RegExp(`^rgba\\(${reP},${reP},${reP},${reN}\\)$`);
var reHslPercent = new RegExp(`^hsl\\(${reN},${reP},${reP}\\)$`);
var reHslaPercent = new RegExp(`^hsla\\(${reN},${reP},${reP},${reN}\\)$`);
var named = {
  aliceblue: 15792383,
  antiquewhite: 16444375,
  aqua: 65535,
  aquamarine: 8388564,
  azure: 15794175,
  beige: 16119260,
  bisque: 16770244,
  black: 0,
  blanchedalmond: 16772045,
  blue: 255,
  blueviolet: 9055202,
  brown: 10824234,
  burlywood: 14596231,
  cadetblue: 6266528,
  chartreuse: 8388352,
  chocolate: 13789470,
  coral: 16744272,
  cornflowerblue: 6591981,
  cornsilk: 16775388,
  crimson: 14423100,
  cyan: 65535,
  darkblue: 139,
  darkcyan: 35723,
  darkgoldenrod: 12092939,
  darkgray: 11119017,
  darkgreen: 25600,
  darkgrey: 11119017,
  darkkhaki: 12433259,
  darkmagenta: 9109643,
  darkolivegreen: 5597999,
  darkorange: 16747520,
  darkorchid: 10040012,
  darkred: 9109504,
  darksalmon: 15308410,
  darkseagreen: 9419919,
  darkslateblue: 4734347,
  darkslategray: 3100495,
  darkslategrey: 3100495,
  darkturquoise: 52945,
  darkviolet: 9699539,
  deeppink: 16716947,
  deepskyblue: 49151,
  dimgray: 6908265,
  dimgrey: 6908265,
  dodgerblue: 2003199,
  firebrick: 11674146,
  floralwhite: 16775920,
  forestgreen: 2263842,
  fuchsia: 16711935,
  gainsboro: 14474460,
  ghostwhite: 16316671,
  gold: 16766720,
  goldenrod: 14329120,
  gray: 8421504,
  green: 32768,
  greenyellow: 11403055,
  grey: 8421504,
  honeydew: 15794160,
  hotpink: 16738740,
  indianred: 13458524,
  indigo: 4915330,
  ivory: 16777200,
  khaki: 15787660,
  lavender: 15132410,
  lavenderblush: 16773365,
  lawngreen: 8190976,
  lemonchiffon: 16775885,
  lightblue: 11393254,
  lightcoral: 15761536,
  lightcyan: 14745599,
  lightgoldenrodyellow: 16448210,
  lightgray: 13882323,
  lightgreen: 9498256,
  lightgrey: 13882323,
  lightpink: 16758465,
  lightsalmon: 16752762,
  lightseagreen: 2142890,
  lightskyblue: 8900346,
  lightslategray: 7833753,
  lightslategrey: 7833753,
  lightsteelblue: 11584734,
  lightyellow: 16777184,
  lime: 65280,
  limegreen: 3329330,
  linen: 16445670,
  magenta: 16711935,
  maroon: 8388608,
  mediumaquamarine: 6737322,
  mediumblue: 205,
  mediumorchid: 12211667,
  mediumpurple: 9662683,
  mediumseagreen: 3978097,
  mediumslateblue: 8087790,
  mediumspringgreen: 64154,
  mediumturquoise: 4772300,
  mediumvioletred: 13047173,
  midnightblue: 1644912,
  mintcream: 16121850,
  mistyrose: 16770273,
  moccasin: 16770229,
  navajowhite: 16768685,
  navy: 128,
  oldlace: 16643558,
  olive: 8421376,
  olivedrab: 7048739,
  orange: 16753920,
  orangered: 16729344,
  orchid: 14315734,
  palegoldenrod: 15657130,
  palegreen: 10025880,
  paleturquoise: 11529966,
  palevioletred: 14381203,
  papayawhip: 16773077,
  peachpuff: 16767673,
  peru: 13468991,
  pink: 16761035,
  plum: 14524637,
  powderblue: 11591910,
  purple: 8388736,
  rebeccapurple: 6697881,
  red: 16711680,
  rosybrown: 12357519,
  royalblue: 4286945,
  saddlebrown: 9127187,
  salmon: 16416882,
  sandybrown: 16032864,
  seagreen: 3050327,
  seashell: 16774638,
  sienna: 10506797,
  silver: 12632256,
  skyblue: 8900331,
  slateblue: 6970061,
  slategray: 7372944,
  slategrey: 7372944,
  snow: 16775930,
  springgreen: 65407,
  steelblue: 4620980,
  tan: 13808780,
  teal: 32896,
  thistle: 14204888,
  tomato: 16737095,
  turquoise: 4251856,
  violet: 15631086,
  wheat: 16113331,
  white: 16777215,
  whitesmoke: 16119285,
  yellow: 16776960,
  yellowgreen: 10145074
};
define_default(Color2, color, {
  copy(channels) {
    return Object.assign(new this.constructor, this, channels);
  },
  displayable() {
    return this.rgb().displayable();
  },
  hex: color_formatHex,
  formatHex: color_formatHex,
  formatHex8: color_formatHex8,
  formatHsl: color_formatHsl,
  formatRgb: color_formatRgb,
  toString: color_formatRgb
});
function color_formatHex() {
  return this.rgb().formatHex();
}
function color_formatHex8() {
  return this.rgb().formatHex8();
}
function color_formatHsl() {
  return hslConvert(this).formatHsl();
}
function color_formatRgb() {
  return this.rgb().formatRgb();
}
function color(format2) {
  var m, l;
  format2 = (format2 + "").trim().toLowerCase();
  return (m = reHex.exec(format2)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) : l === 3 ? new Rgb(m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, (m & 15) << 4 | m & 15, 1) : l === 8 ? rgba(m >> 24 & 255, m >> 16 & 255, m >> 8 & 255, (m & 255) / 255) : l === 4 ? rgba(m >> 12 & 15 | m >> 8 & 240, m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, ((m & 15) << 4 | m & 15) / 255) : null) : (m = reRgbInteger.exec(format2)) ? new Rgb(m[1], m[2], m[3], 1) : (m = reRgbPercent.exec(format2)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) : (m = reRgbaInteger.exec(format2)) ? rgba(m[1], m[2], m[3], m[4]) : (m = reRgbaPercent.exec(format2)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) : (m = reHslPercent.exec(format2)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) : (m = reHslaPercent.exec(format2)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) : named.hasOwnProperty(format2) ? rgbn(named[format2]) : format2 === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null;
}
function rgbn(n) {
  return new Rgb(n >> 16 & 255, n >> 8 & 255, n & 255, 1);
}
function rgba(r, g, b, a) {
  if (a <= 0)
    r = g = b = NaN;
  return new Rgb(r, g, b, a);
}
function rgbConvert(o) {
  if (!(o instanceof Color2))
    o = color(o);
  if (!o)
    return new Rgb;
  o = o.rgb();
  return new Rgb(o.r, o.g, o.b, o.opacity);
}
function rgb(r, g, b, opacity) {
  return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
}
function Rgb(r, g, b, opacity) {
  this.r = +r;
  this.g = +g;
  this.b = +b;
  this.opacity = +opacity;
}
define_default(Rgb, rgb, extend(Color2, {
  brighter(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  darker(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  rgb() {
    return this;
  },
  clamp() {
    return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity));
  },
  displayable() {
    return -0.5 <= this.r && this.r < 255.5 && (-0.5 <= this.g && this.g < 255.5) && (-0.5 <= this.b && this.b < 255.5) && (0 <= this.opacity && this.opacity <= 1);
  },
  hex: rgb_formatHex,
  formatHex: rgb_formatHex,
  formatHex8: rgb_formatHex8,
  formatRgb: rgb_formatRgb,
  toString: rgb_formatRgb
}));
function rgb_formatHex() {
  return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`;
}
function rgb_formatHex8() {
  return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;
}
function rgb_formatRgb() {
  const a = clampa(this.opacity);
  return `${a === 1 ? "rgb(" : "rgba("}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? ")" : `, ${a})`}`;
}
function clampa(opacity) {
  return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity));
}
function clampi(value) {
  return Math.max(0, Math.min(255, Math.round(value) || 0));
}
function hex(value) {
  value = clampi(value);
  return (value < 16 ? "0" : "") + value.toString(16);
}
function hsla(h, s, l, a) {
  if (a <= 0)
    h = s = l = NaN;
  else if (l <= 0 || l >= 1)
    h = s = NaN;
  else if (s <= 0)
    h = NaN;
  return new Hsl(h, s, l, a);
}
function hslConvert(o) {
  if (o instanceof Hsl)
    return new Hsl(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Color2))
    o = color(o);
  if (!o)
    return new Hsl;
  if (o instanceof Hsl)
    return o;
  o = o.rgb();
  var r = o.r / 255, g = o.g / 255, b = o.b / 255, min = Math.min(r, g, b), max = Math.max(r, g, b), h = NaN, s = max - min, l = (max + min) / 2;
  if (s) {
    if (r === max)
      h = (g - b) / s + (g < b) * 6;
    else if (g === max)
      h = (b - r) / s + 2;
    else
      h = (r - g) / s + 4;
    s /= l < 0.5 ? max + min : 2 - max - min;
    h *= 60;
  } else {
    s = l > 0 && l < 1 ? 0 : h;
  }
  return new Hsl(h, s, l, o.opacity);
}
function hsl(h, s, l, opacity) {
  return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
}
function Hsl(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}
define_default(Hsl, hsl, extend(Color2, {
  brighter(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  darker(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  rgb() {
    var h = this.h % 360 + (this.h < 0) * 360, s = isNaN(h) || isNaN(this.s) ? 0 : this.s, l = this.l, m2 = l + (l < 0.5 ? l : 1 - l) * s, m1 = 2 * l - m2;
    return new Rgb(hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2), hsl2rgb(h, m1, m2), hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2), this.opacity);
  },
  clamp() {
    return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity));
  },
  displayable() {
    return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && (0 <= this.l && this.l <= 1) && (0 <= this.opacity && this.opacity <= 1);
  },
  formatHsl() {
    const a = clampa(this.opacity);
    return `${a === 1 ? "hsl(" : "hsla("}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? ")" : `, ${a})`}`;
  }
}));
function clamph(value) {
  value = (value || 0) % 360;
  return value < 0 ? value + 360 : value;
}
function clampt(value) {
  return Math.max(0, Math.min(1, value || 0));
}
function hsl2rgb(h, m1, m2) {
  return (h < 60 ? m1 + (m2 - m1) * h / 60 : h < 180 ? m2 : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60 : m1) * 255;
}
// node_modules/d3-interpolate/src/basis.js
function basis(t1, v0, v1, v2, v3) {
  var t2 = t1 * t1, t3 = t2 * t1;
  return ((1 - 3 * t1 + 3 * t2 - t3) * v0 + (4 - 6 * t2 + 3 * t3) * v1 + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2 + t3 * v3) / 6;
}
function basis_default(values) {
  var n = values.length - 1;
  return function(t) {
    var i = t <= 0 ? t = 0 : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n), v1 = values[i], v2 = values[i + 1], v0 = i > 0 ? values[i - 1] : 2 * v1 - v2, v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;
    return basis((t - i / n) * n, v0, v1, v2, v3);
  };
}

// node_modules/d3-interpolate/src/basisClosed.js
function basisClosed_default(values) {
  var n = values.length;
  return function(t) {
    var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n), v0 = values[(i + n - 1) % n], v1 = values[i % n], v2 = values[(i + 1) % n], v3 = values[(i + 2) % n];
    return basis((t - i / n) * n, v0, v1, v2, v3);
  };
}

// node_modules/d3-interpolate/src/constant.js
var constant_default = (x) => () => x;

// node_modules/d3-interpolate/src/color.js
function linear(a, d) {
  return function(t) {
    return a + t * d;
  };
}
function exponential(a, b, y) {
  return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {
    return Math.pow(a + t * b, y);
  };
}
function gamma(y) {
  return (y = +y) === 1 ? nogamma : function(a, b) {
    return b - a ? exponential(a, b, y) : constant_default(isNaN(a) ? b : a);
  };
}
function nogamma(a, b) {
  var d = b - a;
  return d ? linear(a, d) : constant_default(isNaN(a) ? b : a);
}

// node_modules/d3-interpolate/src/rgb.js
var rgb_default = function rgbGamma(y) {
  var color2 = gamma(y);
  function rgb2(start, end) {
    var r = color2((start = rgb(start)).r, (end = rgb(end)).r), g = color2(start.g, end.g), b = color2(start.b, end.b), opacity = nogamma(start.opacity, end.opacity);
    return function(t) {
      start.r = r(t);
      start.g = g(t);
      start.b = b(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }
  rgb2.gamma = rgbGamma;
  return rgb2;
}(1);
function rgbSpline(spline) {
  return function(colors) {
    var n = colors.length, r = new Array(n), g = new Array(n), b = new Array(n), i, color2;
    for (i = 0;i < n; ++i) {
      color2 = rgb(colors[i]);
      r[i] = color2.r || 0;
      g[i] = color2.g || 0;
      b[i] = color2.b || 0;
    }
    r = spline(r);
    g = spline(g);
    b = spline(b);
    color2.opacity = 1;
    return function(t) {
      color2.r = r(t);
      color2.g = g(t);
      color2.b = b(t);
      return color2 + "";
    };
  };
}
var rgbBasis = rgbSpline(basis_default);
var rgbBasisClosed = rgbSpline(basisClosed_default);

// node_modules/d3-interpolate/src/numberArray.js
function numberArray_default(a, b) {
  if (!b)
    b = [];
  var n = a ? Math.min(b.length, a.length) : 0, c = b.slice(), i;
  return function(t) {
    for (i = 0;i < n; ++i)
      c[i] = a[i] * (1 - t) + b[i] * t;
    return c;
  };
}
function isNumberArray(x) {
  return ArrayBuffer.isView(x) && !(x instanceof DataView);
}

// node_modules/d3-interpolate/src/array.js
function genericArray(a, b) {
  var nb = b ? b.length : 0, na = a ? Math.min(nb, a.length) : 0, x = new Array(na), c = new Array(nb), i;
  for (i = 0;i < na; ++i)
    x[i] = value_default(a[i], b[i]);
  for (;i < nb; ++i)
    c[i] = b[i];
  return function(t) {
    for (i = 0;i < na; ++i)
      c[i] = x[i](t);
    return c;
  };
}

// node_modules/d3-interpolate/src/date.js
function date_default(a, b) {
  var d = new Date;
  return a = +a, b = +b, function(t) {
    return d.setTime(a * (1 - t) + b * t), d;
  };
}

// node_modules/d3-interpolate/src/number.js
function number_default(a, b) {
  return a = +a, b = +b, function(t) {
    return a * (1 - t) + b * t;
  };
}

// node_modules/d3-interpolate/src/object.js
function object_default(a, b) {
  var i = {}, c = {}, k;
  if (a === null || typeof a !== "object")
    a = {};
  if (b === null || typeof b !== "object")
    b = {};
  for (k in b) {
    if (k in a) {
      i[k] = value_default(a[k], b[k]);
    } else {
      c[k] = b[k];
    }
  }
  return function(t) {
    for (k in i)
      c[k] = i[k](t);
    return c;
  };
}

// node_modules/d3-interpolate/src/string.js
var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;
var reB = new RegExp(reA.source, "g");
function zero(b) {
  return function() {
    return b;
  };
}
function one(b) {
  return function(t) {
    return b(t) + "";
  };
}
function string_default(a, b) {
  var bi = reA.lastIndex = reB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = [];
  a = a + "", b = b + "";
  while ((am = reA.exec(a)) && (bm = reB.exec(b))) {
    if ((bs = bm.index) > bi) {
      bs = b.slice(bi, bs);
      if (s[i])
        s[i] += bs;
      else
        s[++i] = bs;
    }
    if ((am = am[0]) === (bm = bm[0])) {
      if (s[i])
        s[i] += bm;
      else
        s[++i] = bm;
    } else {
      s[++i] = null;
      q.push({ i, x: number_default(am, bm) });
    }
    bi = reB.lastIndex;
  }
  if (bi < b.length) {
    bs = b.slice(bi);
    if (s[i])
      s[i] += bs;
    else
      s[++i] = bs;
  }
  return s.length < 2 ? q[0] ? one(q[0].x) : zero(b) : (b = q.length, function(t) {
    for (var i2 = 0, o;i2 < b; ++i2)
      s[(o = q[i2]).i] = o.x(t);
    return s.join("");
  });
}

// node_modules/d3-interpolate/src/value.js
function value_default(a, b) {
  var t = typeof b, c;
  return b == null || t === "boolean" ? constant_default(b) : (t === "number" ? number_default : t === "string" ? (c = color(b)) ? (b = c, rgb_default) : string_default : b instanceof color ? rgb_default : b instanceof Date ? date_default : isNumberArray(b) ? numberArray_default : Array.isArray(b) ? genericArray : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object_default : number_default)(a, b);
}
// node_modules/d3-interpolate/src/round.js
function round_default(a, b) {
  return a = +a, b = +b, function(t) {
    return Math.round(a * (1 - t) + b * t);
  };
}
// node_modules/@oai/granola/dist/draw-utils/chart/consts.js
var FONT_FAMILY = "Carlito, Segoe UI, Helvetica, Arial, sans-serif";
var TICK_FONT_SIZE = 10;
var LEGEND_FONT_SIZE = 11;
var LEGEND_MARK_SIZE = 10;
var AXIS_COLOR = "#666";
var SERIES_COLORS = Tableau10_default;
var BAR_PADDING_INNER = 0.6;
var BAR_CORNER_RADIUS = 2;
var PADDING = {
  top: 12,
  right: 12,
  bottom: 12,
  left: 12
};
var locale2 = locale_default({
  decimal: ".",
  thousands: ",",
  grouping: [3],
  currency: ["", "$"],
  percent: " %"
});

// node_modules/d3-array/src/ascending.js
function ascending(a, b) {
  return a == null || b == null ? NaN : a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

// node_modules/d3-array/src/descending.js
function descending(a, b) {
  return a == null || b == null ? NaN : b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
}

// node_modules/d3-array/src/bisector.js
function bisector(f) {
  let compare1, compare2, delta;
  if (f.length !== 2) {
    compare1 = ascending;
    compare2 = (d, x) => ascending(f(d), x);
    delta = (d, x) => f(d) - x;
  } else {
    compare1 = f === ascending || f === descending ? f : zero2;
    compare2 = f;
    delta = f;
  }
  function left(a, x, lo = 0, hi = a.length) {
    if (lo < hi) {
      if (compare1(x, x) !== 0)
        return hi;
      do {
        const mid = lo + hi >>> 1;
        if (compare2(a[mid], x) < 0)
          lo = mid + 1;
        else
          hi = mid;
      } while (lo < hi);
    }
    return lo;
  }
  function right(a, x, lo = 0, hi = a.length) {
    if (lo < hi) {
      if (compare1(x, x) !== 0)
        return hi;
      do {
        const mid = lo + hi >>> 1;
        if (compare2(a[mid], x) <= 0)
          lo = mid + 1;
        else
          hi = mid;
      } while (lo < hi);
    }
    return lo;
  }
  function center(a, x, lo = 0, hi = a.length) {
    const i = left(a, x, lo, hi - 1);
    return i > lo && delta(a[i - 1], x) > -delta(a[i], x) ? i - 1 : i;
  }
  return { left, center, right };
}
function zero2() {
  return 0;
}

// node_modules/d3-array/src/number.js
function number(x) {
  return x === null ? NaN : +x;
}

// node_modules/d3-array/src/bisect.js
var ascendingBisect = bisector(ascending);
var bisectRight = ascendingBisect.right;
var bisectLeft = ascendingBisect.left;
var bisectCenter = bisector(number).center;
var bisect_default = bisectRight;
// node_modules/d3-array/src/count.js
function count(values, valueof) {
  let count2 = 0;
  if (valueof === undefined) {
    for (let value of values) {
      if (value != null && (value = +value) >= value) {
        ++count2;
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {
        ++count2;
      }
    }
  }
  return count2;
}

// node_modules/d3-array/src/extent.js
function extent(values, valueof) {
  let min;
  let max;
  if (valueof === undefined) {
    for (const value of values) {
      if (value != null) {
        if (min === undefined) {
          if (value >= value)
            min = max = value;
        } else {
          if (min > value)
            min = value;
          if (max < value)
            max = value;
        }
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index, values)) != null) {
        if (min === undefined) {
          if (value >= value)
            min = max = value;
        } else {
          if (min > value)
            min = value;
          if (max < value)
            max = value;
        }
      }
    }
  }
  return [min, max];
}
// node_modules/internmap/src/index.js
class InternMap extends Map {
  constructor(entries, key = keyof) {
    super();
    Object.defineProperties(this, { _intern: { value: new Map }, _key: { value: key } });
    if (entries != null)
      for (const [key2, value] of entries)
        this.set(key2, value);
  }
  get(key) {
    return super.get(intern_get(this, key));
  }
  has(key) {
    return super.has(intern_get(this, key));
  }
  set(key, value) {
    return super.set(intern_set(this, key), value);
  }
  delete(key) {
    return super.delete(intern_delete(this, key));
  }
}
function intern_get({ _intern, _key }, value) {
  const key = _key(value);
  return _intern.has(key) ? _intern.get(key) : value;
}
function intern_set({ _intern, _key }, value) {
  const key = _key(value);
  if (_intern.has(key))
    return _intern.get(key);
  _intern.set(key, value);
  return value;
}
function intern_delete({ _intern, _key }, value) {
  const key = _key(value);
  if (_intern.has(key)) {
    value = _intern.get(key);
    _intern.delete(key);
  }
  return value;
}
function keyof(value) {
  return value !== null && typeof value === "object" ? value.valueOf() : value;
}

// node_modules/d3-array/src/identity.js
function identity(x) {
  return x;
}

// node_modules/d3-array/src/array.js
var array = Array.prototype;
var slice = array.slice;
var map2 = array.map;

// node_modules/d3-array/src/constant.js
function constant(x) {
  return () => x;
}

// node_modules/d3-array/src/ticks.js
var e10 = Math.sqrt(50);
var e5 = Math.sqrt(10);
var e2 = Math.sqrt(2);
function tickSpec(start, stop, count2) {
  const step = (stop - start) / Math.max(0, count2), power = Math.floor(Math.log10(step)), error = step / Math.pow(10, power), factor = error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1;
  let i1, i2, inc;
  if (power < 0) {
    inc = Math.pow(10, -power) / factor;
    i1 = Math.round(start * inc);
    i2 = Math.round(stop * inc);
    if (i1 / inc < start)
      ++i1;
    if (i2 / inc > stop)
      --i2;
    inc = -inc;
  } else {
    inc = Math.pow(10, power) * factor;
    i1 = Math.round(start / inc);
    i2 = Math.round(stop / inc);
    if (i1 * inc < start)
      ++i1;
    if (i2 * inc > stop)
      --i2;
  }
  if (i2 < i1 && 0.5 <= count2 && count2 < 2)
    return tickSpec(start, stop, count2 * 2);
  return [i1, i2, inc];
}
function ticks(start, stop, count2) {
  stop = +stop, start = +start, count2 = +count2;
  if (!(count2 > 0))
    return [];
  if (start === stop)
    return [start];
  const reverse = stop < start, [i1, i2, inc] = reverse ? tickSpec(stop, start, count2) : tickSpec(start, stop, count2);
  if (!(i2 >= i1))
    return [];
  const n = i2 - i1 + 1, ticks2 = new Array(n);
  if (reverse) {
    if (inc < 0)
      for (let i = 0;i < n; ++i)
        ticks2[i] = (i2 - i) / -inc;
    else
      for (let i = 0;i < n; ++i)
        ticks2[i] = (i2 - i) * inc;
  } else {
    if (inc < 0)
      for (let i = 0;i < n; ++i)
        ticks2[i] = (i1 + i) / -inc;
    else
      for (let i = 0;i < n; ++i)
        ticks2[i] = (i1 + i) * inc;
  }
  return ticks2;
}
function tickIncrement(start, stop, count2) {
  stop = +stop, start = +start, count2 = +count2;
  return tickSpec(start, stop, count2)[2];
}
function tickStep(start, stop, count2) {
  stop = +stop, start = +start, count2 = +count2;
  const reverse = stop < start, inc = reverse ? tickIncrement(stop, start, count2) : tickIncrement(start, stop, count2);
  return (reverse ? -1 : 1) * (inc < 0 ? 1 / -inc : inc);
}

// node_modules/d3-array/src/nice.js
function nice(start, stop, count2) {
  let prestep;
  while (true) {
    const step = tickIncrement(start, stop, count2);
    if (step === prestep || step === 0 || !isFinite(step)) {
      return [start, stop];
    } else if (step > 0) {
      start = Math.floor(start / step) * step;
      stop = Math.ceil(stop / step) * step;
    } else if (step < 0) {
      start = Math.ceil(start * step) / step;
      stop = Math.floor(stop * step) / step;
    }
    prestep = step;
  }
}

// node_modules/d3-array/src/threshold/sturges.js
function thresholdSturges(values) {
  return Math.max(1, Math.ceil(Math.log(count(values)) / Math.LN2) + 1);
}

// node_modules/d3-array/src/bin.js
function bin() {
  var value = identity, domain = extent, threshold = thresholdSturges;
  function histogram(data) {
    if (!Array.isArray(data))
      data = Array.from(data);
    var i, n = data.length, x, step, values = new Array(n);
    for (i = 0;i < n; ++i) {
      values[i] = value(data[i], i, data);
    }
    var xz = domain(values), x0 = xz[0], x1 = xz[1], tz = threshold(values, x0, x1);
    if (!Array.isArray(tz)) {
      const max = x1, tn = +tz;
      if (domain === extent)
        [x0, x1] = nice(x0, x1, tn);
      tz = ticks(x0, x1, tn);
      if (tz[0] <= x0)
        step = tickIncrement(x0, x1, tn);
      if (tz[tz.length - 1] >= x1) {
        if (max >= x1 && domain === extent) {
          const step2 = tickIncrement(x0, x1, tn);
          if (isFinite(step2)) {
            if (step2 > 0) {
              x1 = (Math.floor(x1 / step2) + 1) * step2;
            } else if (step2 < 0) {
              x1 = (Math.ceil(x1 * -step2) + 1) / -step2;
            }
          }
        } else {
          tz.pop();
        }
      }
    }
    var m = tz.length, a = 0, b = m;
    while (tz[a] <= x0)
      ++a;
    while (tz[b - 1] > x1)
      --b;
    if (a || b < m)
      tz = tz.slice(a, b), m = b - a;
    var bins = new Array(m + 1), bin2;
    for (i = 0;i <= m; ++i) {
      bin2 = bins[i] = [];
      bin2.x0 = i > 0 ? tz[i - 1] : x0;
      bin2.x1 = i < m ? tz[i] : x1;
    }
    if (isFinite(step)) {
      if (step > 0) {
        for (i = 0;i < n; ++i) {
          if ((x = values[i]) != null && x0 <= x && x <= x1) {
            bins[Math.min(m, Math.floor((x - x0) / step))].push(data[i]);
          }
        }
      } else if (step < 0) {
        for (i = 0;i < n; ++i) {
          if ((x = values[i]) != null && x0 <= x && x <= x1) {
            const j = Math.floor((x0 - x) * step);
            bins[Math.min(m, j + (tz[j] <= x))].push(data[i]);
          }
        }
      }
    } else {
      for (i = 0;i < n; ++i) {
        if ((x = values[i]) != null && x0 <= x && x <= x1) {
          bins[bisect_default(tz, x, 0, m)].push(data[i]);
        }
      }
    }
    return bins;
  }
  histogram.value = function(_) {
    return arguments.length ? (value = typeof _ === "function" ? _ : constant(_), histogram) : value;
  };
  histogram.domain = function(_) {
    return arguments.length ? (domain = typeof _ === "function" ? _ : constant([_[0], _[1]]), histogram) : domain;
  };
  histogram.thresholds = function(_) {
    return arguments.length ? (threshold = typeof _ === "function" ? _ : constant(Array.isArray(_) ? slice.call(_) : _), histogram) : threshold;
  };
  return histogram;
}
// node_modules/d3-array/src/max.js
function max(values, valueof) {
  let max2;
  if (valueof === undefined) {
    for (const value of values) {
      if (value != null && (max2 < value || max2 === undefined && value >= value)) {
        max2 = value;
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index, values)) != null && (max2 < value || max2 === undefined && value >= value)) {
        max2 = value;
      }
    }
  }
  return max2;
}

// node_modules/d3-array/src/quantile.js
function quantileSorted(values, p, valueof = number) {
  if (!(n = values.length) || isNaN(p = +p))
    return;
  if (p <= 0 || n < 2)
    return +valueof(values[0], 0, values);
  if (p >= 1)
    return +valueof(values[n - 1], n - 1, values);
  var n, i = (n - 1) * p, i0 = Math.floor(i), value0 = +valueof(values[i0], i0, values), value1 = +valueof(values[i0 + 1], i0 + 1, values);
  return value0 + (value1 - value0) * (i - i0);
}
// node_modules/d3-array/src/mean.js
function mean(values, valueof) {
  let count2 = 0;
  let sum = 0;
  if (valueof === undefined) {
    for (let value of values) {
      if (value != null && (value = +value) >= value) {
        ++count2, sum += value;
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {
        ++count2, sum += value;
      }
    }
  }
  if (count2)
    return sum / count2;
}
// node_modules/d3-array/src/range.js
function range(start, stop, step) {
  start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;
  var i = -1, n = Math.max(0, Math.ceil((stop - start) / step)) | 0, range2 = new Array(n);
  while (++i < n) {
    range2[i] = start + i * step;
  }
  return range2;
}
// node_modules/d3-array/src/sum.js
function sum(values, valueof) {
  let sum2 = 0;
  if (valueof === undefined) {
    for (let value of values) {
      if (value = +value) {
        sum2 += value;
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      if (value = +valueof(value, ++index, values)) {
        sum2 += value;
      }
    }
  }
  return sum2;
}
// node_modules/d3-scale/src/init.js
function initRange(domain, range2) {
  switch (arguments.length) {
    case 0:
      break;
    case 1:
      this.range(domain);
      break;
    default:
      this.range(range2).domain(domain);
      break;
  }
  return this;
}

// node_modules/d3-scale/src/ordinal.js
var implicit = Symbol("implicit");
function ordinal() {
  var index = new InternMap, domain = [], range2 = [], unknown = implicit;
  function scale(d) {
    let i = index.get(d);
    if (i === undefined) {
      if (unknown !== implicit)
        return unknown;
      index.set(d, i = domain.push(d) - 1);
    }
    return range2[i % range2.length];
  }
  scale.domain = function(_) {
    if (!arguments.length)
      return domain.slice();
    domain = [], index = new InternMap;
    for (const value of _) {
      if (index.has(value))
        continue;
      index.set(value, domain.push(value) - 1);
    }
    return scale;
  };
  scale.range = function(_) {
    return arguments.length ? (range2 = Array.from(_), scale) : range2.slice();
  };
  scale.unknown = function(_) {
    return arguments.length ? (unknown = _, scale) : unknown;
  };
  scale.copy = function() {
    return ordinal(domain, range2).unknown(unknown);
  };
  initRange.apply(scale, arguments);
  return scale;
}

// node_modules/d3-scale/src/band.js
function band() {
  var scale = ordinal().unknown(undefined), domain = scale.domain, ordinalRange = scale.range, r0 = 0, r1 = 1, step, bandwidth, round = false, paddingInner = 0, paddingOuter = 0, align = 0.5;
  delete scale.unknown;
  function rescale() {
    var n = domain().length, reverse = r1 < r0, start = reverse ? r1 : r0, stop = reverse ? r0 : r1;
    step = (stop - start) / Math.max(1, n - paddingInner + paddingOuter * 2);
    if (round)
      step = Math.floor(step);
    start += (stop - start - step * (n - paddingInner)) * align;
    bandwidth = step * (1 - paddingInner);
    if (round)
      start = Math.round(start), bandwidth = Math.round(bandwidth);
    var values = range(n).map(function(i) {
      return start + step * i;
    });
    return ordinalRange(reverse ? values.reverse() : values);
  }
  scale.domain = function(_) {
    return arguments.length ? (domain(_), rescale()) : domain();
  };
  scale.range = function(_) {
    return arguments.length ? ([r0, r1] = _, r0 = +r0, r1 = +r1, rescale()) : [r0, r1];
  };
  scale.rangeRound = function(_) {
    return [r0, r1] = _, r0 = +r0, r1 = +r1, round = true, rescale();
  };
  scale.bandwidth = function() {
    return bandwidth;
  };
  scale.step = function() {
    return step;
  };
  scale.round = function(_) {
    return arguments.length ? (round = !!_, rescale()) : round;
  };
  scale.padding = function(_) {
    return arguments.length ? (paddingInner = Math.min(1, paddingOuter = +_), rescale()) : paddingInner;
  };
  scale.paddingInner = function(_) {
    return arguments.length ? (paddingInner = Math.min(1, _), rescale()) : paddingInner;
  };
  scale.paddingOuter = function(_) {
    return arguments.length ? (paddingOuter = +_, rescale()) : paddingOuter;
  };
  scale.align = function(_) {
    return arguments.length ? (align = Math.max(0, Math.min(1, _)), rescale()) : align;
  };
  scale.copy = function() {
    return band(domain(), [r0, r1]).round(round).paddingInner(paddingInner).paddingOuter(paddingOuter).align(align);
  };
  return initRange.apply(rescale(), arguments);
}
function pointish(scale) {
  var copy = scale.copy;
  scale.padding = scale.paddingOuter;
  delete scale.paddingInner;
  delete scale.paddingOuter;
  scale.copy = function() {
    return pointish(copy());
  };
  return scale;
}
function point() {
  return pointish(band.apply(null, arguments).paddingInner(1));
}
// node_modules/d3-scale/src/constant.js
function constants(x) {
  return function() {
    return x;
  };
}

// node_modules/d3-scale/src/number.js
function number2(x) {
  return +x;
}

// node_modules/d3-scale/src/continuous.js
var unit = [0, 1];
function identity2(x) {
  return x;
}
function normalize(a, b) {
  return (b -= a = +a) ? function(x) {
    return (x - a) / b;
  } : constants(isNaN(b) ? NaN : 0.5);
}
function clamper(a, b) {
  var t;
  if (a > b)
    t = a, a = b, b = t;
  return function(x) {
    return Math.max(a, Math.min(b, x));
  };
}
function bimap(domain, range2, interpolate) {
  var d0 = domain[0], d1 = domain[1], r0 = range2[0], r1 = range2[1];
  if (d1 < d0)
    d0 = normalize(d1, d0), r0 = interpolate(r1, r0);
  else
    d0 = normalize(d0, d1), r0 = interpolate(r0, r1);
  return function(x) {
    return r0(d0(x));
  };
}
function polymap(domain, range2, interpolate) {
  var j = Math.min(domain.length, range2.length) - 1, d = new Array(j), r = new Array(j), i = -1;
  if (domain[j] < domain[0]) {
    domain = domain.slice().reverse();
    range2 = range2.slice().reverse();
  }
  while (++i < j) {
    d[i] = normalize(domain[i], domain[i + 1]);
    r[i] = interpolate(range2[i], range2[i + 1]);
  }
  return function(x) {
    var i2 = bisect_default(domain, x, 1, j) - 1;
    return r[i2](d[i2](x));
  };
}
function copy(source, target) {
  return target.domain(source.domain()).range(source.range()).interpolate(source.interpolate()).clamp(source.clamp()).unknown(source.unknown());
}
function transformer() {
  var domain = unit, range2 = unit, interpolate = value_default, transform, untransform, unknown, clamp3 = identity2, piecewise, output, input;
  function rescale() {
    var n = Math.min(domain.length, range2.length);
    if (clamp3 !== identity2)
      clamp3 = clamper(domain[0], domain[n - 1]);
    piecewise = n > 2 ? polymap : bimap;
    output = input = null;
    return scale;
  }
  function scale(x) {
    return x == null || isNaN(x = +x) ? unknown : (output || (output = piecewise(domain.map(transform), range2, interpolate)))(transform(clamp3(x)));
  }
  scale.invert = function(y) {
    return clamp3(untransform((input || (input = piecewise(range2, domain.map(transform), number_default)))(y)));
  };
  scale.domain = function(_) {
    return arguments.length ? (domain = Array.from(_, number2), rescale()) : domain.slice();
  };
  scale.range = function(_) {
    return arguments.length ? (range2 = Array.from(_), rescale()) : range2.slice();
  };
  scale.rangeRound = function(_) {
    return range2 = Array.from(_), interpolate = round_default, rescale();
  };
  scale.clamp = function(_) {
    return arguments.length ? (clamp3 = _ ? true : identity2, rescale()) : clamp3 !== identity2;
  };
  scale.interpolate = function(_) {
    return arguments.length ? (interpolate = _, rescale()) : interpolate;
  };
  scale.unknown = function(_) {
    return arguments.length ? (unknown = _, scale) : unknown;
  };
  return function(t, u) {
    transform = t, untransform = u;
    return rescale();
  };
}
function continuous() {
  return transformer()(identity2, identity2);
}

// node_modules/d3-scale/src/tickFormat.js
function tickFormat(start, stop, count2, specifier) {
  var step = tickStep(start, stop, count2), precision;
  specifier = formatSpecifier(specifier == null ? ",f" : specifier);
  switch (specifier.type) {
    case "s": {
      var value = Math.max(Math.abs(start), Math.abs(stop));
      if (specifier.precision == null && !isNaN(precision = precisionPrefix_default(step, value)))
        specifier.precision = precision;
      return formatPrefix(specifier, value);
    }
    case "":
    case "e":
    case "g":
    case "p":
    case "r": {
      if (specifier.precision == null && !isNaN(precision = precisionRound_default(step, Math.max(Math.abs(start), Math.abs(stop)))))
        specifier.precision = precision - (specifier.type === "e");
      break;
    }
    case "f":
    case "%": {
      if (specifier.precision == null && !isNaN(precision = precisionFixed_default(step)))
        specifier.precision = precision - (specifier.type === "%") * 2;
      break;
    }
  }
  return format(specifier);
}

// node_modules/d3-scale/src/linear.js
function linearish(scale) {
  var domain = scale.domain;
  scale.ticks = function(count2) {
    var d = domain();
    return ticks(d[0], d[d.length - 1], count2 == null ? 10 : count2);
  };
  scale.tickFormat = function(count2, specifier) {
    var d = domain();
    return tickFormat(d[0], d[d.length - 1], count2 == null ? 10 : count2, specifier);
  };
  scale.nice = function(count2) {
    if (count2 == null)
      count2 = 10;
    var d = domain();
    var i0 = 0;
    var i1 = d.length - 1;
    var start = d[i0];
    var stop = d[i1];
    var prestep;
    var step;
    var maxIter = 10;
    if (stop < start) {
      step = start, start = stop, stop = step;
      step = i0, i0 = i1, i1 = step;
    }
    while (maxIter-- > 0) {
      step = tickIncrement(start, stop, count2);
      if (step === prestep) {
        d[i0] = start;
        d[i1] = stop;
        return domain(d);
      } else if (step > 0) {
        start = Math.floor(start / step) * step;
        stop = Math.ceil(stop / step) * step;
      } else if (step < 0) {
        start = Math.ceil(start * step) / step;
        stop = Math.floor(stop * step) / step;
      } else {
        break;
      }
      prestep = step;
    }
    return scale;
  };
  return scale;
}
function linear2() {
  var scale = continuous();
  scale.copy = function() {
    return copy(scale, linear2());
  };
  initRange.apply(scale, arguments);
  return linearish(scale);
}
// node_modules/d3-scale/src/pow.js
function transformPow(exponent) {
  return function(x) {
    return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);
  };
}
function transformSqrt(x) {
  return x < 0 ? -Math.sqrt(-x) : Math.sqrt(x);
}
function transformSquare(x) {
  return x < 0 ? -x * x : x * x;
}
function powish(transform) {
  var scale = transform(identity2, identity2), exponent = 1;
  function rescale() {
    return exponent === 1 ? transform(identity2, identity2) : exponent === 0.5 ? transform(transformSqrt, transformSquare) : transform(transformPow(exponent), transformPow(1 / exponent));
  }
  scale.exponent = function(_) {
    return arguments.length ? (exponent = +_, rescale()) : exponent;
  };
  return linearish(scale);
}
function pow() {
  var scale = powish(transformer());
  scale.copy = function() {
    return copy(scale, pow()).exponent(scale.exponent());
  };
  initRange.apply(scale, arguments);
  return scale;
}
function sqrt() {
  return pow.apply(null, arguments).exponent(0.5);
}
// node_modules/@oai/granola/dist/draw-utils/chart/compute-bar-domain.js
function getCategoryCount(chart) {
  if (chart.categories.length > 0) {
    return chart.categories.length;
  }
  return chart.series.reduce((acc, series) => Math.max(acc, series.values.length), 0);
}
function computeBarDomain(chart) {
  const isAreaChart = chart.type === 2 /* CHART_TYPE_AREA */ || chart.type === 1 /* CHART_TYPE_AREA_3D */;
  const isLineChart = chart.type === 13 /* CHART_TYPE_LINE */ || chart.type === 12 /* CHART_TYPE_LINE_3D */;
  const barGrouping = chart.barOptions?.grouping;
  const areaGrouping = chart.areaOptions?.grouping;
  const lineGrouping = chart.lineOptions?.grouping;
  let isStacked = false;
  let isPercentStacked = false;
  if (isAreaChart) {
    isStacked = areaGrouping === 2 /* AREA_GROUPING_STACKED */;
    isPercentStacked = areaGrouping === 3 /* AREA_GROUPING_PERCENT_STACKED */;
  } else if (isLineChart) {
    isStacked = lineGrouping === 2 /* LINE_GROUPING_STACKED */;
    isPercentStacked = lineGrouping === 3 /* LINE_GROUPING_PERCENT_STACKED */;
  } else {
    isStacked = barGrouping === 2 /* BAR_GROUPING_STACKED */;
    isPercentStacked = barGrouping === 3 /* BAR_GROUPING_PERCENT_STACKED */;
  }
  if (isStacked) {
    const categoryCount = getCategoryCount(chart);
    let maxPositive = 0;
    let maxNegative = 0;
    for (let categoryIndex = 0;categoryIndex < categoryCount; categoryIndex++) {
      let positiveSum = 0;
      let negativeSum = 0;
      chart.series.forEach((series) => {
        const value = series.values[categoryIndex] ?? 0;
        if (value >= 0)
          positiveSum += value;
        else
          negativeSum += value;
      });
      if (positiveSum > maxPositive)
        maxPositive = positiveSum;
      if (negativeSum < maxNegative)
        maxNegative = negativeSum;
    }
    return {
      min: Math.min(0, maxNegative),
      max: Math.max(0, maxPositive)
    };
  }
  if (isPercentStacked) {
    const hasNegative = chart.series.some((series) => series.values.some((value) => (value ?? 0) < 0));
    const hasPositive = chart.series.some((series) => series.values.some((value) => (value ?? 0) > 0));
    return {
      min: hasNegative ? -1 : 0,
      max: hasPositive ? 1 : 0
    };
  }
  const flatValues = chart.series.flatMap((series) => series.values);
  const [minValue, maxValue] = extent(flatValues);
  const min = Number.isFinite(minValue) ? minValue : 0;
  const max2 = Number.isFinite(maxValue) ? maxValue : 0;
  return {
    min,
    max: max2
  };
}

// node_modules/@oai/granola/dist/draw-utils/chart/prepare-waterfall-data.js
function getCategories(chart, seriesIndex) {
  if (chart.categories.length > 0) {
    return chart.categories;
  }
  const seriesCategories = chart.series[seriesIndex]?.categories ?? [];
  return seriesCategories.length > 0 ? seriesCategories : [];
}
function prepareWaterfallData(chart, hiddenSeriesIndices) {
  const hidden = hiddenSeriesIndices ?? new Set;
  const seriesIndex = chart.series.findIndex((_, idx) => !hidden.has(idx));
  if (seriesIndex === -1) {
    return {
      categories: [],
      seriesIndex: -1,
      segments: [],
      extents: { min: 0, max: 0 }
    };
  }
  const series = chart.series[seriesIndex];
  const values = series?.values ?? [];
  const categories = getCategories(chart, seriesIndex);
  const subtotalSet = new Set(chart.waterfallOptions?.subtotalIndices ?? []);
  const categoryCount = Math.max(values.length, categories.length);
  let running = 0;
  let extentMin = 0;
  let extentMax = 0;
  const segments = [];
  for (let i = 0;i < categoryCount; i++) {
    const rawValue = values[i] ?? 0;
    const isSubtotal = subtotalSet.has(i);
    const category = categories[i] ?? series?.categories?.[i] ?? `Item ${i + 1}`;
    const cumulativeBefore = running;
    let start;
    let end;
    let cumulativeAfter;
    let kind;
    if (isSubtotal) {
      start = 0;
      end = rawValue;
      cumulativeAfter = rawValue;
      kind = "total";
    } else {
      start = running;
      cumulativeAfter = running + rawValue;
      end = cumulativeAfter;
      kind = rawValue >= 0 ? "increase" : "decrease";
    }
    running = cumulativeAfter;
    extentMin = Math.min(extentMin, start, end);
    extentMax = Math.max(extentMax, start, end);
    segments.push({
      index: i,
      category,
      value: rawValue,
      start,
      end,
      cumulativeBefore,
      cumulativeAfter,
      isSubtotal,
      kind,
      labelValue: isSubtotal ? cumulativeAfter : rawValue
    });
  }
  extentMin = Math.min(extentMin, 0);
  extentMax = Math.max(extentMax, 0);
  return {
    categories,
    seriesIndex,
    segments,
    extents: {
      min: extentMin,
      max: extentMax
    }
  };
}

// node_modules/@oai/granola/dist/draw-utils/chart/create-scales.js
var DEFAULT_CATEGORY_VALUE_TICK_COUNT = 5;
function createScales(chart, dims) {
  const baseCategories = chart.categories.length > 0 ? chart.categories : chart.series[0]?.categories ?? [];
  const { maxBackward, maxForward } = (() => {
    let backward = 0;
    let forward = 0;
    for (const series of chart.series ?? []) {
      const trendlines = series?.trendlines;
      if (!Array.isArray(trendlines))
        continue;
      for (const t of trendlines) {
        if (!t || typeof t !== "object")
          continue;
        const tl = t;
        const b = typeof tl.backward === "number" && Number.isFinite(tl.backward) ? Math.max(0, Math.floor(tl.backward)) : 0;
        const f = typeof tl.forward === "number" && Number.isFinite(tl.forward) ? Math.max(0, Math.floor(tl.forward)) : 0;
        if (b > backward)
          backward = b;
        if (f > forward)
          forward = f;
      }
    }
    return { maxBackward: backward, maxForward: forward };
  })();
  const categories = maxBackward > 0 || maxForward > 0 ? padCategories(baseCategories, maxBackward, maxForward) : baseCategories;
  let domainMin;
  let domainMax;
  if (chart.type === 27 /* CHART_TYPE_WATERFALL */) {
    const prepared = prepareWaterfallData(chart);
    domainMin = prepared.extents.min;
    domainMax = prepared.extents.max;
  } else {
    const domain = computeBarDomain(chart);
    domainMin = domain.min;
    domainMax = domain.max;
  }
  const vMin = Math.min(0, domainMin);
  const vMax = Math.max(0, domainMax);
  const gap = chart.barOptions?.gapWidth;
  const paddingInner = typeof gap === "number" && isFinite(gap) ? 1 - 1 / (1 + gap / 100) : BAR_PADDING_INNER;
  const isLineChart = chart.type === 13 /* CHART_TYPE_LINE */ || chart.type === 12 /* CHART_TYPE_LINE_3D */;
  const isAreaChart = chart.type === 2 /* CHART_TYPE_AREA */ || chart.type === 1 /* CHART_TYPE_AREA_3D */;
  const x = isLineChart || isAreaChart ? point().domain(categories).range([dims.x, dims.x + dims.width]).padding(isLineChart ? 0.5 : 0) : band().domain(categories).range([dims.x, dims.x + dims.width]).paddingInner(paddingInner).paddingOuter(0.5);
  const y = linear2().domain([Math.min(0, vMin), vMax]).nice(DEFAULT_CATEGORY_VALUE_TICK_COUNT).range([dims.y + dims.height, dims.y]);
  return { x, y };
}
function padCategories(categories, maxBackward, maxForward) {
  if (categories.length === 0)
    return categories;
  if (maxBackward <= 0 && maxForward <= 0)
    return categories;
  const taken = new Set(categories);
  const make = (base) => {
    let next = base;
    while (taken.has(next)) {
      next = `${next}_`;
    }
    taken.add(next);
    return next;
  };
  const before = maxBackward > 0 ? Array.from({ length: maxBackward }, (_, i) => make(`__trendpad_before_${i + 1}__`)) : [];
  const after = maxForward > 0 ? Array.from({ length: maxForward }, (_, i) => make(`__trendpad_after_${i + 1}__`)) : [];
  return [...before, ...categories, ...after];
}

// node_modules/@oai/granola/dist/draw-utils/chart/utils.js
function isBandScale(scale) {
  return typeof scale.bandwidth === "function";
}
function getCenter(scale, cat) {
  if (cat === undefined)
    return;
  if (isBandScale(scale)) {
    const start = scale(cat);
    return start !== undefined ? start + scale.bandwidth() / 2 : undefined;
  }
  return scale(cat);
}
function isPieLike(t) {
  return t === 16 /* CHART_TYPE_PIE */ || t === 15 /* CHART_TYPE_PIE_3D */ || t === 8 /* CHART_TYPE_DOUGHNUT */;
}

// node_modules/@oai/granola/dist/draw-utils/ellipsize.js
function ellipsize(ctx, text, maxWidth) {
  if (ctx.measureText(text).width <= maxWidth)
    return text;
  const ellipsis = "…";
  let lo = 0, hi = text.length;
  while (lo < hi) {
    const mid = Math.ceil((lo + hi) / 2);
    if (ctx.measureText(text.slice(0, mid) + ellipsis).width <= maxWidth) {
      lo = mid;
    } else {
      hi = mid - 1;
    }
  }
  return text.slice(0, lo) + ellipsis;
}

// node_modules/@oai/granola/dist/draw-utils/chart/get-axis-styles.js
function getAxisStyles(axis, themeMap) {
  const lineColor = axis?.line?.fill?.color ? resolveColor(axis.line.fill.color, themeMap) : AXIS_COLOR;
  const textColor = axis?.textStyle?.fill?.color ? resolveColor(axis.textStyle.fill.color, themeMap) : lineColor;
  const fontSize = axis?.textStyle?.fontSize ? fontSizeToPx(axis.textStyle.fontSize) : TICK_FONT_SIZE;
  const gridLineColor = axis?.majorGridlines?.fill?.color ? resolveColor(axis.majorGridlines.fill.color, themeMap) : undefined;
  return { lineColor, textColor, fontSize, gridLineColor };
}
function getAxisRotationDegrees(axis) {
  const raw = axis?.textStyle?.rotation;
  if (typeof raw !== "number" || Number.isNaN(raw)) {
    return 0;
  }
  if (raw === -1000) {
    return 0;
  }
  let rotation = raw;
  if (Math.abs(rotation) > 360) {
    const maybeDegrees = rotation / 60000;
    if (Number.isFinite(maybeDegrees) && Math.abs(maybeDegrees) <= 360) {
      rotation = maybeDegrees;
    } else if (Number.isFinite(rotation)) {
      rotation = rotation % 360;
    }
  }
  if (!Number.isFinite(rotation)) {
    return 0;
  }
  if (Math.abs(rotation) >= 360) {
    rotation = rotation % 360;
  }
  if (Math.abs(rotation) < 0.001) {
    return 0;
  }
  return rotation;
}

// node_modules/@oai/granola/dist/draw-utils/chart/apply-line-style.js
function applyLineStyle(ctx, line, themeMap, fallback = {}) {
  const color2 = line?.fill?.color !== undefined ? resolveColor(line.fill.color, themeMap, fallback.color) : fallback.color;
  const widthRaw = line?.widthEmu;
  const widthPx = widthRaw !== undefined && widthRaw !== null && Number.isFinite(Number(widthRaw)) ? Math.max(0, Number(widthRaw) * EMU_TO_PX) : fallback.widthPx;
  if (color2) {
    ctx.strokeStyle = color2;
  }
  if (widthPx !== undefined) {
    ctx.lineWidth = widthPx;
  }
  const style = line?.style;
  switch (style) {
    case 2 /* LINE_STYLE_DASHED */:
      ctx.setLineDash([4, 3]);
      break;
    case 3 /* LINE_STYLE_DOTTED */:
      ctx.setLineDash([1, 2]);
      break;
    case 4 /* LINE_STYLE_DASH_DOT */:
      ctx.setLineDash([4, 2, 1, 2]);
      break;
    case 5 /* LINE_STYLE_DASH_DOT_DOT */:
      ctx.setLineDash([4, 2, 1, 2, 1, 2]);
      break;
    case 1 /* LINE_STYLE_SOLID */:
    case 0 /* LINE_STYLE_UNSPECIFIED */:
    default:
      ctx.setLineDash([]);
      break;
  }
  return { color: color2, widthPx };
}

// node_modules/@oai/granola/dist/draw-utils/chart/get-axis-render-extras.js
var POINTS_PER_INCH = 72;
var PX_PER_INCH = 96;
function getAxisRenderExtras(axis) {
  if (!axis || typeof axis !== "object")
    return {};
  const maybe = axis;
  const rawTickLabelInterval = maybe["tickLabelInterval"];
  const tickLabelInterval = typeof rawTickLabelInterval === "number" && Number.isFinite(rawTickLabelInterval) ? rawTickLabelInterval : undefined;
  const rawTickLabelDistanceFromAxis = maybe["tickLabelDistanceFromAxis"];
  const tickLabelDistanceFromAxis = typeof rawTickLabelDistanceFromAxis === "number" && Number.isFinite(rawTickLabelDistanceFromAxis) ? rawTickLabelDistanceFromAxis : undefined;
  const rawTickLabelPositionName = maybe["tickLabelPositionName"];
  const tickLabelPositionName = typeof rawTickLabelPositionName === "string" ? rawTickLabelPositionName : undefined;
  return {
    tickLabelInterval,
    tickLabelDistanceFromAxis,
    tickLabelPositionName
  };
}
function getAxisTickLabelDistancePx(axis) {
  const extras = getAxisRenderExtras(axis);
  return extras.tickLabelDistanceFromAxis !== undefined ? extras.tickLabelDistanceFromAxis * PX_PER_INCH / POINTS_PER_INCH : 0;
}
function shouldHideAxisTickLabels(axis) {
  const extras = getAxisRenderExtras(axis);
  return extras.tickLabelPositionName?.toLowerCase() === "none";
}

// node_modules/@oai/granola/dist/draw-utils/chart/measure-rotated-text.js
function rotatedRectBounds(width, height, angleRad) {
  if (!isFinite(angleRad) || angleRad === 0)
    return { width, height };
  const c = Math.cos(angleRad);
  const s = Math.sin(angleRad);
  const w = Math.abs(width * c) + Math.abs(height * s);
  const h = Math.abs(width * s) + Math.abs(height * c);
  return { width: w, height: h };
}

// node_modules/@oai/granola/dist/draw-utils/chart/measure-axis-title.js
function measureAxisTitle(ctx, title, style, fallbackFontPx, defaultRotationDeg) {
  const text = title?.trim();
  if (!text)
    return;
  const fontPx = style?.fontSize ? fontSizeToPx(style.fontSize) : fallbackFontPx;
  const rotationDeg = style?.rotation ?? defaultRotationDeg;
  const rotationRad = rotationDeg * Math.PI / 180;
  const isBold = !!style?.bold;
  ctx.save();
  ctx.font = `${isBold ? "bold " : ""}${fontPx}px ${FONT_FAMILY}`;
  const rawWidth = ctx.measureText(text).width;
  ctx.restore();
  const bounds = rotatedRectBounds(rawWidth, fontPx, rotationRad);
  return {
    text,
    fontPx,
    rotationRad,
    width: bounds.width,
    height: bounds.height,
    isBold
  };
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-rotated-axis-tick-label.js
function drawRotatedXAxisTickLabel(args) {
  const { ctx, text, anchorX, anchorY, rotationDeg, fontSizePx, side } = args;
  const widthPx = ctx.measureText(text).width;
  if (!(widthPx > 0) || !(fontSizePx > 0))
    return;
  const layout = getRotatedXAxisTickLabelLayout({
    widthPx,
    heightPx: fontSizePx,
    rotationDeg,
    side
  });
  ctx.save();
  ctx.translate(anchorX, anchorY);
  ctx.rotate(rotationDeg * Math.PI / 180);
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText(text, layout.leftPx, layout.topPx);
  ctx.restore();
}
function getRotatedXAxisTickLabelLayout(args) {
  const { widthPx, heightPx, rotationDeg } = args;
  const leftPx = rotationDeg < 0 ? -widthPx : 0;
  const topPx = -heightPx / 2;
  return {
    leftPx,
    topPx,
    widthPx,
    heightPx
  };
}

// node_modules/@oai/granola/dist/draw-utils/chart/format-value-axis-tick.js
var import_ssf = __toESM(require_ssf(), 1);
function formatValueAxisTick(value, formatCode) {
  if (!Number.isFinite(value))
    return "";
  if (formatCode) {
    try {
      return import_ssf.default.format(formatCode, value);
    } catch {}
  }
  return format("~s")(value);
}

// node_modules/@oai/granola/dist/draw-utils/chart/plan-value-axis.js
var AXIS_TICK_GAP_PX = 6;
var MIN_LABEL_VERTICAL_SEPARATION_PX = 4;
function planValueAxis(args) {
  const { ctx, axis, scale, preferredTickCount, themeMap } = args;
  const styles = getAxisStyles(axis, themeMap);
  ctx.font = `${styles.fontSize}px ${FONT_FAMILY}`;
  const hideTickLabels = shouldHideAxisTickLabels(axis);
  const sanitizedPreferredTickCount = Math.max(1, Math.floor(preferredTickCount || 1));
  if (hideTickLabels) {
    const ticks2 = scale.ticks(sanitizedPreferredTickCount);
    return {
      ticks: ticks2,
      minorTicks: buildMinorTicks(ticks2),
      labelBandWidth: 0,
      hideTickLabels: true,
      preferredTickCount: sanitizedPreferredTickCount,
      chosenTickCount: sanitizedPreferredTickCount,
      minTickSeparationPx: computeMinTickSeparationPx(scale, ticks2)
    };
  }
  let bestFallback;
  for (let tickCount = sanitizedPreferredTickCount;tickCount >= 1; tickCount -= 1) {
    const candidate = evaluateCandidate({
      ctx,
      axis,
      scale,
      fontSizePx: styles.fontSize,
      preferredTickCount: sanitizedPreferredTickCount,
      tickCount
    });
    if (candidate.fits) {
      return candidate;
    }
    if (!bestFallback || candidate.overflowPx < bestFallback.overflowPx) {
      bestFallback = candidate;
    }
  }
  return bestFallback ?? {
    ticks: [],
    minorTicks: [],
    labelBandWidth: 0,
    hideTickLabels: false,
    preferredTickCount: sanitizedPreferredTickCount,
    chosenTickCount: sanitizedPreferredTickCount,
    minTickSeparationPx: Number.POSITIVE_INFINITY,
    fits: true,
    overflowPx: 0
  };
}
function evaluateCandidate(args) {
  const { ctx, axis, scale, fontSizePx, preferredTickCount, tickCount } = args;
  const ticks2 = scale.ticks(tickCount);
  const minTickSeparationPx = computeMinTickSeparationPx(scale, ticks2);
  const requiredSeparationPx = fontSizePx + MIN_LABEL_VERTICAL_SEPARATION_PX;
  let maxLabelWidthPx = 0;
  for (const tick of ticks2) {
    const label = formatValueAxisTick(tick, axis?.numberFormatCode);
    maxLabelWidthPx = Math.max(maxLabelWidthPx, ctx.measureText(label).width);
  }
  const overflowPx = Math.max(0, requiredSeparationPx - minTickSeparationPx);
  return {
    ticks: ticks2,
    minorTicks: buildMinorTicks(ticks2),
    labelBandWidth: maxLabelWidthPx > 0 ? maxLabelWidthPx + AXIS_TICK_GAP_PX : 0,
    hideTickLabels: false,
    preferredTickCount,
    chosenTickCount: tickCount,
    minTickSeparationPx,
    fits: ticks2.length <= 1 || overflowPx <= 0,
    overflowPx
  };
}
function buildMinorTicks(ticks2) {
  if (ticks2.length <= 1)
    return [];
  const minorTicks = [];
  for (let index = 0;index < ticks2.length - 1; index += 1) {
    const current = ticks2[index];
    const next = ticks2[index + 1];
    if (current === undefined || next === undefined)
      continue;
    if (!Number.isFinite(current) || !Number.isFinite(next))
      continue;
    minorTicks.push((current + next) / 2);
  }
  return minorTicks;
}
function computeMinTickSeparationPx(scale, ticks2) {
  if (ticks2.length <= 1)
    return Number.POSITIVE_INFINITY;
  let minSeparationPx = Number.POSITIVE_INFINITY;
  for (let index = 1;index < ticks2.length; index += 1) {
    const previousPx = scale(ticks2[index - 1] ?? 0);
    const currentPx = scale(ticks2[index] ?? 0);
    if (!Number.isFinite(previousPx) || !Number.isFinite(currentPx))
      continue;
    minSeparationPx = Math.min(minSeparationPx, Math.abs(currentPx - previousPx));
  }
  return minSeparationPx;
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-axes.js
var AXIS_TICK_GAP_PX2 = 6;
var AXIS_TITLE_GAP_PX = 8;
var AXIS_GRIDLINE_EPSILON_PX = 0.5;
var VALUE_TICK_COUNT = 5;
function overlapsAxisLine(a, b) {
  return Math.abs(a - b) <= AXIS_GRIDLINE_EPSILON_PX;
}
function drawAxes(ctx, chart, scales, dims, themeMap, xAxisPlan) {
  const { x, y } = scales;
  const categories = chart.categories.length > 0 ? chart.categories : chart.series[0]?.categories ?? [];
  ctx.save();
  ctx.font = `${TICK_FONT_SIZE}px ${FONT_FAMILY}`;
  ctx.fillStyle = AXIS_COLOR;
  ctx.strokeStyle = AXIS_COLOR;
  ctx.lineWidth = 1;
  const xAxisStyles = getAxisStyles(chart.xAxis, themeMap);
  const yDomain = y.domain();
  const domainStart = yDomain[0];
  const domainEnd = yDomain[yDomain.length - 1];
  const domainMin = typeof domainStart === "number" && typeof domainEnd === "number" ? Math.min(domainStart, domainEnd) : undefined;
  let yBaseline = domainMin !== undefined ? y(domainMin) : y(Math.min(0, domainStart ?? 0));
  if (!Number.isFinite(yBaseline)) {
    yBaseline = dims.y + dims.height;
  }
  const plotBottom = dims.y + dims.height;
  const plotTop = dims.y;
  const baselineCloserToBottom = Math.abs(yBaseline - plotBottom) <= Math.abs(yBaseline - plotTop);
  const tickDirection = baselineCloserToBottom ? 1 : -1;
  const tickLength = 4;
  const xAxisExtras = getAxisRenderExtras(chart.xAxis);
  const extraLabelDistancePx = xAxisPlan?.tickLabelDistancePx ?? getAxisTickLabelDistancePx(chart.xAxis);
  const labelOffset = tickLength + 2 + extraLabelDistancePx;
  const xAxisConfig = chart.xAxis;
  const xAxisDeleted = !!xAxisConfig?.deleted;
  let xLabelBand = 0;
  if (!xAxisDeleted) {
    const xAxisLineVisible = !!xAxisConfig?.line?.fill?.color;
    if (xAxisLineVisible) {
      ctx.strokeStyle = xAxisStyles.lineColor;
      ctx.beginPath();
      ctx.moveTo(dims.x, yBaseline);
      ctx.lineTo(dims.x + dims.width, yBaseline);
      ctx.stroke();
    }
    ctx.strokeStyle = xAxisStyles.lineColor;
    ctx.lineWidth = 1;
    ctx.font = `${xAxisStyles.fontSize}px ${FONT_FAMILY}`;
    const rotDeg = xAxisPlan?.rotationDeg ?? getAxisRotationDegrees(chart.xAxis);
    const rotRad = rotDeg * Math.PI / 180;
    if (xAxisPlan) {
      xLabelBand = xAxisPlan.labelBandHeight;
    } else {
      let maxXLabelTextWidth = 0;
      categories.forEach((cat) => {
        const text = cat ?? "";
        const width = ctx.measureText(text).width;
        if (width > maxXLabelTextWidth)
          maxXLabelTextWidth = width;
      });
      const xLabelRect = rotatedRectBounds(maxXLabelTextWidth, xAxisStyles.fontSize, rotRad);
      xLabelBand = maxXLabelTextWidth > 0 ? xLabelRect.height + AXIS_TICK_GAP_PX2 + extraLabelDistancePx : 0;
    }
    ctx.textAlign = "center";
    ctx.textBaseline = baselineCloserToBottom ? "top" : "bottom";
    ctx.fillStyle = xAxisStyles.textColor;
    const hideTickLabels = xAxisPlan?.hideTickLabels ?? shouldHideAxisTickLabels(chart.xAxis);
    const xHasTicks = xAxisConfig?.majorTickMark !== undefined && xAxisConfig.majorTickMark !== 0 /* TICK_MARK_UNSPECIFIED */ && xAxisConfig.majorTickMark !== 1 /* TICK_MARK_NONE */;
    const xGridVisible = Boolean(xAxisConfig?.majorGridlines?.fill?.color);
    const xGridLine = xAxisConfig?.majorGridlines;
    const interval = xAxisExtras.tickLabelInterval;
    const step = xAxisPlan?.step ?? (interval !== undefined && interval > 0 ? Math.floor(interval) : 1);
    const visibleIndexSet = xAxisPlan ? new Set(xAxisPlan.visibleIndices) : undefined;
    categories.forEach((cat, idx) => {
      const cx = getCenter(x, cat);
      if (cx === undefined)
        return;
      const shouldShowMajor = visibleIndexSet !== undefined ? visibleIndexSet.has(idx) : step <= 1 || idx % step === 0;
      if (shouldShowMajor && xGridVisible && xGridLine) {
        ctx.save();
        applyLineStyle(ctx, xGridLine, themeMap, {
          color: xAxisStyles.gridLineColor ?? xAxisStyles.lineColor,
          widthPx: 1
        });
        if (!overlapsAxisLine(cx, dims.x)) {
          ctx.beginPath();
          ctx.moveTo(cx, dims.y);
          ctx.lineTo(cx, dims.y + dims.height);
          ctx.stroke();
        }
        ctx.restore();
      }
      if (shouldShowMajor && xHasTicks) {
        ctx.beginPath();
        ctx.moveTo(cx, yBaseline);
        ctx.lineTo(cx, yBaseline + tickDirection * tickLength);
        ctx.stroke();
      }
      const maxLabelWidth = xAxisPlan?.labelMaxWidthPx ?? (isBandScale(x) ? x.step() : dims.width / Math.max(1, categories.length));
      const label = ellipsize(ctx, cat, maxLabelWidth);
      if (hideTickLabels || !shouldShowMajor) {
        return;
      }
      if (rotRad !== 0) {
        drawRotatedXAxisTickLabel({
          ctx,
          text: label,
          anchorX: cx,
          anchorY: yBaseline + tickDirection * labelOffset,
          rotationDeg: rotDeg,
          fontSizePx: xAxisStyles.fontSize,
          side: baselineCloserToBottom ? "bottom" : "top"
        });
      } else {
        ctx.fillText(label, cx, yBaseline + tickDirection * labelOffset);
      }
    });
  }
  const yAxisStyles = getAxisStyles(chart.yAxis, themeMap);
  const yAxisConfig = chart.yAxis;
  const yAxisDeleted = !!yAxisConfig?.deleted;
  let yLabelBand = 0;
  if (!yAxisDeleted) {
    const yAxisLineVisible = !!yAxisConfig?.line?.fill?.color;
    if (yAxisLineVisible) {
      ctx.strokeStyle = yAxisStyles.lineColor;
      ctx.beginPath();
      ctx.moveTo(dims.x, dims.y);
      ctx.lineTo(dims.x, dims.y + dims.height);
      ctx.stroke();
    }
    ctx.textAlign = "right";
    ctx.textBaseline = "middle";
    ctx.fillStyle = yAxisStyles.textColor;
    const yAxisPlan = planValueAxis({
      ctx,
      axis: yAxisConfig,
      scale: y,
      preferredTickCount: VALUE_TICK_COUNT,
      themeMap
    });
    yLabelBand = yAxisPlan.labelBandWidth;
    const drawMajorGrid = Boolean(yAxisConfig?.majorGridlines?.fill?.color);
    const drawMinorGrid = Boolean(yAxisConfig?.minorGridlines?.fill?.color);
    const yHasTicks = yAxisConfig?.majorTickMark !== undefined && yAxisConfig.majorTickMark !== 0 /* TICK_MARK_UNSPECIFIED */ && yAxisConfig.majorTickMark !== 1 /* TICK_MARK_NONE */;
    const yTicks = yAxisPlan.ticks;
    const minorTicks = drawMinorGrid ? yAxisPlan.minorTicks : [];
    if (drawMinorGrid && yAxisConfig?.minorGridlines) {
      ctx.save();
      applyLineStyle(ctx, yAxisConfig.minorGridlines, themeMap, {
        color: yAxisStyles.gridLineColor ?? yAxisStyles.lineColor,
        widthPx: 0.75
      });
      minorTicks.forEach((tick) => {
        const py = y(tick);
        if (!Number.isFinite(py))
          return;
        if (overlapsAxisLine(py, yBaseline))
          return;
        ctx.beginPath();
        ctx.moveTo(dims.x, py);
        ctx.lineTo(dims.x + dims.width, py);
        ctx.stroke();
      });
      ctx.restore();
    }
    yTicks.forEach((tick) => {
      const py = y(tick);
      if (drawMajorGrid && yAxisConfig?.majorGridlines) {
        ctx.save();
        applyLineStyle(ctx, yAxisConfig.majorGridlines, themeMap, {
          color: yAxisStyles.gridLineColor ?? yAxisStyles.lineColor,
          widthPx: 1
        });
        if (!overlapsAxisLine(py, yBaseline)) {
          ctx.beginPath();
          ctx.moveTo(dims.x, py);
          ctx.lineTo(dims.x + dims.width, py);
          ctx.stroke();
        }
        ctx.restore();
      }
      if (yHasTicks) {
        ctx.strokeStyle = yAxisStyles.lineColor;
        ctx.beginPath();
        ctx.moveTo(dims.x - 4, py);
        ctx.lineTo(dims.x, py);
        ctx.stroke();
      }
      if (!yAxisPlan.hideTickLabels) {
        ctx.font = `${yAxisStyles.fontSize}px ${FONT_FAMILY}`;
        const label = formatValueAxisTick(tick, chart.yAxis?.numberFormatCode);
        ctx.fillText(label, dims.x - 6, py);
      }
    });
  }
  const xTitleMetrics = !xAxisDeleted ? measureAxisTitle(ctx, xAxisConfig?.title, xAxisConfig?.titleTextStyle, xAxisStyles.fontSize, 0) : undefined;
  const yTitleMetrics = !yAxisDeleted ? measureAxisTitle(ctx, yAxisConfig?.title, yAxisConfig?.titleTextStyle, yAxisStyles.fontSize, -90) : undefined;
  if (xTitleMetrics) {
    const xTitleStyle = xAxisConfig?.titleTextStyle;
    const txtColor = xTitleStyle?.fill?.color ? resolveColor(xTitleStyle.fill.color, themeMap) : xAxisStyles.textColor;
    const offset = xLabelBand + AXIS_TITLE_GAP_PX + xTitleMetrics.height / 2;
    const titleY = yBaseline + tickDirection * offset;
    ctx.save();
    ctx.fillStyle = txtColor ?? xAxisStyles.textColor;
    ctx.font = `${xTitleMetrics.isBold ? "bold " : ""}${xTitleMetrics.fontPx}px ${FONT_FAMILY}`;
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.translate(dims.x + dims.width / 2, titleY);
    ctx.rotate(xTitleMetrics.rotationRad);
    ctx.fillText(xTitleMetrics.text, 0, 0);
    ctx.restore();
  }
  if (yTitleMetrics) {
    const yTitleStyle = yAxisConfig?.titleTextStyle;
    const txtColor = yTitleStyle?.fill?.color ? resolveColor(yTitleStyle.fill.color, themeMap) : yAxisStyles.textColor;
    const cx = dims.x - yLabelBand - AXIS_TITLE_GAP_PX - yTitleMetrics.width / 2;
    const cy = dims.y + dims.height / 2;
    ctx.save();
    ctx.fillStyle = txtColor ?? yAxisStyles.textColor;
    ctx.font = `${yTitleMetrics.isBold ? "bold " : ""}${yTitleMetrics.fontPx}px ${FONT_FAMILY}`;
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.translate(cx, cy);
    ctx.rotate(yTitleMetrics.rotationRad);
    ctx.fillText(yTitleMetrics.text, 0, 0);
    ctx.restore();
  }
  ctx.restore();
}

// node_modules/@oai/granola/dist/draw-utils/chart/adjust-dims-for-y-axis.js
function adjustDimsForYAxis(ctx, dims, categories, yAxis, themeMap, opts = {}) {
  if (yAxis?.deleted) {
    return dims;
  }
  const { maxLeftFrac = 0.35, sidePaddingPx = 8 } = opts;
  const { fontSize } = getAxisStyles(yAxis, themeMap);
  ctx.save();
  ctx.font = `${fontSize}px ${FONT_FAMILY}`;
  let widest = 0;
  for (const category of categories) {
    const width = ctx.measureText(category).width;
    if (width > widest)
      widest = width;
  }
  ctx.restore();
  if (widest <= 0) {
    return dims;
  }
  const maxReserveFromFrac = Math.max(0, dims.width * maxLeftFrac);
  const required = Math.min(maxReserveFromFrac, widest + sidePaddingPx);
  const currentReserve = PADDING.left;
  const extraNeeded = Math.max(0, required - currentReserve);
  if (extraNeeded <= 0)
    return dims;
  const MIN_PLOT_WIDTH = 24;
  const maxShift = Math.max(0, dims.width - MIN_PLOT_WIDTH);
  if (maxShift === 0)
    return dims;
  const shift = Math.min(extraNeeded, maxShift);
  return {
    x: dims.x + shift,
    y: dims.y,
    width: Math.max(0, dims.width - shift),
    height: dims.height
  };
}

// node_modules/@oai/granola/dist/draw-utils/chart/get-series-color.js
var ACCENT_KEYS = [
  "accent1",
  "accent2",
  "accent3",
  "accent4",
  "accent5",
  "accent6"
];
function getSeriesColor(series, index, themeMap) {
  if (series.fill?.color) {
    return resolveColor(series.fill.color, themeMap);
  }
  const strokeColor = series.stroke?.fill?.color ? resolveColor(series.stroke.fill.color, themeMap) : undefined;
  if (strokeColor) {
    return strokeColor;
  }
  const accentKey = ACCENT_KEYS[index % ACCENT_KEYS.length];
  const accentColor = themeMap.colorMap[accentKey ?? ""];
  if (accentColor) {
    return accentColor;
  }
  return SERIES_COLORS[index % SERIES_COLORS.length];
}

// node_modules/@oai/granola/dist/draw-utils/map/draw-map-chart.js
var COUNTRY_SOURCE_URL = "mapbox://mapbox.country-boundaries-v1";
var COUNTRY_SOURCE_LAYER = "country_boundaries";
function sanitizeIdSegment(value) {
  if (!value)
    return "map";
  return value.replace(/[^a-zA-Z0-9_-]/g, "_") || "map";
}
function resolveRampColors(baseColor) {
  const parsed = baseColor ? color(baseColor) : null;
  if (!parsed) {
    return {
      start: "#c1e4ff",
      end: "#0f5aad",
      fallback: "#d6dbe1"
    };
  }
  const start = parsed.brighter(1.8).formatHex();
  const end = parsed.darker(0.6).formatHex();
  return { start, end, fallback: "#d6dbe1" };
}
function drawMapChart(mapCtx, chart, _dims, themeMap, opts = {}) {
  const map3 = mapCtx.map;
  if (!chart.series.length)
    return;
  const baseSeriesIndex = 0;
  if (opts.hiddenSeriesIndices?.has(baseSeriesIndex) || chart.series[baseSeriesIndex] == null) {
    mapCtx.clear();
    return;
  }
  const series = chart.series[baseSeriesIndex];
  const categories = series.categories && series.categories.length > 0 ? series.categories : chart.categories;
  const values = series.values ?? [];
  if (!categories || categories.length === 0 || values.length === 0) {
    mapCtx.clear();
    return;
  }
  const valueByRegion = new Map;
  categories.forEach((category, idx) => {
    const value = values[idx];
    const normalizedKey = normalizeRegionKey(category);
    if (normalizedKey && typeof value === "number" && Number.isFinite(value)) {
      valueByRegion.set(normalizedKey, value);
    }
  });
  if (valueByRegion.size === 0) {
    mapCtx.clear();
    return;
  }
  const validValues = Array.from(valueByRegion.values());
  const [min, max2] = extent(validValues);
  const colorBase = getSeriesColor(series, baseSeriesIndex, themeMap);
  const ramp = resolveRampColors(colorBase);
  const domainMin = min ?? 0;
  const domainMax = max2 ?? domainMin;
  const epsilon = domainMax === domainMin ? 1 : 0;
  const scale = linear2().domain([domainMin, domainMax + epsilon]).range([ramp.start, ramp.end]);
  const colorByRegion = new Map;
  const opacityByRegion = new Map;
  valueByRegion.forEach((value, region) => {
    colorByRegion.set(region, scale(value));
    opacityByRegion.set(region, 0.9);
  });
  const fillExpression = buildCountryMatchExpression(colorByRegion, ramp.fallback);
  const opacityExpression = buildCountryMatchExpression(opacityByRegion, 0.55);
  const baseId = sanitizeIdSegment(opts.elementId ?? chart.id ?? "chart");
  const sourceId = `granola-map-source-${baseId}`;
  const fillLayerId = `granola-map-fill-${baseId}`;
  const outlineLayerId = `granola-map-outline-${baseId}`;
  const ensureLayers = () => {
    if (!map3.getSource(sourceId)) {
      map3.addSource(sourceId, {
        type: "vector",
        url: COUNTRY_SOURCE_URL
      });
      mapCtx.trackSource(sourceId);
    }
    if (!map3.getLayer(fillLayerId)) {
      map3.addLayer({
        id: fillLayerId,
        type: "fill",
        source: sourceId,
        "source-layer": COUNTRY_SOURCE_LAYER,
        paint: {
          "fill-color": fillExpression,
          "fill-opacity": opacityExpression
        }
      });
      mapCtx.trackLayer(fillLayerId);
    } else {
      map3.setPaintProperty(fillLayerId, "fill-color", fillExpression);
      map3.setPaintProperty(fillLayerId, "fill-opacity", opacityExpression);
    }
    if (!map3.getLayer(outlineLayerId)) {
      map3.addLayer({
        id: outlineLayerId,
        type: "line",
        source: sourceId,
        "source-layer": COUNTRY_SOURCE_LAYER,
        paint: {
          "line-color": "#ffffff",
          "line-width": 0.5,
          "line-opacity": 0.6
        }
      });
      mapCtx.trackLayer(outlineLayerId);
    }
    const targetZoom = 0.2;
    const targetCenter = [0, 15];
    const currentZoom = map3.getZoom();
    const currentCenter = map3.getCenter();
    if (Math.abs(currentZoom - targetZoom) > 0.01 || Math.abs(currentCenter.lng - targetCenter[0]) > 0.5 || Math.abs(currentCenter.lat - targetCenter[1]) > 0.5) {
      map3.jumpTo({
        center: targetCenter,
        zoom: targetZoom,
        bearing: 0,
        pitch: 0
      });
    }
  };
  if (map3.isStyleLoaded()) {
    ensureLayers();
  } else {
    const once = () => {
      map3.off("styledata", once);
      map3.off("load", once);
      ensureLayers();
    };
    map3.on("styledata", once);
    map3.on("load", once);
  }
}
function normalizeRegionKey(value) {
  if (typeof value !== "string") {
    return null;
  }
  const trimmed = value.trim();
  if (!trimmed) {
    return null;
  }
  return trimmed.toUpperCase();
}
function buildCountryMatchExpression(values, fallback) {
  const expression = ["case"];
  values.forEach((value, key) => {
    expression.push(buildCountryCondition(key), value);
  });
  expression.push(fallback);
  return expression;
}
function buildCountryCondition(normalizedKey) {
  return [
    "any",
    ["==", ["upcase", ["coalesce", ["get", "name_en"], ""]], normalizedKey],
    ["==", ["upcase", ["coalesce", ["get", "name"], ""]], normalizedKey],
    [
      "==",
      ["upcase", ["coalesce", ["get", "iso_3166_1_alpha_2"], ""]],
      normalizedKey
    ],
    [
      "==",
      ["upcase", ["coalesce", ["get", "iso_3166_1_alpha_3"], ""]],
      normalizedKey
    ]
  ];
}

// node_modules/@oai/granola/dist/draw-utils/build-linear-gradient.js
function normalizeGradientOffset(position, useUnitRange) {
  const rawOffset = useUnitRange ? position : position / 1e5;
  return Math.min(1, Math.max(0, rawOffset));
}
function buildLinearGradient(ctx, bbox, fill, themeMap) {
  const theta = (fill.angleDeg ?? 0) * (Math.PI / 180);
  const { x, y, width: w, height: h } = bbox;
  const cx = x + w / 2;
  const cy = y + h / 2;
  const halfLen = Math.sqrt(w * w + h * h) / 2;
  const dx = Math.cos(theta) * halfLen;
  const dy = Math.sin(theta) * halfLen;
  const grad = ctx.createLinearGradient(cx - dx, cy - dy, cx + dx, cy + dy);
  const sortedStops = [...fill.gradientStops ?? []].sort((a, b) => (a.position ?? 0) - (b.position ?? 0));
  const useUnitRange = sortedStops.every((stop) => Math.abs(stop.position ?? 0) <= 1);
  if (sortedStops.length === 0) {
    const fallback = resolveColor(fill.color, themeMap, "transparent");
    grad.addColorStop(0, fallback);
    grad.addColorStop(1, fallback);
    return grad;
  }
  sortedStops.forEach((s, idx) => {
    const offset = normalizeGradientOffset(s.position ?? 0, useUnitRange);
    const col = resolveColor(s.color, themeMap);
    const appliedOffset = idx === 0 && offset > 0 && sortedStops.length === 1 ? 0 : offset;
    grad.addColorStop(appliedOffset, col);
  });
  return grad;
}

// node_modules/@oai/granola/dist/draw-utils/build-path-gradient.js
function normalizeGradientOffset2(position, useUnitRange) {
  const rawOffset = useUnitRange ? position : position / 1e5;
  return Math.min(1, Math.max(0, rawOffset));
}
function buildPathGradient(ctx, bbox, fill, themeMap) {
  const { x, y, width: w, height: h } = bbox;
  const clamp01 = (value) => Math.min(1, Math.max(0, value));
  const frac = (v) => clamp01((v ?? 0) / 1e5);
  const fr = fill.fillRect;
  const l = frac(fr?.l);
  const t = frac(fr?.t);
  const r = frac(fr?.r);
  const b = frac(fr?.b);
  const centerXFrac = (l + (1 - r)) / 2;
  const centerYFrac = (t + (1 - b)) / 2;
  const cx = x + centerXFrac * w;
  const cy = y + centerYFrac * h;
  const left = x + l * w;
  const top = y + t * h;
  const right = x + (1 - r) * w;
  const bottom = y + (1 - b) * h;
  const dxLeft = cx - left;
  const dxRight = right - cx;
  const dyTop = cy - top;
  const dyBottom = bottom - cy;
  const distanceToCorner = (px, py) => Math.hypot(px - cx, py - cy);
  const shapeRadius = Math.max(distanceToCorner(x, y), distanceToCorner(x + w, y), distanceToCorner(x, y + h), distanceToCorner(x + w, y + h));
  let radius;
  switch (fill.pathType) {
    case 3 /* GRADIENT_PATH_TYPE_CIRCLE */:
      radius = Math.max(0.000001, Math.min(dxLeft, dxRight, dyTop, dyBottom));
      break;
    case 2 /* GRADIENT_PATH_TYPE_RECT */:
      radius = Math.max(0.000001, Math.max(dxLeft, dxRight, dyTop, dyBottom));
      break;
    case 1 /* GRADIENT_PATH_TYPE_SHAPE */:
    case 0 /* GRADIENT_PATH_TYPE_UNSPECIFIED */:
    case -1 /* UNRECOGNIZED */:
    default:
      radius = Math.max(0.000001, shapeRadius);
      break;
  }
  const grad = ctx.createRadialGradient(cx, cy, 0, cx, cy, radius);
  const sortedStops = [...fill.gradientStops ?? []].sort((a, b2) => (a.position ?? 0) - (b2.position ?? 0));
  const useUnitRange = sortedStops.every((stop) => Math.abs(stop.position ?? 0) <= 1);
  if (sortedStops.length === 0) {
    const fallback = resolveColor(fill.color, themeMap, "transparent");
    grad.addColorStop(0, fallback);
    grad.addColorStop(1, fallback);
    return grad;
  }
  sortedStops.forEach((s, idx) => {
    const offset = normalizeGradientOffset2(s.position ?? 0, useUnitRange);
    const col = resolveColor(s.color, themeMap);
    const appliedOffset = idx === 0 && offset > 0 && sortedStops.length === 1 ? 0 : offset;
    grad.addColorStop(appliedOffset, col);
  });
  return grad;
}

// node_modules/@oai/granola/dist/draw-utils/pattern-generators.js
var strokePx = (dpr, cssPx) => Math.max(1, cssPx * dpr);
var strokeOffset = (dpr, cssPx) => strokePx(dpr, cssPx) / 2;
var genHorz = (c, fg, bg, s, dpr) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.fillStyle = fg;
  const linePx = strokePx(dpr, 1);
  c.fillRect(0, s - linePx / 2, 2 * s, linePx);
};
var genVert = (c, fg, bg, s, dpr) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.fillStyle = fg;
  const linePx = strokePx(dpr, 1);
  c.fillRect(s - linePx / 2, 0, linePx, 2 * s);
};
var genCross = (c, fg, bg, s, dpr) => {
  genHorz(c, fg, bg, s, dpr);
  genVert(c, fg, "rgba(0,0,0,0)", s, dpr);
};
function fillPatternTile(c, bg, s) {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
}
function drawDiagonalLines(c, fg, s, dpr, options) {
  c.strokeStyle = fg;
  const linePx = strokePx(dpr, 1);
  c.lineWidth = linePx;
  c.lineCap = "butt";
  c.lineJoin = "bevel";
  c.miterLimit = 1;
  if (options?.dashed) {
    c.setLineDash([s * 0.6, s * 0.6]);
  }
  c.beginPath();
  c.moveTo(-2 * s, 2 * s);
  c.lineTo(2 * s, -2 * s);
  c.moveTo(0, 2 * s);
  c.lineTo(4 * s, -2 * s);
  c.moveTo(2 * s, 2 * s);
  c.lineTo(6 * s, -2 * s);
  c.stroke();
  if (options?.dashed) {
    c.setLineDash([]);
  }
}
var genDiag = (c, fg, bg, s, dpr) => {
  fillPatternTile(c, bg, s);
  drawDiagonalLines(c, fg, s, dpr);
};
var genDiagDashed = (c, fg, bg, s, dpr) => {
  fillPatternTile(c, bg, s);
  drawDiagonalLines(c, fg, s, dpr, { dashed: true });
};
var genDiagCross = (c, fg, bg, s, dpr) => {
  genDiag(c, fg, bg, s, dpr);
  c.save();
  c.translate(s, s);
  c.rotate(Math.PI / 2);
  c.translate(-s, -s);
  drawDiagonalLines(c, fg, s, dpr);
  c.restore();
};
var genGrid = (c, fg, bg, s, dpr) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.fillStyle = fg;
  const linePx = strokePx(dpr, 1);
  c.fillRect(0, s - linePx / 2, 2 * s, linePx);
  c.fillRect(s - linePx / 2, 0, linePx, 2 * s);
};
var genDots = (c, fg, bg, s, dpr) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.fillStyle = fg;
  const r = Math.max(1, 0.75 * dpr);
  c.beginPath();
  c.arc(0.5 * s, 0.5 * s, r, 0, Math.PI * 2);
  c.fill();
  c.beginPath();
  c.arc(1.5 * s, 1.5 * s, r, 0, Math.PI * 2);
  c.fill();
};
var genCheck = (c, fg, bg, s, dpr) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.fillStyle = fg;
  const inset = strokeOffset(dpr, 1);
  c.fillRect(0, 0, s - inset, s - inset);
  c.fillRect(s + inset, s + inset, s - inset, s - inset);
};
var genTrellis = (c, fg, bg, s, dpr) => {
  genGrid(c, fg, bg, s, dpr);
  c.strokeStyle = fg;
  c.lineWidth = strokePx(dpr, 2);
  c.lineCap = "butt";
  c.lineJoin = "miter";
  c.miterLimit = 2;
  c.beginPath();
  c.moveTo(0, 0);
  c.lineTo(2 * s, 2 * s);
  c.moveTo(0, 2 * s);
  c.lineTo(2 * s, 0);
  c.stroke();
};
var genHorzDashed = (c, fg, bg, s, dpr) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.strokeStyle = fg;
  c.lineWidth = strokePx(dpr, 1);
  c.setLineDash([s * 0.6, s * 0.6]);
  c.lineCap = "butt";
  c.lineJoin = "miter";
  c.miterLimit = 2;
  c.beginPath();
  c.moveTo(0, s);
  c.lineTo(2 * s, s);
  c.stroke();
  c.setLineDash([]);
};
var genVertDashed = (c, fg, bg, s, dpr) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.strokeStyle = fg;
  c.lineWidth = strokePx(dpr, 1);
  c.setLineDash([s * 0.6, s * 0.6]);
  c.lineCap = "butt";
  c.lineJoin = "miter";
  c.miterLimit = 2;
  c.beginPath();
  c.moveTo(s, 0);
  c.lineTo(s, 2 * s);
  c.stroke();
  c.setLineDash([]);
};
var genPlaid = (c, fg, bg, s, dpr) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.fillStyle = fg;
  const band2 = strokePx(dpr, 3);
  c.fillRect(0, s - band2 / 2, 2 * s, band2);
  c.fillRect(s - band2 / 2, 0, band2, 2 * s);
};
var genHorizontalBrick = (c, fg, bg, s, dpr) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.strokeStyle = fg;
  c.lineWidth = strokePx(dpr, 1);
  c.lineCap = "butt";
  c.lineJoin = "miter";
  c.miterLimit = 2;
  c.beginPath();
  const offset = strokeOffset(dpr, 1);
  c.moveTo(0, offset);
  c.lineTo(2 * s, offset);
  c.moveTo(0, s + offset);
  c.lineTo(2 * s, s + offset);
  c.moveTo(0, 2 * s + offset);
  c.lineTo(2 * s, 2 * s + offset);
  c.moveTo(offset, 0);
  c.lineTo(offset, s);
  c.moveTo(s + offset, 0);
  c.lineTo(s + offset, s);
  c.moveTo(0.5 * s + offset, s);
  c.lineTo(0.5 * s + offset, 2 * s);
  c.moveTo(1.5 * s + offset, s);
  c.lineTo(1.5 * s + offset, 2 * s);
  c.stroke();
};
var genDiagonalBrick = (c, fg, bg, s, dpr) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.strokeStyle = fg;
  c.lineWidth = strokePx(dpr, 1);
  c.lineCap = "butt";
  c.lineJoin = "miter";
  c.miterLimit = 2;
  const offset = strokeOffset(dpr, 1);
  c.beginPath();
  c.moveTo(-s, s);
  c.lineTo(s, -s);
  c.moveTo(0, 2 * s);
  c.lineTo(2 * s, 0);
  c.moveTo(s, 2 * s);
  c.lineTo(3 * s, 0);
  c.moveTo(0, offset);
  c.lineTo(2 * s, offset);
  c.moveTo(0, s + offset);
  c.lineTo(2 * s, s + offset);
  c.moveTo(0, 2 * s + offset);
  c.lineTo(2 * s, 2 * s + offset);
  c.stroke();
};
var genSolidDiamond = (c, fg, bg, s) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.fillStyle = fg;
  const size = 0.55 * s;
  const drawDiamond = (cx, cy) => {
    c.beginPath();
    c.moveTo(cx, cy - size);
    c.lineTo(cx + size, cy);
    c.lineTo(cx, cy + size);
    c.lineTo(cx - size, cy);
    c.closePath();
    c.fill();
  };
  drawDiamond(0.5 * s, 0.5 * s);
  drawDiamond(1.5 * s, 1.5 * s);
};
var genOpenDiamond = (c, fg, bg, s, dpr) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.strokeStyle = fg;
  c.lineWidth = strokePx(dpr, 1);
  c.lineCap = "butt";
  c.lineJoin = "miter";
  c.miterLimit = 2;
  const size = 0.55 * s;
  const drawDiamond = (cx, cy) => {
    c.beginPath();
    c.moveTo(cx, cy - size);
    c.lineTo(cx + size, cy);
    c.lineTo(cx, cy + size);
    c.lineTo(cx - size, cy);
    c.closePath();
    c.stroke();
  };
  drawDiamond(0.5 * s, 0.5 * s);
  drawDiamond(1.5 * s, 1.5 * s);
};
var genDottedDiamond = (c, fg, bg, s, dpr) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.fillStyle = fg;
  const r = Math.max(1, 0.65 * dpr);
  const pts = [
    [s, 0.5 * s],
    [0.5 * s, s],
    [s, 1.5 * s],
    [1.5 * s, s]
  ];
  for (const [x, y] of pts) {
    c.beginPath();
    c.arc(x, y, r, 0, Math.PI * 2);
    c.fill();
  }
};
var genConfettiSmall = (c, fg, bg, s) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.fillStyle = fg;
  const sz = Math.max(1, Math.round(0.5 * (s / 6)));
  const squares = [
    [0.3 * s, 0.4 * s],
    [1.2 * s, 0.6 * s],
    [0.8 * s, 1.3 * s],
    [1.6 * s, 1.7 * s]
  ];
  for (const [x, y] of squares) {
    c.fillRect(Math.round(x) - sz, Math.round(y) - sz, 2 * sz, 2 * sz);
  }
};
var genConfettiLarge = (c, fg, bg, s) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.fillStyle = fg;
  const sz = Math.max(1, Math.round(0.9 * (s / 6)));
  const squares = [
    [0.4 * s, 0.5 * s],
    [1.3 * s, 0.8 * s],
    [0.6 * s, 1.5 * s],
    [1.7 * s, 1.2 * s]
  ];
  for (const [x, y] of squares) {
    c.fillRect(Math.round(x) - sz, Math.round(y) - sz, 2 * sz, 2 * sz);
  }
};
var genSphere = (c, fg, bg, s) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.fillStyle = fg;
  const r = Math.max(1, Math.round(0.25 * s));
  const centers = [
    [0.5 * s, 0.5 * s],
    [1.5 * s, 0.5 * s],
    [0.5 * s, 1.5 * s],
    [1.5 * s, 1.5 * s]
  ];
  for (const [x, y] of centers) {
    c.beginPath();
    c.arc(x, y, r, 0, Math.PI * 2);
    c.fill();
  }
};
var genWeave = (c, fg, bg, s) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.fillStyle = fg;
  const band2 = Math.max(2, Math.round(0.4 * s));
  c.fillRect(0, s - band2 / 2, 2 * s, band2);
  c.fillRect(s - band2 / 2, 0, band2, 2 * s);
};
var genDivot = (c, fg, bg, s, dpr) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.strokeStyle = fg;
  c.lineWidth = strokePx(dpr, 1);
  c.lineCap = "butt";
  c.lineJoin = "miter";
  c.miterLimit = 2;
  const r = Math.max(1, Math.round(0.3 * s));
  const centers = [
    [0.5 * s, 0.5 * s],
    [1.5 * s, 1.5 * s]
  ];
  for (const [x, y] of centers) {
    c.beginPath();
    c.arc(x, y, r, 0, Math.PI * 2);
    c.stroke();
  }
};
var genShingle = (c, fg, bg, s, dpr) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.strokeStyle = fg;
  c.lineWidth = strokePx(dpr, 1);
  c.lineCap = "butt";
  c.lineJoin = "miter";
  c.miterLimit = 2;
  const r = 0.5 * s;
  c.beginPath();
  c.arc(0.5 * s, s, r, Math.PI, 0);
  c.arc(1.5 * s, s, r, Math.PI, 0);
  c.arc(s, 2 * s, r, Math.PI, 0);
  c.stroke();
};
var genWave = (c, fg, bg, s, dpr) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.strokeStyle = fg;
  c.lineWidth = strokePx(dpr, 1);
  c.lineCap = "butt";
  c.lineJoin = "miter";
  c.miterLimit = 2;
  c.beginPath();
  c.moveTo(0, s);
  c.bezierCurveTo(0.5 * s, 0.5 * s, 1.5 * s, 1.5 * s, 2 * s, s);
  c.stroke();
};
var genZigZag = (c, fg, bg, s, dpr) => {
  c.fillStyle = bg;
  c.fillRect(0, 0, 2 * s, 2 * s);
  c.strokeStyle = fg;
  c.lineWidth = strokePx(dpr, 1);
  c.lineCap = "butt";
  c.lineJoin = "miter";
  c.miterLimit = 2;
  c.beginPath();
  c.moveTo(0, s);
  c.lineTo(0.5 * s, 0.5 * s);
  c.lineTo(s, s);
  c.lineTo(1.5 * s, 1.5 * s);
  c.lineTo(2 * s, s);
  c.stroke();
};
var generators = {
  horz: genHorz,
  vert: genVert,
  cross: genCross,
  diag: genDiag,
  diagDashed: genDiagDashed,
  diagCross: genDiagCross,
  grid: genGrid,
  dots: genDots,
  check: genCheck,
  trellis: genTrellis,
  horzDashed: genHorzDashed,
  vertDashed: genVertDashed,
  plaid: genPlaid,
  horizontalBrick: genHorizontalBrick,
  diagonalBrick: genDiagonalBrick,
  solidDiamond: genSolidDiamond,
  openDiamond: genOpenDiamond,
  dottedDiamond: genDottedDiamond,
  confettiSmall: genConfettiSmall,
  confettiLarge: genConfettiLarge,
  sphere: genSphere,
  weave: genWeave,
  divot: genDivot,
  shingle: genShingle,
  wave: genWave,
  zigZag: genZigZag
};

// node_modules/@oai/granola/dist/draw-utils/build-pattern-fill.js
var PATTERN_FILL_RENDER_MAP = {
  [5 /* PATTERN_TYPE_LIGHT_GRAY */]: { id: "dots", scale: 1.8 },
  [3 /* PATTERN_TYPE_MEDIUM_GRAY */]: {
    id: "dots",
    scale: 1.15
  },
  [4 /* PATTERN_TYPE_DARK_GRAY */]: { id: "dots", scale: 0.85 },
  [6 /* PATTERN_TYPE_DARK_HORIZONTAL */]: {
    id: "horz",
    scale: 1
  },
  [12 /* PATTERN_TYPE_LIGHT_HORIZONTAL */]: {
    id: "horz",
    scale: 1.2
  },
  [32 /* PATTERN_TYPE_HORIZONTAL */]: { id: "horz", scale: 1 },
  [34 /* PATTERN_TYPE_NARROW_HORIZONTAL */]: {
    id: "horz",
    scale: 0.75
  },
  [36 /* PATTERN_TYPE_DASHED_HORIZONTAL */]: {
    id: "horzDashed",
    scale: 1
  },
  [7 /* PATTERN_TYPE_DARK_VERTICAL */]: {
    id: "vert",
    scale: 1
  },
  [13 /* PATTERN_TYPE_LIGHT_VERTICAL */]: {
    id: "vert",
    scale: 1.2
  },
  [33 /* PATTERN_TYPE_VERTICAL */]: { id: "vert", scale: 1 },
  [35 /* PATTERN_TYPE_NARROW_VERTICAL */]: {
    id: "vert",
    scale: 0.75
  },
  [37 /* PATTERN_TYPE_DASHED_VERTICAL */]: {
    id: "vertDashed",
    scale: 1
  },
  [38 /* PATTERN_TYPE_CROSS */]: { id: "cross" },
  [48 /* PATTERN_TYPE_DIAGONAL_CROSS */]: {
    id: "cross",
    extraAngle: 45,
    scale: 0.5
  },
  [8 /* PATTERN_TYPE_DARK_DOWN */]: {
    id: "vert",
    extraAngle: 135,
    scale: 0.5
  },
  [9 /* PATTERN_TYPE_DARK_UP */]: {
    id: "vert",
    extraAngle: 45,
    scale: 0.5
  },
  [14 /* PATTERN_TYPE_LIGHT_DOWN */]: {
    id: "vert",
    extraAngle: 135,
    scale: 1
  },
  [15 /* PATTERN_TYPE_LIGHT_UP */]: {
    id: "vert",
    extraAngle: 45,
    scale: 1
  },
  [42 /* PATTERN_TYPE_DOWNWARD_DIAGONAL */]: {
    id: "vert",
    extraAngle: 135,
    scale: 0.5
  },
  [43 /* PATTERN_TYPE_UPWARD_DIAGONAL */]: {
    id: "vert",
    extraAngle: 45,
    scale: 0.5
  },
  [44 /* PATTERN_TYPE_WIDE_DOWNWARD_DIAGONAL */]: {
    id: "vert",
    extraAngle: 135,
    scale: 1
  },
  [45 /* PATTERN_TYPE_WIDE_UPWARD_DIAGONAL */]: {
    id: "vert",
    extraAngle: 45,
    scale: 1
  },
  [46 /* PATTERN_TYPE_DASHED_DOWNWARD_DIAGONAL */]: {
    id: "vertDashed",
    extraAngle: 135,
    scale: 0.45
  },
  [47 /* PATTERN_TYPE_DASHED_UPWARD_DIAGONAL */]: {
    id: "vertDashed",
    extraAngle: 45,
    scale: 0.45
  },
  [40 /* PATTERN_TYPE_SMALL_GRID */]: { id: "grid", scale: 1 },
  [39 /* PATTERN_TYPE_LARGE_GRID */]: { id: "grid", scale: 2 },
  [16 /* PATTERN_TYPE_LIGHT_GRID */]: { id: "grid", scale: 1.2 },
  [10 /* PATTERN_TYPE_DARK_GRID */]: { id: "grid", scale: 0.85 },
  [41 /* PATTERN_TYPE_DOT_GRID */]: { id: "dots", scale: 1 },
  [49 /* PATTERN_TYPE_SMALL_CHECK */]: { id: "check", scale: 1 },
  [50 /* PATTERN_TYPE_LARGE_CHECK */]: { id: "check", scale: 2 },
  [64 /* PATTERN_TYPE_TRELLIS */]: { id: "trellis", scale: 1 },
  [17 /* PATTERN_TYPE_LIGHT_TRELLIS */]: {
    id: "trellis",
    scale: 1.5
  },
  [11 /* PATTERN_TYPE_DARK_TRELLIS */]: {
    id: "trellis",
    scale: 0.85
  },
  [51 /* PATTERN_TYPE_SMALL_CONFETTI */]: {
    id: "confettiSmall",
    scale: 1
  },
  [52 /* PATTERN_TYPE_LARGE_CONFETTI */]: {
    id: "confettiLarge",
    scale: 1
  },
  [53 /* PATTERN_TYPE_HORIZONTAL_BRICK */]: {
    id: "horizontalBrick",
    scale: 1
  },
  [54 /* PATTERN_TYPE_DIAGONAL_BRICK */]: {
    id: "diagonalBrick",
    scale: 1
  },
  [55 /* PATTERN_TYPE_SOLID_DIAMOND */]: {
    id: "solidDiamond",
    scale: 1
  },
  [56 /* PATTERN_TYPE_OPEN_DIAMOND */]: {
    id: "openDiamond",
    scale: 1
  },
  [57 /* PATTERN_TYPE_DOTTED_DIAMOND */]: {
    id: "dottedDiamond",
    scale: 1
  },
  [58 /* PATTERN_TYPE_PLAID */]: { id: "plaid", scale: 1 },
  [59 /* PATTERN_TYPE_SPHERE */]: { id: "sphere", scale: 1 },
  [60 /* PATTERN_TYPE_WEAVE */]: { id: "weave", scale: 1 },
  [61 /* PATTERN_TYPE_DIVOT */]: { id: "divot", scale: 1 },
  [62 /* PATTERN_TYPE_SHINGLE */]: { id: "shingle", scale: 1 },
  [63 /* PATTERN_TYPE_WAVE */]: { id: "wave", scale: 1 },
  [65 /* PATTERN_TYPE_ZIG_ZAG */]: { id: "zigZag", scale: 1 },
  [19 /* PATTERN_TYPE_GRAY0625 */]: { id: "dots", scale: 2.3 },
  [18 /* PATTERN_TYPE_GRAY125 */]: { id: "dots", scale: 1.9 },
  [20 /* PATTERN_TYPE_PERCENT_5 */]: { id: "dots", scale: 2.6 },
  [21 /* PATTERN_TYPE_PERCENT_10 */]: { id: "dots", scale: 2.1 },
  [22 /* PATTERN_TYPE_PERCENT_20 */]: { id: "dots", scale: 1.7 },
  [23 /* PATTERN_TYPE_PERCENT_25 */]: {
    id: "dots",
    scale: 1.55
  },
  [24 /* PATTERN_TYPE_PERCENT_30 */]: {
    id: "dots",
    scale: 1.45
  },
  [25 /* PATTERN_TYPE_PERCENT_40 */]: { id: "dots", scale: 1.3 },
  [26 /* PATTERN_TYPE_PERCENT_50 */]: {
    id: "dots",
    scale: 1.15
  },
  [27 /* PATTERN_TYPE_PERCENT_60 */]: { id: "dots", scale: 1 },
  [28 /* PATTERN_TYPE_PERCENT_70 */]: { id: "dots", scale: 0.9 },
  [29 /* PATTERN_TYPE_PERCENT_75 */]: {
    id: "dots",
    scale: 0.85
  },
  [30 /* PATTERN_TYPE_PERCENT_80 */]: { id: "dots", scale: 0.8 },
  [31 /* PATTERN_TYPE_PERCENT_90 */]: { id: "dots", scale: 0.7 }
};
var tileCache = new Map;
function tileKeyOf(prst, fg, bg, base, dpr) {
  return [prst, fg, bg, base, dpr].join("|");
}
function makeOffscreen(w, h) {
  if (typeof OffscreenCanvas !== "undefined") {
    return new OffscreenCanvas(w, h);
  }
  throw new Error("OffscreenCanvas API not available for pattern tiles.");
}
function makeTile(prstId, fg, bg, s, dpr) {
  const w = 2 * s, h = 2 * s;
  const off = makeOffscreen(w, h);
  const tctx = off.getContext("2d");
  if (tctx) {
    tctx.imageSmoothingEnabled = false;
    const fn = generators[prstId];
    fn?.(tctx, fg, bg, s, dpr);
  }
  return off;
}
function buildPatternFill(ctx, bbox, fill, theme, opts) {
  const baseDpr = opts?.dpr ?? (typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1);
  const transform = typeof ctx.getTransform === "function" ? ctx.getTransform() : null;
  const transformScaleX = transform ? Math.hypot(transform.a, transform.b) : 1;
  const transformScaleY = transform ? Math.hypot(transform.c, transform.d) : 1;
  const resolutionBoost = Math.max(1, Math.min(8, Math.ceil(Math.max(transformScaleX, transformScaleY))));
  const dpr = baseDpr * resolutionBoost;
  const bg = resolveColor(fill.color, theme, "#ffffff");
  const fg = resolveColor(fill.pattern?.color, theme, bg);
  const pr = fill.pattern?.patternType ?? 2 /* PATTERN_TYPE_SOLID */;
  if (pr === 1 /* PATTERN_TYPE_NONE */) {
    return "transparent";
  }
  if (pr === 2 /* PATTERN_TYPE_SOLID */ || pr === 0 /* PATTERN_TYPE_UNSPECIFIED */) {
    return fg;
  }
  const map3 = PATTERN_FILL_RENDER_MAP[pr] ?? {
    id: "grid",
    scale: 1,
    extraAngle: 0
  };
  const isDiag = pr === 42 /* PATTERN_TYPE_DOWNWARD_DIAGONAL */ || pr === 43 /* PATTERN_TYPE_UPWARD_DIAGONAL */ || pr === 44 /* PATTERN_TYPE_WIDE_DOWNWARD_DIAGONAL */ || pr === 45 /* PATTERN_TYPE_WIDE_UPWARD_DIAGONAL */ || pr === 46 /* PATTERN_TYPE_DASHED_DOWNWARD_DIAGONAL */ || pr === 47 /* PATTERN_TYPE_DASHED_UPWARD_DIAGONAL */ || pr === 48 /* PATTERN_TYPE_DIAGONAL_CROSS */ || pr === 8 /* PATTERN_TYPE_DARK_DOWN */ || pr === 9 /* PATTERN_TYPE_DARK_UP */ || pr === 14 /* PATTERN_TYPE_LIGHT_DOWN */ || pr === 15 /* PATTERN_TYPE_LIGHT_UP */;
  const minBase = isDiag ? 3 : 4;
  const base = Math.max(minBase, Math.round(6 * (opts?.scale ?? map3.scale ?? 1)));
  const s = base * dpr;
  const prstId = map3.id ?? "grid";
  const key = tileKeyOf(prstId, fg, bg, base, dpr);
  let tile = tileCache.get(key);
  if (!tile) {
    tile = makeTile(prstId, fg, bg, s, dpr);
    tileCache.set(key, tile);
  }
  const angleDeg = (opts?.angleDeg ?? 0) + (map3.extraAngle ?? 0);
  const anchorMode = opts?.anchor ?? "object";
  const ax = opts?.anchorX ?? (anchorMode === "object" ? bbox.x + bbox.width / 2 : 0);
  const ay = opts?.anchorY ?? (anchorMode === "object" ? bbox.y + bbox.height / 2 : 0);
  const pat = ctx.createPattern(tile, "repeat");
  const hasSetTransform = typeof pat.setTransform === "function";
  if (hasSetTransform) {
    const tileWcss2 = tile.width / dpr;
    const tileHcss2 = tile.height / dpr;
    const phaseXcss2 = ((ax - tileWcss2 / 2) % tileWcss2 + tileWcss2) % tileWcss2;
    const phaseYcss2 = ((ay - tileHcss2 / 2) % tileHcss2 + tileHcss2) % tileHcss2;
    const rotDeg = angleDeg;
    const m = new DOMMatrix().translate(phaseXcss2, phaseYcss2).rotate(rotDeg).scale(1 / dpr, 1 / dpr);
    pat.setTransform(m);
    return pat;
  }
  const tileWcss = tile.width / dpr;
  const tileHcss = tile.height / dpr;
  const phaseXcss = ((ax - tileWcss / 2) % tileWcss + tileWcss) % tileWcss;
  const phaseYcss = ((ay - tileHcss / 2) % tileHcss + tileHcss) % tileHcss;
  const tileW = tile.width;
  const tileH = tile.height;
  const mega = makeOffscreen(tileW * 8, tileH * 8);
  const pctx = mega.getContext("2d");
  pctx.imageSmoothingEnabled = false;
  const rep = pctx.createPattern(tile, "repeat");
  pctx.save();
  const phaseXdev = phaseXcss * dpr;
  const phaseYdev = phaseYcss * dpr;
  pctx.translate(mega.width / 2, mega.height / 2);
  pctx.rotate(angleDeg * Math.PI / 180);
  pctx.translate(-(mega.width / 2 - phaseXdev), -(mega.height / 2 - phaseYdev));
  pctx.fillStyle = rep;
  pctx.fillRect(-tileW, -tileH, mega.width + 2 * tileW, mega.height + 2 * tileH);
  pctx.restore();
  return ctx.createPattern(mega, "repeat");
}

// node_modules/@oai/granola/dist/draw-utils/resolve-fill-paint.js
function resolveFillPaint(ctx, bbox, fill, themeMap, fallback = "transparent") {
  if (!fill)
    return fallback;
  if (fill.type === 2 /* FILL_TYPE_GRADIENT */ && fill.gradientStops?.length) {
    if (fill.gradientKind === 1 /* GRADIENT_KIND_LINEAR */) {
      return buildLinearGradient(ctx, bbox, fill, themeMap);
    }
    if (fill.gradientKind === 2 /* GRADIENT_KIND_PATH */) {
      return buildPathGradient(ctx, bbox, fill, themeMap);
    }
  }
  if (fill.pattern) {
    return buildPatternFill(ctx, bbox, fill, themeMap);
  }
  return resolveColor(fill.color, themeMap, fallback);
}

// node_modules/@oai/granola/dist/draw-utils/chart/point-styles.js
function findPointOverride(series, pointIdx) {
  if (!series.points || series.points.length === 0)
    return;
  for (let i = 0;i < series.points.length; i++) {
    const pt = series.points[i];
    const rawIdx = pt?.idx;
    const idx = rawIdx ?? i;
    if (idx === pointIdx)
      return pt;
  }
  return;
}
function getPointFillColor(series, pointIdx, seriesIdx, themeMap, fallbackIndex) {
  const pt = findPointOverride(series, pointIdx);
  const fill = pt?.fill;
  if (fill) {
    if (fill.color) {
      return resolveColor(fill.color, themeMap);
    }
    return;
  }
  const paletteIndex = typeof fallbackIndex === "number" ? fallbackIndex : seriesIdx;
  return getSeriesColor(series, paletteIndex, themeMap);
}
function getPointFillPaint(ctx, bbox, series, pointIdx, seriesIdx, themeMap, fallbackIndex) {
  const pt = findPointOverride(series, pointIdx);
  const fill = pt?.fill ?? series.fill;
  if (fill) {
    if (pt?.fill && !pt.fill.color && !pt.fill.pattern) {
      return;
    }
    return resolveFillPaint(ctx, bbox, fill, themeMap, "transparent");
  }
  const paletteIndex = typeof fallbackIndex === "number" ? fallbackIndex : seriesIdx;
  return getSeriesColor(series, paletteIndex, themeMap);
}
function getPointStroke(series, pointIdx, themeMap) {
  const pt = findPointOverride(series, pointIdx);
  if (pt?.stroke?.fill?.color) {
    const color2 = resolveColor(pt.stroke.fill.color, themeMap);
    const widthPx = pt.stroke.widthEmu ? pt.stroke.widthEmu * EMU_TO_PX : undefined;
    return { color: color2, widthPx };
  }
  const s = series;
  if (s?.stroke?.fill?.color) {
    const color2 = resolveColor(s.stroke.fill.color, themeMap);
    const widthPx = s.stroke.widthEmu ? s.stroke.widthEmu * EMU_TO_PX : undefined;
    return { color: color2, widthPx };
  }
  return {};
}
function pointHasNoFill(series, pointIdx) {
  const pt = findPointOverride(series, pointIdx);
  const fill = pt?.fill;
  return !!(fill && !fill.color && !fill.pattern);
}

// node_modules/d3-hierarchy/src/hierarchy/count.js
function count2(node) {
  var sum2 = 0, children = node.children, i = children && children.length;
  if (!i)
    sum2 = 1;
  else
    while (--i >= 0)
      sum2 += children[i].value;
  node.value = sum2;
}
function count_default() {
  return this.eachAfter(count2);
}

// node_modules/d3-hierarchy/src/hierarchy/each.js
function each_default(callback, that) {
  let index = -1;
  for (const node of this) {
    callback.call(that, node, ++index, this);
  }
  return this;
}

// node_modules/d3-hierarchy/src/hierarchy/eachBefore.js
function eachBefore_default(callback, that) {
  var node = this, nodes = [node], children, i, index = -1;
  while (node = nodes.pop()) {
    callback.call(that, node, ++index, this);
    if (children = node.children) {
      for (i = children.length - 1;i >= 0; --i) {
        nodes.push(children[i]);
      }
    }
  }
  return this;
}

// node_modules/d3-hierarchy/src/hierarchy/eachAfter.js
function eachAfter_default(callback, that) {
  var node = this, nodes = [node], next = [], children, i, n, index = -1;
  while (node = nodes.pop()) {
    next.push(node);
    if (children = node.children) {
      for (i = 0, n = children.length;i < n; ++i) {
        nodes.push(children[i]);
      }
    }
  }
  while (node = next.pop()) {
    callback.call(that, node, ++index, this);
  }
  return this;
}

// node_modules/d3-hierarchy/src/hierarchy/find.js
function find_default(callback, that) {
  let index = -1;
  for (const node of this) {
    if (callback.call(that, node, ++index, this)) {
      return node;
    }
  }
}

// node_modules/d3-hierarchy/src/hierarchy/sum.js
function sum_default(value) {
  return this.eachAfter(function(node) {
    var sum2 = +value(node.data) || 0, children = node.children, i = children && children.length;
    while (--i >= 0)
      sum2 += children[i].value;
    node.value = sum2;
  });
}

// node_modules/d3-hierarchy/src/hierarchy/sort.js
function sort_default(compare) {
  return this.eachBefore(function(node) {
    if (node.children) {
      node.children.sort(compare);
    }
  });
}

// node_modules/d3-hierarchy/src/hierarchy/path.js
function path_default(end) {
  var start = this, ancestor = leastCommonAncestor(start, end), nodes = [start];
  while (start !== ancestor) {
    start = start.parent;
    nodes.push(start);
  }
  var k = nodes.length;
  while (end !== ancestor) {
    nodes.splice(k, 0, end);
    end = end.parent;
  }
  return nodes;
}
function leastCommonAncestor(a, b) {
  if (a === b)
    return a;
  var aNodes = a.ancestors(), bNodes = b.ancestors(), c = null;
  a = aNodes.pop();
  b = bNodes.pop();
  while (a === b) {
    c = a;
    a = aNodes.pop();
    b = bNodes.pop();
  }
  return c;
}

// node_modules/d3-hierarchy/src/hierarchy/ancestors.js
function ancestors_default() {
  var node = this, nodes = [node];
  while (node = node.parent) {
    nodes.push(node);
  }
  return nodes;
}

// node_modules/d3-hierarchy/src/hierarchy/descendants.js
function descendants_default() {
  return Array.from(this);
}

// node_modules/d3-hierarchy/src/hierarchy/leaves.js
function leaves_default() {
  var leaves = [];
  this.eachBefore(function(node) {
    if (!node.children) {
      leaves.push(node);
    }
  });
  return leaves;
}

// node_modules/d3-hierarchy/src/hierarchy/links.js
function links_default() {
  var root = this, links = [];
  root.each(function(node) {
    if (node !== root) {
      links.push({ source: node.parent, target: node });
    }
  });
  return links;
}

// node_modules/d3-hierarchy/src/hierarchy/iterator.js
function* iterator_default() {
  var node = this, current, next = [node], children, i, n;
  do {
    current = next.reverse(), next = [];
    while (node = current.pop()) {
      yield node;
      if (children = node.children) {
        for (i = 0, n = children.length;i < n; ++i) {
          next.push(children[i]);
        }
      }
    }
  } while (next.length);
}

// node_modules/d3-hierarchy/src/hierarchy/index.js
function hierarchy(data, children) {
  if (data instanceof Map) {
    data = [undefined, data];
    if (children === undefined)
      children = mapChildren;
  } else if (children === undefined) {
    children = objectChildren;
  }
  var root = new Node(data), node, nodes = [root], child, childs, i, n;
  while (node = nodes.pop()) {
    if ((childs = children(node.data)) && (n = (childs = Array.from(childs)).length)) {
      node.children = childs;
      for (i = n - 1;i >= 0; --i) {
        nodes.push(child = childs[i] = new Node(childs[i]));
        child.parent = node;
        child.depth = node.depth + 1;
      }
    }
  }
  return root.eachBefore(computeHeight);
}
function node_copy() {
  return hierarchy(this).eachBefore(copyData);
}
function objectChildren(d) {
  return d.children;
}
function mapChildren(d) {
  return Array.isArray(d) ? d[1] : null;
}
function copyData(node) {
  if (node.data.value !== undefined)
    node.value = node.data.value;
  node.data = node.data.data;
}
function computeHeight(node) {
  var height = 0;
  do
    node.height = height;
  while ((node = node.parent) && node.height < ++height);
}
function Node(data) {
  this.data = data;
  this.depth = this.height = 0;
  this.parent = null;
}
Node.prototype = hierarchy.prototype = {
  constructor: Node,
  count: count_default,
  each: each_default,
  eachAfter: eachAfter_default,
  eachBefore: eachBefore_default,
  find: find_default,
  sum: sum_default,
  sort: sort_default,
  path: path_default,
  ancestors: ancestors_default,
  descendants: descendants_default,
  leaves: leaves_default,
  links: links_default,
  copy: node_copy,
  [Symbol.iterator]: iterator_default
};
// node_modules/d3-hierarchy/src/accessors.js
function required(f) {
  if (typeof f !== "function")
    throw new Error;
  return f;
}

// node_modules/d3-hierarchy/src/constant.js
function constantZero() {
  return 0;
}
function constant_default2(x) {
  return function() {
    return x;
  };
}

// node_modules/d3-hierarchy/src/treemap/round.js
function round_default2(node) {
  node.x0 = Math.round(node.x0);
  node.y0 = Math.round(node.y0);
  node.x1 = Math.round(node.x1);
  node.y1 = Math.round(node.y1);
}

// node_modules/d3-hierarchy/src/treemap/dice.js
function dice_default(parent, x0, y0, x1, y1) {
  var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (x1 - x0) / parent.value;
  while (++i < n) {
    node = nodes[i], node.y0 = y0, node.y1 = y1;
    node.x0 = x0, node.x1 = x0 += node.value * k;
  }
}

// node_modules/d3-hierarchy/src/partition.js
function partition_default() {
  var dx = 1, dy = 1, padding = 0, round = false;
  function partition(root) {
    var n = root.height + 1;
    root.x0 = root.y0 = padding;
    root.x1 = dx;
    root.y1 = dy / n;
    root.eachBefore(positionNode(dy, n));
    if (round)
      root.eachBefore(round_default2);
    return root;
  }
  function positionNode(dy2, n) {
    return function(node) {
      if (node.children) {
        dice_default(node, node.x0, dy2 * (node.depth + 1) / n, node.x1, dy2 * (node.depth + 2) / n);
      }
      var { x0, y0 } = node, x1 = node.x1 - padding, y1 = node.y1 - padding;
      if (x1 < x0)
        x0 = x1 = (x0 + x1) / 2;
      if (y1 < y0)
        y0 = y1 = (y0 + y1) / 2;
      node.x0 = x0;
      node.y0 = y0;
      node.x1 = x1;
      node.y1 = y1;
    };
  }
  partition.round = function(x) {
    return arguments.length ? (round = !!x, partition) : round;
  };
  partition.size = function(x) {
    return arguments.length ? (dx = +x[0], dy = +x[1], partition) : [dx, dy];
  };
  partition.padding = function(x) {
    return arguments.length ? (padding = +x, partition) : padding;
  };
  return partition;
}
// node_modules/d3-hierarchy/src/treemap/slice.js
function slice_default(parent, x0, y0, x1, y1) {
  var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (y1 - y0) / parent.value;
  while (++i < n) {
    node = nodes[i], node.x0 = x0, node.x1 = x1;
    node.y0 = y0, node.y1 = y0 += node.value * k;
  }
}

// node_modules/d3-hierarchy/src/treemap/squarify.js
var phi = (1 + Math.sqrt(5)) / 2;
function squarifyRatio(ratio, parent, x0, y0, x1, y1) {
  var rows = [], nodes = parent.children, row, nodeValue, i0 = 0, i1 = 0, n = nodes.length, dx, dy, value = parent.value, sumValue, minValue, maxValue, newRatio, minRatio, alpha, beta;
  while (i0 < n) {
    dx = x1 - x0, dy = y1 - y0;
    do
      sumValue = nodes[i1++].value;
    while (!sumValue && i1 < n);
    minValue = maxValue = sumValue;
    alpha = Math.max(dy / dx, dx / dy) / (value * ratio);
    beta = sumValue * sumValue * alpha;
    minRatio = Math.max(maxValue / beta, beta / minValue);
    for (;i1 < n; ++i1) {
      sumValue += nodeValue = nodes[i1].value;
      if (nodeValue < minValue)
        minValue = nodeValue;
      if (nodeValue > maxValue)
        maxValue = nodeValue;
      beta = sumValue * sumValue * alpha;
      newRatio = Math.max(maxValue / beta, beta / minValue);
      if (newRatio > minRatio) {
        sumValue -= nodeValue;
        break;
      }
      minRatio = newRatio;
    }
    rows.push(row = { value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1) });
    if (row.dice)
      dice_default(row, x0, y0, x1, value ? y0 += dy * sumValue / value : y1);
    else
      slice_default(row, x0, y0, value ? x0 += dx * sumValue / value : x1, y1);
    value -= sumValue, i0 = i1;
  }
  return rows;
}
var squarify_default = function custom(ratio) {
  function squarify(parent, x0, y0, x1, y1) {
    squarifyRatio(ratio, parent, x0, y0, x1, y1);
  }
  squarify.ratio = function(x) {
    return custom((x = +x) > 1 ? x : 1);
  };
  return squarify;
}(phi);

// node_modules/d3-hierarchy/src/treemap/index.js
function treemap_default() {
  var tile = squarify_default, round = false, dx = 1, dy = 1, paddingStack = [0], paddingInner = constantZero, paddingTop = constantZero, paddingRight = constantZero, paddingBottom = constantZero, paddingLeft = constantZero;
  function treemap(root) {
    root.x0 = root.y0 = 0;
    root.x1 = dx;
    root.y1 = dy;
    root.eachBefore(positionNode);
    paddingStack = [0];
    if (round)
      root.eachBefore(round_default2);
    return root;
  }
  function positionNode(node) {
    var p = paddingStack[node.depth], x0 = node.x0 + p, y0 = node.y0 + p, x1 = node.x1 - p, y1 = node.y1 - p;
    if (x1 < x0)
      x0 = x1 = (x0 + x1) / 2;
    if (y1 < y0)
      y0 = y1 = (y0 + y1) / 2;
    node.x0 = x0;
    node.y0 = y0;
    node.x1 = x1;
    node.y1 = y1;
    if (node.children) {
      p = paddingStack[node.depth + 1] = paddingInner(node) / 2;
      x0 += paddingLeft(node) - p;
      y0 += paddingTop(node) - p;
      x1 -= paddingRight(node) - p;
      y1 -= paddingBottom(node) - p;
      if (x1 < x0)
        x0 = x1 = (x0 + x1) / 2;
      if (y1 < y0)
        y0 = y1 = (y0 + y1) / 2;
      tile(node, x0, y0, x1, y1);
    }
  }
  treemap.round = function(x) {
    return arguments.length ? (round = !!x, treemap) : round;
  };
  treemap.size = function(x) {
    return arguments.length ? (dx = +x[0], dy = +x[1], treemap) : [dx, dy];
  };
  treemap.tile = function(x) {
    return arguments.length ? (tile = required(x), treemap) : tile;
  };
  treemap.padding = function(x) {
    return arguments.length ? treemap.paddingInner(x).paddingOuter(x) : treemap.paddingInner();
  };
  treemap.paddingInner = function(x) {
    return arguments.length ? (paddingInner = typeof x === "function" ? x : constant_default2(+x), treemap) : paddingInner;
  };
  treemap.paddingOuter = function(x) {
    return arguments.length ? treemap.paddingTop(x).paddingRight(x).paddingBottom(x).paddingLeft(x) : treemap.paddingTop();
  };
  treemap.paddingTop = function(x) {
    return arguments.length ? (paddingTop = typeof x === "function" ? x : constant_default2(+x), treemap) : paddingTop;
  };
  treemap.paddingRight = function(x) {
    return arguments.length ? (paddingRight = typeof x === "function" ? x : constant_default2(+x), treemap) : paddingRight;
  };
  treemap.paddingBottom = function(x) {
    return arguments.length ? (paddingBottom = typeof x === "function" ? x : constant_default2(+x), treemap) : paddingBottom;
  };
  treemap.paddingLeft = function(x) {
    return arguments.length ? (paddingLeft = typeof x === "function" ? x : constant_default2(+x), treemap) : paddingLeft;
  };
  return treemap;
}
// node_modules/@oai/granola/dist/draw-utils/chart/treemap/prepare-treemap.js
var PATH_DELIMITER = "\x00";
function prepareTreemapData(chart, dims, themeMap) {
  const aggregated = aggregateLeaves(chart);
  if (aggregated.length === 0) {
    return { leaves: [], parents: [] };
  }
  const builderRoot = buildTree(aggregated);
  const rootDatum = toDatum(builderRoot);
  const rootNode = hierarchy(rootDatum).sum((d) => typeof d.value === "number" && d.value > 0 ? d.value : 0).sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
  const width = Math.max(0, dims.width);
  const height = Math.max(0, dims.height);
  const treemapLayout = treemap_default().tile(squarify_default).size([width, height]).paddingInner(1).paddingOuter(0).round(true);
  const rectRoot = treemapLayout(rootNode);
  const colorScale = buildColorScale(themeMap, aggregated);
  const leaves = rectRoot.leaves().filter((leaf) => (leaf.value ?? 0) > 0).map((leaf) => {
    const x = dims.x + leaf.x0;
    const y = dims.y + leaf.y0;
    const widthPx = Math.max(0, leaf.x1 - leaf.x0);
    const heightPx = Math.max(0, leaf.y1 - leaf.y0);
    const path2 = leaf.data.path;
    const parentPath = leaf.parent?.data.path ?? [];
    const parentName = parentPath.length > 0 ? parentPath[parentPath.length - 1] : undefined;
    const topParentName = path2.length > 0 ? path2[0] : undefined;
    const colorKey = topParentName && topParentName.length > 0 ? topParentName : leaf.data.name;
    return {
      x,
      y,
      width: widthPx,
      height: heightPx,
      value: leaf.value ?? 0,
      name: leaf.data.name,
      path: path2,
      depth: leaf.depth,
      parentName,
      topParentName,
      fill: colorScale(colorKey)
    };
  });
  const parents = rectRoot.descendants().filter((node) => node.depth > 0 && node.children && node.children.length > 0).map((node) => ({
    name: node.data.name,
    path: node.data.path,
    depth: node.depth,
    x: dims.x + node.x0,
    y: dims.y + node.y0,
    width: Math.max(0, node.x1 - node.x0),
    height: Math.max(0, node.y1 - node.y0)
  })).sort((a, b) => a.depth - b.depth);
  return { leaves, parents };
}
function aggregateLeaves(chart) {
  const results = new Map;
  for (const series of chart.series) {
    const values = series.values ?? [];
    const categoryPaths = normalizePaths(series.categoryPaths, values.length);
    const fallbackCategories = series.categories?.length ? series.categories : chart.categories;
    for (let i = 0;i < values.length; i += 1) {
      const value = values[i];
      if (typeof value !== "number" || !isFinite(value) || value <= 0)
        continue;
      const rawPath = categoryPaths[i]?.levels;
      let levels = rawPath && rawPath.length ? rawPath : undefined;
      if (!levels) {
        const fallback = fallbackCategories?.[i];
        if (typeof fallback === "string" && fallback.length > 0) {
          levels = [fallback];
        }
      }
      if (!levels || levels.length === 0)
        continue;
      const path2 = [...levels].reverse();
      const key = path2.join(PATH_DELIMITER);
      const existing = results.get(key);
      if (existing) {
        existing.value += value;
      } else {
        results.set(key, {
          path: path2,
          value
        });
      }
    }
  }
  return Array.from(results.values());
}
function normalizePaths(paths, length) {
  if (!paths || paths.length === 0) {
    return new Array(length).fill(undefined);
  }
  if (paths.length >= length)
    return paths;
  const padded = paths.slice();
  while (padded.length < length) {
    padded.push({ levels: [] });
  }
  return padded;
}
function buildTree(leaves) {
  const root = {
    name: "root",
    path: [],
    children: new Map
  };
  for (const leaf of leaves) {
    let current = root;
    leaf.path.forEach((segment, idx) => {
      let child = current.children.get(segment);
      if (!child) {
        child = {
          name: segment,
          path: current.path.concat(segment),
          children: new Map
        };
        current.children.set(segment, child);
      }
      current = child;
      if (idx === leaf.path.length - 1) {
        current.value = (current.value ?? 0) + leaf.value;
      }
    });
  }
  return root;
}
function toDatum(node) {
  const children = Array.from(node.children.values()).map(toDatum);
  if (children.length === 0) {
    return {
      name: node.name,
      path: node.path,
      value: node.value ?? 0
    };
  }
  return {
    name: node.name,
    path: node.path,
    children
  };
}
function buildColorScale(themeMap, leaves) {
  const domainSet = new Set;
  for (const leaf of leaves) {
    const candidate = leaf.path[0];
    if (candidate && candidate.length > 0) {
      domainSet.add(candidate);
    }
  }
  const domain = Array.from(domainSet.values());
  if (domain.length === 0) {
    return (_key) => SERIES_COLORS[0] ?? "#999999";
  }
  const accentKeys = [
    "accent1",
    "accent2",
    "accent3",
    "accent4",
    "accent5",
    "accent6"
  ];
  const colorForIndex = (index) => {
    const accentKey = accentKeys[index % accentKeys.length];
    const accentColor = themeMap.colorMap[accentKey ?? ""];
    if (accentColor)
      return accentColor;
    return SERIES_COLORS[index % SERIES_COLORS.length] ?? SERIES_COLORS[0] ?? "#999999";
  };
  const colors = domain.map((_, index) => colorForIndex(index));
  const scale = ordinal().domain(domain).range(colors);
  return (key) => {
    if (!key) {
      return SERIES_COLORS[0] ?? "#999999";
    }
    if (scale.domain().includes(key)) {
      return scale(key);
    }
    const idx = scale.domain().length;
    return colorForIndex(idx);
  };
}
function buildTreemapLegendEntries(chart, themeMap) {
  const aggregated = aggregateLeaves(chart);
  if (aggregated.length === 0)
    return [];
  const colorScale = buildColorScale(themeMap, aggregated);
  const domainSet = new Set;
  for (const leaf of aggregated) {
    const topLevel = leaf.path[0];
    if (!topLevel || domainSet.has(topLevel))
      continue;
    domainSet.add(topLevel);
  }
  return Array.from(domainSet.values()).map((key) => ({
    key,
    label: key,
    color: colorScale(key)
  }));
}

// node_modules/@oai/granola/dist/draw-utils/chart/format-number.js
var import_ssf2 = __toESM(require_ssf(), 1);
function formatValue(value, formatCode) {
  if (formatCode) {
    try {
      return import_ssf2.default.format(formatCode, value);
    } catch {}
  }
  return format("~s")(value);
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-legend.js
function resolveLegendTextColor(chart, themeMap) {
  const legendFill = chart.legend?.textStyle?.fill?.color;
  if (legendFill) {
    return resolveColor(legendFill, themeMap);
  }
  return AXIS_COLOR;
}
var WATERFALL_LEGEND_LABELS = [
  { label: "Increase", slot: "accent1", fallback: "#5b9bd5" },
  { label: "Decrease", slot: "accent2", fallback: "#ed7d31" },
  { label: "Total", slot: "accent3", fallback: "#a5a5a5" }
];
function buildWaterfallLegend(themeMap) {
  return WATERFALL_LEGEND_LABELS.map((cfg) => ({
    label: cfg.label,
    seriesIndex: 0,
    fillColor: themeMap.colorMap?.[cfg.slot] ?? cfg.fallback
  }));
}
var MAP_LEGEND_MAX_GRADIENT_LENGTH = 120;
var MAP_LEGEND_PAD = 12;
var MAP_LEGEND_LABEL_GAP = 4;
var MAP_LEGEND_GRADIENT_HEIGHT = 12;
var MAP_LEGEND_TITLE_BAR_GAP = 12;
var LEGEND_OUTER_PAD = 8;
var PIE_FAMILY = new Set([
  16 /* CHART_TYPE_PIE */,
  15 /* CHART_TYPE_PIE_3D */,
  8 /* CHART_TYPE_DOUGHNUT */
]);
var LEGEND_INNER_PAD = 8;
var LEGEND_BOTTOM_INNER_PAD = 8;
var LEGEND_SYMBOL_TO_LABEL_GAP = 6;
var LEGEND_ITEM_GAP = 16;
var LEGEND_ROW_HEIGHT = LEGEND_MARK_SIZE;
var HORIZONTAL_LEGEND_ROW_GAP = 8;
var LINE_LEGEND_SYMBOL_WIDTH = 12;
var LINE_LEGEND_SYMBOL_STROKE_WIDTH = 2;
function isPieFamily(chart) {
  return PIE_FAMILY.has(chart.type);
}
function normalizeLegendPosition(position) {
  if (position === 5 /* LEGEND_POSITION_TOP_RIGHT */) {
    return 1 /* LEGEND_POSITION_RIGHT */;
  }
  return position ?? 1 /* LEGEND_POSITION_RIGHT */;
}
function isHorizontalLegendPosition(position) {
  return position === 3 /* LEGEND_POSITION_TOP */ || position === 4 /* LEGEND_POSITION_BOTTOM */;
}
function getHorizontalLegendInnerPadding(position) {
  if (position === 4 /* LEGEND_POSITION_BOTTOM */) {
    return {
      top: LEGEND_INNER_PAD,
      bottom: LEGEND_BOTTOM_INNER_PAD
    };
  }
  return {
    top: LEGEND_INNER_PAD,
    bottom: LEGEND_INNER_PAD
  };
}
function buildLegendEntries(chart, themeMap) {
  if (isPieFamily(chart)) {
    const primarySeries = chart.series[0];
    if (!primarySeries)
      return [];
    const seriesIndex = chart.series.indexOf(primarySeries);
    const categories = (primarySeries.categories?.length ? primarySeries.categories : chart.categories) ?? [];
    const valueCount = primarySeries.values?.length ?? 0;
    const count3 = Math.max(valueCount, categories.length);
    if (count3 === 0)
      return [];
    const baseLabel = primarySeries.name || "Slice";
    const entries = [];
    for (let i = 0;i < count3; i++) {
      const label = categories[i] ?? `${baseLabel} ${i + 1}`;
      entries.push({ label, seriesIndex, pointIndex: i });
    }
    return entries;
  }
  if (chart.type === 29 /* CHART_TYPE_TREEMAP */) {
    const entries = buildTreemapLegendEntries(chart, themeMap);
    if (entries.length === 0)
      return [];
    return entries.map((entry) => ({
      label: entry.label,
      seriesIndex: 0,
      fillColor: entry.color
    }));
  }
  if (chart.type === 27 /* CHART_TYPE_WATERFALL */) {
    return buildWaterfallLegend(themeMap);
  }
  return chart.series.map((s, idx) => ({
    label: s.name || `Series ${idx + 1}`,
    seriesIndex: idx
  }));
}
function getMapLegendData(chart, themeMap) {
  if (!chart.series.length)
    return null;
  const series = chart.series[0];
  if (!series)
    return null;
  const categories = series.categories && series.categories.length > 0 ? series.categories : chart.categories;
  const values = series.values ?? [];
  if (!categories || categories.length === 0 || values.length === 0) {
    return null;
  }
  const numericValues = [];
  categories.forEach((category, idx) => {
    const value = values[idx];
    if (category != null && typeof value === "number" && Number.isFinite(value)) {
      numericValues.push(value);
    }
  });
  if (numericValues.length === 0)
    return null;
  const [minRaw, maxRaw] = extent(numericValues);
  const min = minRaw ?? 0;
  const max2 = maxRaw ?? min;
  const baseColor = getSeriesColor(series, 0, themeMap);
  const ramp = resolveRampColors(baseColor);
  const formatCode = series.valuesFormatCode ?? undefined;
  const seriesName = series.name?.trim();
  return {
    min,
    max: max2,
    rampStart: ramp.start,
    rampEnd: ramp.end,
    minLabel: formatValue(min, formatCode),
    maxLabel: formatValue(max2, formatCode),
    seriesName: seriesName && seriesName.length > 0 ? seriesName : undefined
  };
}
function measureMapLegendSizeInternal(ctx, chart, themeMap, position) {
  const legendPtHund = chart.legend?.textStyle?.fontSize;
  const legendPx = legendPtHund ? fontSizeToPx(legendPtHund) : LEGEND_FONT_SIZE;
  ctx.font = `${legendPx}px ${FONT_FAMILY}`;
  const data = getMapLegendData(chart, themeMap);
  if (!data)
    return { width: 0, height: 0 };
  const minWidth = ctx.measureText(data.minLabel).width;
  const maxWidth = ctx.measureText(data.maxLabel).width;
  const titleWidth = data.seriesName ? ctx.measureText(data.seriesName).width : 0;
  const hasTitle = !!data.seriesName;
  const titleHeight = hasTitle ? legendPx : 0;
  const titleGap = hasTitle ? MAP_LEGEND_TITLE_BAR_GAP : 0;
  if (isHorizontalLegendPosition(position)) {
    const gradientWidth = MAP_LEGEND_MAX_GRADIENT_LENGTH;
    const contentWidth = Math.max(gradientWidth, titleWidth);
    const width2 = MAP_LEGEND_PAD * 2 + contentWidth;
    const height2 = MAP_LEGEND_PAD * 2 + titleHeight + titleGap + MAP_LEGEND_GRADIENT_HEIGHT + MAP_LEGEND_LABEL_GAP + legendPx;
    return { width: width2, height: height2 };
  }
  const labelWidth = Math.max(minWidth, maxWidth);
  const labelGap = labelWidth > 0 ? MAP_LEGEND_LABEL_GAP : 0;
  const gradientThickness = MAP_LEGEND_GRADIENT_HEIGHT;
  const blockWidth = Math.max(gradientThickness + labelGap + labelWidth, titleWidth);
  const width = MAP_LEGEND_PAD * 2 + blockWidth;
  const height = MAP_LEGEND_PAD * 2 + titleHeight + titleGap + MAP_LEGEND_MAX_GRADIENT_LENGTH;
  return { width, height };
}
function measureLegendLayout(ctx, chart, themeMap, opts = {}) {
  ctx.save();
  const resolvedPosition = normalizeLegendPosition(opts.position ?? chart.legend?.position);
  if (chart.type === 23 /* CHART_TYPE_MAP */) {
    const { width: width2, height: height2 } = measureMapLegendSizeInternal(ctx, chart, themeMap, resolvedPosition);
    ctx.restore();
    return { width: width2, height: height2, entries: [], labelWidths: [] };
  }
  const legendPtHund = chart.legend?.textStyle?.fontSize;
  const legendPx = legendPtHund ? fontSizeToPx(legendPtHund) : LEGEND_FONT_SIZE;
  ctx.font = `${legendPx}px ${FONT_FAMILY}`;
  const entries = buildLegendEntries(chart, themeMap);
  const legendFontSizeHp = legendPtHund ?? Math.round(legendPx * 75);
  const labelWidths = entries.map((entry) => {
    const el = {
      paragraphs: [
        {
          runs: [
            {
              text: entry.label,
              citations: [],
              reviewMarkIds: []
            }
          ]
        }
      ],
      textStyle: {
        name: FONT_FAMILY,
        fontSize: legendFontSizeHp
      },
      effects: [],
      children: [],
      levelsStyles: [],
      id: "legend-label",
      citations: [],
      type: 1 /* ELEMENT_TYPE_TEXT */
    };
    const layout = drawText(el, ctx, themeMap, undefined, {
      mode: "layout",
      wrap: false
    });
    if (!layout)
      return 0;
    const maxLine = layout.lines.reduce((m, ln) => Math.max(m, ln.widthPx), 0);
    return maxLine;
  });
  const maxLabel = Math.max(...labelWidths, 0);
  const isLineChart = chart.type === 13 /* CHART_TYPE_LINE */ || chart.type === 12 /* CHART_TYPE_LINE_3D */;
  const symbolWidth = isLineChart ? LINE_LEGEND_SYMBOL_WIDTH : LEGEND_MARK_SIZE;
  const isHorizontalLegend = isHorizontalLegendPosition(resolvedPosition ?? 1 /* LEGEND_POSITION_RIGHT */);
  const totalItemWidths = entries.map((_, idx) => {
    const labelWidth = labelWidths[idx] ?? 0;
    return symbolWidth + LEGEND_SYMBOL_TO_LABEL_GAP + labelWidth;
  });
  let width;
  let height;
  let rows;
  if (isHorizontalLegend) {
    const maxInnerWidth = opts.maxWidthPx !== undefined ? Math.max(0, opts.maxWidthPx - LEGEND_INNER_PAD * 2) : Number.POSITIVE_INFINITY;
    rows = packHorizontalLegendRows(totalItemWidths, maxInnerWidth);
    const contentWidth = rows.reduce((maxWidth, row) => Math.max(maxWidth, row.width), 0);
    width = Math.max(0, contentWidth + LEGEND_INNER_PAD * 2);
    const { top: padTop, bottom: padBottom } = getHorizontalLegendInnerPadding(resolvedPosition);
    height = rows.length * LEGEND_ROW_HEIGHT + Math.max(0, rows.length - 1) * HORIZONTAL_LEGEND_ROW_GAP + padTop + padBottom;
  } else {
    const rowsHeight = entries.length * LEGEND_ROW_HEIGHT + Math.max(0, entries.length - 1) * LEGEND_ITEM_GAP;
    width = symbolWidth + LEGEND_SYMBOL_TO_LABEL_GAP + maxLabel + LEGEND_INNER_PAD * 2;
    height = rowsHeight + LEGEND_INNER_PAD * 2;
  }
  ctx.restore();
  return { width, height, entries, labelWidths, rows };
}
function measureLegendSize(ctx, chart, themeMap, opts = {}) {
  const { width, height, entries } = measureLegendLayout(ctx, chart, themeMap, opts);
  return { width, height, entries };
}
function packHorizontalLegendRows(itemWidths, maxInnerWidth) {
  if (itemWidths.length === 0)
    return [];
  const rows = [];
  let currentRow = {
    itemIndices: [],
    width: 0
  };
  for (let index = 0;index < itemWidths.length; index += 1) {
    const itemWidth = itemWidths[index] ?? 0;
    const gap = currentRow.itemIndices.length > 0 ? LEGEND_ITEM_GAP : 0;
    const nextWidth = currentRow.width + gap + itemWidth;
    const shouldWrap = currentRow.itemIndices.length > 0 && Number.isFinite(maxInnerWidth) && nextWidth > maxInnerWidth;
    if (shouldWrap) {
      rows.push(currentRow);
      currentRow = {
        itemIndices: [index],
        width: itemWidth
      };
      continue;
    }
    currentRow.itemIndices.push(index);
    currentRow.width = nextWidth;
  }
  rows.push(currentRow);
  return rows;
}
function drawLegend(ctx, chart, dims, themeMap, position = 3 /* LEGEND_POSITION_TOP */, opts) {
  if (chart.series.length === 0)
    return;
  ctx.save();
  const legendTextColor = resolveLegendTextColor(chart, themeMap);
  const legendPtHund2 = chart.legend?.textStyle?.fontSize;
  const legendPx2 = legendPtHund2 ? fontSizeToPx(legendPtHund2) : LEGEND_FONT_SIZE;
  ctx.font = `${legendPx2}px ${FONT_FAMILY}`;
  const resolvedLegendPosition = normalizeLegendPosition(position);
  const maxWidthPx = isHorizontalLegendPosition(resolvedLegendPosition) ? Math.max(0, dims.width - LEGEND_OUTER_PAD * 2) : undefined;
  if (chart.type === 23 /* CHART_TYPE_MAP */) {
    drawMapLegend(ctx, chart, dims, themeMap, resolvedLegendPosition, legendPx2, legendTextColor, opts);
    ctx.restore();
    return;
  }
  const { width: boxWidth, height: boxHeight, entries, labelWidths, rows } = measureLegendLayout(ctx, chart, themeMap, {
    position: resolvedLegendPosition,
    maxWidthPx
  });
  if (entries.length === 0) {
    ctx.restore();
    return;
  }
  const pieFamily = isPieFamily(chart);
  const isTreemap = chart.type === 29 /* CHART_TYPE_TREEMAP */;
  const isLineChartLegend = chart.type === 13 /* CHART_TYPE_LINE */ || chart.type === 12 /* CHART_TYPE_LINE_3D */;
  const symbolWidth = isLineChartLegend ? LINE_LEGEND_SYMBOL_WIDTH : LEGEND_MARK_SIZE;
  const symbolHeight = isLineChartLegend ? LINE_LEGEND_SYMBOL_STROKE_WIDTH : LEGEND_MARK_SIZE;
  const rowHeight = LEGEND_ROW_HEIGHT;
  let x0 = dims.x + LEGEND_OUTER_PAD;
  let y0 = dims.y + LEGEND_OUTER_PAD;
  const isHorizontalLegend = isHorizontalLegendPosition(resolvedLegendPosition);
  const horizontalInnerPads = isHorizontalLegend ? getHorizontalLegendInnerPadding(resolvedLegendPosition) : null;
  const innerPadTop = horizontalInnerPads?.top ?? LEGEND_INNER_PAD;
  if (isHorizontalLegend) {
    const rowWidth = boxWidth;
    const innerWidth = Math.max(0, dims.width - LEGEND_OUTER_PAD * 2);
    const centerOffset = Math.max(0, (innerWidth - rowWidth) / 2);
    x0 = dims.x + LEGEND_OUTER_PAD + centerOffset;
    y0 = dims.y + LEGEND_OUTER_PAD;
  } else if (resolvedLegendPosition === 2 /* LEGEND_POSITION_LEFT */ || resolvedLegendPosition === 1 /* LEGEND_POSITION_RIGHT */) {
    x0 = dims.x + LEGEND_OUTER_PAD;
    y0 = Math.max(dims.y + LEGEND_OUTER_PAD, dims.y + (dims.height - boxHeight) / 2);
  }
  const legendOverlay = Boolean(chart.legend?.overlay);
  const legendRect = { x: x0, y: y0, width: boxWidth, height: boxHeight };
  ctx.beginPath();
  ctx.rect(x0, y0, boxWidth, boxHeight);
  if (chart.legend?.fill) {
    ctx.fillStyle = resolveFillPaint(ctx, legendRect, chart.legend.fill, themeMap, "transparent");
    ctx.fill();
  } else if (legendOverlay) {
    ctx.save();
    ctx.globalAlpha = 0.85;
    ctx.fillStyle = "#ffffff";
    ctx.fill();
    ctx.restore();
  }
  const hasLegendStroke = Boolean(chart.legend?.stroke?.fill?.color);
  if (hasLegendStroke) {
    applyLineStyle(ctx, chart.legend?.stroke, themeMap, { widthPx: 0.75 });
    ctx.stroke();
  } else if (legendOverlay) {
    ctx.save();
    ctx.strokeStyle = "#d0d0d0";
    ctx.lineWidth = 0.75;
    ctx.setLineDash([]);
    ctx.stroke();
    ctx.restore();
  }
  const hiddenSet = Array.isArray(opts?.hiddenSeriesIndices) ? new Set(opts?.hiddenSeriesIndices) : opts?.hiddenSeriesIndices;
  const drawLegendItem = (entry, idx, x, rowY) => {
    const series = chart.series[entry.seriesIndex];
    if (!series)
      return;
    const label = entry.label;
    const labelWidth = labelWidths[idx] ?? ctx.measureText(label).width;
    const fillColor = entry.fillColor ?? (pieFamily ? getPointFillColor(series, entry.pointIndex ?? 0, entry.seriesIndex, themeMap, entry.pointIndex ?? 0) : getSeriesColor(series, entry.seriesIndex, themeMap));
    const { color: strokeColor, widthPx: strokeWidthPx } = pieFamily ? getPointStroke(series, entry.pointIndex ?? 0, themeMap) : isTreemap ? { color: undefined, widthPx: undefined } : getPointStroke(series, 0, themeMap);
    const defaultStrokeWidth = isTreemap ? 0 : pieFamily ? 1 : 2;
    const strokeWidth = strokeWidthPx !== undefined ? strokeWidthPx : defaultStrokeWidth;
    const symbolY = rowY - symbolHeight / 2;
    const w = symbolWidth;
    const h = symbolHeight;
    const r = 2;
    const lineLegendStrokeColor = strokeColor ?? fillColor;
    const lineLegendStrokeWidth = Math.max(LINE_LEGEND_SYMBOL_STROKE_WIDTH, strokeWidth - 2);
    const skipFill = pieFamily && entry.pointIndex !== undefined ? pointHasNoFill(series, entry.pointIndex) : false;
    const isHidden = hiddenSet?.has(entry.seriesIndex) ?? false;
    if (isHidden) {
      if (isLineChartLegend && lineLegendStrokeColor) {
        ctx.save();
        ctx.globalAlpha = 0.5;
        ctx.strokeStyle = lineLegendStrokeColor;
        ctx.lineWidth = lineLegendStrokeWidth;
        ctx.beginPath();
        ctx.moveTo(x, rowY);
        ctx.lineTo(x + w, rowY);
        ctx.stroke();
        ctx.restore();
      } else {
        const xi = x + 0.5;
        const yi = symbolY + 0.5;
        const wi = w - 1;
        const hi = h - 1;
        const ri = Math.max(0, r - 0.5);
        ctx.beginPath();
        ctx.moveTo(xi + ri, yi);
        ctx.lineTo(xi + wi - ri, yi);
        ctx.quadraticCurveTo(xi + wi, yi, xi + wi, yi + ri);
        ctx.lineTo(xi + wi, yi + hi - ri);
        ctx.quadraticCurveTo(xi + wi, yi + hi, xi + wi - ri, yi + hi);
        ctx.lineTo(xi + ri, yi + hi);
        ctx.quadraticCurveTo(xi, yi + hi, xi, yi + hi - ri);
        ctx.lineTo(xi, yi + ri);
        ctx.quadraticCurveTo(xi, yi, xi + ri, yi);
        ctx.closePath();
        if (strokeColor) {
          ctx.strokeStyle = strokeColor;
          ctx.lineWidth = strokeWidth;
        } else if (fillColor) {
          ctx.strokeStyle = fillColor;
          ctx.lineWidth = 1;
        }
        ctx.stroke();
      }
    } else {
      if (isLineChartLegend && lineLegendStrokeColor) {
        ctx.strokeStyle = lineLegendStrokeColor;
        ctx.lineWidth = lineLegendStrokeWidth;
        ctx.beginPath();
        ctx.moveTo(x, rowY);
        ctx.lineTo(x + w, rowY);
        ctx.stroke();
      } else {
        if (!skipFill && fillColor) {
          ctx.fillStyle = fillColor;
        }
        ctx.beginPath();
        ctx.moveTo(x + r, symbolY);
        ctx.lineTo(x + w - r, symbolY);
        ctx.quadraticCurveTo(x + w, symbolY, x + w, symbolY + r);
        ctx.lineTo(x + w, symbolY + h - r);
        ctx.quadraticCurveTo(x + w, symbolY + h, x + w - r, symbolY + h);
        ctx.lineTo(x + r, symbolY + h);
        ctx.quadraticCurveTo(x, symbolY + h, x, symbolY + h - r);
        ctx.lineTo(x, symbolY + r);
        ctx.quadraticCurveTo(x, symbolY, x + r, symbolY);
        ctx.closePath();
        if (!skipFill && fillColor) {
          ctx.fill();
        }
        if (!isTreemap) {
          const effectiveStrokeColor = strokeColor ?? (!skipFill ? undefined : fillColor);
          const effectiveStrokeWidth = strokeWidthPx !== undefined ? strokeWidthPx : defaultStrokeWidth;
          if (effectiveStrokeColor) {
            ctx.strokeStyle = effectiveStrokeColor;
            ctx.lineWidth = effectiveStrokeWidth;
            ctx.stroke();
          }
        }
      }
    }
    ctx.fillStyle = legendTextColor;
    ctx.textAlign = "left";
    ctx.textBaseline = "middle";
    const labelX = x + w + LEGEND_SYMBOL_TO_LABEL_GAP;
    ctx.fillText(label, labelX, rowY);
    if (opts?.chartHoverTargets) {
      const anchorX = x + w;
      const anchorY = rowY;
      const rowW = w + LEGEND_SYMBOL_TO_LABEL_GAP + labelWidth;
      const targetY = rowY - rowHeight / 2;
      const targetHeight = rowHeight;
      opts.chartHoverTargets.push({
        kind: "legend",
        x,
        y: targetY,
        width: rowW,
        height: targetHeight,
        value: 0,
        color: fillColor,
        anchorX,
        anchorY,
        elementId: opts.elementId,
        seriesIndex: entry.seriesIndex,
        seriesName: series.name
      });
    }
  };
  if (isHorizontalLegend) {
    const packedRows = rows ?? [];
    const innerContentWidth = Math.max(0, boxWidth - LEGEND_INNER_PAD * 2);
    packedRows.forEach((row, rowIndex) => {
      let cursorX = x0 + LEGEND_INNER_PAD + Math.max(0, (innerContentWidth - row.width) / 2);
      const rowY = y0 + innerPadTop + rowHeight / 2 + rowIndex * (rowHeight + HORIZONTAL_LEGEND_ROW_GAP);
      row.itemIndices.forEach((entryIndex) => {
        const entry = entries[entryIndex];
        if (!entry)
          return;
        drawLegendItem(entry, entryIndex, cursorX, rowY);
        const labelWidth = labelWidths[entryIndex] ?? ctx.measureText(entry.label).width;
        cursorX += symbolWidth + LEGEND_SYMBOL_TO_LABEL_GAP + labelWidth + LEGEND_ITEM_GAP;
      });
    });
  } else {
    let cursorX = x0 + LEGEND_INNER_PAD;
    let cursorY = y0 + innerPadTop;
    entries.forEach((entry, idx) => {
      drawLegendItem(entry, idx, cursorX, cursorY + rowHeight / 2);
      cursorY += rowHeight + LEGEND_ITEM_GAP;
    });
  }
  ctx.restore();
}
function drawMapLegend(ctx, chart, dims, themeMap, position, legendFontPx, legendTextColor, opts) {
  const data = getMapLegendData(chart, themeMap);
  if (!data)
    return;
  const hiddenSet = Array.isArray(opts?.hiddenSeriesIndices) ? new Set(opts?.hiddenSeriesIndices) : opts?.hiddenSeriesIndices;
  if (hiddenSet?.has(0))
    return;
  const minLabelWidth = ctx.measureText(data.minLabel).width;
  const maxLabelWidth = ctx.measureText(data.maxLabel).width;
  const titleWidth = data.seriesName ? ctx.measureText(data.seriesName).width : 0;
  const hasTitle = !!data.seriesName;
  const isHorizontalLegend = isHorizontalLegendPosition(position);
  const availableWidth = Math.max(0, dims.width - MAP_LEGEND_PAD * 2);
  if (availableWidth <= 0)
    return;
  if (isHorizontalLegend) {
    const gradientWidth2 = Math.max(0, Math.min(availableWidth, MAP_LEGEND_MAX_GRADIENT_LENGTH));
    if (gradientWidth2 <= 0)
      return;
    const blockWidth2 = Math.max(gradientWidth2, titleWidth);
    let blockOffset2 = Math.max(0, (availableWidth - blockWidth2) / 2);
    if (position === 2 /* LEGEND_POSITION_LEFT */) {
      blockOffset2 = 0;
    } else if (position === 1 /* LEGEND_POSITION_RIGHT */) {
      blockOffset2 = Math.max(0, availableWidth - blockWidth2);
    }
    const gradientOffsetWithinBlock = Math.max(0, (blockWidth2 - gradientWidth2) / 2);
    const gradientX2 = dims.x + MAP_LEGEND_PAD + blockOffset2 + gradientOffsetWithinBlock;
    const availableHeight2 = Math.max(0, dims.height - MAP_LEGEND_PAD * 2);
    const contentHeight = (hasTitle ? legendFontPx + MAP_LEGEND_TITLE_BAR_GAP : 0) + MAP_LEGEND_GRADIENT_HEIGHT + MAP_LEGEND_LABEL_GAP + legendFontPx;
    const verticalOffset = Math.max(0, (availableHeight2 - contentHeight) / 2);
    const blockTop = dims.y + MAP_LEGEND_PAD + verticalOffset;
    const gradientY2 = blockTop + (hasTitle ? legendFontPx + MAP_LEGEND_TITLE_BAR_GAP : 0);
    const gradient2 = ctx.createLinearGradient(gradientX2, gradientY2, gradientX2 + gradientWidth2, gradientY2);
    gradient2.addColorStop(0, data.rampStart);
    gradient2.addColorStop(1, data.rampEnd);
    ctx.fillStyle = gradient2;
    ctx.fillRect(gradientX2, gradientY2, gradientWidth2, MAP_LEGEND_GRADIENT_HEIGHT);
    ctx.strokeStyle = "rgba(0, 0, 0, 0.12)";
    ctx.lineWidth = 1;
    ctx.strokeRect(gradientX2, gradientY2, gradientWidth2, MAP_LEGEND_GRADIENT_HEIGHT);
    const labelY = gradientY2 + MAP_LEGEND_GRADIENT_HEIGHT + MAP_LEGEND_LABEL_GAP;
    ctx.fillStyle = legendTextColor;
    ctx.textBaseline = "top";
    ctx.textAlign = "left";
    ctx.fillText(data.minLabel, gradientX2, labelY);
    ctx.textAlign = "right";
    ctx.fillText(data.maxLabel, gradientX2 + gradientWidth2, labelY);
    if (data.seriesName) {
      ctx.textAlign = "center";
      ctx.textBaseline = "top";
      const titleCenterX = dims.x + MAP_LEGEND_PAD + blockOffset2 + blockWidth2 / 2;
      ctx.fillText(data.seriesName, titleCenterX, blockTop);
    }
    return;
  }
  const labelWidth = Math.max(minLabelWidth, maxLabelWidth);
  const labelGap = labelWidth > 0 ? MAP_LEGEND_LABEL_GAP : 0;
  const gradientWidth = Math.max(0, Math.min(MAP_LEGEND_GRADIENT_HEIGHT, availableWidth - labelGap - labelWidth));
  if (gradientWidth <= 0)
    return;
  const blockWidth = Math.max(gradientWidth + labelGap + labelWidth, titleWidth);
  const blockOffset = Math.max(0, (availableWidth - blockWidth) / 2);
  const gradientX = dims.x + MAP_LEGEND_PAD + blockOffset;
  const labelX = gradientX + gradientWidth + labelGap;
  const availableHeight = Math.max(0, dims.height - MAP_LEGEND_PAD * 2);
  const titleSpace = hasTitle ? legendFontPx + MAP_LEGEND_TITLE_BAR_GAP : 0;
  const gradientSpace = Math.max(0, availableHeight - titleSpace);
  const gradientHeight = Math.min(MAP_LEGEND_MAX_GRADIENT_LENGTH, gradientSpace);
  if (gradientHeight <= 0)
    return;
  const gradientY = dims.y + MAP_LEGEND_PAD + titleSpace;
  const gradientBottomY = gradientY + gradientHeight;
  const gradient = ctx.createLinearGradient(gradientX, gradientBottomY, gradientX, gradientY);
  gradient.addColorStop(0, data.rampStart);
  gradient.addColorStop(1, data.rampEnd);
  ctx.fillStyle = gradient;
  ctx.fillRect(gradientX, gradientY, gradientWidth, gradientHeight);
  ctx.strokeStyle = "rgba(0, 0, 0, 0.12)";
  ctx.lineWidth = 1;
  ctx.strokeRect(gradientX, gradientY, gradientWidth, gradientHeight);
  ctx.fillStyle = legendTextColor;
  ctx.textAlign = "left";
  ctx.textBaseline = "middle";
  if (labelWidth > 0) {
    ctx.fillText(data.maxLabel, labelX, gradientY);
    ctx.fillText(data.minLabel, labelX, gradientBottomY);
  }
  if (data.seriesName) {
    ctx.textAlign = "center";
    ctx.textBaseline = "top";
    const titleCenterX = dims.x + MAP_LEGEND_PAD + blockOffset + blockWidth / 2;
    ctx.fillText(data.seriesName, titleCenterX, dims.y + MAP_LEGEND_PAD);
  }
}

// node_modules/@oai/granola/dist/draw-utils/chart/layout-legend.js
var BOTTOM_LEGEND_MARGIN_PX = 12;
var LEGEND_LAYOUT_OUTER_PAD_PX = LEGEND_OUTER_PAD * 2;
function computeLegendLayout(ctx, chart, plotDimsIn, themeMap, opts = {}) {
  let plotDims = plotDimsIn;
  if (!chart.hasLegend)
    return { plotDims };
  const rawPos = chart.legend?.position ?? 1 /* LEGEND_POSITION_RIGHT */;
  const pos = rawPos === 5 /* LEGEND_POSITION_TOP_RIGHT */ ? 1 /* LEGEND_POSITION_RIGHT */ : rawPos;
  const { width: measuredWidth, height: measuredHeight } = measureLegendSize(ctx, chart, themeMap, {
    position: pos,
    maxWidthPx: pos === 3 /* LEGEND_POSITION_TOP */ || pos === 4 /* LEGEND_POSITION_BOTTOM */ ? Math.max(0, plotDims.width - LEGEND_LAYOUT_OUTER_PAD_PX) : undefined
  });
  const lw = measuredWidth + LEGEND_LAYOUT_OUTER_PAD_PX;
  const lh = measuredHeight + LEGEND_LAYOUT_OUTER_PAD_PX;
  const sideLimitRaw = opts.outerDims && opts.outerDims.width > 0 ? Math.max(0, opts.outerDims.width * (opts.maxSideFrac ?? 0.35)) : Number.POSITIVE_INFINITY;
  const sidePadding = Math.max(0, opts.sidePaddingPx ?? 8);
  const GAP = 8;
  let legendRect;
  const overlay = Boolean(chart.legend?.overlay);
  const overlayPadding = 8;
  switch (pos) {
    case 3 /* LEGEND_POSITION_TOP */: {
      const h = Math.min(Math.max(0, plotDims.height), lh + GAP);
      legendRect = overlay ? {
        x: plotDims.x + overlayPadding,
        y: plotDims.y + overlayPadding,
        width: Math.max(0, plotDims.width - overlayPadding * 2),
        height: h
      } : {
        x: plotDims.x,
        y: plotDims.y,
        width: plotDims.width,
        height: h
      };
      if (!overlay) {
        plotDims = {
          x: plotDims.x,
          y: plotDims.y + h,
          width: plotDims.width,
          height: Math.max(0, plotDims.height - h)
        };
      }
      break;
    }
    case 4 /* LEGEND_POSITION_BOTTOM */: {
      const measured = Math.min(Math.max(0, plotDims.height), lh);
      const outerBottom = opts.outerDims ? opts.outerDims.y + opts.outerDims.height - BOTTOM_LEGEND_MARGIN_PX : plotDims.y + plotDims.height - BOTTOM_LEGEND_MARGIN_PX;
      const maxHeight = Math.max(0, outerBottom - plotDims.y);
      const legendHeight = Math.min(measured, maxHeight);
      const legendY = Math.max(plotDims.y, outerBottom - legendHeight);
      legendRect = overlay ? {
        x: plotDims.x + overlayPadding,
        y: plotDims.y + Math.max(0, plotDims.height - legendHeight) - overlayPadding,
        width: Math.max(0, plotDims.width - overlayPadding * 2),
        height: legendHeight
      } : {
        x: plotDims.x,
        y: legendY,
        width: plotDims.width,
        height: legendHeight
      };
      if (!overlay) {
        plotDims = {
          x: plotDims.x,
          y: plotDims.y,
          width: plotDims.width,
          height: Math.max(0, legendY - plotDims.y)
        };
      }
      break;
    }
    case 2 /* LEGEND_POSITION_LEFT */: {
      const base = lw + GAP;
      let desired = base + sidePadding;
      if (desired < base)
        desired = base;
      if (sideLimitRaw < desired)
        desired = Math.max(base, sideLimitRaw);
      const w = Math.min(Math.max(0, plotDims.width), desired);
      legendRect = overlay ? {
        x: plotDims.x + overlayPadding,
        y: plotDims.y + overlayPadding,
        width: w,
        height: Math.max(0, plotDims.height - overlayPadding * 2)
      } : {
        x: plotDims.x,
        y: plotDims.y,
        width: w,
        height: plotDims.height
      };
      if (!overlay) {
        plotDims = {
          x: plotDims.x + w,
          y: plotDims.y,
          width: Math.max(0, plotDims.width - w),
          height: plotDims.height
        };
      }
      break;
    }
    case 1 /* LEGEND_POSITION_RIGHT */:
    default: {
      const base = lw + GAP;
      let desired = base + sidePadding;
      if (desired < base)
        desired = base;
      if (sideLimitRaw < desired)
        desired = Math.max(base, sideLimitRaw);
      const w = Math.min(Math.max(0, plotDims.width), desired);
      legendRect = overlay ? {
        x: plotDims.x + Math.max(0, plotDims.width - w) - overlayPadding,
        y: plotDims.y + overlayPadding,
        width: w,
        height: Math.max(0, plotDims.height - overlayPadding * 2)
      } : {
        x: plotDims.x + Math.max(0, plotDims.width - w),
        y: plotDims.y,
        width: w,
        height: plotDims.height
      };
      if (!overlay) {
        plotDims = {
          x: plotDims.x,
          y: plotDims.y,
          width: Math.max(0, plotDims.width - w),
          height: plotDims.height
        };
      }
      break;
    }
  }
  return { plotDims, legendRect, legendPosition: pos };
}

// node_modules/d3-shape/src/constant.js
function constant_default3(x) {
  return function constant() {
    return x;
  };
}

// node_modules/d3-shape/src/math.js
var abs = Math.abs;
var atan2 = Math.atan2;
var cos = Math.cos;
var max2 = Math.max;
var min = Math.min;
var sin = Math.sin;
var sqrt2 = Math.sqrt;
var epsilon = 0.000000000001;
var pi = Math.PI;
var halfPi = pi / 2;
var tau = 2 * pi;
function acos(x) {
  return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);
}
function asin(x) {
  return x >= 1 ? halfPi : x <= -1 ? -halfPi : Math.asin(x);
}

// node_modules/d3-path/src/path.js
var pi2 = Math.PI;
var tau2 = 2 * pi2;
var epsilon2 = 0.000001;
var tauEpsilon = tau2 - epsilon2;
function append(strings) {
  this._ += strings[0];
  for (let i = 1, n = strings.length;i < n; ++i) {
    this._ += arguments[i] + strings[i];
  }
}
function appendRound(digits) {
  let d = Math.floor(digits);
  if (!(d >= 0))
    throw new Error(`invalid digits: ${digits}`);
  if (d > 15)
    return append;
  const k = 10 ** d;
  return function(strings) {
    this._ += strings[0];
    for (let i = 1, n = strings.length;i < n; ++i) {
      this._ += Math.round(arguments[i] * k) / k + strings[i];
    }
  };
}

class Path {
  constructor(digits) {
    this._x0 = this._y0 = this._x1 = this._y1 = null;
    this._ = "";
    this._append = digits == null ? append : appendRound(digits);
  }
  moveTo(x, y) {
    this._append`M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}`;
  }
  closePath() {
    if (this._x1 !== null) {
      this._x1 = this._x0, this._y1 = this._y0;
      this._append`Z`;
    }
  }
  lineTo(x, y) {
    this._append`L${this._x1 = +x},${this._y1 = +y}`;
  }
  quadraticCurveTo(x1, y1, x, y) {
    this._append`Q${+x1},${+y1},${this._x1 = +x},${this._y1 = +y}`;
  }
  bezierCurveTo(x1, y1, x2, y2, x, y) {
    this._append`C${+x1},${+y1},${+x2},${+y2},${this._x1 = +x},${this._y1 = +y}`;
  }
  arcTo(x1, y1, x2, y2, r) {
    x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;
    if (r < 0)
      throw new Error(`negative radius: ${r}`);
    let x0 = this._x1, y0 = this._y1, x21 = x2 - x1, y21 = y2 - y1, x01 = x0 - x1, y01 = y0 - y1, l01_2 = x01 * x01 + y01 * y01;
    if (this._x1 === null) {
      this._append`M${this._x1 = x1},${this._y1 = y1}`;
    } else if (!(l01_2 > epsilon2))
      ;
    else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon2) || !r) {
      this._append`L${this._x1 = x1},${this._y1 = y1}`;
    } else {
      let x20 = x2 - x0, y20 = y2 - y0, l21_2 = x21 * x21 + y21 * y21, l20_2 = x20 * x20 + y20 * y20, l21 = Math.sqrt(l21_2), l01 = Math.sqrt(l01_2), l = r * Math.tan((pi2 - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2), t01 = l / l01, t21 = l / l21;
      if (Math.abs(t01 - 1) > epsilon2) {
        this._append`L${x1 + t01 * x01},${y1 + t01 * y01}`;
      }
      this._append`A${r},${r},0,0,${+(y01 * x20 > x01 * y20)},${this._x1 = x1 + t21 * x21},${this._y1 = y1 + t21 * y21}`;
    }
  }
  arc(x, y, r, a0, a1, ccw) {
    x = +x, y = +y, r = +r, ccw = !!ccw;
    if (r < 0)
      throw new Error(`negative radius: ${r}`);
    let dx = r * Math.cos(a0), dy = r * Math.sin(a0), x0 = x + dx, y0 = y + dy, cw = 1 ^ ccw, da = ccw ? a0 - a1 : a1 - a0;
    if (this._x1 === null) {
      this._append`M${x0},${y0}`;
    } else if (Math.abs(this._x1 - x0) > epsilon2 || Math.abs(this._y1 - y0) > epsilon2) {
      this._append`L${x0},${y0}`;
    }
    if (!r)
      return;
    if (da < 0)
      da = da % tau2 + tau2;
    if (da > tauEpsilon) {
      this._append`A${r},${r},0,1,${cw},${x - dx},${y - dy}A${r},${r},0,1,${cw},${this._x1 = x0},${this._y1 = y0}`;
    } else if (da > epsilon2) {
      this._append`A${r},${r},0,${+(da >= pi2)},${cw},${this._x1 = x + r * Math.cos(a1)},${this._y1 = y + r * Math.sin(a1)}`;
    }
  }
  rect(x, y, w, h) {
    this._append`M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}h${w = +w}v${+h}h${-w}Z`;
  }
  toString() {
    return this._;
  }
}
function path2() {
  return new Path;
}
path2.prototype = Path.prototype;
// node_modules/d3-shape/src/path.js
function withPath(shape) {
  let digits = 3;
  shape.digits = function(_) {
    if (!arguments.length)
      return digits;
    if (_ == null) {
      digits = null;
    } else {
      const d = Math.floor(_);
      if (!(d >= 0))
        throw new RangeError(`invalid digits: ${_}`);
      digits = d;
    }
    return shape;
  };
  return () => new Path(digits);
}

// node_modules/d3-shape/src/arc.js
function arcInnerRadius(d) {
  return d.innerRadius;
}
function arcOuterRadius(d) {
  return d.outerRadius;
}
function arcStartAngle(d) {
  return d.startAngle;
}
function arcEndAngle(d) {
  return d.endAngle;
}
function arcPadAngle(d) {
  return d && d.padAngle;
}
function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  var x10 = x1 - x0, y10 = y1 - y0, x32 = x3 - x2, y32 = y3 - y2, t = y32 * x10 - x32 * y10;
  if (t * t < epsilon)
    return;
  t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t;
  return [x0 + t * x10, y0 + t * y10];
}
function cornerTangents(x0, y0, x1, y1, r1, rc, cw) {
  var x01 = x0 - x1, y01 = y0 - y1, lo = (cw ? rc : -rc) / sqrt2(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x11 = x0 + ox, y11 = y0 + oy, x10 = x1 + ox, y10 = y1 + oy, x00 = (x11 + x10) / 2, y00 = (y11 + y10) / 2, dx = x10 - x11, dy = y10 - y11, d2 = dx * dx + dy * dy, r = r1 - rc, D = x11 * y10 - x10 * y11, d = (dy < 0 ? -1 : 1) * sqrt2(max2(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x00, dy0 = cy0 - y00, dx1 = cx1 - x00, dy1 = cy1 - y00;
  if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1)
    cx0 = cx1, cy0 = cy1;
  return {
    cx: cx0,
    cy: cy0,
    x01: -ox,
    y01: -oy,
    x11: cx0 * (r1 / r - 1),
    y11: cy0 * (r1 / r - 1)
  };
}
function arc_default() {
  var innerRadius = arcInnerRadius, outerRadius = arcOuterRadius, cornerRadius = constant_default3(0), padRadius = null, startAngle = arcStartAngle, endAngle = arcEndAngle, padAngle = arcPadAngle, context = null, path3 = withPath(arc);
  function arc() {
    var buffer, r, r0 = +innerRadius.apply(this, arguments), r1 = +outerRadius.apply(this, arguments), a0 = startAngle.apply(this, arguments) - halfPi, a1 = endAngle.apply(this, arguments) - halfPi, da = abs(a1 - a0), cw = a1 > a0;
    if (!context)
      context = buffer = path3();
    if (r1 < r0)
      r = r1, r1 = r0, r0 = r;
    if (!(r1 > epsilon))
      context.moveTo(0, 0);
    else if (da > tau - epsilon) {
      context.moveTo(r1 * cos(a0), r1 * sin(a0));
      context.arc(0, 0, r1, a0, a1, !cw);
      if (r0 > epsilon) {
        context.moveTo(r0 * cos(a1), r0 * sin(a1));
        context.arc(0, 0, r0, a1, a0, cw);
      }
    } else {
      var a01 = a0, a11 = a1, a00 = a0, a10 = a1, da0 = da, da1 = da, ap = padAngle.apply(this, arguments) / 2, rp = ap > epsilon && (padRadius ? +padRadius.apply(this, arguments) : sqrt2(r0 * r0 + r1 * r1)), rc = min(abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments)), rc0 = rc, rc1 = rc, t0, t1;
      if (rp > epsilon) {
        var p0 = asin(rp / r0 * sin(ap)), p1 = asin(rp / r1 * sin(ap));
        if ((da0 -= p0 * 2) > epsilon)
          p0 *= cw ? 1 : -1, a00 += p0, a10 -= p0;
        else
          da0 = 0, a00 = a10 = (a0 + a1) / 2;
        if ((da1 -= p1 * 2) > epsilon)
          p1 *= cw ? 1 : -1, a01 += p1, a11 -= p1;
        else
          da1 = 0, a01 = a11 = (a0 + a1) / 2;
      }
      var x01 = r1 * cos(a01), y01 = r1 * sin(a01), x10 = r0 * cos(a10), y10 = r0 * sin(a10);
      if (rc > epsilon) {
        var x11 = r1 * cos(a11), y11 = r1 * sin(a11), x00 = r0 * cos(a00), y00 = r0 * sin(a00), oc;
        if (da < pi) {
          if (oc = intersect(x01, y01, x00, y00, x11, y11, x10, y10)) {
            var ax = x01 - oc[0], ay = y01 - oc[1], bx = x11 - oc[0], by = y11 - oc[1], kc = 1 / sin(acos((ax * bx + ay * by) / (sqrt2(ax * ax + ay * ay) * sqrt2(bx * bx + by * by))) / 2), lc = sqrt2(oc[0] * oc[0] + oc[1] * oc[1]);
            rc0 = min(rc, (r0 - lc) / (kc - 1));
            rc1 = min(rc, (r1 - lc) / (kc + 1));
          } else {
            rc0 = rc1 = 0;
          }
        }
      }
      if (!(da1 > epsilon))
        context.moveTo(x01, y01);
      else if (rc1 > epsilon) {
        t0 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw);
        t1 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw);
        context.moveTo(t0.cx + t0.x01, t0.cy + t0.y01);
        if (rc1 < rc)
          context.arc(t0.cx, t0.cy, rc1, atan2(t0.y01, t0.x01), atan2(t1.y01, t1.x01), !cw);
        else {
          context.arc(t0.cx, t0.cy, rc1, atan2(t0.y01, t0.x01), atan2(t0.y11, t0.x11), !cw);
          context.arc(0, 0, r1, atan2(t0.cy + t0.y11, t0.cx + t0.x11), atan2(t1.cy + t1.y11, t1.cx + t1.x11), !cw);
          context.arc(t1.cx, t1.cy, rc1, atan2(t1.y11, t1.x11), atan2(t1.y01, t1.x01), !cw);
        }
      } else
        context.moveTo(x01, y01), context.arc(0, 0, r1, a01, a11, !cw);
      if (!(r0 > epsilon) || !(da0 > epsilon))
        context.lineTo(x10, y10);
      else if (rc0 > epsilon) {
        t0 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw);
        t1 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw);
        context.lineTo(t0.cx + t0.x01, t0.cy + t0.y01);
        if (rc0 < rc)
          context.arc(t0.cx, t0.cy, rc0, atan2(t0.y01, t0.x01), atan2(t1.y01, t1.x01), !cw);
        else {
          context.arc(t0.cx, t0.cy, rc0, atan2(t0.y01, t0.x01), atan2(t0.y11, t0.x11), !cw);
          context.arc(0, 0, r0, atan2(t0.cy + t0.y11, t0.cx + t0.x11), atan2(t1.cy + t1.y11, t1.cx + t1.x11), cw);
          context.arc(t1.cx, t1.cy, rc0, atan2(t1.y11, t1.x11), atan2(t1.y01, t1.x01), !cw);
        }
      } else
        context.arc(0, 0, r0, a10, a00, cw);
    }
    context.closePath();
    if (buffer)
      return context = null, buffer + "" || null;
  }
  arc.centroid = function() {
    var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - pi / 2;
    return [cos(a) * r, sin(a) * r];
  };
  arc.innerRadius = function(_) {
    return arguments.length ? (innerRadius = typeof _ === "function" ? _ : constant_default3(+_), arc) : innerRadius;
  };
  arc.outerRadius = function(_) {
    return arguments.length ? (outerRadius = typeof _ === "function" ? _ : constant_default3(+_), arc) : outerRadius;
  };
  arc.cornerRadius = function(_) {
    return arguments.length ? (cornerRadius = typeof _ === "function" ? _ : constant_default3(+_), arc) : cornerRadius;
  };
  arc.padRadius = function(_) {
    return arguments.length ? (padRadius = _ == null ? null : typeof _ === "function" ? _ : constant_default3(+_), arc) : padRadius;
  };
  arc.startAngle = function(_) {
    return arguments.length ? (startAngle = typeof _ === "function" ? _ : constant_default3(+_), arc) : startAngle;
  };
  arc.endAngle = function(_) {
    return arguments.length ? (endAngle = typeof _ === "function" ? _ : constant_default3(+_), arc) : endAngle;
  };
  arc.padAngle = function(_) {
    return arguments.length ? (padAngle = typeof _ === "function" ? _ : constant_default3(+_), arc) : padAngle;
  };
  arc.context = function(_) {
    return arguments.length ? (context = _ == null ? null : _, arc) : context;
  };
  return arc;
}
// node_modules/d3-shape/src/array.js
var slice2 = Array.prototype.slice;
function array_default(x) {
  return typeof x === "object" && "length" in x ? x : Array.from(x);
}

// node_modules/d3-shape/src/curve/linear.js
function Linear(context) {
  this._context = context;
}
Linear.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line || this._line !== 0 && this._point === 1)
      this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0:
        this._point = 1;
        this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y);
        break;
      case 1:
        this._point = 2;
      default:
        this._context.lineTo(x, y);
        break;
    }
  }
};
function linear_default(context) {
  return new Linear(context);
}

// node_modules/d3-shape/src/point.js
function x(p) {
  return p[0];
}
function y(p) {
  return p[1];
}

// node_modules/d3-shape/src/line.js
function line_default(x2, y2) {
  var defined = constant_default3(true), context = null, curve = linear_default, output = null, path3 = withPath(line);
  x2 = typeof x2 === "function" ? x2 : x2 === undefined ? x : constant_default3(x2);
  y2 = typeof y2 === "function" ? y2 : y2 === undefined ? y : constant_default3(y2);
  function line(data) {
    var i, n = (data = array_default(data)).length, d, defined0 = false, buffer;
    if (context == null)
      output = curve(buffer = path3());
    for (i = 0;i <= n; ++i) {
      if (!(i < n && defined(d = data[i], i, data)) === defined0) {
        if (defined0 = !defined0)
          output.lineStart();
        else
          output.lineEnd();
      }
      if (defined0)
        output.point(+x2(d, i, data), +y2(d, i, data));
    }
    if (buffer)
      return output = null, buffer + "" || null;
  }
  line.x = function(_) {
    return arguments.length ? (x2 = typeof _ === "function" ? _ : constant_default3(+_), line) : x2;
  };
  line.y = function(_) {
    return arguments.length ? (y2 = typeof _ === "function" ? _ : constant_default3(+_), line) : y2;
  };
  line.defined = function(_) {
    return arguments.length ? (defined = typeof _ === "function" ? _ : constant_default3(!!_), line) : defined;
  };
  line.curve = function(_) {
    return arguments.length ? (curve = _, context != null && (output = curve(context)), line) : curve;
  };
  line.context = function(_) {
    return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), line) : context;
  };
  return line;
}
// node_modules/d3-shape/src/descending.js
function descending_default(a, b) {
  return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
}

// node_modules/d3-shape/src/identity.js
function identity_default2(d) {
  return d;
}

// node_modules/d3-shape/src/pie.js
function pie_default() {
  var value = identity_default2, sortValues = descending_default, sort = null, startAngle = constant_default3(0), endAngle = constant_default3(tau), padAngle = constant_default3(0);
  function pie(data) {
    var i, n = (data = array_default(data)).length, j, k, sum2 = 0, index = new Array(n), arcs = new Array(n), a0 = +startAngle.apply(this, arguments), da = Math.min(tau, Math.max(-tau, endAngle.apply(this, arguments) - a0)), a1, p = Math.min(Math.abs(da) / n, padAngle.apply(this, arguments)), pa = p * (da < 0 ? -1 : 1), v;
    for (i = 0;i < n; ++i) {
      if ((v = arcs[index[i] = i] = +value(data[i], i, data)) > 0) {
        sum2 += v;
      }
    }
    if (sortValues != null)
      index.sort(function(i2, j2) {
        return sortValues(arcs[i2], arcs[j2]);
      });
    else if (sort != null)
      index.sort(function(i2, j2) {
        return sort(data[i2], data[j2]);
      });
    for (i = 0, k = sum2 ? (da - n * pa) / sum2 : 0;i < n; ++i, a0 = a1) {
      j = index[i], v = arcs[j], a1 = a0 + (v > 0 ? v * k : 0) + pa, arcs[j] = {
        data: data[j],
        index: i,
        value: v,
        startAngle: a0,
        endAngle: a1,
        padAngle: p
      };
    }
    return arcs;
  }
  pie.value = function(_) {
    return arguments.length ? (value = typeof _ === "function" ? _ : constant_default3(+_), pie) : value;
  };
  pie.sortValues = function(_) {
    return arguments.length ? (sortValues = _, sort = null, pie) : sortValues;
  };
  pie.sort = function(_) {
    return arguments.length ? (sort = _, sortValues = null, pie) : sort;
  };
  pie.startAngle = function(_) {
    return arguments.length ? (startAngle = typeof _ === "function" ? _ : constant_default3(+_), pie) : startAngle;
  };
  pie.endAngle = function(_) {
    return arguments.length ? (endAngle = typeof _ === "function" ? _ : constant_default3(+_), pie) : endAngle;
  };
  pie.padAngle = function(_) {
    return arguments.length ? (padAngle = typeof _ === "function" ? _ : constant_default3(+_), pie) : padAngle;
  };
  return pie;
}
// node_modules/d3-shape/src/curve/monotone.js
function sign(x2) {
  return x2 < 0 ? -1 : 1;
}
function slope3(that, x2, y2) {
  var h0 = that._x1 - that._x0, h1 = x2 - that._x1, s0 = (that._y1 - that._y0) / (h0 || h1 < 0 && -0), s1 = (y2 - that._y1) / (h1 || h0 < 0 && -0), p = (s0 * h1 + s1 * h0) / (h0 + h1);
  return (sign(s0) + sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0;
}
function slope2(that, t) {
  var h = that._x1 - that._x0;
  return h ? (3 * (that._y1 - that._y0) / h - t) / 2 : t;
}
function point2(that, t0, t1) {
  var { _x0: x0, _y0: y0, _x1: x1, _y1: y1 } = that, dx = (x1 - x0) / 3;
  that._context.bezierCurveTo(x0 + dx, y0 + dx * t0, x1 - dx, y1 - dx * t1, x1, y1);
}
function MonotoneX(context) {
  this._context = context;
}
MonotoneX.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._y0 = this._y1 = this._t0 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 2:
        this._context.lineTo(this._x1, this._y1);
        break;
      case 3:
        point2(this, this._t0, slope2(this, this._t0));
        break;
    }
    if (this._line || this._line !== 0 && this._point === 1)
      this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x2, y2) {
    var t1 = NaN;
    x2 = +x2, y2 = +y2;
    if (x2 === this._x1 && y2 === this._y1)
      return;
    switch (this._point) {
      case 0:
        this._point = 1;
        this._line ? this._context.lineTo(x2, y2) : this._context.moveTo(x2, y2);
        break;
      case 1:
        this._point = 2;
        break;
      case 2:
        this._point = 3;
        point2(this, slope2(this, t1 = slope3(this, x2, y2)), t1);
        break;
      default:
        point2(this, this._t0, t1 = slope3(this, x2, y2));
        break;
    }
    this._x0 = this._x1, this._x1 = x2;
    this._y0 = this._y1, this._y1 = y2;
    this._t0 = t1;
  }
};
function MonotoneY(context) {
  this._context = new ReflectContext(context);
}
(MonotoneY.prototype = Object.create(MonotoneX.prototype)).point = function(x2, y2) {
  MonotoneX.prototype.point.call(this, y2, x2);
};
function ReflectContext(context) {
  this._context = context;
}
ReflectContext.prototype = {
  moveTo: function(x2, y2) {
    this._context.moveTo(y2, x2);
  },
  closePath: function() {
    this._context.closePath();
  },
  lineTo: function(x2, y2) {
    this._context.lineTo(y2, x2);
  },
  bezierCurveTo: function(x1, y1, x2, y2, x3, y3) {
    this._context.bezierCurveTo(y1, x1, y2, x2, y3, x3);
  }
};
function monotoneX(context) {
  return new MonotoneX(context);
}
// node_modules/d3-shape/src/offset/none.js
function none_default(series, order) {
  if (!((n = series.length) > 1))
    return;
  for (var i = 1, j, s0, s1 = series[order[0]], n, m = s1.length;i < n; ++i) {
    s0 = s1, s1 = series[order[i]];
    for (j = 0;j < m; ++j) {
      s1[j][1] += s1[j][0] = isNaN(s0[j][1]) ? s0[j][0] : s0[j][1];
    }
  }
}

// node_modules/d3-shape/src/order/none.js
function none_default2(series) {
  var n = series.length, o = new Array(n);
  while (--n >= 0)
    o[n] = n;
  return o;
}

// node_modules/d3-shape/src/stack.js
function stackValue(d, key) {
  return d[key];
}
function stackSeries(key) {
  const series = [];
  series.key = key;
  return series;
}
function stack_default() {
  var keys = constant_default3([]), order = none_default2, offset = none_default, value = stackValue;
  function stack(data) {
    var sz = Array.from(keys.apply(this, arguments), stackSeries), i, n = sz.length, j = -1, oz;
    for (const d of data) {
      for (i = 0, ++j;i < n; ++i) {
        (sz[i][j] = [0, +value(d, sz[i].key, j, data)]).data = d;
      }
    }
    for (i = 0, oz = array_default(order(sz));i < n; ++i) {
      sz[oz[i]].index = i;
    }
    offset(sz, oz);
    return sz;
  }
  stack.keys = function(_) {
    return arguments.length ? (keys = typeof _ === "function" ? _ : constant_default3(Array.from(_)), stack) : keys;
  };
  stack.value = function(_) {
    return arguments.length ? (value = typeof _ === "function" ? _ : constant_default3(+_), stack) : value;
  };
  stack.order = function(_) {
    return arguments.length ? (order = _ == null ? none_default2 : typeof _ === "function" ? _ : constant_default3(Array.from(_)), stack) : order;
  };
  stack.offset = function(_) {
    return arguments.length ? (offset = _ == null ? none_default : _, stack) : offset;
  };
  return stack;
}
// node_modules/d3-shape/src/offset/expand.js
function expand_default(series, order) {
  if (!((n = series.length) > 0))
    return;
  for (var i, n, j = 0, m = series[0].length, y2;j < m; ++j) {
    for (y2 = i = 0;i < n; ++i)
      y2 += series[i][j][1] || 0;
    if (y2)
      for (i = 0;i < n; ++i)
        series[i][j][1] /= y2;
  }
  none_default(series, order);
}
// node_modules/d3-shape/src/offset/diverging.js
function diverging_default(series, order) {
  if (!((n = series.length) > 0))
    return;
  for (var i, j = 0, d, dy, yp, yn, n, m = series[order[0]].length;j < m; ++j) {
    for (yp = yn = 0, i = 0;i < n; ++i) {
      if ((dy = (d = series[order[i]][j])[1] - d[0]) > 0) {
        d[0] = yp, d[1] = yp += dy;
      } else if (dy < 0) {
        d[1] = yn, d[0] = yn += dy;
      } else {
        d[0] = 0, d[1] = dy;
      }
    }
  }
}
// node_modules/@oai/granola/dist/draw-utils/chart/draw-pie-chart.js
function drawPieChart(ctx, chart, dims, themeMap, chartHoverTargets, hiddenSeriesIndices) {
  const series = chart.series[0];
  if (!series)
    return;
  if (hiddenSeriesIndices?.has(0))
    return;
  const seriesIndex = chart.series.indexOf(series);
  const values = series.values;
  const total = sum(values);
  if (total === 0)
    return;
  const cx = dims.x + dims.width / 2;
  const cy = dims.y + dims.height / 2;
  const radius = Math.min(dims.width, dims.height) / 2;
  const isDoughnut = chart.type === 8 /* CHART_TYPE_DOUGHNUT */;
  const doughnutHolePct = isDoughnut ? Math.max(0, Math.min(100, chart.doughnutOptions?.holeSize ?? 55)) : 0;
  const innerRadius = isDoughnut ? radius * (doughnutHolePct / 100) : 0;
  const arcGen = arc_default().innerRadius(innerRadius).outerRadius(radius).context(ctx);
  const firstSliceAngle = chart.pieOptions?.firstSliceAngle ?? 0;
  const startAngle = firstSliceAngle / 360 * Math.PI * 2;
  const pie = pie_default().sort(null).startAngle(startAngle).endAngle(startAngle + Math.PI * 2);
  const categories = series.categories?.length ? series.categories : chart.categories ?? [];
  ctx.save();
  ctx.translate(cx, cy);
  ctx.lineJoin = "bevel";
  pie(values).forEach((d, i) => {
    const pointIndex = d.index ?? i;
    const clr = getPointFillColor(series, pointIndex, seriesIndex, themeMap, pointIndex);
    const skipFill = pointHasNoFill(series, pointIndex);
    if (!skipFill) {
      if (clr)
        ctx.fillStyle = clr;
      ctx.beginPath();
      arcGen(d);
      ctx.fill();
    }
    const { color: strokeColor, widthPx: strokeWidthPx } = getPointStroke(series, pointIndex, themeMap);
    const effectiveStrokeColor = strokeColor ?? "#fff";
    const effectiveStrokeWidth = strokeWidthPx !== undefined ? strokeWidthPx : 1;
    if (effectiveStrokeWidth > 0) {
      ctx.beginPath();
      arcGen(d);
      ctx.strokeStyle = effectiveStrokeColor;
      ctx.lineWidth = effectiveStrokeWidth;
      ctx.stroke();
    }
    if (chartHoverTargets) {
      const rInner = innerRadius;
      const rOuter = radius;
      const mid = (d.startAngle + d.endAngle) / 2;
      const anchorX = cx + Math.cos(mid) * rOuter;
      const anchorY = cy + Math.sin(mid) * rOuter;
      const category = categories[pointIndex] ?? chart.categories?.[pointIndex] ?? series.name;
      chartHoverTargets.push({
        kind: "pie",
        cx,
        cy,
        rInner,
        rOuter,
        startAngle: d.startAngle,
        endAngle: d.endAngle,
        value: d.value,
        seriesName: series.name,
        category,
        color: clr,
        anchorX,
        anchorY
      });
    }
  });
  ctx.restore();
}

// node_modules/@oai/granola/dist/draw-utils/chart/get-inner-dims.js
function getInnerDims(dims, padding = PADDING) {
  return {
    x: dims.x + padding.left,
    y: dims.y + padding.top,
    width: dims.width - padding.left - padding.right,
    height: dims.height - padding.top - padding.bottom
  };
}

// node_modules/@oai/granola/dist/draw-utils/chart/normalize-chart-categories.js
var ZERO_WIDTH_SPACE = "​";
var hasCategories = (series) => Boolean(series?.categories && series.categories.length > 0);
var getSeriesCategoryCount = (series) => series?.values?.length ?? 0;
function normalizeChartCategories(chart) {
  if (!chart) {
    return;
  }
  if (!Array.isArray(chart.categories)) {
    chart.categories = [];
  }
  if (chart.categories.length > 0) {
    return;
  }
  const withCategories = chart.series.find(hasCategories);
  if (withCategories?.categories) {
    chart.categories = [...withCategories.categories];
    return;
  }
  const maxCount = chart.series.reduce((count3, series) => Math.max(count3, getSeriesCategoryCount(series)), 0);
  if (maxCount <= 0) {
    return;
  }
  chart.categories = Array.from({ length: maxCount }, (_, idx) => ZERO_WIDTH_SPACE.repeat(idx + 1) || ZERO_WIDTH_SPACE);
}

// node_modules/@oai/granola/dist/draw-utils/chart/get-chart-data.js
function getChartData(chartReference, pres) {
  const chartId = chartReference?.id;
  if (!chartId) {
    return null;
  }
  const chart = pres.charts.getById(chartId);
  const chartProto = chart?.toProto() ?? null;
  normalizeChartCategories(chartProto);
  return chartProto;
}

// node_modules/@oai/granola/dist/draw-utils/chart/create-scales-horizontal-bar.js
function createScalesHorizontalBar(chart, dims) {
  const categories = chart.categories.length > 0 ? chart.categories : chart.series[0]?.categories ?? [];
  const domain = computeBarDomain(chart);
  const defaultMin = domain.min;
  const defaultMax = domain.max;
  const userMin = chart.yAxis?.min;
  const userMax = chart.yAxis?.max;
  const rawMin = userMin !== undefined ? userMin : defaultMin;
  const rawMax = userMax !== undefined ? userMax : defaultMax;
  const domainMin = Math.min(0, rawMin);
  const domainMax = Math.max(0, rawMax);
  const x2 = linear2().domain([domainMin, domainMax]).range([dims.x, dims.x + dims.width]);
  if (userMin === undefined || userMax === undefined) {
    x2.nice();
  }
  const gap = chart.barOptions?.gapWidth;
  const paddingInner = typeof gap === "number" && isFinite(gap) ? 1 - 1 / (1 + gap / 100) : BAR_PADDING_INNER;
  const y2 = band().domain([...categories].reverse()).range([dims.y, dims.y + dims.height]).paddingInner(paddingInner).paddingOuter(0.5);
  return { x: x2, y: y2 };
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-axes-horizontal-bar.js
var AXIS_GRIDLINE_EPSILON_PX2 = 0.5;
function overlapsAxisLine2(a, b) {
  return Math.abs(a - b) <= AXIS_GRIDLINE_EPSILON_PX2;
}
function drawAxesHorizontalBar(ctx, chart, scales, dims, drawVerticalGuides = true, themeMap) {
  const { x: x2, y: y2 } = scales;
  const categories = chart.categories.length > 0 ? chart.categories : chart.series[0]?.categories ?? [];
  ctx.save();
  ctx.lineWidth = 1;
  const yAxisConfig = chart.yAxis;
  const yAxisDeleted = !!yAxisConfig?.deleted;
  if (!yAxisDeleted) {
    const yStyles = getAxisStyles(chart.yAxis, themeMap);
    ctx.font = `${yStyles.fontSize}px ${FONT_FAMILY}`;
    ctx.fillStyle = yStyles.textColor;
    ctx.strokeStyle = yStyles.lineColor;
    ctx.textAlign = "right";
    ctx.textBaseline = "middle";
    if (chart.yAxis?.line?.fill?.color) {
      ctx.beginPath();
      ctx.moveTo(dims.x, dims.y);
      ctx.lineTo(dims.x, dims.y + dims.height);
      ctx.stroke();
    }
    const labelMaxWidth = Math.min(140, Math.max(0, dims.x - 10));
    const yExtras = getAxisRenderExtras(yAxisConfig);
    const hideLabels = shouldHideAxisTickLabels(yAxisConfig);
    const step = yExtras.tickLabelInterval !== undefined && yExtras.tickLabelInterval > 0 ? Math.floor(yExtras.tickLabelInterval) : 1;
    const extraDistancePx = getAxisTickLabelDistancePx(yAxisConfig);
    const yHasTicks = yAxisConfig?.majorTickMark !== undefined && yAxisConfig.majorTickMark !== 0 /* TICK_MARK_UNSPECIFIED */ && yAxisConfig.majorTickMark !== 1 /* TICK_MARK_NONE */;
    categories.forEach((cat, idx) => {
      const cy = (y2(cat) ?? 0) + y2.bandwidth() / 2;
      if (yHasTicks) {
        ctx.beginPath();
        ctx.moveTo(dims.x - 4, cy);
        ctx.lineTo(dims.x, cy);
        ctx.stroke();
      }
      if (!hideLabels && (step <= 1 || idx % step === 0)) {
        const text = ellipsize(ctx, cat, labelMaxWidth);
        ctx.fillText(text, dims.x - 6 - extraDistancePx, cy);
      }
    });
  }
  const xAxisConfig = chart.xAxis;
  const xAxisDeleted = !!xAxisConfig?.deleted;
  if (!xAxisDeleted) {
    const xStyles = getAxisStyles(chart.xAxis, themeMap);
    ctx.font = `${xStyles.fontSize}px ${FONT_FAMILY}`;
    ctx.fillStyle = xStyles.textColor;
    ctx.strokeStyle = xStyles.lineColor;
    ctx.textAlign = "center";
    ctx.textBaseline = "top";
    const baselineY = dims.y + dims.height;
    ctx.beginPath();
    ctx.moveTo(dims.x, baselineY);
    ctx.lineTo(dims.x + dims.width, baselineY);
    ctx.stroke();
    const tickFormat2 = locale2.format(".2~f");
    const drawGridLines = drawVerticalGuides && !!chart.xAxis?.majorGridlines?.fill?.color;
    x2.ticks(5).forEach((tick) => {
      const px = x2(tick);
      ctx.beginPath();
      ctx.moveTo(px, baselineY);
      ctx.lineTo(px, baselineY + 4);
      ctx.stroke();
      if (drawGridLines && !overlapsAxisLine2(px, dims.x)) {
        ctx.save();
        applyLineStyle(ctx, chart.xAxis?.majorGridlines, themeMap, {
          color: xStyles.gridLineColor ?? xStyles.lineColor,
          widthPx: 1
        });
        ctx.beginPath();
        ctx.moveTo(px, dims.y);
        ctx.lineTo(px, baselineY);
        ctx.stroke();
        ctx.restore();
      }
      ctx.fillText(tickFormat2(tick), px, baselineY + 6);
    });
  }
  ctx.restore();
}

// node_modules/@oai/granola/dist/draw-utils/chart/prepare-bar-data.js
function getCategories2(chart) {
  if (chart.categories.length > 0) {
    return chart.categories;
  }
  const firstSeriesCategories = chart.series[0]?.categories;
  return firstSeriesCategories && firstSeriesCategories.length > 0 ? firstSeriesCategories : [];
}
function prepareBarData(chart, hiddenSeriesIndices) {
  const categories = getCategories2(chart);
  const visibleSeries = chart.series.map((_, index) => index).filter((index) => !hiddenSeriesIndices?.has(index));
  const grouping = chart.barOptions?.grouping;
  const mode = grouping === 2 /* BAR_GROUPING_STACKED */ ? "stacked" : grouping === 3 /* BAR_GROUPING_PERCENT_STACKED */ ? "percent" : "clustered";
  const segmentsByCategory = categories.map(() => []);
  if (mode === "clustered" || visibleSeries.length === 0) {
    categories.forEach((_, categoryIndex) => {
      visibleSeries.forEach((seriesIndex) => {
        const series = chart.series[seriesIndex];
        if (!series)
          return;
        const raw = series.values[categoryIndex] ?? 0;
        segmentsByCategory[categoryIndex]?.push({
          seriesIndex,
          valueRaw: raw,
          start: 0,
          end: raw
        });
      });
    });
    return {
      categories,
      visibleSeries,
      mode,
      segmentsByCategory
    };
  }
  const records = categories.map((_, categoryIndex) => {
    const record = {};
    visibleSeries.forEach((seriesIndex) => {
      const series = chart.series[seriesIndex];
      record[String(seriesIndex)] = series?.values[categoryIndex] ?? 0;
    });
    return record;
  });
  const stackGenerator = stack_default().keys(visibleSeries.map((seriesIndex) => String(seriesIndex))).value((d, key) => d[key] ?? 0).order(none_default2);
  if (mode === "percent") {
    stackGenerator.offset(expand_default);
  } else {
    stackGenerator.offset(diverging_default);
  }
  const stacks = stackGenerator(records);
  stacks.forEach((stackLayer) => {
    const key = stackLayer.key;
    const seriesIndex = Number.parseInt(key, 10);
    categories.forEach((_, categoryIndex) => {
      const tuple = stackLayer[categoryIndex];
      if (!tuple)
        return;
      const start = Number.isFinite(tuple[0]) ? tuple[0] : 0;
      const end = Number.isFinite(tuple[1]) ? tuple[1] : 0;
      const raw = chart.series[seriesIndex]?.values[categoryIndex] ?? 0;
      segmentsByCategory[categoryIndex]?.push({
        seriesIndex,
        valueRaw: raw,
        start,
        end
      });
    });
  });
  return {
    categories,
    visibleSeries,
    mode,
    segmentsByCategory
  };
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-bar-chart-horizontal.js
function drawBarChartHorizontal(ctx, chart, scales, themeMap, chartHoverTargets, hiddenSeriesIndices) {
  const { x: x2, y: y2 } = scales;
  const prepared = prepareBarData(chart, hiddenSeriesIndices);
  const categories = prepared.categories;
  const isClustered = prepared.mode === "clustered";
  const overlap = chart.barOptions?.overlap;
  const clusteredInnerPadding = typeof overlap === "number" && isFinite(overlap) ? Math.max(0, Math.min(0.3, 0.1 - overlap / 100 * 0.1)) : 0.1;
  const innerY = isClustered && prepared.visibleSeries.length > 0 ? band().domain(range(prepared.visibleSeries.length)).range([0, y2.bandwidth()]).padding(clusteredInnerPadding) : undefined;
  categories.forEach((cat, catIdx) => {
    const catY = y2(cat);
    if (catY === undefined)
      return;
    const segments = prepared.segmentsByCategory[catIdx];
    if (!segments)
      return;
    const outerPositiveIndex = isClustered || segments.length === 0 ? undefined : segments.reduce((acc, seg, idx) => {
      if (seg.end < seg.start)
        return acc;
      if (acc === undefined)
        return idx;
      const accSeg = segments[acc];
      if (!accSeg)
        return acc;
      return accSeg.end < seg.end ? idx : acc;
    }, undefined);
    const outerNegativeIndex = isClustered || segments.length === 0 ? undefined : segments.reduce((acc, seg, idx) => {
      if (seg.end >= seg.start)
        return acc;
      if (acc === undefined)
        return idx;
      const accSeg = segments[acc];
      if (!accSeg)
        return acc;
      return accSeg.end > seg.end ? idx : acc;
    }, undefined);
    segments.forEach((segment, orderIdx) => {
      const series = chart.series[segment.seriesIndex];
      if (!series)
        return;
      const value = segment.valueRaw;
      const offset = innerY ? innerY(orderIdx) ?? 0 : 0;
      const barY = isClustered ? catY + offset : catY;
      const barHeight = isClustered ? innerY?.bandwidth() ?? 0 : y2.bandwidth();
      const xStart = x2(segment.start);
      const xEnd = x2(segment.end);
      const left = Math.min(xStart, xEnd);
      const right = Math.max(xStart, xEnd);
      const barWidth = Math.abs(right - left);
      const isPositive = segment.end >= segment.start;
      const noFill = pointHasNoFill(series, catIdx);
      const clr = getPointFillColor(series, catIdx, segment.seriesIndex, themeMap);
      const fillPaint = getPointFillPaint(ctx, { x: left, y: barY, width: barWidth, height: barHeight }, series, catIdx, segment.seriesIndex, themeMap);
      if (!noFill && fillPaint)
        ctx.fillStyle = fillPaint;
      const rUser = BAR_CORNER_RADIUS;
      const baseRadius = Math.max(0, Math.min(rUser, barHeight / 2, barWidth));
      const shouldRound = isClustered || (segment.end >= segment.start ? orderIdx === outerPositiveIndex : orderIdx === outerNegativeIndex);
      const r = shouldRound ? baseRadius : 0;
      ctx.beginPath();
      if (isPositive) {
        ctx.moveTo(left, barY);
        ctx.lineTo(right - r, barY);
        ctx.arcTo(right, barY, right, barY + r, r);
        ctx.lineTo(right, barY + barHeight - r);
        ctx.arcTo(right, barY + barHeight, right - r, barY + barHeight, r);
        ctx.lineTo(left, barY + barHeight);
        ctx.closePath();
      } else {
        ctx.moveTo(right, barY);
        ctx.lineTo(left + r, barY);
        ctx.arcTo(left, barY, left, barY + r, r);
        ctx.lineTo(left, barY + barHeight - r);
        ctx.arcTo(left, barY + barHeight, left + r, barY + barHeight, r);
        ctx.lineTo(right, barY + barHeight);
        ctx.closePath();
      }
      if (!noFill && fillPaint)
        ctx.fill();
      const { color: strokeColor, widthPx } = getPointStroke(series, catIdx, themeMap);
      if (strokeColor) {
        ctx.strokeStyle = strokeColor;
        ctx.lineWidth = widthPx ?? 1;
        ctx.stroke();
      }
      if (chartHoverTargets) {
        const anchorX = isPositive ? right : left;
        chartHoverTargets.push({
          kind: "bar-horizontal",
          x: left,
          y: barY,
          width: barWidth,
          height: barHeight,
          seriesName: series.name,
          category: cat,
          value,
          color: clr,
          anchorX,
          anchorY: barY
        });
      }
      if (chart.dataLabels?.showValue && barHeight > 0) {
        const pos = chart.dataLabels.position;
        const label = locale2.format(".2~f")(value);
        const fs2 = chart.dataLabels.textStyle?.fontSize ? fontSizeToPx(chart.dataLabels.textStyle.fontSize) : TICK_FONT_SIZE;
        const lblColor = chart.dataLabels.textStyle?.fill?.color ? resolveColor(chart.dataLabels.textStyle.fill.color, themeMap) : AXIS_COLOR;
        ctx.fillStyle = lblColor;
        ctx.font = `${fs2}px ${FONT_FAMILY}`;
        ctx.textBaseline = "middle";
        let tx = isPositive ? right + 4 : left - 4;
        if (pos === 2) {
          tx = isPositive ? right - 4 : left + 4;
        }
        if (pos === 3) {
          tx = left + barWidth / 2;
        }
        if (pos === 3) {
          ctx.textAlign = "center";
        } else if (pos === 2) {
          ctx.textAlign = isPositive ? "right" : "left";
        } else {
          ctx.textAlign = isPositive ? "left" : "right";
        }
        const ty = barY + barHeight / 2;
        ctx.fillText(label, tx, ty);
      }
    });
  });
}

// node_modules/@oai/granola/dist/draw-utils/chart/resolve-data-label.js
function readPositionName(v) {
  if (!v || typeof v !== "object")
    return;
  const maybe = v["positionName"];
  return typeof maybe === "string" && maybe.trim().length > 0 ? maybe : undefined;
}
function resolveDataLabel(chart, series, pointIndex, value) {
  const chartDL = chart.dataLabels;
  const seriesDL = series.dataLabels;
  const ptDL = series.dataLabelOverrides?.find((d) => d.idx === pointIndex);
  const showValue = ptDL?.showValue ?? seriesDL?.showValue ?? chartDL?.showValue ?? false;
  const position = ptDL?.position ?? seriesDL?.position ?? chartDL?.position ?? 1 /* DATA_LABEL_POSITION_OUT_END */;
  const positionName = readPositionName(ptDL) ?? readPositionName(seriesDL) ?? readPositionName(chartDL);
  let text = ptDL?.text ?? "";
  if (!text) {
    const formatCode = series.valuesFormatCode ?? undefined;
    text = formatValue(value, formatCode);
  }
  const textStyle = ptDL?.textStyle ?? seriesDL?.textStyle ?? chartDL?.textStyle ?? undefined;
  return { show: showValue, position, positionName, text, textStyle };
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-data-label.js
function resolvePositionName(positionName) {
  if (!positionName)
    return;
  const normalized = positionName.trim();
  return normalized.length ? normalized : undefined;
}
function drawDataLabel(ctx, text, position, positionName, textStyle, themeMap, anchor, opts = {}) {
  const fs2 = textStyle?.fontSize ? fontSizeToPx(textStyle.fontSize) : TICK_FONT_SIZE;
  const lblColor = textStyle?.fill?.color ? resolveColor(textStyle.fill.color, themeMap) : AXIS_COLOR;
  const isBold = textStyle?.bold ?? true;
  ctx.save();
  ctx.fillStyle = lblColor;
  ctx.font = `${isBold ? "bold " : ""}${fs2}px ${FONT_FAMILY}`;
  ctx.textBaseline = "middle";
  ctx.textAlign = "center";
  const posName = resolvePositionName(positionName)?.toLowerCase();
  const callout = opts.callout || posName === "datacallout";
  const padding = 4;
  const textWidth = ctx.measureText(text).width;
  const labelW = textWidth + padding * 2;
  const labelH = fs2 + padding * 2;
  const box = opts.box;
  const isPositive = opts.isPositive ?? true;
  let x2 = anchor.x;
  let y2 = anchor.y;
  let resolved = position ?? 1 /* DATA_LABEL_POSITION_OUT_END */;
  if (posName === "inbase") {
    resolved = "inbase";
  } else if (posName === "center") {
    resolved = 3 /* DATA_LABEL_POSITION_CENTER */;
  } else if (posName === "inend") {
    resolved = 2 /* DATA_LABEL_POSITION_IN_END */;
  } else if (posName === "outend") {
    resolved = 1 /* DATA_LABEL_POSITION_OUT_END */;
  }
  if (box) {
    switch (resolved) {
      case "inbase":
        x2 = box.x + box.width / 2;
        y2 = isPositive ? box.y + box.height - labelH / 2 : box.y + labelH / 2;
        break;
      case 2 /* DATA_LABEL_POSITION_IN_END */:
        x2 = box.x + box.width / 2;
        y2 = isPositive ? box.y + labelH / 2 : box.y + box.height - labelH / 2;
        break;
      case 3 /* DATA_LABEL_POSITION_CENTER */:
        x2 = box.x + box.width / 2;
        y2 = box.y + box.height / 2;
        break;
      case 1 /* DATA_LABEL_POSITION_OUT_END */:
      default:
        x2 = box.x + box.width / 2;
        y2 = isPositive ? box.y - labelH / 2 - 4 : box.y + box.height + labelH / 2 + 4;
        break;
    }
  } else {
    switch (resolved) {
      case "inbase":
      case 2 /* DATA_LABEL_POSITION_IN_END */:
        x2 = anchor.x;
        y2 = anchor.y + labelH / 2 + 6;
        break;
      case 3 /* DATA_LABEL_POSITION_CENTER */:
        x2 = anchor.x;
        y2 = anchor.y;
        break;
      case 1 /* DATA_LABEL_POSITION_OUT_END */:
      default:
        x2 = anchor.x;
        y2 = anchor.y - labelH / 2 - 6;
        break;
    }
  }
  if (callout) {
    const r = 3;
    const rectX = x2 - labelW / 2;
    const rectY = y2 - labelH / 2;
    ctx.save();
    ctx.globalAlpha = 0.92;
    ctx.fillStyle = "#ffffff";
    ctx.beginPath();
    ctx.moveTo(rectX + r, rectY);
    ctx.lineTo(rectX + labelW - r, rectY);
    ctx.quadraticCurveTo(rectX + labelW, rectY, rectX + labelW, rectY + r);
    ctx.lineTo(rectX + labelW, rectY + labelH - r);
    ctx.quadraticCurveTo(rectX + labelW, rectY + labelH, rectX + labelW - r, rectY + labelH);
    ctx.lineTo(rectX + r, rectY + labelH);
    ctx.quadraticCurveTo(rectX, rectY + labelH, rectX, rectY + labelH - r);
    ctx.lineTo(rectX, rectY + r);
    ctx.quadraticCurveTo(rectX, rectY, rectX + r, rectY);
    ctx.closePath();
    ctx.fill();
    ctx.restore();
    ctx.save();
    ctx.strokeStyle = "#b0b0b0";
    ctx.lineWidth = 0.75;
    ctx.setLineDash([]);
    ctx.stroke();
    ctx.restore();
    ctx.save();
    ctx.strokeStyle = "#b0b0b0";
    ctx.lineWidth = 0.75;
    ctx.setLineDash([]);
    ctx.beginPath();
    ctx.moveTo(anchor.x, anchor.y);
    ctx.lineTo(x2, y2);
    ctx.stroke();
    ctx.restore();
  }
  ctx.fillStyle = lblColor;
  ctx.fillText(text, x2, y2);
  ctx.restore();
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-bar-chart.js
function drawBarChart(ctx, chart, scales, themeMap, chartHoverTargets, hiddenSeriesIndices) {
  if (!isBandScale(scales.x))
    return;
  const x2 = scales.x;
  const y2 = scales.y;
  const prepared = prepareBarData(chart, hiddenSeriesIndices);
  const categories = prepared.categories;
  const isClustered = prepared.mode === "clustered";
  const overlap = chart.barOptions?.overlap;
  const clusteredInnerPadding = typeof overlap === "number" && isFinite(overlap) ? Math.max(0, Math.min(0.3, 0.1 - overlap / 100 * 0.1)) : 0.1;
  const innerX = isClustered && prepared.visibleSeries.length > 0 ? band().domain(range(prepared.visibleSeries.length)).range([0, x2.bandwidth()]).padding(clusteredInnerPadding) : undefined;
  categories.forEach((cat, catIdx) => {
    const catX = x2(cat);
    if (catX === undefined)
      return;
    const segments = prepared.segmentsByCategory[catIdx];
    const topPositiveIndex = isClustered || segments?.length === 0 ? undefined : segments?.reduce((acc, seg, idx) => {
      if (seg.end < seg.start)
        return acc;
      if (acc === undefined)
        return idx;
      const accSeg = segments[acc];
      if (!accSeg)
        return acc;
      return accSeg.end < seg.end ? idx : acc;
    }, undefined);
    const bottomNegativeIndex = isClustered || segments?.length === 0 ? undefined : segments?.reduce((acc, seg, idx) => {
      if (seg.end >= seg.start)
        return acc;
      if (acc === undefined)
        return idx;
      const accSeg = segments[acc];
      if (!accSeg)
        return acc;
      return accSeg.end > seg.end ? idx : acc;
    }, undefined);
    segments?.forEach((segment, orderIdx) => {
      const series = chart.series[segment.seriesIndex];
      if (!series)
        return;
      const value = segment.valueRaw;
      const noFill = pointHasNoFill(series, catIdx);
      const fillClr = getPointFillColor(series, catIdx, segment.seriesIndex, themeMap);
      const innerOffset = innerX !== undefined ? innerX(orderIdx) ?? 0 : 0;
      const barBaseX = isClustered ? catX + innerOffset : catX;
      const barWidth = isClustered ? innerX !== undefined ? innerX.bandwidth() : 0 : x2.bandwidth();
      const yStart = y2(segment.start);
      const yEnd = y2(segment.end);
      const barTop = Math.min(yStart, yEnd);
      const barHeight = Math.abs(yEnd - yStart);
      const barBottom = barTop + barHeight;
      const fillPaint = getPointFillPaint(ctx, {
        x: barBaseX,
        y: Math.min(barTop, barBottom),
        width: barWidth,
        height: barHeight
      }, series, catIdx, segment.seriesIndex, themeMap);
      const rUser = BAR_CORNER_RADIUS;
      const baseRadius = Math.max(0, Math.min(rUser, barWidth / 2, barHeight));
      const shouldRound = isClustered || (segment.end >= segment.start ? orderIdx === topPositiveIndex : orderIdx === bottomNegativeIndex);
      const r = shouldRound ? baseRadius : 0;
      ctx.beginPath();
      if (value >= 0) {
        ctx.moveTo(barBaseX, barBottom);
        ctx.lineTo(barBaseX, barTop + r);
        ctx.arcTo(barBaseX, barTop, barBaseX + r, barTop, r);
        ctx.lineTo(barBaseX + barWidth - r, barTop);
        ctx.arcTo(barBaseX + barWidth, barTop, barBaseX + barWidth, barTop + r, r);
        ctx.lineTo(barBaseX + barWidth, barBottom);
        ctx.closePath();
      } else {
        ctx.moveTo(barBaseX, barTop);
        ctx.lineTo(barBaseX, barBottom - r);
        ctx.arcTo(barBaseX, barBottom, barBaseX + r, barBottom, r);
        ctx.lineTo(barBaseX + barWidth - r, barBottom);
        ctx.arcTo(barBaseX + barWidth, barBottom, barBaseX + barWidth, barBottom - r, r);
        ctx.lineTo(barBaseX + barWidth, barTop);
        ctx.closePath();
      }
      if (!noFill && fillPaint) {
        ctx.fillStyle = fillPaint;
        ctx.fill();
      }
      const { color: strokeColor, widthPx } = getPointStroke(series, catIdx, themeMap);
      if (strokeColor) {
        ctx.strokeStyle = strokeColor;
        ctx.lineWidth = widthPx ?? 1;
        ctx.stroke();
      }
      if (chartHoverTargets) {
        const topY = Math.min(barTop, barBottom);
        chartHoverTargets.push({
          kind: "bar-vertical",
          x: barBaseX,
          y: barTop,
          width: barWidth,
          height: barHeight,
          seriesName: series.name,
          category: cat,
          value,
          color: fillClr,
          anchorX: barBaseX + barWidth,
          anchorY: topY
        });
      }
      const dataLabel = resolveDataLabel(chart, series, catIdx, value);
      if (dataLabel.show && barWidth > 0) {
        const isPositive = value >= 0;
        drawDataLabel(ctx, dataLabel.text, dataLabel.position, dataLabel.positionName, dataLabel.textStyle, themeMap, { x: barBaseX + barWidth / 2, y: barTop }, {
          box: {
            x: barBaseX,
            y: Math.min(barTop, barBottom),
            width: barWidth,
            height: barHeight
          },
          isPositive
        });
      }
    });
  });
}

// node_modules/three/build/three.core.js
var REVISION = "179";
var FrontSide = 0;
var BackSide = 1;
var NormalBlending = 1;
var AddEquation = 100;
var SrcAlphaFactor = 204;
var OneMinusSrcAlphaFactor = 205;
var NeverDepth = 0;
var AlwaysDepth = 1;
var LessDepth = 2;
var LessEqualDepth = 3;
var EqualDepth = 4;
var GreaterEqualDepth = 5;
var GreaterDepth = 6;
var NotEqualDepth = 7;
var MultiplyOperation = 0;
var UVMapping = 300;
var RepeatWrapping = 1000;
var ClampToEdgeWrapping = 1001;
var MirroredRepeatWrapping = 1002;
var LinearFilter = 1006;
var LinearMipmapLinearFilter = 1008;
var UnsignedByteType = 1009;
var FloatType = 1015;
var RGBAFormat = 1023;
var InterpolateDiscrete = 2300;
var InterpolateLinear = 2301;
var InterpolateSmooth = 2302;
var ZeroCurvatureEnding = 2400;
var ZeroSlopeEnding = 2401;
var WrapAroundEnding = 2402;
var TangentSpaceNormalMap = 0;
var NoColorSpace = "";
var SRGBColorSpace = "srgb";
var LinearSRGBColorSpace = "srgb-linear";
var LinearTransfer = "linear";
var SRGBTransfer = "srgb";
var KeepStencilOp = 7680;
var AlwaysStencilFunc = 519;
var StaticDrawUsage = 35044;
var WebGLCoordinateSystem = 2000;
var WebGPUCoordinateSystem = 2001;
class EventDispatcher {
  addEventListener(type, listener) {
    if (this._listeners === undefined)
      this._listeners = {};
    const listeners = this._listeners;
    if (listeners[type] === undefined) {
      listeners[type] = [];
    }
    if (listeners[type].indexOf(listener) === -1) {
      listeners[type].push(listener);
    }
  }
  hasEventListener(type, listener) {
    const listeners = this._listeners;
    if (listeners === undefined)
      return false;
    return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  }
  removeEventListener(type, listener) {
    const listeners = this._listeners;
    if (listeners === undefined)
      return;
    const listenerArray = listeners[type];
    if (listenerArray !== undefined) {
      const index = listenerArray.indexOf(listener);
      if (index !== -1) {
        listenerArray.splice(index, 1);
      }
    }
  }
  dispatchEvent(event) {
    const listeners = this._listeners;
    if (listeners === undefined)
      return;
    const listenerArray = listeners[event.type];
    if (listenerArray !== undefined) {
      event.target = this;
      const array2 = listenerArray.slice(0);
      for (let i = 0, l = array2.length;i < l; i++) {
        array2[i].call(this, event);
      }
      event.target = null;
    }
  }
}
var _lut = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"];
var _seed = 1234567;
var DEG2RAD = Math.PI / 180;
var RAD2DEG = 180 / Math.PI;
function generateUUID() {
  const d0 = Math.random() * 4294967295 | 0;
  const d1 = Math.random() * 4294967295 | 0;
  const d2 = Math.random() * 4294967295 | 0;
  const d3 = Math.random() * 4294967295 | 0;
  const uuid = _lut[d0 & 255] + _lut[d0 >> 8 & 255] + _lut[d0 >> 16 & 255] + _lut[d0 >> 24 & 255] + "-" + _lut[d1 & 255] + _lut[d1 >> 8 & 255] + "-" + _lut[d1 >> 16 & 15 | 64] + _lut[d1 >> 24 & 255] + "-" + _lut[d2 & 63 | 128] + _lut[d2 >> 8 & 255] + "-" + _lut[d2 >> 16 & 255] + _lut[d2 >> 24 & 255] + _lut[d3 & 255] + _lut[d3 >> 8 & 255] + _lut[d3 >> 16 & 255] + _lut[d3 >> 24 & 255];
  return uuid.toLowerCase();
}
function clamp3(value, min2, max3) {
  return Math.max(min2, Math.min(max3, value));
}
function euclideanModulo(n, m) {
  return (n % m + m) % m;
}
function mapLinear(x2, a1, a2, b1, b2) {
  return b1 + (x2 - a1) * (b2 - b1) / (a2 - a1);
}
function inverseLerp(x2, y2, value) {
  if (x2 !== y2) {
    return (value - x2) / (y2 - x2);
  } else {
    return 0;
  }
}
function lerp(x2, y2, t) {
  return (1 - t) * x2 + t * y2;
}
function damp(x2, y2, lambda, dt) {
  return lerp(x2, y2, 1 - Math.exp(-lambda * dt));
}
function pingpong(x2, length = 1) {
  return length - Math.abs(euclideanModulo(x2, length * 2) - length);
}
function smoothstep(x2, min2, max3) {
  if (x2 <= min2)
    return 0;
  if (x2 >= max3)
    return 1;
  x2 = (x2 - min2) / (max3 - min2);
  return x2 * x2 * (3 - 2 * x2);
}
function smootherstep(x2, min2, max3) {
  if (x2 <= min2)
    return 0;
  if (x2 >= max3)
    return 1;
  x2 = (x2 - min2) / (max3 - min2);
  return x2 * x2 * x2 * (x2 * (x2 * 6 - 15) + 10);
}
function randInt(low, high) {
  return low + Math.floor(Math.random() * (high - low + 1));
}
function randFloat(low, high) {
  return low + Math.random() * (high - low);
}
function randFloatSpread(range2) {
  return range2 * (0.5 - Math.random());
}
function seededRandom(s) {
  if (s !== undefined)
    _seed = s;
  let t = _seed += 1831565813;
  t = Math.imul(t ^ t >>> 15, t | 1);
  t ^= t + Math.imul(t ^ t >>> 7, t | 61);
  return ((t ^ t >>> 14) >>> 0) / 4294967296;
}
function degToRad(degrees) {
  return degrees * DEG2RAD;
}
function radToDeg(radians) {
  return radians * RAD2DEG;
}
function isPowerOfTwo(value) {
  return (value & value - 1) === 0 && value !== 0;
}
function ceilPowerOfTwo(value) {
  return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
}
function floorPowerOfTwo(value) {
  return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
}
function setQuaternionFromProperEuler(q, a, b, c, order) {
  const cos2 = Math.cos;
  const sin2 = Math.sin;
  const c2 = cos2(b / 2);
  const s2 = sin2(b / 2);
  const c13 = cos2((a + c) / 2);
  const s13 = sin2((a + c) / 2);
  const c1_3 = cos2((a - c) / 2);
  const s1_3 = sin2((a - c) / 2);
  const c3_1 = cos2((c - a) / 2);
  const s3_1 = sin2((c - a) / 2);
  switch (order) {
    case "XYX":
      q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
      break;
    case "YZY":
      q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
      break;
    case "ZXZ":
      q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
      break;
    case "XZX":
      q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
      break;
    case "YXY":
      q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
      break;
    case "ZYZ":
      q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
      break;
    default:
      console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + order);
  }
}
function denormalize(value, array2) {
  switch (array2.constructor) {
    case Float32Array:
      return value;
    case Uint32Array:
      return value / 4294967295;
    case Uint16Array:
      return value / 65535;
    case Uint8Array:
      return value / 255;
    case Int32Array:
      return Math.max(value / 2147483647, -1);
    case Int16Array:
      return Math.max(value / 32767, -1);
    case Int8Array:
      return Math.max(value / 127, -1);
    default:
      throw new Error("Invalid component type.");
  }
}
function normalize2(value, array2) {
  switch (array2.constructor) {
    case Float32Array:
      return value;
    case Uint32Array:
      return Math.round(value * 4294967295);
    case Uint16Array:
      return Math.round(value * 65535);
    case Uint8Array:
      return Math.round(value * 255);
    case Int32Array:
      return Math.round(value * 2147483647);
    case Int16Array:
      return Math.round(value * 32767);
    case Int8Array:
      return Math.round(value * 127);
    default:
      throw new Error("Invalid component type.");
  }
}
var MathUtils = {
  DEG2RAD,
  RAD2DEG,
  generateUUID,
  clamp: clamp3,
  euclideanModulo,
  mapLinear,
  inverseLerp,
  lerp,
  damp,
  pingpong,
  smoothstep,
  smootherstep,
  randInt,
  randFloat,
  randFloatSpread,
  seededRandom,
  degToRad,
  radToDeg,
  isPowerOfTwo,
  ceilPowerOfTwo,
  floorPowerOfTwo,
  setQuaternionFromProperEuler,
  normalize: normalize2,
  denormalize
};

class Vector2 {
  constructor(x2 = 0, y2 = 0) {
    Vector2.prototype.isVector2 = true;
    this.x = x2;
    this.y = y2;
  }
  get width() {
    return this.x;
  }
  set width(value) {
    this.x = value;
  }
  get height() {
    return this.y;
  }
  set height(value) {
    this.y = value;
  }
  set(x2, y2) {
    this.x = x2;
    this.y = y2;
    return this;
  }
  setScalar(scalar) {
    this.x = scalar;
    this.y = scalar;
    return this;
  }
  setX(x2) {
    this.x = x2;
    return this;
  }
  setY(y2) {
    this.y = y2;
    return this;
  }
  setComponent(index, value) {
    switch (index) {
      case 0:
        this.x = value;
        break;
      case 1:
        this.y = value;
        break;
      default:
        throw new Error("index is out of range: " + index);
    }
    return this;
  }
  getComponent(index) {
    switch (index) {
      case 0:
        return this.x;
      case 1:
        return this.y;
      default:
        throw new Error("index is out of range: " + index);
    }
  }
  clone() {
    return new this.constructor(this.x, this.y);
  }
  copy(v) {
    this.x = v.x;
    this.y = v.y;
    return this;
  }
  add(v) {
    this.x += v.x;
    this.y += v.y;
    return this;
  }
  addScalar(s) {
    this.x += s;
    this.y += s;
    return this;
  }
  addVectors(a, b) {
    this.x = a.x + b.x;
    this.y = a.y + b.y;
    return this;
  }
  addScaledVector(v, s) {
    this.x += v.x * s;
    this.y += v.y * s;
    return this;
  }
  sub(v) {
    this.x -= v.x;
    this.y -= v.y;
    return this;
  }
  subScalar(s) {
    this.x -= s;
    this.y -= s;
    return this;
  }
  subVectors(a, b) {
    this.x = a.x - b.x;
    this.y = a.y - b.y;
    return this;
  }
  multiply(v) {
    this.x *= v.x;
    this.y *= v.y;
    return this;
  }
  multiplyScalar(scalar) {
    this.x *= scalar;
    this.y *= scalar;
    return this;
  }
  divide(v) {
    this.x /= v.x;
    this.y /= v.y;
    return this;
  }
  divideScalar(scalar) {
    return this.multiplyScalar(1 / scalar);
  }
  applyMatrix3(m) {
    const x2 = this.x, y2 = this.y;
    const e = m.elements;
    this.x = e[0] * x2 + e[3] * y2 + e[6];
    this.y = e[1] * x2 + e[4] * y2 + e[7];
    return this;
  }
  min(v) {
    this.x = Math.min(this.x, v.x);
    this.y = Math.min(this.y, v.y);
    return this;
  }
  max(v) {
    this.x = Math.max(this.x, v.x);
    this.y = Math.max(this.y, v.y);
    return this;
  }
  clamp(min2, max3) {
    this.x = clamp3(this.x, min2.x, max3.x);
    this.y = clamp3(this.y, min2.y, max3.y);
    return this;
  }
  clampScalar(minVal, maxVal) {
    this.x = clamp3(this.x, minVal, maxVal);
    this.y = clamp3(this.y, minVal, maxVal);
    return this;
  }
  clampLength(min2, max3) {
    const length = this.length();
    return this.divideScalar(length || 1).multiplyScalar(clamp3(length, min2, max3));
  }
  floor() {
    this.x = Math.floor(this.x);
    this.y = Math.floor(this.y);
    return this;
  }
  ceil() {
    this.x = Math.ceil(this.x);
    this.y = Math.ceil(this.y);
    return this;
  }
  round() {
    this.x = Math.round(this.x);
    this.y = Math.round(this.y);
    return this;
  }
  roundToZero() {
    this.x = Math.trunc(this.x);
    this.y = Math.trunc(this.y);
    return this;
  }
  negate() {
    this.x = -this.x;
    this.y = -this.y;
    return this;
  }
  dot(v) {
    return this.x * v.x + this.y * v.y;
  }
  cross(v) {
    return this.x * v.y - this.y * v.x;
  }
  lengthSq() {
    return this.x * this.x + this.y * this.y;
  }
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y);
  }
  manhattanLength() {
    return Math.abs(this.x) + Math.abs(this.y);
  }
  normalize() {
    return this.divideScalar(this.length() || 1);
  }
  angle() {
    const angle = Math.atan2(-this.y, -this.x) + Math.PI;
    return angle;
  }
  angleTo(v) {
    const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
    if (denominator === 0)
      return Math.PI / 2;
    const theta = this.dot(v) / denominator;
    return Math.acos(clamp3(theta, -1, 1));
  }
  distanceTo(v) {
    return Math.sqrt(this.distanceToSquared(v));
  }
  distanceToSquared(v) {
    const dx = this.x - v.x, dy = this.y - v.y;
    return dx * dx + dy * dy;
  }
  manhattanDistanceTo(v) {
    return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  }
  setLength(length) {
    return this.normalize().multiplyScalar(length);
  }
  lerp(v, alpha) {
    this.x += (v.x - this.x) * alpha;
    this.y += (v.y - this.y) * alpha;
    return this;
  }
  lerpVectors(v1, v2, alpha) {
    this.x = v1.x + (v2.x - v1.x) * alpha;
    this.y = v1.y + (v2.y - v1.y) * alpha;
    return this;
  }
  equals(v) {
    return v.x === this.x && v.y === this.y;
  }
  fromArray(array2, offset = 0) {
    this.x = array2[offset];
    this.y = array2[offset + 1];
    return this;
  }
  toArray(array2 = [], offset = 0) {
    array2[offset] = this.x;
    array2[offset + 1] = this.y;
    return array2;
  }
  fromBufferAttribute(attribute, index) {
    this.x = attribute.getX(index);
    this.y = attribute.getY(index);
    return this;
  }
  rotateAround(center, angle) {
    const c = Math.cos(angle), s = Math.sin(angle);
    const x2 = this.x - center.x;
    const y2 = this.y - center.y;
    this.x = x2 * c - y2 * s + center.x;
    this.y = x2 * s + y2 * c + center.y;
    return this;
  }
  random() {
    this.x = Math.random();
    this.y = Math.random();
    return this;
  }
  *[Symbol.iterator]() {
    yield this.x;
    yield this.y;
  }
}

class Quaternion {
  constructor(x2 = 0, y2 = 0, z = 0, w = 1) {
    this.isQuaternion = true;
    this._x = x2;
    this._y = y2;
    this._z = z;
    this._w = w;
  }
  static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
    let x0 = src0[srcOffset0 + 0], y0 = src0[srcOffset0 + 1], z0 = src0[srcOffset0 + 2], w0 = src0[srcOffset0 + 3];
    const x1 = src1[srcOffset1 + 0], y1 = src1[srcOffset1 + 1], z1 = src1[srcOffset1 + 2], w1 = src1[srcOffset1 + 3];
    if (t === 0) {
      dst[dstOffset + 0] = x0;
      dst[dstOffset + 1] = y0;
      dst[dstOffset + 2] = z0;
      dst[dstOffset + 3] = w0;
      return;
    }
    if (t === 1) {
      dst[dstOffset + 0] = x1;
      dst[dstOffset + 1] = y1;
      dst[dstOffset + 2] = z1;
      dst[dstOffset + 3] = w1;
      return;
    }
    if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
      let s = 1 - t;
      const cos2 = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, dir = cos2 >= 0 ? 1 : -1, sqrSin = 1 - cos2 * cos2;
      if (sqrSin > Number.EPSILON) {
        const sin2 = Math.sqrt(sqrSin), len = Math.atan2(sin2, cos2 * dir);
        s = Math.sin(s * len) / sin2;
        t = Math.sin(t * len) / sin2;
      }
      const tDir = t * dir;
      x0 = x0 * s + x1 * tDir;
      y0 = y0 * s + y1 * tDir;
      z0 = z0 * s + z1 * tDir;
      w0 = w0 * s + w1 * tDir;
      if (s === 1 - t) {
        const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
        x0 *= f;
        y0 *= f;
        z0 *= f;
        w0 *= f;
      }
    }
    dst[dstOffset] = x0;
    dst[dstOffset + 1] = y0;
    dst[dstOffset + 2] = z0;
    dst[dstOffset + 3] = w0;
  }
  static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
    const x0 = src0[srcOffset0];
    const y0 = src0[srcOffset0 + 1];
    const z0 = src0[srcOffset0 + 2];
    const w0 = src0[srcOffset0 + 3];
    const x1 = src1[srcOffset1];
    const y1 = src1[srcOffset1 + 1];
    const z1 = src1[srcOffset1 + 2];
    const w1 = src1[srcOffset1 + 3];
    dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
    dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
    dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
    dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
    return dst;
  }
  get x() {
    return this._x;
  }
  set x(value) {
    this._x = value;
    this._onChangeCallback();
  }
  get y() {
    return this._y;
  }
  set y(value) {
    this._y = value;
    this._onChangeCallback();
  }
  get z() {
    return this._z;
  }
  set z(value) {
    this._z = value;
    this._onChangeCallback();
  }
  get w() {
    return this._w;
  }
  set w(value) {
    this._w = value;
    this._onChangeCallback();
  }
  set(x2, y2, z, w) {
    this._x = x2;
    this._y = y2;
    this._z = z;
    this._w = w;
    this._onChangeCallback();
    return this;
  }
  clone() {
    return new this.constructor(this._x, this._y, this._z, this._w);
  }
  copy(quaternion) {
    this._x = quaternion.x;
    this._y = quaternion.y;
    this._z = quaternion.z;
    this._w = quaternion.w;
    this._onChangeCallback();
    return this;
  }
  setFromEuler(euler, update = true) {
    const { _x: x2, _y: y2, _z: z, _order: order } = euler;
    const cos2 = Math.cos;
    const sin2 = Math.sin;
    const c1 = cos2(x2 / 2);
    const c2 = cos2(y2 / 2);
    const c3 = cos2(z / 2);
    const s1 = sin2(x2 / 2);
    const s2 = sin2(y2 / 2);
    const s3 = sin2(z / 2);
    switch (order) {
      case "XYZ":
        this._x = s1 * c2 * c3 + c1 * s2 * s3;
        this._y = c1 * s2 * c3 - s1 * c2 * s3;
        this._z = c1 * c2 * s3 + s1 * s2 * c3;
        this._w = c1 * c2 * c3 - s1 * s2 * s3;
        break;
      case "YXZ":
        this._x = s1 * c2 * c3 + c1 * s2 * s3;
        this._y = c1 * s2 * c3 - s1 * c2 * s3;
        this._z = c1 * c2 * s3 - s1 * s2 * c3;
        this._w = c1 * c2 * c3 + s1 * s2 * s3;
        break;
      case "ZXY":
        this._x = s1 * c2 * c3 - c1 * s2 * s3;
        this._y = c1 * s2 * c3 + s1 * c2 * s3;
        this._z = c1 * c2 * s3 + s1 * s2 * c3;
        this._w = c1 * c2 * c3 - s1 * s2 * s3;
        break;
      case "ZYX":
        this._x = s1 * c2 * c3 - c1 * s2 * s3;
        this._y = c1 * s2 * c3 + s1 * c2 * s3;
        this._z = c1 * c2 * s3 - s1 * s2 * c3;
        this._w = c1 * c2 * c3 + s1 * s2 * s3;
        break;
      case "YZX":
        this._x = s1 * c2 * c3 + c1 * s2 * s3;
        this._y = c1 * s2 * c3 + s1 * c2 * s3;
        this._z = c1 * c2 * s3 - s1 * s2 * c3;
        this._w = c1 * c2 * c3 - s1 * s2 * s3;
        break;
      case "XZY":
        this._x = s1 * c2 * c3 - c1 * s2 * s3;
        this._y = c1 * s2 * c3 - s1 * c2 * s3;
        this._z = c1 * c2 * s3 + s1 * s2 * c3;
        this._w = c1 * c2 * c3 + s1 * s2 * s3;
        break;
      default:
        console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: " + order);
    }
    if (update === true)
      this._onChangeCallback();
    return this;
  }
  setFromAxisAngle(axis, angle) {
    const halfAngle = angle / 2, s = Math.sin(halfAngle);
    this._x = axis.x * s;
    this._y = axis.y * s;
    this._z = axis.z * s;
    this._w = Math.cos(halfAngle);
    this._onChangeCallback();
    return this;
  }
  setFromRotationMatrix(m) {
    const te = m.elements, m11 = te[0], m12 = te[4], m13 = te[8], m21 = te[1], m22 = te[5], m23 = te[9], m31 = te[2], m32 = te[6], m33 = te[10], trace = m11 + m22 + m33;
    if (trace > 0) {
      const s = 0.5 / Math.sqrt(trace + 1);
      this._w = 0.25 / s;
      this._x = (m32 - m23) * s;
      this._y = (m13 - m31) * s;
      this._z = (m21 - m12) * s;
    } else if (m11 > m22 && m11 > m33) {
      const s = 2 * Math.sqrt(1 + m11 - m22 - m33);
      this._w = (m32 - m23) / s;
      this._x = 0.25 * s;
      this._y = (m12 + m21) / s;
      this._z = (m13 + m31) / s;
    } else if (m22 > m33) {
      const s = 2 * Math.sqrt(1 + m22 - m11 - m33);
      this._w = (m13 - m31) / s;
      this._x = (m12 + m21) / s;
      this._y = 0.25 * s;
      this._z = (m23 + m32) / s;
    } else {
      const s = 2 * Math.sqrt(1 + m33 - m11 - m22);
      this._w = (m21 - m12) / s;
      this._x = (m13 + m31) / s;
      this._y = (m23 + m32) / s;
      this._z = 0.25 * s;
    }
    this._onChangeCallback();
    return this;
  }
  setFromUnitVectors(vFrom, vTo) {
    let r = vFrom.dot(vTo) + 1;
    if (r < 0.00000001) {
      r = 0;
      if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
        this._x = -vFrom.y;
        this._y = vFrom.x;
        this._z = 0;
        this._w = r;
      } else {
        this._x = 0;
        this._y = -vFrom.z;
        this._z = vFrom.y;
        this._w = r;
      }
    } else {
      this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
      this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
      this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
      this._w = r;
    }
    return this.normalize();
  }
  angleTo(q) {
    return 2 * Math.acos(Math.abs(clamp3(this.dot(q), -1, 1)));
  }
  rotateTowards(q, step) {
    const angle = this.angleTo(q);
    if (angle === 0)
      return this;
    const t = Math.min(1, step / angle);
    this.slerp(q, t);
    return this;
  }
  identity() {
    return this.set(0, 0, 0, 1);
  }
  invert() {
    return this.conjugate();
  }
  conjugate() {
    this._x *= -1;
    this._y *= -1;
    this._z *= -1;
    this._onChangeCallback();
    return this;
  }
  dot(v) {
    return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  }
  lengthSq() {
    return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  }
  length() {
    return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  }
  normalize() {
    let l = this.length();
    if (l === 0) {
      this._x = 0;
      this._y = 0;
      this._z = 0;
      this._w = 1;
    } else {
      l = 1 / l;
      this._x = this._x * l;
      this._y = this._y * l;
      this._z = this._z * l;
      this._w = this._w * l;
    }
    this._onChangeCallback();
    return this;
  }
  multiply(q) {
    return this.multiplyQuaternions(this, q);
  }
  premultiply(q) {
    return this.multiplyQuaternions(q, this);
  }
  multiplyQuaternions(a, b) {
    const { _x: qax, _y: qay, _z: qaz, _w: qaw } = a;
    const { _x: qbx, _y: qby, _z: qbz, _w: qbw } = b;
    this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
    this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
    this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
    this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
    this._onChangeCallback();
    return this;
  }
  slerp(qb, t) {
    if (t === 0)
      return this;
    if (t === 1)
      return this.copy(qb);
    const x2 = this._x, y2 = this._y, z = this._z, w = this._w;
    let cosHalfTheta = w * qb._w + x2 * qb._x + y2 * qb._y + z * qb._z;
    if (cosHalfTheta < 0) {
      this._w = -qb._w;
      this._x = -qb._x;
      this._y = -qb._y;
      this._z = -qb._z;
      cosHalfTheta = -cosHalfTheta;
    } else {
      this.copy(qb);
    }
    if (cosHalfTheta >= 1) {
      this._w = w;
      this._x = x2;
      this._y = y2;
      this._z = z;
      return this;
    }
    const sqrSinHalfTheta = 1 - cosHalfTheta * cosHalfTheta;
    if (sqrSinHalfTheta <= Number.EPSILON) {
      const s = 1 - t;
      this._w = s * w + t * this._w;
      this._x = s * x2 + t * this._x;
      this._y = s * y2 + t * this._y;
      this._z = s * z + t * this._z;
      this.normalize();
      return this;
    }
    const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
    const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
    const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta, ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
    this._w = w * ratioA + this._w * ratioB;
    this._x = x2 * ratioA + this._x * ratioB;
    this._y = y2 * ratioA + this._y * ratioB;
    this._z = z * ratioA + this._z * ratioB;
    this._onChangeCallback();
    return this;
  }
  slerpQuaternions(qa, qb, t) {
    return this.copy(qa).slerp(qb, t);
  }
  random() {
    const theta1 = 2 * Math.PI * Math.random();
    const theta2 = 2 * Math.PI * Math.random();
    const x0 = Math.random();
    const r1 = Math.sqrt(1 - x0);
    const r2 = Math.sqrt(x0);
    return this.set(r1 * Math.sin(theta1), r1 * Math.cos(theta1), r2 * Math.sin(theta2), r2 * Math.cos(theta2));
  }
  equals(quaternion) {
    return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  }
  fromArray(array2, offset = 0) {
    this._x = array2[offset];
    this._y = array2[offset + 1];
    this._z = array2[offset + 2];
    this._w = array2[offset + 3];
    this._onChangeCallback();
    return this;
  }
  toArray(array2 = [], offset = 0) {
    array2[offset] = this._x;
    array2[offset + 1] = this._y;
    array2[offset + 2] = this._z;
    array2[offset + 3] = this._w;
    return array2;
  }
  fromBufferAttribute(attribute, index) {
    this._x = attribute.getX(index);
    this._y = attribute.getY(index);
    this._z = attribute.getZ(index);
    this._w = attribute.getW(index);
    this._onChangeCallback();
    return this;
  }
  toJSON() {
    return this.toArray();
  }
  _onChange(callback) {
    this._onChangeCallback = callback;
    return this;
  }
  _onChangeCallback() {}
  *[Symbol.iterator]() {
    yield this._x;
    yield this._y;
    yield this._z;
    yield this._w;
  }
}

class Vector3 {
  constructor(x2 = 0, y2 = 0, z = 0) {
    Vector3.prototype.isVector3 = true;
    this.x = x2;
    this.y = y2;
    this.z = z;
  }
  set(x2, y2, z) {
    if (z === undefined)
      z = this.z;
    this.x = x2;
    this.y = y2;
    this.z = z;
    return this;
  }
  setScalar(scalar) {
    this.x = scalar;
    this.y = scalar;
    this.z = scalar;
    return this;
  }
  setX(x2) {
    this.x = x2;
    return this;
  }
  setY(y2) {
    this.y = y2;
    return this;
  }
  setZ(z) {
    this.z = z;
    return this;
  }
  setComponent(index, value) {
    switch (index) {
      case 0:
        this.x = value;
        break;
      case 1:
        this.y = value;
        break;
      case 2:
        this.z = value;
        break;
      default:
        throw new Error("index is out of range: " + index);
    }
    return this;
  }
  getComponent(index) {
    switch (index) {
      case 0:
        return this.x;
      case 1:
        return this.y;
      case 2:
        return this.z;
      default:
        throw new Error("index is out of range: " + index);
    }
  }
  clone() {
    return new this.constructor(this.x, this.y, this.z);
  }
  copy(v) {
    this.x = v.x;
    this.y = v.y;
    this.z = v.z;
    return this;
  }
  add(v) {
    this.x += v.x;
    this.y += v.y;
    this.z += v.z;
    return this;
  }
  addScalar(s) {
    this.x += s;
    this.y += s;
    this.z += s;
    return this;
  }
  addVectors(a, b) {
    this.x = a.x + b.x;
    this.y = a.y + b.y;
    this.z = a.z + b.z;
    return this;
  }
  addScaledVector(v, s) {
    this.x += v.x * s;
    this.y += v.y * s;
    this.z += v.z * s;
    return this;
  }
  sub(v) {
    this.x -= v.x;
    this.y -= v.y;
    this.z -= v.z;
    return this;
  }
  subScalar(s) {
    this.x -= s;
    this.y -= s;
    this.z -= s;
    return this;
  }
  subVectors(a, b) {
    this.x = a.x - b.x;
    this.y = a.y - b.y;
    this.z = a.z - b.z;
    return this;
  }
  multiply(v) {
    this.x *= v.x;
    this.y *= v.y;
    this.z *= v.z;
    return this;
  }
  multiplyScalar(scalar) {
    this.x *= scalar;
    this.y *= scalar;
    this.z *= scalar;
    return this;
  }
  multiplyVectors(a, b) {
    this.x = a.x * b.x;
    this.y = a.y * b.y;
    this.z = a.z * b.z;
    return this;
  }
  applyEuler(euler) {
    return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  }
  applyAxisAngle(axis, angle) {
    return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  }
  applyMatrix3(m) {
    const x2 = this.x, y2 = this.y, z = this.z;
    const e = m.elements;
    this.x = e[0] * x2 + e[3] * y2 + e[6] * z;
    this.y = e[1] * x2 + e[4] * y2 + e[7] * z;
    this.z = e[2] * x2 + e[5] * y2 + e[8] * z;
    return this;
  }
  applyNormalMatrix(m) {
    return this.applyMatrix3(m).normalize();
  }
  applyMatrix4(m) {
    const x2 = this.x, y2 = this.y, z = this.z;
    const e = m.elements;
    const w = 1 / (e[3] * x2 + e[7] * y2 + e[11] * z + e[15]);
    this.x = (e[0] * x2 + e[4] * y2 + e[8] * z + e[12]) * w;
    this.y = (e[1] * x2 + e[5] * y2 + e[9] * z + e[13]) * w;
    this.z = (e[2] * x2 + e[6] * y2 + e[10] * z + e[14]) * w;
    return this;
  }
  applyQuaternion(q) {
    const vx = this.x, vy = this.y, vz = this.z;
    const { x: qx, y: qy, z: qz, w: qw } = q;
    const tx = 2 * (qy * vz - qz * vy);
    const ty = 2 * (qz * vx - qx * vz);
    const tz = 2 * (qx * vy - qy * vx);
    this.x = vx + qw * tx + qy * tz - qz * ty;
    this.y = vy + qw * ty + qz * tx - qx * tz;
    this.z = vz + qw * tz + qx * ty - qy * tx;
    return this;
  }
  project(camera) {
    return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  }
  unproject(camera) {
    return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  }
  transformDirection(m) {
    const x2 = this.x, y2 = this.y, z = this.z;
    const e = m.elements;
    this.x = e[0] * x2 + e[4] * y2 + e[8] * z;
    this.y = e[1] * x2 + e[5] * y2 + e[9] * z;
    this.z = e[2] * x2 + e[6] * y2 + e[10] * z;
    return this.normalize();
  }
  divide(v) {
    this.x /= v.x;
    this.y /= v.y;
    this.z /= v.z;
    return this;
  }
  divideScalar(scalar) {
    return this.multiplyScalar(1 / scalar);
  }
  min(v) {
    this.x = Math.min(this.x, v.x);
    this.y = Math.min(this.y, v.y);
    this.z = Math.min(this.z, v.z);
    return this;
  }
  max(v) {
    this.x = Math.max(this.x, v.x);
    this.y = Math.max(this.y, v.y);
    this.z = Math.max(this.z, v.z);
    return this;
  }
  clamp(min2, max3) {
    this.x = clamp3(this.x, min2.x, max3.x);
    this.y = clamp3(this.y, min2.y, max3.y);
    this.z = clamp3(this.z, min2.z, max3.z);
    return this;
  }
  clampScalar(minVal, maxVal) {
    this.x = clamp3(this.x, minVal, maxVal);
    this.y = clamp3(this.y, minVal, maxVal);
    this.z = clamp3(this.z, minVal, maxVal);
    return this;
  }
  clampLength(min2, max3) {
    const length = this.length();
    return this.divideScalar(length || 1).multiplyScalar(clamp3(length, min2, max3));
  }
  floor() {
    this.x = Math.floor(this.x);
    this.y = Math.floor(this.y);
    this.z = Math.floor(this.z);
    return this;
  }
  ceil() {
    this.x = Math.ceil(this.x);
    this.y = Math.ceil(this.y);
    this.z = Math.ceil(this.z);
    return this;
  }
  round() {
    this.x = Math.round(this.x);
    this.y = Math.round(this.y);
    this.z = Math.round(this.z);
    return this;
  }
  roundToZero() {
    this.x = Math.trunc(this.x);
    this.y = Math.trunc(this.y);
    this.z = Math.trunc(this.z);
    return this;
  }
  negate() {
    this.x = -this.x;
    this.y = -this.y;
    this.z = -this.z;
    return this;
  }
  dot(v) {
    return this.x * v.x + this.y * v.y + this.z * v.z;
  }
  lengthSq() {
    return this.x * this.x + this.y * this.y + this.z * this.z;
  }
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  }
  manhattanLength() {
    return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  }
  normalize() {
    return this.divideScalar(this.length() || 1);
  }
  setLength(length) {
    return this.normalize().multiplyScalar(length);
  }
  lerp(v, alpha) {
    this.x += (v.x - this.x) * alpha;
    this.y += (v.y - this.y) * alpha;
    this.z += (v.z - this.z) * alpha;
    return this;
  }
  lerpVectors(v1, v2, alpha) {
    this.x = v1.x + (v2.x - v1.x) * alpha;
    this.y = v1.y + (v2.y - v1.y) * alpha;
    this.z = v1.z + (v2.z - v1.z) * alpha;
    return this;
  }
  cross(v) {
    return this.crossVectors(this, v);
  }
  crossVectors(a, b) {
    const { x: ax, y: ay, z: az } = a;
    const { x: bx, y: by, z: bz } = b;
    this.x = ay * bz - az * by;
    this.y = az * bx - ax * bz;
    this.z = ax * by - ay * bx;
    return this;
  }
  projectOnVector(v) {
    const denominator = v.lengthSq();
    if (denominator === 0)
      return this.set(0, 0, 0);
    const scalar = v.dot(this) / denominator;
    return this.copy(v).multiplyScalar(scalar);
  }
  projectOnPlane(planeNormal) {
    _vector$c.copy(this).projectOnVector(planeNormal);
    return this.sub(_vector$c);
  }
  reflect(normal) {
    return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  }
  angleTo(v) {
    const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
    if (denominator === 0)
      return Math.PI / 2;
    const theta = this.dot(v) / denominator;
    return Math.acos(clamp3(theta, -1, 1));
  }
  distanceTo(v) {
    return Math.sqrt(this.distanceToSquared(v));
  }
  distanceToSquared(v) {
    const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
    return dx * dx + dy * dy + dz * dz;
  }
  manhattanDistanceTo(v) {
    return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  }
  setFromSpherical(s) {
    return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  }
  setFromSphericalCoords(radius, phi2, theta) {
    const sinPhiRadius = Math.sin(phi2) * radius;
    this.x = sinPhiRadius * Math.sin(theta);
    this.y = Math.cos(phi2) * radius;
    this.z = sinPhiRadius * Math.cos(theta);
    return this;
  }
  setFromCylindrical(c) {
    return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  }
  setFromCylindricalCoords(radius, theta, y2) {
    this.x = radius * Math.sin(theta);
    this.y = y2;
    this.z = radius * Math.cos(theta);
    return this;
  }
  setFromMatrixPosition(m) {
    const e = m.elements;
    this.x = e[12];
    this.y = e[13];
    this.z = e[14];
    return this;
  }
  setFromMatrixScale(m) {
    const sx = this.setFromMatrixColumn(m, 0).length();
    const sy = this.setFromMatrixColumn(m, 1).length();
    const sz = this.setFromMatrixColumn(m, 2).length();
    this.x = sx;
    this.y = sy;
    this.z = sz;
    return this;
  }
  setFromMatrixColumn(m, index) {
    return this.fromArray(m.elements, index * 4);
  }
  setFromMatrix3Column(m, index) {
    return this.fromArray(m.elements, index * 3);
  }
  setFromEuler(e) {
    this.x = e._x;
    this.y = e._y;
    this.z = e._z;
    return this;
  }
  setFromColor(c) {
    this.x = c.r;
    this.y = c.g;
    this.z = c.b;
    return this;
  }
  equals(v) {
    return v.x === this.x && v.y === this.y && v.z === this.z;
  }
  fromArray(array2, offset = 0) {
    this.x = array2[offset];
    this.y = array2[offset + 1];
    this.z = array2[offset + 2];
    return this;
  }
  toArray(array2 = [], offset = 0) {
    array2[offset] = this.x;
    array2[offset + 1] = this.y;
    array2[offset + 2] = this.z;
    return array2;
  }
  fromBufferAttribute(attribute, index) {
    this.x = attribute.getX(index);
    this.y = attribute.getY(index);
    this.z = attribute.getZ(index);
    return this;
  }
  random() {
    this.x = Math.random();
    this.y = Math.random();
    this.z = Math.random();
    return this;
  }
  randomDirection() {
    const theta = Math.random() * Math.PI * 2;
    const u = Math.random() * 2 - 1;
    const c = Math.sqrt(1 - u * u);
    this.x = c * Math.cos(theta);
    this.y = u;
    this.z = c * Math.sin(theta);
    return this;
  }
  *[Symbol.iterator]() {
    yield this.x;
    yield this.y;
    yield this.z;
  }
}
var _vector$c = /* @__PURE__ */ new Vector3;
var _quaternion$4 = /* @__PURE__ */ new Quaternion;

class Matrix3 {
  constructor(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
    Matrix3.prototype.isMatrix3 = true;
    this.elements = [
      1,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      1
    ];
    if (n11 !== undefined) {
      this.set(n11, n12, n13, n21, n22, n23, n31, n32, n33);
    }
  }
  set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
    const te = this.elements;
    te[0] = n11;
    te[1] = n21;
    te[2] = n31;
    te[3] = n12;
    te[4] = n22;
    te[5] = n32;
    te[6] = n13;
    te[7] = n23;
    te[8] = n33;
    return this;
  }
  identity() {
    this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
    return this;
  }
  copy(m) {
    const te = this.elements;
    const me = m.elements;
    te[0] = me[0];
    te[1] = me[1];
    te[2] = me[2];
    te[3] = me[3];
    te[4] = me[4];
    te[5] = me[5];
    te[6] = me[6];
    te[7] = me[7];
    te[8] = me[8];
    return this;
  }
  extractBasis(xAxis, yAxis, zAxis) {
    xAxis.setFromMatrix3Column(this, 0);
    yAxis.setFromMatrix3Column(this, 1);
    zAxis.setFromMatrix3Column(this, 2);
    return this;
  }
  setFromMatrix4(m) {
    const me = m.elements;
    this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
    return this;
  }
  multiply(m) {
    return this.multiplyMatrices(this, m);
  }
  premultiply(m) {
    return this.multiplyMatrices(m, this);
  }
  multiplyMatrices(a, b) {
    const ae = a.elements;
    const be = b.elements;
    const te = this.elements;
    const a11 = ae[0], a12 = ae[3], a13 = ae[6];
    const a21 = ae[1], a22 = ae[4], a23 = ae[7];
    const a31 = ae[2], a32 = ae[5], a33 = ae[8];
    const b11 = be[0], b12 = be[3], b13 = be[6];
    const b21 = be[1], b22 = be[4], b23 = be[7];
    const b31 = be[2], b32 = be[5], b33 = be[8];
    te[0] = a11 * b11 + a12 * b21 + a13 * b31;
    te[3] = a11 * b12 + a12 * b22 + a13 * b32;
    te[6] = a11 * b13 + a12 * b23 + a13 * b33;
    te[1] = a21 * b11 + a22 * b21 + a23 * b31;
    te[4] = a21 * b12 + a22 * b22 + a23 * b32;
    te[7] = a21 * b13 + a22 * b23 + a23 * b33;
    te[2] = a31 * b11 + a32 * b21 + a33 * b31;
    te[5] = a31 * b12 + a32 * b22 + a33 * b32;
    te[8] = a31 * b13 + a32 * b23 + a33 * b33;
    return this;
  }
  multiplyScalar(s) {
    const te = this.elements;
    te[0] *= s;
    te[3] *= s;
    te[6] *= s;
    te[1] *= s;
    te[4] *= s;
    te[7] *= s;
    te[2] *= s;
    te[5] *= s;
    te[8] *= s;
    return this;
  }
  determinant() {
    const te = this.elements;
    const a = te[0], b = te[1], c = te[2], d = te[3], e = te[4], f = te[5], g = te[6], h = te[7], i = te[8];
    return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  }
  invert() {
    const te = this.elements, n11 = te[0], n21 = te[1], n31 = te[2], n12 = te[3], n22 = te[4], n32 = te[5], n13 = te[6], n23 = te[7], n33 = te[8], t11 = n33 * n22 - n32 * n23, t12 = n32 * n13 - n33 * n12, t13 = n23 * n12 - n22 * n13, det = n11 * t11 + n21 * t12 + n31 * t13;
    if (det === 0)
      return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
    const detInv = 1 / det;
    te[0] = t11 * detInv;
    te[1] = (n31 * n23 - n33 * n21) * detInv;
    te[2] = (n32 * n21 - n31 * n22) * detInv;
    te[3] = t12 * detInv;
    te[4] = (n33 * n11 - n31 * n13) * detInv;
    te[5] = (n31 * n12 - n32 * n11) * detInv;
    te[6] = t13 * detInv;
    te[7] = (n21 * n13 - n23 * n11) * detInv;
    te[8] = (n22 * n11 - n21 * n12) * detInv;
    return this;
  }
  transpose() {
    let tmp;
    const m = this.elements;
    tmp = m[1];
    m[1] = m[3];
    m[3] = tmp;
    tmp = m[2];
    m[2] = m[6];
    m[6] = tmp;
    tmp = m[5];
    m[5] = m[7];
    m[7] = tmp;
    return this;
  }
  getNormalMatrix(matrix4) {
    return this.setFromMatrix4(matrix4).invert().transpose();
  }
  transposeIntoArray(r) {
    const m = this.elements;
    r[0] = m[0];
    r[1] = m[3];
    r[2] = m[6];
    r[3] = m[1];
    r[4] = m[4];
    r[5] = m[7];
    r[6] = m[2];
    r[7] = m[5];
    r[8] = m[8];
    return this;
  }
  setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
    const c = Math.cos(rotation);
    const s = Math.sin(rotation);
    this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1);
    return this;
  }
  scale(sx, sy) {
    this.premultiply(_m3.makeScale(sx, sy));
    return this;
  }
  rotate(theta) {
    this.premultiply(_m3.makeRotation(-theta));
    return this;
  }
  translate(tx, ty) {
    this.premultiply(_m3.makeTranslation(tx, ty));
    return this;
  }
  makeTranslation(x2, y2) {
    if (x2.isVector2) {
      this.set(1, 0, x2.x, 0, 1, x2.y, 0, 0, 1);
    } else {
      this.set(1, 0, x2, 0, 1, y2, 0, 0, 1);
    }
    return this;
  }
  makeRotation(theta) {
    const c = Math.cos(theta);
    const s = Math.sin(theta);
    this.set(c, -s, 0, s, c, 0, 0, 0, 1);
    return this;
  }
  makeScale(x2, y2) {
    this.set(x2, 0, 0, 0, y2, 0, 0, 0, 1);
    return this;
  }
  equals(matrix) {
    const te = this.elements;
    const me = matrix.elements;
    for (let i = 0;i < 9; i++) {
      if (te[i] !== me[i])
        return false;
    }
    return true;
  }
  fromArray(array2, offset = 0) {
    for (let i = 0;i < 9; i++) {
      this.elements[i] = array2[i + offset];
    }
    return this;
  }
  toArray(array2 = [], offset = 0) {
    const te = this.elements;
    array2[offset] = te[0];
    array2[offset + 1] = te[1];
    array2[offset + 2] = te[2];
    array2[offset + 3] = te[3];
    array2[offset + 4] = te[4];
    array2[offset + 5] = te[5];
    array2[offset + 6] = te[6];
    array2[offset + 7] = te[7];
    array2[offset + 8] = te[8];
    return array2;
  }
  clone() {
    return new this.constructor().fromArray(this.elements);
  }
}
var _m3 = /* @__PURE__ */ new Matrix3;
function arrayNeedsUint32(array2) {
  for (let i = array2.length - 1;i >= 0; --i) {
    if (array2[i] >= 65535)
      return true;
  }
  return false;
}
function createElementNS(name) {
  return document.createElementNS("http://www.w3.org/1999/xhtml", name);
}
var _cache = {};
function warnOnce(message) {
  if (message in _cache)
    return;
  _cache[message] = true;
  console.warn(message);
}
var LINEAR_REC709_TO_XYZ = /* @__PURE__ */ new Matrix3().set(0.4123908, 0.3575843, 0.1804808, 0.212639, 0.7151687, 0.0721923, 0.0193308, 0.1191948, 0.9505322);
var XYZ_TO_LINEAR_REC709 = /* @__PURE__ */ new Matrix3().set(3.2409699, -1.5373832, -0.4986108, -0.9692436, 1.8759675, 0.0415551, 0.0556301, -0.203977, 1.0569715);
function createColorManagement() {
  const ColorManagement = {
    enabled: true,
    workingColorSpace: LinearSRGBColorSpace,
    spaces: {},
    convert: function(color2, sourceColorSpace, targetColorSpace) {
      if (this.enabled === false || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) {
        return color2;
      }
      if (this.spaces[sourceColorSpace].transfer === SRGBTransfer) {
        color2.r = SRGBToLinear(color2.r);
        color2.g = SRGBToLinear(color2.g);
        color2.b = SRGBToLinear(color2.b);
      }
      if (this.spaces[sourceColorSpace].primaries !== this.spaces[targetColorSpace].primaries) {
        color2.applyMatrix3(this.spaces[sourceColorSpace].toXYZ);
        color2.applyMatrix3(this.spaces[targetColorSpace].fromXYZ);
      }
      if (this.spaces[targetColorSpace].transfer === SRGBTransfer) {
        color2.r = LinearToSRGB(color2.r);
        color2.g = LinearToSRGB(color2.g);
        color2.b = LinearToSRGB(color2.b);
      }
      return color2;
    },
    workingToColorSpace: function(color2, targetColorSpace) {
      return this.convert(color2, this.workingColorSpace, targetColorSpace);
    },
    colorSpaceToWorking: function(color2, sourceColorSpace) {
      return this.convert(color2, sourceColorSpace, this.workingColorSpace);
    },
    getPrimaries: function(colorSpace) {
      return this.spaces[colorSpace].primaries;
    },
    getTransfer: function(colorSpace) {
      if (colorSpace === NoColorSpace)
        return LinearTransfer;
      return this.spaces[colorSpace].transfer;
    },
    getLuminanceCoefficients: function(target, colorSpace = this.workingColorSpace) {
      return target.fromArray(this.spaces[colorSpace].luminanceCoefficients);
    },
    define: function(colorSpaces) {
      Object.assign(this.spaces, colorSpaces);
    },
    _getMatrix: function(targetMatrix, sourceColorSpace, targetColorSpace) {
      return targetMatrix.copy(this.spaces[sourceColorSpace].toXYZ).multiply(this.spaces[targetColorSpace].fromXYZ);
    },
    _getDrawingBufferColorSpace: function(colorSpace) {
      return this.spaces[colorSpace].outputColorSpaceConfig.drawingBufferColorSpace;
    },
    _getUnpackColorSpace: function(colorSpace = this.workingColorSpace) {
      return this.spaces[colorSpace].workingColorSpaceConfig.unpackColorSpace;
    },
    fromWorkingColorSpace: function(color2, targetColorSpace) {
      warnOnce("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().");
      return ColorManagement.workingToColorSpace(color2, targetColorSpace);
    },
    toWorkingColorSpace: function(color2, sourceColorSpace) {
      warnOnce("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().");
      return ColorManagement.colorSpaceToWorking(color2, sourceColorSpace);
    }
  };
  const REC709_PRIMARIES = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06];
  const REC709_LUMINANCE_COEFFICIENTS = [0.2126, 0.7152, 0.0722];
  const D65 = [0.3127, 0.329];
  ColorManagement.define({
    [LinearSRGBColorSpace]: {
      primaries: REC709_PRIMARIES,
      whitePoint: D65,
      transfer: LinearTransfer,
      toXYZ: LINEAR_REC709_TO_XYZ,
      fromXYZ: XYZ_TO_LINEAR_REC709,
      luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
      workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
      outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
    },
    [SRGBColorSpace]: {
      primaries: REC709_PRIMARIES,
      whitePoint: D65,
      transfer: SRGBTransfer,
      toXYZ: LINEAR_REC709_TO_XYZ,
      fromXYZ: XYZ_TO_LINEAR_REC709,
      luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
      outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
    }
  });
  return ColorManagement;
}
var ColorManagement = /* @__PURE__ */ createColorManagement();
function SRGBToLinear(c) {
  return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
}
function LinearToSRGB(c) {
  return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
}
var _canvas;

class ImageUtils {
  static getDataURL(image, type = "image/png") {
    if (/^data:/i.test(image.src)) {
      return image.src;
    }
    if (typeof HTMLCanvasElement === "undefined") {
      return image.src;
    }
    let canvas;
    if (image instanceof HTMLCanvasElement) {
      canvas = image;
    } else {
      if (_canvas === undefined)
        _canvas = createElementNS("canvas");
      _canvas.width = image.width;
      _canvas.height = image.height;
      const context = _canvas.getContext("2d");
      if (image instanceof ImageData) {
        context.putImageData(image, 0, 0);
      } else {
        context.drawImage(image, 0, 0, image.width, image.height);
      }
      canvas = _canvas;
    }
    return canvas.toDataURL(type);
  }
  static sRGBToLinear(image) {
    if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) {
      const canvas = createElementNS("canvas");
      canvas.width = image.width;
      canvas.height = image.height;
      const context = canvas.getContext("2d");
      context.drawImage(image, 0, 0, image.width, image.height);
      const imageData = context.getImageData(0, 0, image.width, image.height);
      const data = imageData.data;
      for (let i = 0;i < data.length; i++) {
        data[i] = SRGBToLinear(data[i] / 255) * 255;
      }
      context.putImageData(imageData, 0, 0);
      return canvas;
    } else if (image.data) {
      const data = image.data.slice(0);
      for (let i = 0;i < data.length; i++) {
        if (data instanceof Uint8Array || data instanceof Uint8ClampedArray) {
          data[i] = Math.floor(SRGBToLinear(data[i] / 255) * 255);
        } else {
          data[i] = SRGBToLinear(data[i]);
        }
      }
      return {
        data,
        width: image.width,
        height: image.height
      };
    } else {
      console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.");
      return image;
    }
  }
}
var _sourceId = 0;

class Source {
  constructor(data = null) {
    this.isSource = true;
    Object.defineProperty(this, "id", { value: _sourceId++ });
    this.uuid = generateUUID();
    this.data = data;
    this.dataReady = true;
    this.version = 0;
  }
  getSize(target) {
    const data = this.data;
    if (data instanceof HTMLVideoElement) {
      target.set(data.videoWidth, data.videoHeight, 0);
    } else if (data instanceof VideoFrame) {
      target.set(data.displayHeight, data.displayWidth, 0);
    } else if (data !== null) {
      target.set(data.width, data.height, data.depth || 0);
    } else {
      target.set(0, 0, 0);
    }
    return target;
  }
  set needsUpdate(value) {
    if (value === true)
      this.version++;
  }
  toJSON(meta) {
    const isRootObject = meta === undefined || typeof meta === "string";
    if (!isRootObject && meta.images[this.uuid] !== undefined) {
      return meta.images[this.uuid];
    }
    const output = {
      uuid: this.uuid,
      url: ""
    };
    const data = this.data;
    if (data !== null) {
      let url;
      if (Array.isArray(data)) {
        url = [];
        for (let i = 0, l = data.length;i < l; i++) {
          if (data[i].isDataTexture) {
            url.push(serializeImage(data[i].image));
          } else {
            url.push(serializeImage(data[i]));
          }
        }
      } else {
        url = serializeImage(data);
      }
      output.url = url;
    }
    if (!isRootObject) {
      meta.images[this.uuid] = output;
    }
    return output;
  }
}
function serializeImage(image) {
  if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) {
    return ImageUtils.getDataURL(image);
  } else {
    if (image.data) {
      return {
        data: Array.from(image.data),
        width: image.width,
        height: image.height,
        type: image.data.constructor.name
      };
    } else {
      console.warn("THREE.Texture: Unable to serialize Texture.");
      return {};
    }
  }
}
var _textureId = 0;
var _tempVec3 = /* @__PURE__ */ new Vector3;

class Texture extends EventDispatcher {
  constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format2 = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace) {
    super();
    this.isTexture = true;
    Object.defineProperty(this, "id", { value: _textureId++ });
    this.uuid = generateUUID();
    this.name = "";
    this.source = new Source(image);
    this.mipmaps = [];
    this.mapping = mapping;
    this.channel = 0;
    this.wrapS = wrapS;
    this.wrapT = wrapT;
    this.magFilter = magFilter;
    this.minFilter = minFilter;
    this.anisotropy = anisotropy;
    this.format = format2;
    this.internalFormat = null;
    this.type = type;
    this.offset = new Vector2(0, 0);
    this.repeat = new Vector2(1, 1);
    this.center = new Vector2(0, 0);
    this.rotation = 0;
    this.matrixAutoUpdate = true;
    this.matrix = new Matrix3;
    this.generateMipmaps = true;
    this.premultiplyAlpha = false;
    this.flipY = true;
    this.unpackAlignment = 4;
    this.colorSpace = colorSpace;
    this.userData = {};
    this.updateRanges = [];
    this.version = 0;
    this.onUpdate = null;
    this.renderTarget = null;
    this.isRenderTargetTexture = false;
    this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
    this.pmremVersion = 0;
  }
  get width() {
    return this.source.getSize(_tempVec3).x;
  }
  get height() {
    return this.source.getSize(_tempVec3).y;
  }
  get depth() {
    return this.source.getSize(_tempVec3).z;
  }
  get image() {
    return this.source.data;
  }
  set image(value = null) {
    this.source.data = value;
  }
  updateMatrix() {
    this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  }
  addUpdateRange(start, count3) {
    this.updateRanges.push({ start, count: count3 });
  }
  clearUpdateRanges() {
    this.updateRanges.length = 0;
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(source) {
    this.name = source.name;
    this.source = source.source;
    this.mipmaps = source.mipmaps.slice(0);
    this.mapping = source.mapping;
    this.channel = source.channel;
    this.wrapS = source.wrapS;
    this.wrapT = source.wrapT;
    this.magFilter = source.magFilter;
    this.minFilter = source.minFilter;
    this.anisotropy = source.anisotropy;
    this.format = source.format;
    this.internalFormat = source.internalFormat;
    this.type = source.type;
    this.offset.copy(source.offset);
    this.repeat.copy(source.repeat);
    this.center.copy(source.center);
    this.rotation = source.rotation;
    this.matrixAutoUpdate = source.matrixAutoUpdate;
    this.matrix.copy(source.matrix);
    this.generateMipmaps = source.generateMipmaps;
    this.premultiplyAlpha = source.premultiplyAlpha;
    this.flipY = source.flipY;
    this.unpackAlignment = source.unpackAlignment;
    this.colorSpace = source.colorSpace;
    this.renderTarget = source.renderTarget;
    this.isRenderTargetTexture = source.isRenderTargetTexture;
    this.isArrayTexture = source.isArrayTexture;
    this.userData = JSON.parse(JSON.stringify(source.userData));
    this.needsUpdate = true;
    return this;
  }
  setValues(values) {
    for (const key in values) {
      const newValue = values[key];
      if (newValue === undefined) {
        console.warn(`THREE.Texture.setValues(): parameter '${key}' has value of undefined.`);
        continue;
      }
      const currentValue = this[key];
      if (currentValue === undefined) {
        console.warn(`THREE.Texture.setValues(): property '${key}' does not exist.`);
        continue;
      }
      if (currentValue && newValue && (currentValue.isVector2 && newValue.isVector2)) {
        currentValue.copy(newValue);
      } else if (currentValue && newValue && (currentValue.isVector3 && newValue.isVector3)) {
        currentValue.copy(newValue);
      } else if (currentValue && newValue && (currentValue.isMatrix3 && newValue.isMatrix3)) {
        currentValue.copy(newValue);
      } else {
        this[key] = newValue;
      }
    }
  }
  toJSON(meta) {
    const isRootObject = meta === undefined || typeof meta === "string";
    if (!isRootObject && meta.textures[this.uuid] !== undefined) {
      return meta.textures[this.uuid];
    }
    const output = {
      metadata: {
        version: 4.7,
        type: "Texture",
        generator: "Texture.toJSON"
      },
      uuid: this.uuid,
      name: this.name,
      image: this.source.toJSON(meta).uuid,
      mapping: this.mapping,
      channel: this.channel,
      repeat: [this.repeat.x, this.repeat.y],
      offset: [this.offset.x, this.offset.y],
      center: [this.center.x, this.center.y],
      rotation: this.rotation,
      wrap: [this.wrapS, this.wrapT],
      format: this.format,
      internalFormat: this.internalFormat,
      type: this.type,
      colorSpace: this.colorSpace,
      minFilter: this.minFilter,
      magFilter: this.magFilter,
      anisotropy: this.anisotropy,
      flipY: this.flipY,
      generateMipmaps: this.generateMipmaps,
      premultiplyAlpha: this.premultiplyAlpha,
      unpackAlignment: this.unpackAlignment
    };
    if (Object.keys(this.userData).length > 0)
      output.userData = this.userData;
    if (!isRootObject) {
      meta.textures[this.uuid] = output;
    }
    return output;
  }
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
  transformUv(uv) {
    if (this.mapping !== UVMapping)
      return uv;
    uv.applyMatrix3(this.matrix);
    if (uv.x < 0 || uv.x > 1) {
      switch (this.wrapS) {
        case RepeatWrapping:
          uv.x = uv.x - Math.floor(uv.x);
          break;
        case ClampToEdgeWrapping:
          uv.x = uv.x < 0 ? 0 : 1;
          break;
        case MirroredRepeatWrapping:
          if (Math.abs(Math.floor(uv.x) % 2) === 1) {
            uv.x = Math.ceil(uv.x) - uv.x;
          } else {
            uv.x = uv.x - Math.floor(uv.x);
          }
          break;
      }
    }
    if (uv.y < 0 || uv.y > 1) {
      switch (this.wrapT) {
        case RepeatWrapping:
          uv.y = uv.y - Math.floor(uv.y);
          break;
        case ClampToEdgeWrapping:
          uv.y = uv.y < 0 ? 0 : 1;
          break;
        case MirroredRepeatWrapping:
          if (Math.abs(Math.floor(uv.y) % 2) === 1) {
            uv.y = Math.ceil(uv.y) - uv.y;
          } else {
            uv.y = uv.y - Math.floor(uv.y);
          }
          break;
      }
    }
    if (this.flipY) {
      uv.y = 1 - uv.y;
    }
    return uv;
  }
  set needsUpdate(value) {
    if (value === true) {
      this.version++;
      this.source.needsUpdate = true;
    }
  }
  set needsPMREMUpdate(value) {
    if (value === true) {
      this.pmremVersion++;
    }
  }
}
Texture.DEFAULT_IMAGE = null;
Texture.DEFAULT_MAPPING = UVMapping;
Texture.DEFAULT_ANISOTROPY = 1;

class Vector4 {
  constructor(x2 = 0, y2 = 0, z = 0, w = 1) {
    Vector4.prototype.isVector4 = true;
    this.x = x2;
    this.y = y2;
    this.z = z;
    this.w = w;
  }
  get width() {
    return this.z;
  }
  set width(value) {
    this.z = value;
  }
  get height() {
    return this.w;
  }
  set height(value) {
    this.w = value;
  }
  set(x2, y2, z, w) {
    this.x = x2;
    this.y = y2;
    this.z = z;
    this.w = w;
    return this;
  }
  setScalar(scalar) {
    this.x = scalar;
    this.y = scalar;
    this.z = scalar;
    this.w = scalar;
    return this;
  }
  setX(x2) {
    this.x = x2;
    return this;
  }
  setY(y2) {
    this.y = y2;
    return this;
  }
  setZ(z) {
    this.z = z;
    return this;
  }
  setW(w) {
    this.w = w;
    return this;
  }
  setComponent(index, value) {
    switch (index) {
      case 0:
        this.x = value;
        break;
      case 1:
        this.y = value;
        break;
      case 2:
        this.z = value;
        break;
      case 3:
        this.w = value;
        break;
      default:
        throw new Error("index is out of range: " + index);
    }
    return this;
  }
  getComponent(index) {
    switch (index) {
      case 0:
        return this.x;
      case 1:
        return this.y;
      case 2:
        return this.z;
      case 3:
        return this.w;
      default:
        throw new Error("index is out of range: " + index);
    }
  }
  clone() {
    return new this.constructor(this.x, this.y, this.z, this.w);
  }
  copy(v) {
    this.x = v.x;
    this.y = v.y;
    this.z = v.z;
    this.w = v.w !== undefined ? v.w : 1;
    return this;
  }
  add(v) {
    this.x += v.x;
    this.y += v.y;
    this.z += v.z;
    this.w += v.w;
    return this;
  }
  addScalar(s) {
    this.x += s;
    this.y += s;
    this.z += s;
    this.w += s;
    return this;
  }
  addVectors(a, b) {
    this.x = a.x + b.x;
    this.y = a.y + b.y;
    this.z = a.z + b.z;
    this.w = a.w + b.w;
    return this;
  }
  addScaledVector(v, s) {
    this.x += v.x * s;
    this.y += v.y * s;
    this.z += v.z * s;
    this.w += v.w * s;
    return this;
  }
  sub(v) {
    this.x -= v.x;
    this.y -= v.y;
    this.z -= v.z;
    this.w -= v.w;
    return this;
  }
  subScalar(s) {
    this.x -= s;
    this.y -= s;
    this.z -= s;
    this.w -= s;
    return this;
  }
  subVectors(a, b) {
    this.x = a.x - b.x;
    this.y = a.y - b.y;
    this.z = a.z - b.z;
    this.w = a.w - b.w;
    return this;
  }
  multiply(v) {
    this.x *= v.x;
    this.y *= v.y;
    this.z *= v.z;
    this.w *= v.w;
    return this;
  }
  multiplyScalar(scalar) {
    this.x *= scalar;
    this.y *= scalar;
    this.z *= scalar;
    this.w *= scalar;
    return this;
  }
  applyMatrix4(m) {
    const x2 = this.x, y2 = this.y, z = this.z, w = this.w;
    const e = m.elements;
    this.x = e[0] * x2 + e[4] * y2 + e[8] * z + e[12] * w;
    this.y = e[1] * x2 + e[5] * y2 + e[9] * z + e[13] * w;
    this.z = e[2] * x2 + e[6] * y2 + e[10] * z + e[14] * w;
    this.w = e[3] * x2 + e[7] * y2 + e[11] * z + e[15] * w;
    return this;
  }
  divide(v) {
    this.x /= v.x;
    this.y /= v.y;
    this.z /= v.z;
    this.w /= v.w;
    return this;
  }
  divideScalar(scalar) {
    return this.multiplyScalar(1 / scalar);
  }
  setAxisAngleFromQuaternion(q) {
    this.w = 2 * Math.acos(q.w);
    const s = Math.sqrt(1 - q.w * q.w);
    if (s < 0.0001) {
      this.x = 1;
      this.y = 0;
      this.z = 0;
    } else {
      this.x = q.x / s;
      this.y = q.y / s;
      this.z = q.z / s;
    }
    return this;
  }
  setAxisAngleFromRotationMatrix(m) {
    let angle, x2, y2, z;
    const epsilon3 = 0.01, epsilon22 = 0.1, te = m.elements, m11 = te[0], m12 = te[4], m13 = te[8], m21 = te[1], m22 = te[5], m23 = te[9], m31 = te[2], m32 = te[6], m33 = te[10];
    if (Math.abs(m12 - m21) < epsilon3 && Math.abs(m13 - m31) < epsilon3 && Math.abs(m23 - m32) < epsilon3) {
      if (Math.abs(m12 + m21) < epsilon22 && Math.abs(m13 + m31) < epsilon22 && Math.abs(m23 + m32) < epsilon22 && Math.abs(m11 + m22 + m33 - 3) < epsilon22) {
        this.set(1, 0, 0, 0);
        return this;
      }
      angle = Math.PI;
      const xx = (m11 + 1) / 2;
      const yy = (m22 + 1) / 2;
      const zz = (m33 + 1) / 2;
      const xy = (m12 + m21) / 4;
      const xz = (m13 + m31) / 4;
      const yz = (m23 + m32) / 4;
      if (xx > yy && xx > zz) {
        if (xx < epsilon3) {
          x2 = 0;
          y2 = 0.707106781;
          z = 0.707106781;
        } else {
          x2 = Math.sqrt(xx);
          y2 = xy / x2;
          z = xz / x2;
        }
      } else if (yy > zz) {
        if (yy < epsilon3) {
          x2 = 0.707106781;
          y2 = 0;
          z = 0.707106781;
        } else {
          y2 = Math.sqrt(yy);
          x2 = xy / y2;
          z = yz / y2;
        }
      } else {
        if (zz < epsilon3) {
          x2 = 0.707106781;
          y2 = 0.707106781;
          z = 0;
        } else {
          z = Math.sqrt(zz);
          x2 = xz / z;
          y2 = yz / z;
        }
      }
      this.set(x2, y2, z, angle);
      return this;
    }
    let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12));
    if (Math.abs(s) < 0.001)
      s = 1;
    this.x = (m32 - m23) / s;
    this.y = (m13 - m31) / s;
    this.z = (m21 - m12) / s;
    this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
    return this;
  }
  setFromMatrixPosition(m) {
    const e = m.elements;
    this.x = e[12];
    this.y = e[13];
    this.z = e[14];
    this.w = e[15];
    return this;
  }
  min(v) {
    this.x = Math.min(this.x, v.x);
    this.y = Math.min(this.y, v.y);
    this.z = Math.min(this.z, v.z);
    this.w = Math.min(this.w, v.w);
    return this;
  }
  max(v) {
    this.x = Math.max(this.x, v.x);
    this.y = Math.max(this.y, v.y);
    this.z = Math.max(this.z, v.z);
    this.w = Math.max(this.w, v.w);
    return this;
  }
  clamp(min2, max3) {
    this.x = clamp3(this.x, min2.x, max3.x);
    this.y = clamp3(this.y, min2.y, max3.y);
    this.z = clamp3(this.z, min2.z, max3.z);
    this.w = clamp3(this.w, min2.w, max3.w);
    return this;
  }
  clampScalar(minVal, maxVal) {
    this.x = clamp3(this.x, minVal, maxVal);
    this.y = clamp3(this.y, minVal, maxVal);
    this.z = clamp3(this.z, minVal, maxVal);
    this.w = clamp3(this.w, minVal, maxVal);
    return this;
  }
  clampLength(min2, max3) {
    const length = this.length();
    return this.divideScalar(length || 1).multiplyScalar(clamp3(length, min2, max3));
  }
  floor() {
    this.x = Math.floor(this.x);
    this.y = Math.floor(this.y);
    this.z = Math.floor(this.z);
    this.w = Math.floor(this.w);
    return this;
  }
  ceil() {
    this.x = Math.ceil(this.x);
    this.y = Math.ceil(this.y);
    this.z = Math.ceil(this.z);
    this.w = Math.ceil(this.w);
    return this;
  }
  round() {
    this.x = Math.round(this.x);
    this.y = Math.round(this.y);
    this.z = Math.round(this.z);
    this.w = Math.round(this.w);
    return this;
  }
  roundToZero() {
    this.x = Math.trunc(this.x);
    this.y = Math.trunc(this.y);
    this.z = Math.trunc(this.z);
    this.w = Math.trunc(this.w);
    return this;
  }
  negate() {
    this.x = -this.x;
    this.y = -this.y;
    this.z = -this.z;
    this.w = -this.w;
    return this;
  }
  dot(v) {
    return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  }
  lengthSq() {
    return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  }
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  }
  manhattanLength() {
    return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  }
  normalize() {
    return this.divideScalar(this.length() || 1);
  }
  setLength(length) {
    return this.normalize().multiplyScalar(length);
  }
  lerp(v, alpha) {
    this.x += (v.x - this.x) * alpha;
    this.y += (v.y - this.y) * alpha;
    this.z += (v.z - this.z) * alpha;
    this.w += (v.w - this.w) * alpha;
    return this;
  }
  lerpVectors(v1, v2, alpha) {
    this.x = v1.x + (v2.x - v1.x) * alpha;
    this.y = v1.y + (v2.y - v1.y) * alpha;
    this.z = v1.z + (v2.z - v1.z) * alpha;
    this.w = v1.w + (v2.w - v1.w) * alpha;
    return this;
  }
  equals(v) {
    return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  }
  fromArray(array2, offset = 0) {
    this.x = array2[offset];
    this.y = array2[offset + 1];
    this.z = array2[offset + 2];
    this.w = array2[offset + 3];
    return this;
  }
  toArray(array2 = [], offset = 0) {
    array2[offset] = this.x;
    array2[offset + 1] = this.y;
    array2[offset + 2] = this.z;
    array2[offset + 3] = this.w;
    return array2;
  }
  fromBufferAttribute(attribute, index) {
    this.x = attribute.getX(index);
    this.y = attribute.getY(index);
    this.z = attribute.getZ(index);
    this.w = attribute.getW(index);
    return this;
  }
  random() {
    this.x = Math.random();
    this.y = Math.random();
    this.z = Math.random();
    this.w = Math.random();
    return this;
  }
  *[Symbol.iterator]() {
    yield this.x;
    yield this.y;
    yield this.z;
    yield this.w;
  }
}
class Box3 {
  constructor(min2 = new Vector3(Infinity, Infinity, Infinity), max3 = new Vector3(-Infinity, -Infinity, -Infinity)) {
    this.isBox3 = true;
    this.min = min2;
    this.max = max3;
  }
  set(min2, max3) {
    this.min.copy(min2);
    this.max.copy(max3);
    return this;
  }
  setFromArray(array2) {
    this.makeEmpty();
    for (let i = 0, il = array2.length;i < il; i += 3) {
      this.expandByPoint(_vector$b.fromArray(array2, i));
    }
    return this;
  }
  setFromBufferAttribute(attribute) {
    this.makeEmpty();
    for (let i = 0, il = attribute.count;i < il; i++) {
      this.expandByPoint(_vector$b.fromBufferAttribute(attribute, i));
    }
    return this;
  }
  setFromPoints(points) {
    this.makeEmpty();
    for (let i = 0, il = points.length;i < il; i++) {
      this.expandByPoint(points[i]);
    }
    return this;
  }
  setFromCenterAndSize(center, size) {
    const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
    this.min.copy(center).sub(halfSize);
    this.max.copy(center).add(halfSize);
    return this;
  }
  setFromObject(object, precise = false) {
    this.makeEmpty();
    return this.expandByObject(object, precise);
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(box) {
    this.min.copy(box.min);
    this.max.copy(box.max);
    return this;
  }
  makeEmpty() {
    this.min.x = this.min.y = this.min.z = Infinity;
    this.max.x = this.max.y = this.max.z = -Infinity;
    return this;
  }
  isEmpty() {
    return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  }
  getCenter(target) {
    return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  }
  getSize(target) {
    return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  }
  expandByPoint(point3) {
    this.min.min(point3);
    this.max.max(point3);
    return this;
  }
  expandByVector(vector) {
    this.min.sub(vector);
    this.max.add(vector);
    return this;
  }
  expandByScalar(scalar) {
    this.min.addScalar(-scalar);
    this.max.addScalar(scalar);
    return this;
  }
  expandByObject(object, precise = false) {
    object.updateWorldMatrix(false, false);
    const geometry = object.geometry;
    if (geometry !== undefined) {
      const positionAttribute = geometry.getAttribute("position");
      if (precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true) {
        for (let i = 0, l = positionAttribute.count;i < l; i++) {
          if (object.isMesh === true) {
            object.getVertexPosition(i, _vector$b);
          } else {
            _vector$b.fromBufferAttribute(positionAttribute, i);
          }
          _vector$b.applyMatrix4(object.matrixWorld);
          this.expandByPoint(_vector$b);
        }
      } else {
        if (object.boundingBox !== undefined) {
          if (object.boundingBox === null) {
            object.computeBoundingBox();
          }
          _box$4.copy(object.boundingBox);
        } else {
          if (geometry.boundingBox === null) {
            geometry.computeBoundingBox();
          }
          _box$4.copy(geometry.boundingBox);
        }
        _box$4.applyMatrix4(object.matrixWorld);
        this.union(_box$4);
      }
    }
    const children = object.children;
    for (let i = 0, l = children.length;i < l; i++) {
      this.expandByObject(children[i], precise);
    }
    return this;
  }
  containsPoint(point3) {
    return point3.x >= this.min.x && point3.x <= this.max.x && point3.y >= this.min.y && point3.y <= this.max.y && point3.z >= this.min.z && point3.z <= this.max.z;
  }
  containsBox(box) {
    return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z;
  }
  getParameter(point3, target) {
    return target.set((point3.x - this.min.x) / (this.max.x - this.min.x), (point3.y - this.min.y) / (this.max.y - this.min.y), (point3.z - this.min.z) / (this.max.z - this.min.z));
  }
  intersectsBox(box) {
    return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y && box.max.z >= this.min.z && box.min.z <= this.max.z;
  }
  intersectsSphere(sphere) {
    this.clampPoint(sphere.center, _vector$b);
    return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  }
  intersectsPlane(plane) {
    let min2, max3;
    if (plane.normal.x > 0) {
      min2 = plane.normal.x * this.min.x;
      max3 = plane.normal.x * this.max.x;
    } else {
      min2 = plane.normal.x * this.max.x;
      max3 = plane.normal.x * this.min.x;
    }
    if (plane.normal.y > 0) {
      min2 += plane.normal.y * this.min.y;
      max3 += plane.normal.y * this.max.y;
    } else {
      min2 += plane.normal.y * this.max.y;
      max3 += plane.normal.y * this.min.y;
    }
    if (plane.normal.z > 0) {
      min2 += plane.normal.z * this.min.z;
      max3 += plane.normal.z * this.max.z;
    } else {
      min2 += plane.normal.z * this.max.z;
      max3 += plane.normal.z * this.min.z;
    }
    return min2 <= -plane.constant && max3 >= -plane.constant;
  }
  intersectsTriangle(triangle) {
    if (this.isEmpty()) {
      return false;
    }
    this.getCenter(_center);
    _extents.subVectors(this.max, _center);
    _v0$2.subVectors(triangle.a, _center);
    _v1$7.subVectors(triangle.b, _center);
    _v2$4.subVectors(triangle.c, _center);
    _f0.subVectors(_v1$7, _v0$2);
    _f1.subVectors(_v2$4, _v1$7);
    _f2.subVectors(_v0$2, _v2$4);
    let axes = [
      0,
      -_f0.z,
      _f0.y,
      0,
      -_f1.z,
      _f1.y,
      0,
      -_f2.z,
      _f2.y,
      _f0.z,
      0,
      -_f0.x,
      _f1.z,
      0,
      -_f1.x,
      _f2.z,
      0,
      -_f2.x,
      -_f0.y,
      _f0.x,
      0,
      -_f1.y,
      _f1.x,
      0,
      -_f2.y,
      _f2.x,
      0
    ];
    if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) {
      return false;
    }
    axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
    if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) {
      return false;
    }
    _triangleNormal.crossVectors(_f0, _f1);
    axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
    return satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents);
  }
  clampPoint(point3, target) {
    return target.copy(point3).clamp(this.min, this.max);
  }
  distanceToPoint(point3) {
    return this.clampPoint(point3, _vector$b).distanceTo(point3);
  }
  getBoundingSphere(target) {
    if (this.isEmpty()) {
      target.makeEmpty();
    } else {
      this.getCenter(target.center);
      target.radius = this.getSize(_vector$b).length() * 0.5;
    }
    return target;
  }
  intersect(box) {
    this.min.max(box.min);
    this.max.min(box.max);
    if (this.isEmpty())
      this.makeEmpty();
    return this;
  }
  union(box) {
    this.min.min(box.min);
    this.max.max(box.max);
    return this;
  }
  applyMatrix4(matrix) {
    if (this.isEmpty())
      return this;
    _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix);
    _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix);
    _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix);
    _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix);
    _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix);
    _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix);
    _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix);
    _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix);
    this.setFromPoints(_points);
    return this;
  }
  translate(offset) {
    this.min.add(offset);
    this.max.add(offset);
    return this;
  }
  equals(box) {
    return box.min.equals(this.min) && box.max.equals(this.max);
  }
  toJSON() {
    return {
      min: this.min.toArray(),
      max: this.max.toArray()
    };
  }
  fromJSON(json) {
    this.min.fromArray(json.min);
    this.max.fromArray(json.max);
    return this;
  }
}
var _points = [
  /* @__PURE__ */ new Vector3,
  /* @__PURE__ */ new Vector3,
  /* @__PURE__ */ new Vector3,
  /* @__PURE__ */ new Vector3,
  /* @__PURE__ */ new Vector3,
  /* @__PURE__ */ new Vector3,
  /* @__PURE__ */ new Vector3,
  /* @__PURE__ */ new Vector3
];
var _vector$b = /* @__PURE__ */ new Vector3;
var _box$4 = /* @__PURE__ */ new Box3;
var _v0$2 = /* @__PURE__ */ new Vector3;
var _v1$7 = /* @__PURE__ */ new Vector3;
var _v2$4 = /* @__PURE__ */ new Vector3;
var _f0 = /* @__PURE__ */ new Vector3;
var _f1 = /* @__PURE__ */ new Vector3;
var _f2 = /* @__PURE__ */ new Vector3;
var _center = /* @__PURE__ */ new Vector3;
var _extents = /* @__PURE__ */ new Vector3;
var _triangleNormal = /* @__PURE__ */ new Vector3;
var _testAxis = /* @__PURE__ */ new Vector3;
function satForAxes(axes, v0, v1, v2, extents) {
  for (let i = 0, j = axes.length - 3;i <= j; i += 3) {
    _testAxis.fromArray(axes, i);
    const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z);
    const p0 = v0.dot(_testAxis);
    const p1 = v1.dot(_testAxis);
    const p2 = v2.dot(_testAxis);
    if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
      return false;
    }
  }
  return true;
}
var _box$3 = /* @__PURE__ */ new Box3;
var _v1$6 = /* @__PURE__ */ new Vector3;
var _v2$3 = /* @__PURE__ */ new Vector3;

class Sphere {
  constructor(center = new Vector3, radius = -1) {
    this.isSphere = true;
    this.center = center;
    this.radius = radius;
  }
  set(center, radius) {
    this.center.copy(center);
    this.radius = radius;
    return this;
  }
  setFromPoints(points, optionalCenter) {
    const center = this.center;
    if (optionalCenter !== undefined) {
      center.copy(optionalCenter);
    } else {
      _box$3.setFromPoints(points).getCenter(center);
    }
    let maxRadiusSq = 0;
    for (let i = 0, il = points.length;i < il; i++) {
      maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
    }
    this.radius = Math.sqrt(maxRadiusSq);
    return this;
  }
  copy(sphere) {
    this.center.copy(sphere.center);
    this.radius = sphere.radius;
    return this;
  }
  isEmpty() {
    return this.radius < 0;
  }
  makeEmpty() {
    this.center.set(0, 0, 0);
    this.radius = -1;
    return this;
  }
  containsPoint(point3) {
    return point3.distanceToSquared(this.center) <= this.radius * this.radius;
  }
  distanceToPoint(point3) {
    return point3.distanceTo(this.center) - this.radius;
  }
  intersectsSphere(sphere) {
    const radiusSum = this.radius + sphere.radius;
    return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  }
  intersectsBox(box) {
    return box.intersectsSphere(this);
  }
  intersectsPlane(plane) {
    return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  }
  clampPoint(point3, target) {
    const deltaLengthSq = this.center.distanceToSquared(point3);
    target.copy(point3);
    if (deltaLengthSq > this.radius * this.radius) {
      target.sub(this.center).normalize();
      target.multiplyScalar(this.radius).add(this.center);
    }
    return target;
  }
  getBoundingBox(target) {
    if (this.isEmpty()) {
      target.makeEmpty();
      return target;
    }
    target.set(this.center, this.center);
    target.expandByScalar(this.radius);
    return target;
  }
  applyMatrix4(matrix) {
    this.center.applyMatrix4(matrix);
    this.radius = this.radius * matrix.getMaxScaleOnAxis();
    return this;
  }
  translate(offset) {
    this.center.add(offset);
    return this;
  }
  expandByPoint(point3) {
    if (this.isEmpty()) {
      this.center.copy(point3);
      this.radius = 0;
      return this;
    }
    _v1$6.subVectors(point3, this.center);
    const lengthSq = _v1$6.lengthSq();
    if (lengthSq > this.radius * this.radius) {
      const length = Math.sqrt(lengthSq);
      const delta = (length - this.radius) * 0.5;
      this.center.addScaledVector(_v1$6, delta / length);
      this.radius += delta;
    }
    return this;
  }
  union(sphere) {
    if (sphere.isEmpty()) {
      return this;
    }
    if (this.isEmpty()) {
      this.copy(sphere);
      return this;
    }
    if (this.center.equals(sphere.center) === true) {
      this.radius = Math.max(this.radius, sphere.radius);
    } else {
      _v2$3.subVectors(sphere.center, this.center).setLength(sphere.radius);
      this.expandByPoint(_v1$6.copy(sphere.center).add(_v2$3));
      this.expandByPoint(_v1$6.copy(sphere.center).sub(_v2$3));
    }
    return this;
  }
  equals(sphere) {
    return sphere.center.equals(this.center) && sphere.radius === this.radius;
  }
  clone() {
    return new this.constructor().copy(this);
  }
  toJSON() {
    return {
      radius: this.radius,
      center: this.center.toArray()
    };
  }
  fromJSON(json) {
    this.radius = json.radius;
    this.center.fromArray(json.center);
    return this;
  }
}
var _vector$a = /* @__PURE__ */ new Vector3;
var _segCenter = /* @__PURE__ */ new Vector3;
var _segDir = /* @__PURE__ */ new Vector3;
var _diff = /* @__PURE__ */ new Vector3;
var _edge1 = /* @__PURE__ */ new Vector3;
var _edge2 = /* @__PURE__ */ new Vector3;
var _normal$1 = /* @__PURE__ */ new Vector3;

class Ray {
  constructor(origin = new Vector3, direction = new Vector3(0, 0, -1)) {
    this.origin = origin;
    this.direction = direction;
  }
  set(origin, direction) {
    this.origin.copy(origin);
    this.direction.copy(direction);
    return this;
  }
  copy(ray) {
    this.origin.copy(ray.origin);
    this.direction.copy(ray.direction);
    return this;
  }
  at(t, target) {
    return target.copy(this.origin).addScaledVector(this.direction, t);
  }
  lookAt(v) {
    this.direction.copy(v).sub(this.origin).normalize();
    return this;
  }
  recast(t) {
    this.origin.copy(this.at(t, _vector$a));
    return this;
  }
  closestPointToPoint(point3, target) {
    target.subVectors(point3, this.origin);
    const directionDistance = target.dot(this.direction);
    if (directionDistance < 0) {
      return target.copy(this.origin);
    }
    return target.copy(this.origin).addScaledVector(this.direction, directionDistance);
  }
  distanceToPoint(point3) {
    return Math.sqrt(this.distanceSqToPoint(point3));
  }
  distanceSqToPoint(point3) {
    const directionDistance = _vector$a.subVectors(point3, this.origin).dot(this.direction);
    if (directionDistance < 0) {
      return this.origin.distanceToSquared(point3);
    }
    _vector$a.copy(this.origin).addScaledVector(this.direction, directionDistance);
    return _vector$a.distanceToSquared(point3);
  }
  distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
    _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
    _segDir.copy(v1).sub(v0).normalize();
    _diff.copy(this.origin).sub(_segCenter);
    const segExtent = v0.distanceTo(v1) * 0.5;
    const a01 = -this.direction.dot(_segDir);
    const b0 = _diff.dot(this.direction);
    const b1 = -_diff.dot(_segDir);
    const c = _diff.lengthSq();
    const det = Math.abs(1 - a01 * a01);
    let s0, s1, sqrDist, extDet;
    if (det > 0) {
      s0 = a01 * b1 - b0;
      s1 = a01 * b0 - b1;
      extDet = segExtent * det;
      if (s0 >= 0) {
        if (s1 >= -extDet) {
          if (s1 <= extDet) {
            const invDet = 1 / det;
            s0 *= invDet;
            s1 *= invDet;
            sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
          } else {
            s1 = segExtent;
            s0 = Math.max(0, -(a01 * s1 + b0));
            sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
          }
        } else {
          s1 = -segExtent;
          s0 = Math.max(0, -(a01 * s1 + b0));
          sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
        }
      } else {
        if (s1 <= -extDet) {
          s0 = Math.max(0, -(-a01 * segExtent + b0));
          s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
          sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
        } else if (s1 <= extDet) {
          s0 = 0;
          s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
          sqrDist = s1 * (s1 + 2 * b1) + c;
        } else {
          s0 = Math.max(0, -(a01 * segExtent + b0));
          s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
          sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
        }
      }
    } else {
      s1 = a01 > 0 ? -segExtent : segExtent;
      s0 = Math.max(0, -(a01 * s1 + b0));
      sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
    }
    if (optionalPointOnRay) {
      optionalPointOnRay.copy(this.origin).addScaledVector(this.direction, s0);
    }
    if (optionalPointOnSegment) {
      optionalPointOnSegment.copy(_segCenter).addScaledVector(_segDir, s1);
    }
    return sqrDist;
  }
  intersectSphere(sphere, target) {
    _vector$a.subVectors(sphere.center, this.origin);
    const tca = _vector$a.dot(this.direction);
    const d2 = _vector$a.dot(_vector$a) - tca * tca;
    const radius2 = sphere.radius * sphere.radius;
    if (d2 > radius2)
      return null;
    const thc = Math.sqrt(radius2 - d2);
    const t0 = tca - thc;
    const t1 = tca + thc;
    if (t1 < 0)
      return null;
    if (t0 < 0)
      return this.at(t1, target);
    return this.at(t0, target);
  }
  intersectsSphere(sphere) {
    if (sphere.radius < 0)
      return false;
    return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  }
  distanceToPlane(plane) {
    const denominator = plane.normal.dot(this.direction);
    if (denominator === 0) {
      if (plane.distanceToPoint(this.origin) === 0) {
        return 0;
      }
      return null;
    }
    const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator;
    return t >= 0 ? t : null;
  }
  intersectPlane(plane, target) {
    const t = this.distanceToPlane(plane);
    if (t === null) {
      return null;
    }
    return this.at(t, target);
  }
  intersectsPlane(plane) {
    const distToPoint = plane.distanceToPoint(this.origin);
    if (distToPoint === 0) {
      return true;
    }
    const denominator = plane.normal.dot(this.direction);
    if (denominator * distToPoint < 0) {
      return true;
    }
    return false;
  }
  intersectBox(box, target) {
    let tmin, tmax, tymin, tymax, tzmin, tzmax;
    const invdirx = 1 / this.direction.x, invdiry = 1 / this.direction.y, invdirz = 1 / this.direction.z;
    const origin = this.origin;
    if (invdirx >= 0) {
      tmin = (box.min.x - origin.x) * invdirx;
      tmax = (box.max.x - origin.x) * invdirx;
    } else {
      tmin = (box.max.x - origin.x) * invdirx;
      tmax = (box.min.x - origin.x) * invdirx;
    }
    if (invdiry >= 0) {
      tymin = (box.min.y - origin.y) * invdiry;
      tymax = (box.max.y - origin.y) * invdiry;
    } else {
      tymin = (box.max.y - origin.y) * invdiry;
      tymax = (box.min.y - origin.y) * invdiry;
    }
    if (tmin > tymax || tymin > tmax)
      return null;
    if (tymin > tmin || isNaN(tmin))
      tmin = tymin;
    if (tymax < tmax || isNaN(tmax))
      tmax = tymax;
    if (invdirz >= 0) {
      tzmin = (box.min.z - origin.z) * invdirz;
      tzmax = (box.max.z - origin.z) * invdirz;
    } else {
      tzmin = (box.max.z - origin.z) * invdirz;
      tzmax = (box.min.z - origin.z) * invdirz;
    }
    if (tmin > tzmax || tzmin > tmax)
      return null;
    if (tzmin > tmin || tmin !== tmin)
      tmin = tzmin;
    if (tzmax < tmax || tmax !== tmax)
      tmax = tzmax;
    if (tmax < 0)
      return null;
    return this.at(tmin >= 0 ? tmin : tmax, target);
  }
  intersectsBox(box) {
    return this.intersectBox(box, _vector$a) !== null;
  }
  intersectTriangle(a, b, c, backfaceCulling, target) {
    _edge1.subVectors(b, a);
    _edge2.subVectors(c, a);
    _normal$1.crossVectors(_edge1, _edge2);
    let DdN = this.direction.dot(_normal$1);
    let sign2;
    if (DdN > 0) {
      if (backfaceCulling)
        return null;
      sign2 = 1;
    } else if (DdN < 0) {
      sign2 = -1;
      DdN = -DdN;
    } else {
      return null;
    }
    _diff.subVectors(this.origin, a);
    const DdQxE2 = sign2 * this.direction.dot(_edge2.crossVectors(_diff, _edge2));
    if (DdQxE2 < 0) {
      return null;
    }
    const DdE1xQ = sign2 * this.direction.dot(_edge1.cross(_diff));
    if (DdE1xQ < 0) {
      return null;
    }
    if (DdQxE2 + DdE1xQ > DdN) {
      return null;
    }
    const QdN = -sign2 * _diff.dot(_normal$1);
    if (QdN < 0) {
      return null;
    }
    return this.at(QdN / DdN, target);
  }
  applyMatrix4(matrix4) {
    this.origin.applyMatrix4(matrix4);
    this.direction.transformDirection(matrix4);
    return this;
  }
  equals(ray) {
    return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  }
  clone() {
    return new this.constructor().copy(this);
  }
}

class Matrix4 {
  constructor(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
    Matrix4.prototype.isMatrix4 = true;
    this.elements = [
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    ];
    if (n11 !== undefined) {
      this.set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44);
    }
  }
  set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
    const te = this.elements;
    te[0] = n11;
    te[4] = n12;
    te[8] = n13;
    te[12] = n14;
    te[1] = n21;
    te[5] = n22;
    te[9] = n23;
    te[13] = n24;
    te[2] = n31;
    te[6] = n32;
    te[10] = n33;
    te[14] = n34;
    te[3] = n41;
    te[7] = n42;
    te[11] = n43;
    te[15] = n44;
    return this;
  }
  identity() {
    this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
    return this;
  }
  clone() {
    return new Matrix4().fromArray(this.elements);
  }
  copy(m) {
    const te = this.elements;
    const me = m.elements;
    te[0] = me[0];
    te[1] = me[1];
    te[2] = me[2];
    te[3] = me[3];
    te[4] = me[4];
    te[5] = me[5];
    te[6] = me[6];
    te[7] = me[7];
    te[8] = me[8];
    te[9] = me[9];
    te[10] = me[10];
    te[11] = me[11];
    te[12] = me[12];
    te[13] = me[13];
    te[14] = me[14];
    te[15] = me[15];
    return this;
  }
  copyPosition(m) {
    const te = this.elements, me = m.elements;
    te[12] = me[12];
    te[13] = me[13];
    te[14] = me[14];
    return this;
  }
  setFromMatrix3(m) {
    const me = m.elements;
    this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1);
    return this;
  }
  extractBasis(xAxis, yAxis, zAxis) {
    xAxis.setFromMatrixColumn(this, 0);
    yAxis.setFromMatrixColumn(this, 1);
    zAxis.setFromMatrixColumn(this, 2);
    return this;
  }
  makeBasis(xAxis, yAxis, zAxis) {
    this.set(xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1);
    return this;
  }
  extractRotation(m) {
    const te = this.elements;
    const me = m.elements;
    const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
    const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
    const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
    te[0] = me[0] * scaleX;
    te[1] = me[1] * scaleX;
    te[2] = me[2] * scaleX;
    te[3] = 0;
    te[4] = me[4] * scaleY;
    te[5] = me[5] * scaleY;
    te[6] = me[6] * scaleY;
    te[7] = 0;
    te[8] = me[8] * scaleZ;
    te[9] = me[9] * scaleZ;
    te[10] = me[10] * scaleZ;
    te[11] = 0;
    te[12] = 0;
    te[13] = 0;
    te[14] = 0;
    te[15] = 1;
    return this;
  }
  makeRotationFromEuler(euler) {
    const te = this.elements;
    const { x: x2, y: y2, z } = euler;
    const a = Math.cos(x2), b = Math.sin(x2);
    const c = Math.cos(y2), d = Math.sin(y2);
    const e = Math.cos(z), f = Math.sin(z);
    if (euler.order === "XYZ") {
      const ae = a * e, af = a * f, be = b * e, bf = b * f;
      te[0] = c * e;
      te[4] = -c * f;
      te[8] = d;
      te[1] = af + be * d;
      te[5] = ae - bf * d;
      te[9] = -b * c;
      te[2] = bf - ae * d;
      te[6] = be + af * d;
      te[10] = a * c;
    } else if (euler.order === "YXZ") {
      const ce = c * e, cf = c * f, de = d * e, df = d * f;
      te[0] = ce + df * b;
      te[4] = de * b - cf;
      te[8] = a * d;
      te[1] = a * f;
      te[5] = a * e;
      te[9] = -b;
      te[2] = cf * b - de;
      te[6] = df + ce * b;
      te[10] = a * c;
    } else if (euler.order === "ZXY") {
      const ce = c * e, cf = c * f, de = d * e, df = d * f;
      te[0] = ce - df * b;
      te[4] = -a * f;
      te[8] = de + cf * b;
      te[1] = cf + de * b;
      te[5] = a * e;
      te[9] = df - ce * b;
      te[2] = -a * d;
      te[6] = b;
      te[10] = a * c;
    } else if (euler.order === "ZYX") {
      const ae = a * e, af = a * f, be = b * e, bf = b * f;
      te[0] = c * e;
      te[4] = be * d - af;
      te[8] = ae * d + bf;
      te[1] = c * f;
      te[5] = bf * d + ae;
      te[9] = af * d - be;
      te[2] = -d;
      te[6] = b * c;
      te[10] = a * c;
    } else if (euler.order === "YZX") {
      const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
      te[0] = c * e;
      te[4] = bd - ac * f;
      te[8] = bc * f + ad;
      te[1] = f;
      te[5] = a * e;
      te[9] = -b * e;
      te[2] = -d * e;
      te[6] = ad * f + bc;
      te[10] = ac - bd * f;
    } else if (euler.order === "XZY") {
      const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
      te[0] = c * e;
      te[4] = -f;
      te[8] = d * e;
      te[1] = ac * f + bd;
      te[5] = a * e;
      te[9] = ad * f - bc;
      te[2] = bc * f - ad;
      te[6] = b * e;
      te[10] = bd * f + ac;
    }
    te[3] = 0;
    te[7] = 0;
    te[11] = 0;
    te[12] = 0;
    te[13] = 0;
    te[14] = 0;
    te[15] = 1;
    return this;
  }
  makeRotationFromQuaternion(q) {
    return this.compose(_zero, q, _one);
  }
  lookAt(eye, target, up) {
    const te = this.elements;
    _z.subVectors(eye, target);
    if (_z.lengthSq() === 0) {
      _z.z = 1;
    }
    _z.normalize();
    _x.crossVectors(up, _z);
    if (_x.lengthSq() === 0) {
      if (Math.abs(up.z) === 1) {
        _z.x += 0.0001;
      } else {
        _z.z += 0.0001;
      }
      _z.normalize();
      _x.crossVectors(up, _z);
    }
    _x.normalize();
    _y.crossVectors(_z, _x);
    te[0] = _x.x;
    te[4] = _y.x;
    te[8] = _z.x;
    te[1] = _x.y;
    te[5] = _y.y;
    te[9] = _z.y;
    te[2] = _x.z;
    te[6] = _y.z;
    te[10] = _z.z;
    return this;
  }
  multiply(m) {
    return this.multiplyMatrices(this, m);
  }
  premultiply(m) {
    return this.multiplyMatrices(m, this);
  }
  multiplyMatrices(a, b) {
    const ae = a.elements;
    const be = b.elements;
    const te = this.elements;
    const a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
    const a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
    const a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
    const a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
    const b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
    const b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
    const b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
    const b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
    te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
    te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
    te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
    te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
    te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
    te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
    te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
    te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
    te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
    te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
    te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
    te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
    te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
    te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
    te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
    te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
    return this;
  }
  multiplyScalar(s) {
    const te = this.elements;
    te[0] *= s;
    te[4] *= s;
    te[8] *= s;
    te[12] *= s;
    te[1] *= s;
    te[5] *= s;
    te[9] *= s;
    te[13] *= s;
    te[2] *= s;
    te[6] *= s;
    te[10] *= s;
    te[14] *= s;
    te[3] *= s;
    te[7] *= s;
    te[11] *= s;
    te[15] *= s;
    return this;
  }
  determinant() {
    const te = this.elements;
    const n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
    const n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
    const n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
    const n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
    return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31);
  }
  transpose() {
    const te = this.elements;
    let tmp;
    tmp = te[1];
    te[1] = te[4];
    te[4] = tmp;
    tmp = te[2];
    te[2] = te[8];
    te[8] = tmp;
    tmp = te[6];
    te[6] = te[9];
    te[9] = tmp;
    tmp = te[3];
    te[3] = te[12];
    te[12] = tmp;
    tmp = te[7];
    te[7] = te[13];
    te[13] = tmp;
    tmp = te[11];
    te[11] = te[14];
    te[14] = tmp;
    return this;
  }
  setPosition(x2, y2, z) {
    const te = this.elements;
    if (x2.isVector3) {
      te[12] = x2.x;
      te[13] = x2.y;
      te[14] = x2.z;
    } else {
      te[12] = x2;
      te[13] = y2;
      te[14] = z;
    }
    return this;
  }
  invert() {
    const te = this.elements, n11 = te[0], n21 = te[1], n31 = te[2], n41 = te[3], n12 = te[4], n22 = te[5], n32 = te[6], n42 = te[7], n13 = te[8], n23 = te[9], n33 = te[10], n43 = te[11], n14 = te[12], n24 = te[13], n34 = te[14], n44 = te[15], t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
    const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
    if (det === 0)
      return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    const detInv = 1 / det;
    te[0] = t11 * detInv;
    te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
    te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
    te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
    te[4] = t12 * detInv;
    te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
    te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
    te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
    te[8] = t13 * detInv;
    te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
    te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
    te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
    te[12] = t14 * detInv;
    te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
    te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
    te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
    return this;
  }
  scale(v) {
    const te = this.elements;
    const { x: x2, y: y2, z } = v;
    te[0] *= x2;
    te[4] *= y2;
    te[8] *= z;
    te[1] *= x2;
    te[5] *= y2;
    te[9] *= z;
    te[2] *= x2;
    te[6] *= y2;
    te[10] *= z;
    te[3] *= x2;
    te[7] *= y2;
    te[11] *= z;
    return this;
  }
  getMaxScaleOnAxis() {
    const te = this.elements;
    const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
    const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
    const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
    return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  }
  makeTranslation(x2, y2, z) {
    if (x2.isVector3) {
      this.set(1, 0, 0, x2.x, 0, 1, 0, x2.y, 0, 0, 1, x2.z, 0, 0, 0, 1);
    } else {
      this.set(1, 0, 0, x2, 0, 1, 0, y2, 0, 0, 1, z, 0, 0, 0, 1);
    }
    return this;
  }
  makeRotationX(theta) {
    const c = Math.cos(theta), s = Math.sin(theta);
    this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
    return this;
  }
  makeRotationY(theta) {
    const c = Math.cos(theta), s = Math.sin(theta);
    this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
    return this;
  }
  makeRotationZ(theta) {
    const c = Math.cos(theta), s = Math.sin(theta);
    this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
    return this;
  }
  makeRotationAxis(axis, angle) {
    const c = Math.cos(angle);
    const s = Math.sin(angle);
    const t = 1 - c;
    const { x: x2, y: y2, z } = axis;
    const tx = t * x2, ty = t * y2;
    this.set(tx * x2 + c, tx * y2 - s * z, tx * z + s * y2, 0, tx * y2 + s * z, ty * y2 + c, ty * z - s * x2, 0, tx * z - s * y2, ty * z + s * x2, t * z * z + c, 0, 0, 0, 0, 1);
    return this;
  }
  makeScale(x2, y2, z) {
    this.set(x2, 0, 0, 0, 0, y2, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
    return this;
  }
  makeShear(xy, xz, yx, yz, zx, zy) {
    this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
    return this;
  }
  compose(position, quaternion, scale) {
    const te = this.elements;
    const { _x: x2, _y: y2, _z: z, _w: w } = quaternion;
    const x22 = x2 + x2, y22 = y2 + y2, z2 = z + z;
    const xx = x2 * x22, xy = x2 * y22, xz = x2 * z2;
    const yy = y2 * y22, yz = y2 * z2, zz = z * z2;
    const wx = w * x22, wy = w * y22, wz = w * z2;
    const { x: sx, y: sy, z: sz } = scale;
    te[0] = (1 - (yy + zz)) * sx;
    te[1] = (xy + wz) * sx;
    te[2] = (xz - wy) * sx;
    te[3] = 0;
    te[4] = (xy - wz) * sy;
    te[5] = (1 - (xx + zz)) * sy;
    te[6] = (yz + wx) * sy;
    te[7] = 0;
    te[8] = (xz + wy) * sz;
    te[9] = (yz - wx) * sz;
    te[10] = (1 - (xx + yy)) * sz;
    te[11] = 0;
    te[12] = position.x;
    te[13] = position.y;
    te[14] = position.z;
    te[15] = 1;
    return this;
  }
  decompose(position, quaternion, scale) {
    const te = this.elements;
    let sx = _v1$5.set(te[0], te[1], te[2]).length();
    const sy = _v1$5.set(te[4], te[5], te[6]).length();
    const sz = _v1$5.set(te[8], te[9], te[10]).length();
    const det = this.determinant();
    if (det < 0)
      sx = -sx;
    position.x = te[12];
    position.y = te[13];
    position.z = te[14];
    _m1$2.copy(this);
    const invSX = 1 / sx;
    const invSY = 1 / sy;
    const invSZ = 1 / sz;
    _m1$2.elements[0] *= invSX;
    _m1$2.elements[1] *= invSX;
    _m1$2.elements[2] *= invSX;
    _m1$2.elements[4] *= invSY;
    _m1$2.elements[5] *= invSY;
    _m1$2.elements[6] *= invSY;
    _m1$2.elements[8] *= invSZ;
    _m1$2.elements[9] *= invSZ;
    _m1$2.elements[10] *= invSZ;
    quaternion.setFromRotationMatrix(_m1$2);
    scale.x = sx;
    scale.y = sy;
    scale.z = sz;
    return this;
  }
  makePerspective(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false) {
    const te = this.elements;
    const x2 = 2 * near / (right - left);
    const y2 = 2 * near / (top - bottom);
    const a = (right + left) / (right - left);
    const b = (top + bottom) / (top - bottom);
    let c, d;
    if (reversedDepth) {
      c = near / (far - near);
      d = far * near / (far - near);
    } else {
      if (coordinateSystem === WebGLCoordinateSystem) {
        c = -(far + near) / (far - near);
        d = -2 * far * near / (far - near);
      } else if (coordinateSystem === WebGPUCoordinateSystem) {
        c = -far / (far - near);
        d = -far * near / (far - near);
      } else {
        throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + coordinateSystem);
      }
    }
    te[0] = x2;
    te[4] = 0;
    te[8] = a;
    te[12] = 0;
    te[1] = 0;
    te[5] = y2;
    te[9] = b;
    te[13] = 0;
    te[2] = 0;
    te[6] = 0;
    te[10] = c;
    te[14] = d;
    te[3] = 0;
    te[7] = 0;
    te[11] = -1;
    te[15] = 0;
    return this;
  }
  makeOrthographic(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false) {
    const te = this.elements;
    const x2 = 2 / (right - left);
    const y2 = 2 / (top - bottom);
    const a = -(right + left) / (right - left);
    const b = -(top + bottom) / (top - bottom);
    let c, d;
    if (reversedDepth) {
      c = 1 / (far - near);
      d = far / (far - near);
    } else {
      if (coordinateSystem === WebGLCoordinateSystem) {
        c = -2 / (far - near);
        d = -(far + near) / (far - near);
      } else if (coordinateSystem === WebGPUCoordinateSystem) {
        c = -1 / (far - near);
        d = -near / (far - near);
      } else {
        throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + coordinateSystem);
      }
    }
    te[0] = x2;
    te[4] = 0;
    te[8] = 0;
    te[12] = a;
    te[1] = 0;
    te[5] = y2;
    te[9] = 0;
    te[13] = b;
    te[2] = 0;
    te[6] = 0;
    te[10] = c;
    te[14] = d;
    te[3] = 0;
    te[7] = 0;
    te[11] = 0;
    te[15] = 1;
    return this;
  }
  equals(matrix) {
    const te = this.elements;
    const me = matrix.elements;
    for (let i = 0;i < 16; i++) {
      if (te[i] !== me[i])
        return false;
    }
    return true;
  }
  fromArray(array2, offset = 0) {
    for (let i = 0;i < 16; i++) {
      this.elements[i] = array2[i + offset];
    }
    return this;
  }
  toArray(array2 = [], offset = 0) {
    const te = this.elements;
    array2[offset] = te[0];
    array2[offset + 1] = te[1];
    array2[offset + 2] = te[2];
    array2[offset + 3] = te[3];
    array2[offset + 4] = te[4];
    array2[offset + 5] = te[5];
    array2[offset + 6] = te[6];
    array2[offset + 7] = te[7];
    array2[offset + 8] = te[8];
    array2[offset + 9] = te[9];
    array2[offset + 10] = te[10];
    array2[offset + 11] = te[11];
    array2[offset + 12] = te[12];
    array2[offset + 13] = te[13];
    array2[offset + 14] = te[14];
    array2[offset + 15] = te[15];
    return array2;
  }
}
var _v1$5 = /* @__PURE__ */ new Vector3;
var _m1$2 = /* @__PURE__ */ new Matrix4;
var _zero = /* @__PURE__ */ new Vector3(0, 0, 0);
var _one = /* @__PURE__ */ new Vector3(1, 1, 1);
var _x = /* @__PURE__ */ new Vector3;
var _y = /* @__PURE__ */ new Vector3;
var _z = /* @__PURE__ */ new Vector3;
var _matrix$2 = /* @__PURE__ */ new Matrix4;
var _quaternion$3 = /* @__PURE__ */ new Quaternion;

class Euler {
  constructor(x2 = 0, y2 = 0, z = 0, order = Euler.DEFAULT_ORDER) {
    this.isEuler = true;
    this._x = x2;
    this._y = y2;
    this._z = z;
    this._order = order;
  }
  get x() {
    return this._x;
  }
  set x(value) {
    this._x = value;
    this._onChangeCallback();
  }
  get y() {
    return this._y;
  }
  set y(value) {
    this._y = value;
    this._onChangeCallback();
  }
  get z() {
    return this._z;
  }
  set z(value) {
    this._z = value;
    this._onChangeCallback();
  }
  get order() {
    return this._order;
  }
  set order(value) {
    this._order = value;
    this._onChangeCallback();
  }
  set(x2, y2, z, order = this._order) {
    this._x = x2;
    this._y = y2;
    this._z = z;
    this._order = order;
    this._onChangeCallback();
    return this;
  }
  clone() {
    return new this.constructor(this._x, this._y, this._z, this._order);
  }
  copy(euler) {
    this._x = euler._x;
    this._y = euler._y;
    this._z = euler._z;
    this._order = euler._order;
    this._onChangeCallback();
    return this;
  }
  setFromRotationMatrix(m, order = this._order, update = true) {
    const te = m.elements;
    const m11 = te[0], m12 = te[4], m13 = te[8];
    const m21 = te[1], m22 = te[5], m23 = te[9];
    const m31 = te[2], m32 = te[6], m33 = te[10];
    switch (order) {
      case "XYZ":
        this._y = Math.asin(clamp3(m13, -1, 1));
        if (Math.abs(m13) < 0.9999999) {
          this._x = Math.atan2(-m23, m33);
          this._z = Math.atan2(-m12, m11);
        } else {
          this._x = Math.atan2(m32, m22);
          this._z = 0;
        }
        break;
      case "YXZ":
        this._x = Math.asin(-clamp3(m23, -1, 1));
        if (Math.abs(m23) < 0.9999999) {
          this._y = Math.atan2(m13, m33);
          this._z = Math.atan2(m21, m22);
        } else {
          this._y = Math.atan2(-m31, m11);
          this._z = 0;
        }
        break;
      case "ZXY":
        this._x = Math.asin(clamp3(m32, -1, 1));
        if (Math.abs(m32) < 0.9999999) {
          this._y = Math.atan2(-m31, m33);
          this._z = Math.atan2(-m12, m22);
        } else {
          this._y = 0;
          this._z = Math.atan2(m21, m11);
        }
        break;
      case "ZYX":
        this._y = Math.asin(-clamp3(m31, -1, 1));
        if (Math.abs(m31) < 0.9999999) {
          this._x = Math.atan2(m32, m33);
          this._z = Math.atan2(m21, m11);
        } else {
          this._x = 0;
          this._z = Math.atan2(-m12, m22);
        }
        break;
      case "YZX":
        this._z = Math.asin(clamp3(m21, -1, 1));
        if (Math.abs(m21) < 0.9999999) {
          this._x = Math.atan2(-m23, m22);
          this._y = Math.atan2(-m31, m11);
        } else {
          this._x = 0;
          this._y = Math.atan2(m13, m33);
        }
        break;
      case "XZY":
        this._z = Math.asin(-clamp3(m12, -1, 1));
        if (Math.abs(m12) < 0.9999999) {
          this._x = Math.atan2(m32, m22);
          this._y = Math.atan2(m13, m11);
        } else {
          this._x = Math.atan2(-m23, m33);
          this._y = 0;
        }
        break;
      default:
        console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: " + order);
    }
    this._order = order;
    if (update === true)
      this._onChangeCallback();
    return this;
  }
  setFromQuaternion(q, order, update) {
    _matrix$2.makeRotationFromQuaternion(q);
    return this.setFromRotationMatrix(_matrix$2, order, update);
  }
  setFromVector3(v, order = this._order) {
    return this.set(v.x, v.y, v.z, order);
  }
  reorder(newOrder) {
    _quaternion$3.setFromEuler(this);
    return this.setFromQuaternion(_quaternion$3, newOrder);
  }
  equals(euler) {
    return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  }
  fromArray(array2) {
    this._x = array2[0];
    this._y = array2[1];
    this._z = array2[2];
    if (array2[3] !== undefined)
      this._order = array2[3];
    this._onChangeCallback();
    return this;
  }
  toArray(array2 = [], offset = 0) {
    array2[offset] = this._x;
    array2[offset + 1] = this._y;
    array2[offset + 2] = this._z;
    array2[offset + 3] = this._order;
    return array2;
  }
  _onChange(callback) {
    this._onChangeCallback = callback;
    return this;
  }
  _onChangeCallback() {}
  *[Symbol.iterator]() {
    yield this._x;
    yield this._y;
    yield this._z;
    yield this._order;
  }
}
Euler.DEFAULT_ORDER = "XYZ";

class Layers {
  constructor() {
    this.mask = 1 | 0;
  }
  set(layer) {
    this.mask = (1 << layer | 0) >>> 0;
  }
  enable(layer) {
    this.mask |= 1 << layer | 0;
  }
  enableAll() {
    this.mask = 4294967295 | 0;
  }
  toggle(layer) {
    this.mask ^= 1 << layer | 0;
  }
  disable(layer) {
    this.mask &= ~(1 << layer | 0);
  }
  disableAll() {
    this.mask = 0;
  }
  test(layers) {
    return (this.mask & layers.mask) !== 0;
  }
  isEnabled(layer) {
    return (this.mask & (1 << layer | 0)) !== 0;
  }
}
var _object3DId = 0;
var _v1$4 = /* @__PURE__ */ new Vector3;
var _q1 = /* @__PURE__ */ new Quaternion;
var _m1$1 = /* @__PURE__ */ new Matrix4;
var _target = /* @__PURE__ */ new Vector3;
var _position$3 = /* @__PURE__ */ new Vector3;
var _scale$2 = /* @__PURE__ */ new Vector3;
var _quaternion$2 = /* @__PURE__ */ new Quaternion;
var _xAxis = /* @__PURE__ */ new Vector3(1, 0, 0);
var _yAxis = /* @__PURE__ */ new Vector3(0, 1, 0);
var _zAxis = /* @__PURE__ */ new Vector3(0, 0, 1);
var _addedEvent = { type: "added" };
var _removedEvent = { type: "removed" };
var _childaddedEvent = { type: "childadded", child: null };
var _childremovedEvent = { type: "childremoved", child: null };

class Object3D extends EventDispatcher {
  constructor() {
    super();
    this.isObject3D = true;
    Object.defineProperty(this, "id", { value: _object3DId++ });
    this.uuid = generateUUID();
    this.name = "";
    this.type = "Object3D";
    this.parent = null;
    this.children = [];
    this.up = Object3D.DEFAULT_UP.clone();
    const position = new Vector3;
    const rotation = new Euler;
    const quaternion = new Quaternion;
    const scale = new Vector3(1, 1, 1);
    function onRotationChange() {
      quaternion.setFromEuler(rotation, false);
    }
    function onQuaternionChange() {
      rotation.setFromQuaternion(quaternion, undefined, false);
    }
    rotation._onChange(onRotationChange);
    quaternion._onChange(onQuaternionChange);
    Object.defineProperties(this, {
      position: {
        configurable: true,
        enumerable: true,
        value: position
      },
      rotation: {
        configurable: true,
        enumerable: true,
        value: rotation
      },
      quaternion: {
        configurable: true,
        enumerable: true,
        value: quaternion
      },
      scale: {
        configurable: true,
        enumerable: true,
        value: scale
      },
      modelViewMatrix: {
        value: new Matrix4
      },
      normalMatrix: {
        value: new Matrix3
      }
    });
    this.matrix = new Matrix4;
    this.matrixWorld = new Matrix4;
    this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
    this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE;
    this.matrixWorldNeedsUpdate = false;
    this.layers = new Layers;
    this.visible = true;
    this.castShadow = false;
    this.receiveShadow = false;
    this.frustumCulled = true;
    this.renderOrder = 0;
    this.animations = [];
    this.customDepthMaterial = undefined;
    this.customDistanceMaterial = undefined;
    this.userData = {};
  }
  onBeforeShadow() {}
  onAfterShadow() {}
  onBeforeRender() {}
  onAfterRender() {}
  applyMatrix4(matrix) {
    if (this.matrixAutoUpdate)
      this.updateMatrix();
    this.matrix.premultiply(matrix);
    this.matrix.decompose(this.position, this.quaternion, this.scale);
  }
  applyQuaternion(q) {
    this.quaternion.premultiply(q);
    return this;
  }
  setRotationFromAxisAngle(axis, angle) {
    this.quaternion.setFromAxisAngle(axis, angle);
  }
  setRotationFromEuler(euler) {
    this.quaternion.setFromEuler(euler, true);
  }
  setRotationFromMatrix(m) {
    this.quaternion.setFromRotationMatrix(m);
  }
  setRotationFromQuaternion(q) {
    this.quaternion.copy(q);
  }
  rotateOnAxis(axis, angle) {
    _q1.setFromAxisAngle(axis, angle);
    this.quaternion.multiply(_q1);
    return this;
  }
  rotateOnWorldAxis(axis, angle) {
    _q1.setFromAxisAngle(axis, angle);
    this.quaternion.premultiply(_q1);
    return this;
  }
  rotateX(angle) {
    return this.rotateOnAxis(_xAxis, angle);
  }
  rotateY(angle) {
    return this.rotateOnAxis(_yAxis, angle);
  }
  rotateZ(angle) {
    return this.rotateOnAxis(_zAxis, angle);
  }
  translateOnAxis(axis, distance) {
    _v1$4.copy(axis).applyQuaternion(this.quaternion);
    this.position.add(_v1$4.multiplyScalar(distance));
    return this;
  }
  translateX(distance) {
    return this.translateOnAxis(_xAxis, distance);
  }
  translateY(distance) {
    return this.translateOnAxis(_yAxis, distance);
  }
  translateZ(distance) {
    return this.translateOnAxis(_zAxis, distance);
  }
  localToWorld(vector) {
    this.updateWorldMatrix(true, false);
    return vector.applyMatrix4(this.matrixWorld);
  }
  worldToLocal(vector) {
    this.updateWorldMatrix(true, false);
    return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  }
  lookAt(x2, y2, z) {
    if (x2.isVector3) {
      _target.copy(x2);
    } else {
      _target.set(x2, y2, z);
    }
    const parent = this.parent;
    this.updateWorldMatrix(true, false);
    _position$3.setFromMatrixPosition(this.matrixWorld);
    if (this.isCamera || this.isLight) {
      _m1$1.lookAt(_position$3, _target, this.up);
    } else {
      _m1$1.lookAt(_target, _position$3, this.up);
    }
    this.quaternion.setFromRotationMatrix(_m1$1);
    if (parent) {
      _m1$1.extractRotation(parent.matrixWorld);
      _q1.setFromRotationMatrix(_m1$1);
      this.quaternion.premultiply(_q1.invert());
    }
  }
  add(object) {
    if (arguments.length > 1) {
      for (let i = 0;i < arguments.length; i++) {
        this.add(arguments[i]);
      }
      return this;
    }
    if (object === this) {
      console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
      return this;
    }
    if (object && object.isObject3D) {
      object.removeFromParent();
      object.parent = this;
      this.children.push(object);
      object.dispatchEvent(_addedEvent);
      _childaddedEvent.child = object;
      this.dispatchEvent(_childaddedEvent);
      _childaddedEvent.child = null;
    } else {
      console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
    }
    return this;
  }
  remove(object) {
    if (arguments.length > 1) {
      for (let i = 0;i < arguments.length; i++) {
        this.remove(arguments[i]);
      }
      return this;
    }
    const index = this.children.indexOf(object);
    if (index !== -1) {
      object.parent = null;
      this.children.splice(index, 1);
      object.dispatchEvent(_removedEvent);
      _childremovedEvent.child = object;
      this.dispatchEvent(_childremovedEvent);
      _childremovedEvent.child = null;
    }
    return this;
  }
  removeFromParent() {
    const parent = this.parent;
    if (parent !== null) {
      parent.remove(this);
    }
    return this;
  }
  clear() {
    return this.remove(...this.children);
  }
  attach(object) {
    this.updateWorldMatrix(true, false);
    _m1$1.copy(this.matrixWorld).invert();
    if (object.parent !== null) {
      object.parent.updateWorldMatrix(true, false);
      _m1$1.multiply(object.parent.matrixWorld);
    }
    object.applyMatrix4(_m1$1);
    object.removeFromParent();
    object.parent = this;
    this.children.push(object);
    object.updateWorldMatrix(false, true);
    object.dispatchEvent(_addedEvent);
    _childaddedEvent.child = object;
    this.dispatchEvent(_childaddedEvent);
    _childaddedEvent.child = null;
    return this;
  }
  getObjectById(id) {
    return this.getObjectByProperty("id", id);
  }
  getObjectByName(name) {
    return this.getObjectByProperty("name", name);
  }
  getObjectByProperty(name, value) {
    if (this[name] === value)
      return this;
    for (let i = 0, l = this.children.length;i < l; i++) {
      const child = this.children[i];
      const object = child.getObjectByProperty(name, value);
      if (object !== undefined) {
        return object;
      }
    }
    return;
  }
  getObjectsByProperty(name, value, result = []) {
    if (this[name] === value)
      result.push(this);
    const children = this.children;
    for (let i = 0, l = children.length;i < l; i++) {
      children[i].getObjectsByProperty(name, value, result);
    }
    return result;
  }
  getWorldPosition(target) {
    this.updateWorldMatrix(true, false);
    return target.setFromMatrixPosition(this.matrixWorld);
  }
  getWorldQuaternion(target) {
    this.updateWorldMatrix(true, false);
    this.matrixWorld.decompose(_position$3, target, _scale$2);
    return target;
  }
  getWorldScale(target) {
    this.updateWorldMatrix(true, false);
    this.matrixWorld.decompose(_position$3, _quaternion$2, target);
    return target;
  }
  getWorldDirection(target) {
    this.updateWorldMatrix(true, false);
    const e = this.matrixWorld.elements;
    return target.set(e[8], e[9], e[10]).normalize();
  }
  raycast() {}
  traverse(callback) {
    callback(this);
    const children = this.children;
    for (let i = 0, l = children.length;i < l; i++) {
      children[i].traverse(callback);
    }
  }
  traverseVisible(callback) {
    if (this.visible === false)
      return;
    callback(this);
    const children = this.children;
    for (let i = 0, l = children.length;i < l; i++) {
      children[i].traverseVisible(callback);
    }
  }
  traverseAncestors(callback) {
    const parent = this.parent;
    if (parent !== null) {
      callback(parent);
      parent.traverseAncestors(callback);
    }
  }
  updateMatrix() {
    this.matrix.compose(this.position, this.quaternion, this.scale);
    this.matrixWorldNeedsUpdate = true;
  }
  updateMatrixWorld(force) {
    if (this.matrixAutoUpdate)
      this.updateMatrix();
    if (this.matrixWorldNeedsUpdate || force) {
      if (this.matrixWorldAutoUpdate === true) {
        if (this.parent === null) {
          this.matrixWorld.copy(this.matrix);
        } else {
          this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
        }
      }
      this.matrixWorldNeedsUpdate = false;
      force = true;
    }
    const children = this.children;
    for (let i = 0, l = children.length;i < l; i++) {
      const child = children[i];
      child.updateMatrixWorld(force);
    }
  }
  updateWorldMatrix(updateParents, updateChildren) {
    const parent = this.parent;
    if (updateParents === true && parent !== null) {
      parent.updateWorldMatrix(true, false);
    }
    if (this.matrixAutoUpdate)
      this.updateMatrix();
    if (this.matrixWorldAutoUpdate === true) {
      if (this.parent === null) {
        this.matrixWorld.copy(this.matrix);
      } else {
        this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
      }
    }
    if (updateChildren === true) {
      const children = this.children;
      for (let i = 0, l = children.length;i < l; i++) {
        const child = children[i];
        child.updateWorldMatrix(false, true);
      }
    }
  }
  toJSON(meta) {
    const isRootObject = meta === undefined || typeof meta === "string";
    const output = {};
    if (isRootObject) {
      meta = {
        geometries: {},
        materials: {},
        textures: {},
        images: {},
        shapes: {},
        skeletons: {},
        animations: {},
        nodes: {}
      };
      output.metadata = {
        version: 4.7,
        type: "Object",
        generator: "Object3D.toJSON"
      };
    }
    const object = {};
    object.uuid = this.uuid;
    object.type = this.type;
    if (this.name !== "")
      object.name = this.name;
    if (this.castShadow === true)
      object.castShadow = true;
    if (this.receiveShadow === true)
      object.receiveShadow = true;
    if (this.visible === false)
      object.visible = false;
    if (this.frustumCulled === false)
      object.frustumCulled = false;
    if (this.renderOrder !== 0)
      object.renderOrder = this.renderOrder;
    if (Object.keys(this.userData).length > 0)
      object.userData = this.userData;
    object.layers = this.layers.mask;
    object.matrix = this.matrix.toArray();
    object.up = this.up.toArray();
    if (this.matrixAutoUpdate === false)
      object.matrixAutoUpdate = false;
    if (this.isInstancedMesh) {
      object.type = "InstancedMesh";
      object.count = this.count;
      object.instanceMatrix = this.instanceMatrix.toJSON();
      if (this.instanceColor !== null)
        object.instanceColor = this.instanceColor.toJSON();
    }
    if (this.isBatchedMesh) {
      object.type = "BatchedMesh";
      object.perObjectFrustumCulled = this.perObjectFrustumCulled;
      object.sortObjects = this.sortObjects;
      object.drawRanges = this._drawRanges;
      object.reservedRanges = this._reservedRanges;
      object.geometryInfo = this._geometryInfo.map((info) => ({
        ...info,
        boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
        boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
      }));
      object.instanceInfo = this._instanceInfo.map((info) => ({ ...info }));
      object.availableInstanceIds = this._availableInstanceIds.slice();
      object.availableGeometryIds = this._availableGeometryIds.slice();
      object.nextIndexStart = this._nextIndexStart;
      object.nextVertexStart = this._nextVertexStart;
      object.geometryCount = this._geometryCount;
      object.maxInstanceCount = this._maxInstanceCount;
      object.maxVertexCount = this._maxVertexCount;
      object.maxIndexCount = this._maxIndexCount;
      object.geometryInitialized = this._geometryInitialized;
      object.matricesTexture = this._matricesTexture.toJSON(meta);
      object.indirectTexture = this._indirectTexture.toJSON(meta);
      if (this._colorsTexture !== null) {
        object.colorsTexture = this._colorsTexture.toJSON(meta);
      }
      if (this.boundingSphere !== null) {
        object.boundingSphere = this.boundingSphere.toJSON();
      }
      if (this.boundingBox !== null) {
        object.boundingBox = this.boundingBox.toJSON();
      }
    }
    function serialize(library, element) {
      if (library[element.uuid] === undefined) {
        library[element.uuid] = element.toJSON(meta);
      }
      return element.uuid;
    }
    if (this.isScene) {
      if (this.background) {
        if (this.background.isColor) {
          object.background = this.background.toJSON();
        } else if (this.background.isTexture) {
          object.background = this.background.toJSON(meta).uuid;
        }
      }
      if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) {
        object.environment = this.environment.toJSON(meta).uuid;
      }
    } else if (this.isMesh || this.isLine || this.isPoints) {
      object.geometry = serialize(meta.geometries, this.geometry);
      const parameters = this.geometry.parameters;
      if (parameters !== undefined && parameters.shapes !== undefined) {
        const shapes = parameters.shapes;
        if (Array.isArray(shapes)) {
          for (let i = 0, l = shapes.length;i < l; i++) {
            const shape = shapes[i];
            serialize(meta.shapes, shape);
          }
        } else {
          serialize(meta.shapes, shapes);
        }
      }
    }
    if (this.isSkinnedMesh) {
      object.bindMode = this.bindMode;
      object.bindMatrix = this.bindMatrix.toArray();
      if (this.skeleton !== undefined) {
        serialize(meta.skeletons, this.skeleton);
        object.skeleton = this.skeleton.uuid;
      }
    }
    if (this.material !== undefined) {
      if (Array.isArray(this.material)) {
        const uuids = [];
        for (let i = 0, l = this.material.length;i < l; i++) {
          uuids.push(serialize(meta.materials, this.material[i]));
        }
        object.material = uuids;
      } else {
        object.material = serialize(meta.materials, this.material);
      }
    }
    if (this.children.length > 0) {
      object.children = [];
      for (let i = 0;i < this.children.length; i++) {
        object.children.push(this.children[i].toJSON(meta).object);
      }
    }
    if (this.animations.length > 0) {
      object.animations = [];
      for (let i = 0;i < this.animations.length; i++) {
        const animation = this.animations[i];
        object.animations.push(serialize(meta.animations, animation));
      }
    }
    if (isRootObject) {
      const geometries = extractFromCache(meta.geometries);
      const materials = extractFromCache(meta.materials);
      const textures = extractFromCache(meta.textures);
      const images = extractFromCache(meta.images);
      const shapes = extractFromCache(meta.shapes);
      const skeletons = extractFromCache(meta.skeletons);
      const animations = extractFromCache(meta.animations);
      const nodes = extractFromCache(meta.nodes);
      if (geometries.length > 0)
        output.geometries = geometries;
      if (materials.length > 0)
        output.materials = materials;
      if (textures.length > 0)
        output.textures = textures;
      if (images.length > 0)
        output.images = images;
      if (shapes.length > 0)
        output.shapes = shapes;
      if (skeletons.length > 0)
        output.skeletons = skeletons;
      if (animations.length > 0)
        output.animations = animations;
      if (nodes.length > 0)
        output.nodes = nodes;
    }
    output.object = object;
    return output;
    function extractFromCache(cache) {
      const values = [];
      for (const key in cache) {
        const data = cache[key];
        delete data.metadata;
        values.push(data);
      }
      return values;
    }
  }
  clone(recursive) {
    return new this.constructor().copy(this, recursive);
  }
  copy(source, recursive = true) {
    this.name = source.name;
    this.up.copy(source.up);
    this.position.copy(source.position);
    this.rotation.order = source.rotation.order;
    this.quaternion.copy(source.quaternion);
    this.scale.copy(source.scale);
    this.matrix.copy(source.matrix);
    this.matrixWorld.copy(source.matrixWorld);
    this.matrixAutoUpdate = source.matrixAutoUpdate;
    this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
    this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
    this.layers.mask = source.layers.mask;
    this.visible = source.visible;
    this.castShadow = source.castShadow;
    this.receiveShadow = source.receiveShadow;
    this.frustumCulled = source.frustumCulled;
    this.renderOrder = source.renderOrder;
    this.animations = source.animations.slice();
    this.userData = JSON.parse(JSON.stringify(source.userData));
    if (recursive === true) {
      for (let i = 0;i < source.children.length; i++) {
        const child = source.children[i];
        this.add(child.clone());
      }
    }
    return this;
  }
}
Object3D.DEFAULT_UP = /* @__PURE__ */ new Vector3(0, 1, 0);
Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
var _v0$1 = /* @__PURE__ */ new Vector3;
var _v1$3 = /* @__PURE__ */ new Vector3;
var _v2$2 = /* @__PURE__ */ new Vector3;
var _v3$2 = /* @__PURE__ */ new Vector3;
var _vab = /* @__PURE__ */ new Vector3;
var _vac = /* @__PURE__ */ new Vector3;
var _vbc = /* @__PURE__ */ new Vector3;
var _vap = /* @__PURE__ */ new Vector3;
var _vbp = /* @__PURE__ */ new Vector3;
var _vcp = /* @__PURE__ */ new Vector3;
var _v40 = /* @__PURE__ */ new Vector4;
var _v41 = /* @__PURE__ */ new Vector4;
var _v42 = /* @__PURE__ */ new Vector4;

class Triangle {
  constructor(a = new Vector3, b = new Vector3, c = new Vector3) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  static getNormal(a, b, c, target) {
    target.subVectors(c, b);
    _v0$1.subVectors(a, b);
    target.cross(_v0$1);
    const targetLengthSq = target.lengthSq();
    if (targetLengthSq > 0) {
      return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
    }
    return target.set(0, 0, 0);
  }
  static getBarycoord(point3, a, b, c, target) {
    _v0$1.subVectors(c, a);
    _v1$3.subVectors(b, a);
    _v2$2.subVectors(point3, a);
    const dot00 = _v0$1.dot(_v0$1);
    const dot01 = _v0$1.dot(_v1$3);
    const dot02 = _v0$1.dot(_v2$2);
    const dot11 = _v1$3.dot(_v1$3);
    const dot12 = _v1$3.dot(_v2$2);
    const denom = dot00 * dot11 - dot01 * dot01;
    if (denom === 0) {
      target.set(0, 0, 0);
      return null;
    }
    const invDenom = 1 / denom;
    const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
    const v = (dot00 * dot12 - dot01 * dot02) * invDenom;
    return target.set(1 - u - v, v, u);
  }
  static containsPoint(point3, a, b, c) {
    if (this.getBarycoord(point3, a, b, c, _v3$2) === null) {
      return false;
    }
    return _v3$2.x >= 0 && _v3$2.y >= 0 && _v3$2.x + _v3$2.y <= 1;
  }
  static getInterpolation(point3, p1, p2, p3, v1, v2, v3, target) {
    if (this.getBarycoord(point3, p1, p2, p3, _v3$2) === null) {
      target.x = 0;
      target.y = 0;
      if ("z" in target)
        target.z = 0;
      if ("w" in target)
        target.w = 0;
      return null;
    }
    target.setScalar(0);
    target.addScaledVector(v1, _v3$2.x);
    target.addScaledVector(v2, _v3$2.y);
    target.addScaledVector(v3, _v3$2.z);
    return target;
  }
  static getInterpolatedAttribute(attr, i1, i2, i3, barycoord, target) {
    _v40.setScalar(0);
    _v41.setScalar(0);
    _v42.setScalar(0);
    _v40.fromBufferAttribute(attr, i1);
    _v41.fromBufferAttribute(attr, i2);
    _v42.fromBufferAttribute(attr, i3);
    target.setScalar(0);
    target.addScaledVector(_v40, barycoord.x);
    target.addScaledVector(_v41, barycoord.y);
    target.addScaledVector(_v42, barycoord.z);
    return target;
  }
  static isFrontFacing(a, b, c, direction) {
    _v0$1.subVectors(c, b);
    _v1$3.subVectors(a, b);
    return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  }
  set(a, b, c) {
    this.a.copy(a);
    this.b.copy(b);
    this.c.copy(c);
    return this;
  }
  setFromPointsAndIndices(points, i0, i1, i2) {
    this.a.copy(points[i0]);
    this.b.copy(points[i1]);
    this.c.copy(points[i2]);
    return this;
  }
  setFromAttributeAndIndices(attribute, i0, i1, i2) {
    this.a.fromBufferAttribute(attribute, i0);
    this.b.fromBufferAttribute(attribute, i1);
    this.c.fromBufferAttribute(attribute, i2);
    return this;
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(triangle) {
    this.a.copy(triangle.a);
    this.b.copy(triangle.b);
    this.c.copy(triangle.c);
    return this;
  }
  getArea() {
    _v0$1.subVectors(this.c, this.b);
    _v1$3.subVectors(this.a, this.b);
    return _v0$1.cross(_v1$3).length() * 0.5;
  }
  getMidpoint(target) {
    return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  }
  getNormal(target) {
    return Triangle.getNormal(this.a, this.b, this.c, target);
  }
  getPlane(target) {
    return target.setFromCoplanarPoints(this.a, this.b, this.c);
  }
  getBarycoord(point3, target) {
    return Triangle.getBarycoord(point3, this.a, this.b, this.c, target);
  }
  getInterpolation(point3, v1, v2, v3, target) {
    return Triangle.getInterpolation(point3, this.a, this.b, this.c, v1, v2, v3, target);
  }
  containsPoint(point3) {
    return Triangle.containsPoint(point3, this.a, this.b, this.c);
  }
  isFrontFacing(direction) {
    return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  }
  intersectsBox(box) {
    return box.intersectsTriangle(this);
  }
  closestPointToPoint(p, target) {
    const a = this.a, b = this.b, c = this.c;
    let v, w;
    _vab.subVectors(b, a);
    _vac.subVectors(c, a);
    _vap.subVectors(p, a);
    const d1 = _vab.dot(_vap);
    const d2 = _vac.dot(_vap);
    if (d1 <= 0 && d2 <= 0) {
      return target.copy(a);
    }
    _vbp.subVectors(p, b);
    const d3 = _vab.dot(_vbp);
    const d4 = _vac.dot(_vbp);
    if (d3 >= 0 && d4 <= d3) {
      return target.copy(b);
    }
    const vc = d1 * d4 - d3 * d2;
    if (vc <= 0 && d1 >= 0 && d3 <= 0) {
      v = d1 / (d1 - d3);
      return target.copy(a).addScaledVector(_vab, v);
    }
    _vcp.subVectors(p, c);
    const d5 = _vab.dot(_vcp);
    const d6 = _vac.dot(_vcp);
    if (d6 >= 0 && d5 <= d6) {
      return target.copy(c);
    }
    const vb = d5 * d2 - d1 * d6;
    if (vb <= 0 && d2 >= 0 && d6 <= 0) {
      w = d2 / (d2 - d6);
      return target.copy(a).addScaledVector(_vac, w);
    }
    const va = d3 * d6 - d5 * d4;
    if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
      _vbc.subVectors(c, b);
      w = (d4 - d3) / (d4 - d3 + (d5 - d6));
      return target.copy(b).addScaledVector(_vbc, w);
    }
    const denom = 1 / (va + vb + vc);
    v = vb * denom;
    w = vc * denom;
    return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  }
  equals(triangle) {
    return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  }
}
var _colorKeywords = {
  aliceblue: 15792383,
  antiquewhite: 16444375,
  aqua: 65535,
  aquamarine: 8388564,
  azure: 15794175,
  beige: 16119260,
  bisque: 16770244,
  black: 0,
  blanchedalmond: 16772045,
  blue: 255,
  blueviolet: 9055202,
  brown: 10824234,
  burlywood: 14596231,
  cadetblue: 6266528,
  chartreuse: 8388352,
  chocolate: 13789470,
  coral: 16744272,
  cornflowerblue: 6591981,
  cornsilk: 16775388,
  crimson: 14423100,
  cyan: 65535,
  darkblue: 139,
  darkcyan: 35723,
  darkgoldenrod: 12092939,
  darkgray: 11119017,
  darkgreen: 25600,
  darkgrey: 11119017,
  darkkhaki: 12433259,
  darkmagenta: 9109643,
  darkolivegreen: 5597999,
  darkorange: 16747520,
  darkorchid: 10040012,
  darkred: 9109504,
  darksalmon: 15308410,
  darkseagreen: 9419919,
  darkslateblue: 4734347,
  darkslategray: 3100495,
  darkslategrey: 3100495,
  darkturquoise: 52945,
  darkviolet: 9699539,
  deeppink: 16716947,
  deepskyblue: 49151,
  dimgray: 6908265,
  dimgrey: 6908265,
  dodgerblue: 2003199,
  firebrick: 11674146,
  floralwhite: 16775920,
  forestgreen: 2263842,
  fuchsia: 16711935,
  gainsboro: 14474460,
  ghostwhite: 16316671,
  gold: 16766720,
  goldenrod: 14329120,
  gray: 8421504,
  green: 32768,
  greenyellow: 11403055,
  grey: 8421504,
  honeydew: 15794160,
  hotpink: 16738740,
  indianred: 13458524,
  indigo: 4915330,
  ivory: 16777200,
  khaki: 15787660,
  lavender: 15132410,
  lavenderblush: 16773365,
  lawngreen: 8190976,
  lemonchiffon: 16775885,
  lightblue: 11393254,
  lightcoral: 15761536,
  lightcyan: 14745599,
  lightgoldenrodyellow: 16448210,
  lightgray: 13882323,
  lightgreen: 9498256,
  lightgrey: 13882323,
  lightpink: 16758465,
  lightsalmon: 16752762,
  lightseagreen: 2142890,
  lightskyblue: 8900346,
  lightslategray: 7833753,
  lightslategrey: 7833753,
  lightsteelblue: 11584734,
  lightyellow: 16777184,
  lime: 65280,
  limegreen: 3329330,
  linen: 16445670,
  magenta: 16711935,
  maroon: 8388608,
  mediumaquamarine: 6737322,
  mediumblue: 205,
  mediumorchid: 12211667,
  mediumpurple: 9662683,
  mediumseagreen: 3978097,
  mediumslateblue: 8087790,
  mediumspringgreen: 64154,
  mediumturquoise: 4772300,
  mediumvioletred: 13047173,
  midnightblue: 1644912,
  mintcream: 16121850,
  mistyrose: 16770273,
  moccasin: 16770229,
  navajowhite: 16768685,
  navy: 128,
  oldlace: 16643558,
  olive: 8421376,
  olivedrab: 7048739,
  orange: 16753920,
  orangered: 16729344,
  orchid: 14315734,
  palegoldenrod: 15657130,
  palegreen: 10025880,
  paleturquoise: 11529966,
  palevioletred: 14381203,
  papayawhip: 16773077,
  peachpuff: 16767673,
  peru: 13468991,
  pink: 16761035,
  plum: 14524637,
  powderblue: 11591910,
  purple: 8388736,
  rebeccapurple: 6697881,
  red: 16711680,
  rosybrown: 12357519,
  royalblue: 4286945,
  saddlebrown: 9127187,
  salmon: 16416882,
  sandybrown: 16032864,
  seagreen: 3050327,
  seashell: 16774638,
  sienna: 10506797,
  silver: 12632256,
  skyblue: 8900331,
  slateblue: 6970061,
  slategray: 7372944,
  slategrey: 7372944,
  snow: 16775930,
  springgreen: 65407,
  steelblue: 4620980,
  tan: 13808780,
  teal: 32896,
  thistle: 14204888,
  tomato: 16737095,
  turquoise: 4251856,
  violet: 15631086,
  wheat: 16113331,
  white: 16777215,
  whitesmoke: 16119285,
  yellow: 16776960,
  yellowgreen: 10145074
};
var _hslA = { h: 0, s: 0, l: 0 };
var _hslB = { h: 0, s: 0, l: 0 };
function hue2rgb(p, q, t) {
  if (t < 0)
    t += 1;
  if (t > 1)
    t -= 1;
  if (t < 1 / 6)
    return p + (q - p) * 6 * t;
  if (t < 1 / 2)
    return q;
  if (t < 2 / 3)
    return p + (q - p) * 6 * (2 / 3 - t);
  return p;
}

class Color3 {
  constructor(r, g, b) {
    this.isColor = true;
    this.r = 1;
    this.g = 1;
    this.b = 1;
    return this.set(r, g, b);
  }
  set(r, g, b) {
    if (g === undefined && b === undefined) {
      const value = r;
      if (value && value.isColor) {
        this.copy(value);
      } else if (typeof value === "number") {
        this.setHex(value);
      } else if (typeof value === "string") {
        this.setStyle(value);
      }
    } else {
      this.setRGB(r, g, b);
    }
    return this;
  }
  setScalar(scalar) {
    this.r = scalar;
    this.g = scalar;
    this.b = scalar;
    return this;
  }
  setHex(hex2, colorSpace = SRGBColorSpace) {
    hex2 = Math.floor(hex2);
    this.r = (hex2 >> 16 & 255) / 255;
    this.g = (hex2 >> 8 & 255) / 255;
    this.b = (hex2 & 255) / 255;
    ColorManagement.colorSpaceToWorking(this, colorSpace);
    return this;
  }
  setRGB(r, g, b, colorSpace = ColorManagement.workingColorSpace) {
    this.r = r;
    this.g = g;
    this.b = b;
    ColorManagement.colorSpaceToWorking(this, colorSpace);
    return this;
  }
  setHSL(h, s, l, colorSpace = ColorManagement.workingColorSpace) {
    h = euclideanModulo(h, 1);
    s = clamp3(s, 0, 1);
    l = clamp3(l, 0, 1);
    if (s === 0) {
      this.r = this.g = this.b = l;
    } else {
      const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
      const q = 2 * l - p;
      this.r = hue2rgb(q, p, h + 1 / 3);
      this.g = hue2rgb(q, p, h);
      this.b = hue2rgb(q, p, h - 1 / 3);
    }
    ColorManagement.colorSpaceToWorking(this, colorSpace);
    return this;
  }
  setStyle(style, colorSpace = SRGBColorSpace) {
    function handleAlpha(string) {
      if (string === undefined)
        return;
      if (parseFloat(string) < 1) {
        console.warn("THREE.Color: Alpha component of " + style + " will be ignored.");
      }
    }
    let m;
    if (m = /^(\w+)\(([^\)]*)\)/.exec(style)) {
      let color2;
      const name = m[1];
      const components = m[2];
      switch (name) {
        case "rgb":
        case "rgba":
          if (color2 = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
            handleAlpha(color2[4]);
            return this.setRGB(Math.min(255, parseInt(color2[1], 10)) / 255, Math.min(255, parseInt(color2[2], 10)) / 255, Math.min(255, parseInt(color2[3], 10)) / 255, colorSpace);
          }
          if (color2 = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
            handleAlpha(color2[4]);
            return this.setRGB(Math.min(100, parseInt(color2[1], 10)) / 100, Math.min(100, parseInt(color2[2], 10)) / 100, Math.min(100, parseInt(color2[3], 10)) / 100, colorSpace);
          }
          break;
        case "hsl":
        case "hsla":
          if (color2 = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
            handleAlpha(color2[4]);
            return this.setHSL(parseFloat(color2[1]) / 360, parseFloat(color2[2]) / 100, parseFloat(color2[3]) / 100, colorSpace);
          }
          break;
        default:
          console.warn("THREE.Color: Unknown color model " + style);
      }
    } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
      const hex2 = m[1];
      const size = hex2.length;
      if (size === 3) {
        return this.setRGB(parseInt(hex2.charAt(0), 16) / 15, parseInt(hex2.charAt(1), 16) / 15, parseInt(hex2.charAt(2), 16) / 15, colorSpace);
      } else if (size === 6) {
        return this.setHex(parseInt(hex2, 16), colorSpace);
      } else {
        console.warn("THREE.Color: Invalid hex color " + style);
      }
    } else if (style && style.length > 0) {
      return this.setColorName(style, colorSpace);
    }
    return this;
  }
  setColorName(style, colorSpace = SRGBColorSpace) {
    const hex2 = _colorKeywords[style.toLowerCase()];
    if (hex2 !== undefined) {
      this.setHex(hex2, colorSpace);
    } else {
      console.warn("THREE.Color: Unknown color " + style);
    }
    return this;
  }
  clone() {
    return new this.constructor(this.r, this.g, this.b);
  }
  copy(color2) {
    this.r = color2.r;
    this.g = color2.g;
    this.b = color2.b;
    return this;
  }
  copySRGBToLinear(color2) {
    this.r = SRGBToLinear(color2.r);
    this.g = SRGBToLinear(color2.g);
    this.b = SRGBToLinear(color2.b);
    return this;
  }
  copyLinearToSRGB(color2) {
    this.r = LinearToSRGB(color2.r);
    this.g = LinearToSRGB(color2.g);
    this.b = LinearToSRGB(color2.b);
    return this;
  }
  convertSRGBToLinear() {
    this.copySRGBToLinear(this);
    return this;
  }
  convertLinearToSRGB() {
    this.copyLinearToSRGB(this);
    return this;
  }
  getHex(colorSpace = SRGBColorSpace) {
    ColorManagement.workingToColorSpace(_color.copy(this), colorSpace);
    return Math.round(clamp3(_color.r * 255, 0, 255)) * 65536 + Math.round(clamp3(_color.g * 255, 0, 255)) * 256 + Math.round(clamp3(_color.b * 255, 0, 255));
  }
  getHexString(colorSpace = SRGBColorSpace) {
    return ("000000" + this.getHex(colorSpace).toString(16)).slice(-6);
  }
  getHSL(target, colorSpace = ColorManagement.workingColorSpace) {
    ColorManagement.workingToColorSpace(_color.copy(this), colorSpace);
    const { r, g, b } = _color;
    const max3 = Math.max(r, g, b);
    const min2 = Math.min(r, g, b);
    let hue, saturation;
    const lightness = (min2 + max3) / 2;
    if (min2 === max3) {
      hue = 0;
      saturation = 0;
    } else {
      const delta = max3 - min2;
      saturation = lightness <= 0.5 ? delta / (max3 + min2) : delta / (2 - max3 - min2);
      switch (max3) {
        case r:
          hue = (g - b) / delta + (g < b ? 6 : 0);
          break;
        case g:
          hue = (b - r) / delta + 2;
          break;
        case b:
          hue = (r - g) / delta + 4;
          break;
      }
      hue /= 6;
    }
    target.h = hue;
    target.s = saturation;
    target.l = lightness;
    return target;
  }
  getRGB(target, colorSpace = ColorManagement.workingColorSpace) {
    ColorManagement.workingToColorSpace(_color.copy(this), colorSpace);
    target.r = _color.r;
    target.g = _color.g;
    target.b = _color.b;
    return target;
  }
  getStyle(colorSpace = SRGBColorSpace) {
    ColorManagement.workingToColorSpace(_color.copy(this), colorSpace);
    const { r, g, b } = _color;
    if (colorSpace !== SRGBColorSpace) {
      return `color(${colorSpace} ${r.toFixed(3)} ${g.toFixed(3)} ${b.toFixed(3)})`;
    }
    return `rgb(${Math.round(r * 255)},${Math.round(g * 255)},${Math.round(b * 255)})`;
  }
  offsetHSL(h, s, l) {
    this.getHSL(_hslA);
    return this.setHSL(_hslA.h + h, _hslA.s + s, _hslA.l + l);
  }
  add(color2) {
    this.r += color2.r;
    this.g += color2.g;
    this.b += color2.b;
    return this;
  }
  addColors(color1, color2) {
    this.r = color1.r + color2.r;
    this.g = color1.g + color2.g;
    this.b = color1.b + color2.b;
    return this;
  }
  addScalar(s) {
    this.r += s;
    this.g += s;
    this.b += s;
    return this;
  }
  sub(color2) {
    this.r = Math.max(0, this.r - color2.r);
    this.g = Math.max(0, this.g - color2.g);
    this.b = Math.max(0, this.b - color2.b);
    return this;
  }
  multiply(color2) {
    this.r *= color2.r;
    this.g *= color2.g;
    this.b *= color2.b;
    return this;
  }
  multiplyScalar(s) {
    this.r *= s;
    this.g *= s;
    this.b *= s;
    return this;
  }
  lerp(color2, alpha) {
    this.r += (color2.r - this.r) * alpha;
    this.g += (color2.g - this.g) * alpha;
    this.b += (color2.b - this.b) * alpha;
    return this;
  }
  lerpColors(color1, color2, alpha) {
    this.r = color1.r + (color2.r - color1.r) * alpha;
    this.g = color1.g + (color2.g - color1.g) * alpha;
    this.b = color1.b + (color2.b - color1.b) * alpha;
    return this;
  }
  lerpHSL(color2, alpha) {
    this.getHSL(_hslA);
    color2.getHSL(_hslB);
    const h = lerp(_hslA.h, _hslB.h, alpha);
    const s = lerp(_hslA.s, _hslB.s, alpha);
    const l = lerp(_hslA.l, _hslB.l, alpha);
    this.setHSL(h, s, l);
    return this;
  }
  setFromVector3(v) {
    this.r = v.x;
    this.g = v.y;
    this.b = v.z;
    return this;
  }
  applyMatrix3(m) {
    const r = this.r, g = this.g, b = this.b;
    const e = m.elements;
    this.r = e[0] * r + e[3] * g + e[6] * b;
    this.g = e[1] * r + e[4] * g + e[7] * b;
    this.b = e[2] * r + e[5] * g + e[8] * b;
    return this;
  }
  equals(c) {
    return c.r === this.r && c.g === this.g && c.b === this.b;
  }
  fromArray(array2, offset = 0) {
    this.r = array2[offset];
    this.g = array2[offset + 1];
    this.b = array2[offset + 2];
    return this;
  }
  toArray(array2 = [], offset = 0) {
    array2[offset] = this.r;
    array2[offset + 1] = this.g;
    array2[offset + 2] = this.b;
    return array2;
  }
  fromBufferAttribute(attribute, index) {
    this.r = attribute.getX(index);
    this.g = attribute.getY(index);
    this.b = attribute.getZ(index);
    return this;
  }
  toJSON() {
    return this.getHex();
  }
  *[Symbol.iterator]() {
    yield this.r;
    yield this.g;
    yield this.b;
  }
}
var _color = /* @__PURE__ */ new Color3;
Color3.NAMES = _colorKeywords;
var _materialId = 0;

class Material extends EventDispatcher {
  constructor() {
    super();
    this.isMaterial = true;
    Object.defineProperty(this, "id", { value: _materialId++ });
    this.uuid = generateUUID();
    this.name = "";
    this.type = "Material";
    this.blending = NormalBlending;
    this.side = FrontSide;
    this.vertexColors = false;
    this.opacity = 1;
    this.transparent = false;
    this.alphaHash = false;
    this.blendSrc = SrcAlphaFactor;
    this.blendDst = OneMinusSrcAlphaFactor;
    this.blendEquation = AddEquation;
    this.blendSrcAlpha = null;
    this.blendDstAlpha = null;
    this.blendEquationAlpha = null;
    this.blendColor = new Color3(0, 0, 0);
    this.blendAlpha = 0;
    this.depthFunc = LessEqualDepth;
    this.depthTest = true;
    this.depthWrite = true;
    this.stencilWriteMask = 255;
    this.stencilFunc = AlwaysStencilFunc;
    this.stencilRef = 0;
    this.stencilFuncMask = 255;
    this.stencilFail = KeepStencilOp;
    this.stencilZFail = KeepStencilOp;
    this.stencilZPass = KeepStencilOp;
    this.stencilWrite = false;
    this.clippingPlanes = null;
    this.clipIntersection = false;
    this.clipShadows = false;
    this.shadowSide = null;
    this.colorWrite = true;
    this.precision = null;
    this.polygonOffset = false;
    this.polygonOffsetFactor = 0;
    this.polygonOffsetUnits = 0;
    this.dithering = false;
    this.alphaToCoverage = false;
    this.premultipliedAlpha = false;
    this.forceSinglePass = false;
    this.allowOverride = true;
    this.visible = true;
    this.toneMapped = true;
    this.userData = {};
    this.version = 0;
    this._alphaTest = 0;
  }
  get alphaTest() {
    return this._alphaTest;
  }
  set alphaTest(value) {
    if (this._alphaTest > 0 !== value > 0) {
      this.version++;
    }
    this._alphaTest = value;
  }
  onBeforeRender() {}
  onBeforeCompile() {}
  customProgramCacheKey() {
    return this.onBeforeCompile.toString();
  }
  setValues(values) {
    if (values === undefined)
      return;
    for (const key in values) {
      const newValue = values[key];
      if (newValue === undefined) {
        console.warn(`THREE.Material: parameter '${key}' has value of undefined.`);
        continue;
      }
      const currentValue = this[key];
      if (currentValue === undefined) {
        console.warn(`THREE.Material: '${key}' is not a property of THREE.${this.type}.`);
        continue;
      }
      if (currentValue && currentValue.isColor) {
        currentValue.set(newValue);
      } else if (currentValue && currentValue.isVector3 && (newValue && newValue.isVector3)) {
        currentValue.copy(newValue);
      } else {
        this[key] = newValue;
      }
    }
  }
  toJSON(meta) {
    const isRootObject = meta === undefined || typeof meta === "string";
    if (isRootObject) {
      meta = {
        textures: {},
        images: {}
      };
    }
    const data = {
      metadata: {
        version: 4.7,
        type: "Material",
        generator: "Material.toJSON"
      }
    };
    data.uuid = this.uuid;
    data.type = this.type;
    if (this.name !== "")
      data.name = this.name;
    if (this.color && this.color.isColor)
      data.color = this.color.getHex();
    if (this.roughness !== undefined)
      data.roughness = this.roughness;
    if (this.metalness !== undefined)
      data.metalness = this.metalness;
    if (this.sheen !== undefined)
      data.sheen = this.sheen;
    if (this.sheenColor && this.sheenColor.isColor)
      data.sheenColor = this.sheenColor.getHex();
    if (this.sheenRoughness !== undefined)
      data.sheenRoughness = this.sheenRoughness;
    if (this.emissive && this.emissive.isColor)
      data.emissive = this.emissive.getHex();
    if (this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1)
      data.emissiveIntensity = this.emissiveIntensity;
    if (this.specular && this.specular.isColor)
      data.specular = this.specular.getHex();
    if (this.specularIntensity !== undefined)
      data.specularIntensity = this.specularIntensity;
    if (this.specularColor && this.specularColor.isColor)
      data.specularColor = this.specularColor.getHex();
    if (this.shininess !== undefined)
      data.shininess = this.shininess;
    if (this.clearcoat !== undefined)
      data.clearcoat = this.clearcoat;
    if (this.clearcoatRoughness !== undefined)
      data.clearcoatRoughness = this.clearcoatRoughness;
    if (this.clearcoatMap && this.clearcoatMap.isTexture) {
      data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
    }
    if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
      data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
    }
    if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
      data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
      data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
    }
    if (this.dispersion !== undefined)
      data.dispersion = this.dispersion;
    if (this.iridescence !== undefined)
      data.iridescence = this.iridescence;
    if (this.iridescenceIOR !== undefined)
      data.iridescenceIOR = this.iridescenceIOR;
    if (this.iridescenceThicknessRange !== undefined)
      data.iridescenceThicknessRange = this.iridescenceThicknessRange;
    if (this.iridescenceMap && this.iridescenceMap.isTexture) {
      data.iridescenceMap = this.iridescenceMap.toJSON(meta).uuid;
    }
    if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) {
      data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta).uuid;
    }
    if (this.anisotropy !== undefined)
      data.anisotropy = this.anisotropy;
    if (this.anisotropyRotation !== undefined)
      data.anisotropyRotation = this.anisotropyRotation;
    if (this.anisotropyMap && this.anisotropyMap.isTexture) {
      data.anisotropyMap = this.anisotropyMap.toJSON(meta).uuid;
    }
    if (this.map && this.map.isTexture)
      data.map = this.map.toJSON(meta).uuid;
    if (this.matcap && this.matcap.isTexture)
      data.matcap = this.matcap.toJSON(meta).uuid;
    if (this.alphaMap && this.alphaMap.isTexture)
      data.alphaMap = this.alphaMap.toJSON(meta).uuid;
    if (this.lightMap && this.lightMap.isTexture) {
      data.lightMap = this.lightMap.toJSON(meta).uuid;
      data.lightMapIntensity = this.lightMapIntensity;
    }
    if (this.aoMap && this.aoMap.isTexture) {
      data.aoMap = this.aoMap.toJSON(meta).uuid;
      data.aoMapIntensity = this.aoMapIntensity;
    }
    if (this.bumpMap && this.bumpMap.isTexture) {
      data.bumpMap = this.bumpMap.toJSON(meta).uuid;
      data.bumpScale = this.bumpScale;
    }
    if (this.normalMap && this.normalMap.isTexture) {
      data.normalMap = this.normalMap.toJSON(meta).uuid;
      data.normalMapType = this.normalMapType;
      data.normalScale = this.normalScale.toArray();
    }
    if (this.displacementMap && this.displacementMap.isTexture) {
      data.displacementMap = this.displacementMap.toJSON(meta).uuid;
      data.displacementScale = this.displacementScale;
      data.displacementBias = this.displacementBias;
    }
    if (this.roughnessMap && this.roughnessMap.isTexture)
      data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
    if (this.metalnessMap && this.metalnessMap.isTexture)
      data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
    if (this.emissiveMap && this.emissiveMap.isTexture)
      data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
    if (this.specularMap && this.specularMap.isTexture)
      data.specularMap = this.specularMap.toJSON(meta).uuid;
    if (this.specularIntensityMap && this.specularIntensityMap.isTexture)
      data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid;
    if (this.specularColorMap && this.specularColorMap.isTexture)
      data.specularColorMap = this.specularColorMap.toJSON(meta).uuid;
    if (this.envMap && this.envMap.isTexture) {
      data.envMap = this.envMap.toJSON(meta).uuid;
      if (this.combine !== undefined)
        data.combine = this.combine;
    }
    if (this.envMapRotation !== undefined)
      data.envMapRotation = this.envMapRotation.toArray();
    if (this.envMapIntensity !== undefined)
      data.envMapIntensity = this.envMapIntensity;
    if (this.reflectivity !== undefined)
      data.reflectivity = this.reflectivity;
    if (this.refractionRatio !== undefined)
      data.refractionRatio = this.refractionRatio;
    if (this.gradientMap && this.gradientMap.isTexture) {
      data.gradientMap = this.gradientMap.toJSON(meta).uuid;
    }
    if (this.transmission !== undefined)
      data.transmission = this.transmission;
    if (this.transmissionMap && this.transmissionMap.isTexture)
      data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
    if (this.thickness !== undefined)
      data.thickness = this.thickness;
    if (this.thicknessMap && this.thicknessMap.isTexture)
      data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
    if (this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity)
      data.attenuationDistance = this.attenuationDistance;
    if (this.attenuationColor !== undefined)
      data.attenuationColor = this.attenuationColor.getHex();
    if (this.size !== undefined)
      data.size = this.size;
    if (this.shadowSide !== null)
      data.shadowSide = this.shadowSide;
    if (this.sizeAttenuation !== undefined)
      data.sizeAttenuation = this.sizeAttenuation;
    if (this.blending !== NormalBlending)
      data.blending = this.blending;
    if (this.side !== FrontSide)
      data.side = this.side;
    if (this.vertexColors === true)
      data.vertexColors = true;
    if (this.opacity < 1)
      data.opacity = this.opacity;
    if (this.transparent === true)
      data.transparent = true;
    if (this.blendSrc !== SrcAlphaFactor)
      data.blendSrc = this.blendSrc;
    if (this.blendDst !== OneMinusSrcAlphaFactor)
      data.blendDst = this.blendDst;
    if (this.blendEquation !== AddEquation)
      data.blendEquation = this.blendEquation;
    if (this.blendSrcAlpha !== null)
      data.blendSrcAlpha = this.blendSrcAlpha;
    if (this.blendDstAlpha !== null)
      data.blendDstAlpha = this.blendDstAlpha;
    if (this.blendEquationAlpha !== null)
      data.blendEquationAlpha = this.blendEquationAlpha;
    if (this.blendColor && this.blendColor.isColor)
      data.blendColor = this.blendColor.getHex();
    if (this.blendAlpha !== 0)
      data.blendAlpha = this.blendAlpha;
    if (this.depthFunc !== LessEqualDepth)
      data.depthFunc = this.depthFunc;
    if (this.depthTest === false)
      data.depthTest = this.depthTest;
    if (this.depthWrite === false)
      data.depthWrite = this.depthWrite;
    if (this.colorWrite === false)
      data.colorWrite = this.colorWrite;
    if (this.stencilWriteMask !== 255)
      data.stencilWriteMask = this.stencilWriteMask;
    if (this.stencilFunc !== AlwaysStencilFunc)
      data.stencilFunc = this.stencilFunc;
    if (this.stencilRef !== 0)
      data.stencilRef = this.stencilRef;
    if (this.stencilFuncMask !== 255)
      data.stencilFuncMask = this.stencilFuncMask;
    if (this.stencilFail !== KeepStencilOp)
      data.stencilFail = this.stencilFail;
    if (this.stencilZFail !== KeepStencilOp)
      data.stencilZFail = this.stencilZFail;
    if (this.stencilZPass !== KeepStencilOp)
      data.stencilZPass = this.stencilZPass;
    if (this.stencilWrite === true)
      data.stencilWrite = this.stencilWrite;
    if (this.rotation !== undefined && this.rotation !== 0)
      data.rotation = this.rotation;
    if (this.polygonOffset === true)
      data.polygonOffset = true;
    if (this.polygonOffsetFactor !== 0)
      data.polygonOffsetFactor = this.polygonOffsetFactor;
    if (this.polygonOffsetUnits !== 0)
      data.polygonOffsetUnits = this.polygonOffsetUnits;
    if (this.linewidth !== undefined && this.linewidth !== 1)
      data.linewidth = this.linewidth;
    if (this.dashSize !== undefined)
      data.dashSize = this.dashSize;
    if (this.gapSize !== undefined)
      data.gapSize = this.gapSize;
    if (this.scale !== undefined)
      data.scale = this.scale;
    if (this.dithering === true)
      data.dithering = true;
    if (this.alphaTest > 0)
      data.alphaTest = this.alphaTest;
    if (this.alphaHash === true)
      data.alphaHash = true;
    if (this.alphaToCoverage === true)
      data.alphaToCoverage = true;
    if (this.premultipliedAlpha === true)
      data.premultipliedAlpha = true;
    if (this.forceSinglePass === true)
      data.forceSinglePass = true;
    if (this.wireframe === true)
      data.wireframe = true;
    if (this.wireframeLinewidth > 1)
      data.wireframeLinewidth = this.wireframeLinewidth;
    if (this.wireframeLinecap !== "round")
      data.wireframeLinecap = this.wireframeLinecap;
    if (this.wireframeLinejoin !== "round")
      data.wireframeLinejoin = this.wireframeLinejoin;
    if (this.flatShading === true)
      data.flatShading = true;
    if (this.visible === false)
      data.visible = false;
    if (this.toneMapped === false)
      data.toneMapped = false;
    if (this.fog === false)
      data.fog = false;
    if (Object.keys(this.userData).length > 0)
      data.userData = this.userData;
    function extractFromCache(cache) {
      const values = [];
      for (const key in cache) {
        const data2 = cache[key];
        delete data2.metadata;
        values.push(data2);
      }
      return values;
    }
    if (isRootObject) {
      const textures = extractFromCache(meta.textures);
      const images = extractFromCache(meta.images);
      if (textures.length > 0)
        data.textures = textures;
      if (images.length > 0)
        data.images = images;
    }
    return data;
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(source) {
    this.name = source.name;
    this.blending = source.blending;
    this.side = source.side;
    this.vertexColors = source.vertexColors;
    this.opacity = source.opacity;
    this.transparent = source.transparent;
    this.blendSrc = source.blendSrc;
    this.blendDst = source.blendDst;
    this.blendEquation = source.blendEquation;
    this.blendSrcAlpha = source.blendSrcAlpha;
    this.blendDstAlpha = source.blendDstAlpha;
    this.blendEquationAlpha = source.blendEquationAlpha;
    this.blendColor.copy(source.blendColor);
    this.blendAlpha = source.blendAlpha;
    this.depthFunc = source.depthFunc;
    this.depthTest = source.depthTest;
    this.depthWrite = source.depthWrite;
    this.stencilWriteMask = source.stencilWriteMask;
    this.stencilFunc = source.stencilFunc;
    this.stencilRef = source.stencilRef;
    this.stencilFuncMask = source.stencilFuncMask;
    this.stencilFail = source.stencilFail;
    this.stencilZFail = source.stencilZFail;
    this.stencilZPass = source.stencilZPass;
    this.stencilWrite = source.stencilWrite;
    const srcPlanes = source.clippingPlanes;
    let dstPlanes = null;
    if (srcPlanes !== null) {
      const n = srcPlanes.length;
      dstPlanes = new Array(n);
      for (let i = 0;i !== n; ++i) {
        dstPlanes[i] = srcPlanes[i].clone();
      }
    }
    this.clippingPlanes = dstPlanes;
    this.clipIntersection = source.clipIntersection;
    this.clipShadows = source.clipShadows;
    this.shadowSide = source.shadowSide;
    this.colorWrite = source.colorWrite;
    this.precision = source.precision;
    this.polygonOffset = source.polygonOffset;
    this.polygonOffsetFactor = source.polygonOffsetFactor;
    this.polygonOffsetUnits = source.polygonOffsetUnits;
    this.dithering = source.dithering;
    this.alphaTest = source.alphaTest;
    this.alphaHash = source.alphaHash;
    this.alphaToCoverage = source.alphaToCoverage;
    this.premultipliedAlpha = source.premultipliedAlpha;
    this.forceSinglePass = source.forceSinglePass;
    this.visible = source.visible;
    this.toneMapped = source.toneMapped;
    this.userData = JSON.parse(JSON.stringify(source.userData));
    return this;
  }
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
  set needsUpdate(value) {
    if (value === true)
      this.version++;
  }
}

class MeshBasicMaterial extends Material {
  constructor(parameters) {
    super();
    this.isMeshBasicMaterial = true;
    this.type = "MeshBasicMaterial";
    this.color = new Color3(16777215);
    this.map = null;
    this.lightMap = null;
    this.lightMapIntensity = 1;
    this.aoMap = null;
    this.aoMapIntensity = 1;
    this.specularMap = null;
    this.alphaMap = null;
    this.envMap = null;
    this.envMapRotation = new Euler;
    this.combine = MultiplyOperation;
    this.reflectivity = 1;
    this.refractionRatio = 0.98;
    this.wireframe = false;
    this.wireframeLinewidth = 1;
    this.wireframeLinecap = "round";
    this.wireframeLinejoin = "round";
    this.fog = true;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.color.copy(source.color);
    this.map = source.map;
    this.lightMap = source.lightMap;
    this.lightMapIntensity = source.lightMapIntensity;
    this.aoMap = source.aoMap;
    this.aoMapIntensity = source.aoMapIntensity;
    this.specularMap = source.specularMap;
    this.alphaMap = source.alphaMap;
    this.envMap = source.envMap;
    this.envMapRotation.copy(source.envMapRotation);
    this.combine = source.combine;
    this.reflectivity = source.reflectivity;
    this.refractionRatio = source.refractionRatio;
    this.wireframe = source.wireframe;
    this.wireframeLinewidth = source.wireframeLinewidth;
    this.wireframeLinecap = source.wireframeLinecap;
    this.wireframeLinejoin = source.wireframeLinejoin;
    this.fog = source.fog;
    return this;
  }
}
var _vector$9 = /* @__PURE__ */ new Vector3;
var _vector2$1 = /* @__PURE__ */ new Vector2;
var _id$2 = 0;

class BufferAttribute {
  constructor(array2, itemSize, normalized = false) {
    if (Array.isArray(array2)) {
      throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");
    }
    this.isBufferAttribute = true;
    Object.defineProperty(this, "id", { value: _id$2++ });
    this.name = "";
    this.array = array2;
    this.itemSize = itemSize;
    this.count = array2 !== undefined ? array2.length / itemSize : 0;
    this.normalized = normalized;
    this.usage = StaticDrawUsage;
    this.updateRanges = [];
    this.gpuType = FloatType;
    this.version = 0;
  }
  onUploadCallback() {}
  set needsUpdate(value) {
    if (value === true)
      this.version++;
  }
  setUsage(value) {
    this.usage = value;
    return this;
  }
  addUpdateRange(start, count3) {
    this.updateRanges.push({ start, count: count3 });
  }
  clearUpdateRanges() {
    this.updateRanges.length = 0;
  }
  copy(source) {
    this.name = source.name;
    this.array = new source.array.constructor(source.array);
    this.itemSize = source.itemSize;
    this.count = source.count;
    this.normalized = source.normalized;
    this.usage = source.usage;
    this.gpuType = source.gpuType;
    return this;
  }
  copyAt(index1, attribute, index2) {
    index1 *= this.itemSize;
    index2 *= attribute.itemSize;
    for (let i = 0, l = this.itemSize;i < l; i++) {
      this.array[index1 + i] = attribute.array[index2 + i];
    }
    return this;
  }
  copyArray(array2) {
    this.array.set(array2);
    return this;
  }
  applyMatrix3(m) {
    if (this.itemSize === 2) {
      for (let i = 0, l = this.count;i < l; i++) {
        _vector2$1.fromBufferAttribute(this, i);
        _vector2$1.applyMatrix3(m);
        this.setXY(i, _vector2$1.x, _vector2$1.y);
      }
    } else if (this.itemSize === 3) {
      for (let i = 0, l = this.count;i < l; i++) {
        _vector$9.fromBufferAttribute(this, i);
        _vector$9.applyMatrix3(m);
        this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
      }
    }
    return this;
  }
  applyMatrix4(m) {
    for (let i = 0, l = this.count;i < l; i++) {
      _vector$9.fromBufferAttribute(this, i);
      _vector$9.applyMatrix4(m);
      this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
    }
    return this;
  }
  applyNormalMatrix(m) {
    for (let i = 0, l = this.count;i < l; i++) {
      _vector$9.fromBufferAttribute(this, i);
      _vector$9.applyNormalMatrix(m);
      this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
    }
    return this;
  }
  transformDirection(m) {
    for (let i = 0, l = this.count;i < l; i++) {
      _vector$9.fromBufferAttribute(this, i);
      _vector$9.transformDirection(m);
      this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
    }
    return this;
  }
  set(value, offset = 0) {
    this.array.set(value, offset);
    return this;
  }
  getComponent(index, component) {
    let value = this.array[index * this.itemSize + component];
    if (this.normalized)
      value = denormalize(value, this.array);
    return value;
  }
  setComponent(index, component, value) {
    if (this.normalized)
      value = normalize2(value, this.array);
    this.array[index * this.itemSize + component] = value;
    return this;
  }
  getX(index) {
    let x2 = this.array[index * this.itemSize];
    if (this.normalized)
      x2 = denormalize(x2, this.array);
    return x2;
  }
  setX(index, x2) {
    if (this.normalized)
      x2 = normalize2(x2, this.array);
    this.array[index * this.itemSize] = x2;
    return this;
  }
  getY(index) {
    let y2 = this.array[index * this.itemSize + 1];
    if (this.normalized)
      y2 = denormalize(y2, this.array);
    return y2;
  }
  setY(index, y2) {
    if (this.normalized)
      y2 = normalize2(y2, this.array);
    this.array[index * this.itemSize + 1] = y2;
    return this;
  }
  getZ(index) {
    let z = this.array[index * this.itemSize + 2];
    if (this.normalized)
      z = denormalize(z, this.array);
    return z;
  }
  setZ(index, z) {
    if (this.normalized)
      z = normalize2(z, this.array);
    this.array[index * this.itemSize + 2] = z;
    return this;
  }
  getW(index) {
    let w = this.array[index * this.itemSize + 3];
    if (this.normalized)
      w = denormalize(w, this.array);
    return w;
  }
  setW(index, w) {
    if (this.normalized)
      w = normalize2(w, this.array);
    this.array[index * this.itemSize + 3] = w;
    return this;
  }
  setXY(index, x2, y2) {
    index *= this.itemSize;
    if (this.normalized) {
      x2 = normalize2(x2, this.array);
      y2 = normalize2(y2, this.array);
    }
    this.array[index + 0] = x2;
    this.array[index + 1] = y2;
    return this;
  }
  setXYZ(index, x2, y2, z) {
    index *= this.itemSize;
    if (this.normalized) {
      x2 = normalize2(x2, this.array);
      y2 = normalize2(y2, this.array);
      z = normalize2(z, this.array);
    }
    this.array[index + 0] = x2;
    this.array[index + 1] = y2;
    this.array[index + 2] = z;
    return this;
  }
  setXYZW(index, x2, y2, z, w) {
    index *= this.itemSize;
    if (this.normalized) {
      x2 = normalize2(x2, this.array);
      y2 = normalize2(y2, this.array);
      z = normalize2(z, this.array);
      w = normalize2(w, this.array);
    }
    this.array[index + 0] = x2;
    this.array[index + 1] = y2;
    this.array[index + 2] = z;
    this.array[index + 3] = w;
    return this;
  }
  onUpload(callback) {
    this.onUploadCallback = callback;
    return this;
  }
  clone() {
    return new this.constructor(this.array, this.itemSize).copy(this);
  }
  toJSON() {
    const data = {
      itemSize: this.itemSize,
      type: this.array.constructor.name,
      array: Array.from(this.array),
      normalized: this.normalized
    };
    if (this.name !== "")
      data.name = this.name;
    if (this.usage !== StaticDrawUsage)
      data.usage = this.usage;
    return data;
  }
}
class Uint16BufferAttribute extends BufferAttribute {
  constructor(array2, itemSize, normalized) {
    super(new Uint16Array(array2), itemSize, normalized);
  }
}
class Uint32BufferAttribute extends BufferAttribute {
  constructor(array2, itemSize, normalized) {
    super(new Uint32Array(array2), itemSize, normalized);
  }
}
class Float32BufferAttribute extends BufferAttribute {
  constructor(array2, itemSize, normalized) {
    super(new Float32Array(array2), itemSize, normalized);
  }
}
var _id$1 = 0;
var _m1 = /* @__PURE__ */ new Matrix4;
var _obj = /* @__PURE__ */ new Object3D;
var _offset = /* @__PURE__ */ new Vector3;
var _box$2 = /* @__PURE__ */ new Box3;
var _boxMorphTargets = /* @__PURE__ */ new Box3;
var _vector$8 = /* @__PURE__ */ new Vector3;

class BufferGeometry extends EventDispatcher {
  constructor() {
    super();
    this.isBufferGeometry = true;
    Object.defineProperty(this, "id", { value: _id$1++ });
    this.uuid = generateUUID();
    this.name = "";
    this.type = "BufferGeometry";
    this.index = null;
    this.indirect = null;
    this.attributes = {};
    this.morphAttributes = {};
    this.morphTargetsRelative = false;
    this.groups = [];
    this.boundingBox = null;
    this.boundingSphere = null;
    this.drawRange = { start: 0, count: Infinity };
    this.userData = {};
  }
  getIndex() {
    return this.index;
  }
  setIndex(index) {
    if (Array.isArray(index)) {
      this.index = new ((arrayNeedsUint32(index)) ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
    } else {
      this.index = index;
    }
    return this;
  }
  setIndirect(indirect) {
    this.indirect = indirect;
    return this;
  }
  getIndirect() {
    return this.indirect;
  }
  getAttribute(name) {
    return this.attributes[name];
  }
  setAttribute(name, attribute) {
    this.attributes[name] = attribute;
    return this;
  }
  deleteAttribute(name) {
    delete this.attributes[name];
    return this;
  }
  hasAttribute(name) {
    return this.attributes[name] !== undefined;
  }
  addGroup(start, count3, materialIndex = 0) {
    this.groups.push({
      start,
      count: count3,
      materialIndex
    });
  }
  clearGroups() {
    this.groups = [];
  }
  setDrawRange(start, count3) {
    this.drawRange.start = start;
    this.drawRange.count = count3;
  }
  applyMatrix4(matrix) {
    const position = this.attributes.position;
    if (position !== undefined) {
      position.applyMatrix4(matrix);
      position.needsUpdate = true;
    }
    const normal = this.attributes.normal;
    if (normal !== undefined) {
      const normalMatrix = new Matrix3().getNormalMatrix(matrix);
      normal.applyNormalMatrix(normalMatrix);
      normal.needsUpdate = true;
    }
    const tangent = this.attributes.tangent;
    if (tangent !== undefined) {
      tangent.transformDirection(matrix);
      tangent.needsUpdate = true;
    }
    if (this.boundingBox !== null) {
      this.computeBoundingBox();
    }
    if (this.boundingSphere !== null) {
      this.computeBoundingSphere();
    }
    return this;
  }
  applyQuaternion(q) {
    _m1.makeRotationFromQuaternion(q);
    this.applyMatrix4(_m1);
    return this;
  }
  rotateX(angle) {
    _m1.makeRotationX(angle);
    this.applyMatrix4(_m1);
    return this;
  }
  rotateY(angle) {
    _m1.makeRotationY(angle);
    this.applyMatrix4(_m1);
    return this;
  }
  rotateZ(angle) {
    _m1.makeRotationZ(angle);
    this.applyMatrix4(_m1);
    return this;
  }
  translate(x2, y2, z) {
    _m1.makeTranslation(x2, y2, z);
    this.applyMatrix4(_m1);
    return this;
  }
  scale(x2, y2, z) {
    _m1.makeScale(x2, y2, z);
    this.applyMatrix4(_m1);
    return this;
  }
  lookAt(vector) {
    _obj.lookAt(vector);
    _obj.updateMatrix();
    this.applyMatrix4(_obj.matrix);
    return this;
  }
  center() {
    this.computeBoundingBox();
    this.boundingBox.getCenter(_offset).negate();
    this.translate(_offset.x, _offset.y, _offset.z);
    return this;
  }
  setFromPoints(points) {
    const positionAttribute = this.getAttribute("position");
    if (positionAttribute === undefined) {
      const position = [];
      for (let i = 0, l = points.length;i < l; i++) {
        const point3 = points[i];
        position.push(point3.x, point3.y, point3.z || 0);
      }
      this.setAttribute("position", new Float32BufferAttribute(position, 3));
    } else {
      const l = Math.min(points.length, positionAttribute.count);
      for (let i = 0;i < l; i++) {
        const point3 = points[i];
        positionAttribute.setXYZ(i, point3.x, point3.y, point3.z || 0);
      }
      if (points.length > positionAttribute.count) {
        console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.");
      }
      positionAttribute.needsUpdate = true;
    }
    return this;
  }
  computeBoundingBox() {
    if (this.boundingBox === null) {
      this.boundingBox = new Box3;
    }
    const position = this.attributes.position;
    const morphAttributesPosition = this.morphAttributes.position;
    if (position && position.isGLBufferAttribute) {
      console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this);
      this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(Infinity, Infinity, Infinity));
      return;
    }
    if (position !== undefined) {
      this.boundingBox.setFromBufferAttribute(position);
      if (morphAttributesPosition) {
        for (let i = 0, il = morphAttributesPosition.length;i < il; i++) {
          const morphAttribute = morphAttributesPosition[i];
          _box$2.setFromBufferAttribute(morphAttribute);
          if (this.morphTargetsRelative) {
            _vector$8.addVectors(this.boundingBox.min, _box$2.min);
            this.boundingBox.expandByPoint(_vector$8);
            _vector$8.addVectors(this.boundingBox.max, _box$2.max);
            this.boundingBox.expandByPoint(_vector$8);
          } else {
            this.boundingBox.expandByPoint(_box$2.min);
            this.boundingBox.expandByPoint(_box$2.max);
          }
        }
      }
    } else {
      this.boundingBox.makeEmpty();
    }
    if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
      console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
    }
  }
  computeBoundingSphere() {
    if (this.boundingSphere === null) {
      this.boundingSphere = new Sphere;
    }
    const position = this.attributes.position;
    const morphAttributesPosition = this.morphAttributes.position;
    if (position && position.isGLBufferAttribute) {
      console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this);
      this.boundingSphere.set(new Vector3, Infinity);
      return;
    }
    if (position) {
      const center = this.boundingSphere.center;
      _box$2.setFromBufferAttribute(position);
      if (morphAttributesPosition) {
        for (let i = 0, il = morphAttributesPosition.length;i < il; i++) {
          const morphAttribute = morphAttributesPosition[i];
          _boxMorphTargets.setFromBufferAttribute(morphAttribute);
          if (this.morphTargetsRelative) {
            _vector$8.addVectors(_box$2.min, _boxMorphTargets.min);
            _box$2.expandByPoint(_vector$8);
            _vector$8.addVectors(_box$2.max, _boxMorphTargets.max);
            _box$2.expandByPoint(_vector$8);
          } else {
            _box$2.expandByPoint(_boxMorphTargets.min);
            _box$2.expandByPoint(_boxMorphTargets.max);
          }
        }
      }
      _box$2.getCenter(center);
      let maxRadiusSq = 0;
      for (let i = 0, il = position.count;i < il; i++) {
        _vector$8.fromBufferAttribute(position, i);
        maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
      }
      if (morphAttributesPosition) {
        for (let i = 0, il = morphAttributesPosition.length;i < il; i++) {
          const morphAttribute = morphAttributesPosition[i];
          const morphTargetsRelative = this.morphTargetsRelative;
          for (let j = 0, jl = morphAttribute.count;j < jl; j++) {
            _vector$8.fromBufferAttribute(morphAttribute, j);
            if (morphTargetsRelative) {
              _offset.fromBufferAttribute(position, j);
              _vector$8.add(_offset);
            }
            maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
          }
        }
      }
      this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
      if (isNaN(this.boundingSphere.radius)) {
        console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
      }
    }
  }
  computeTangents() {
    const index = this.index;
    const attributes = this.attributes;
    if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
      console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");
      return;
    }
    const positionAttribute = attributes.position;
    const normalAttribute = attributes.normal;
    const uvAttribute = attributes.uv;
    if (this.hasAttribute("tangent") === false) {
      this.setAttribute("tangent", new BufferAttribute(new Float32Array(4 * positionAttribute.count), 4));
    }
    const tangentAttribute = this.getAttribute("tangent");
    const tan1 = [], tan2 = [];
    for (let i = 0;i < positionAttribute.count; i++) {
      tan1[i] = new Vector3;
      tan2[i] = new Vector3;
    }
    const vA = new Vector3, vB = new Vector3, vC = new Vector3, uvA = new Vector2, uvB = new Vector2, uvC = new Vector2, sdir = new Vector3, tdir = new Vector3;
    function handleTriangle(a, b, c) {
      vA.fromBufferAttribute(positionAttribute, a);
      vB.fromBufferAttribute(positionAttribute, b);
      vC.fromBufferAttribute(positionAttribute, c);
      uvA.fromBufferAttribute(uvAttribute, a);
      uvB.fromBufferAttribute(uvAttribute, b);
      uvC.fromBufferAttribute(uvAttribute, c);
      vB.sub(vA);
      vC.sub(vA);
      uvB.sub(uvA);
      uvC.sub(uvA);
      const r = 1 / (uvB.x * uvC.y - uvC.x * uvB.y);
      if (!isFinite(r))
        return;
      sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
      tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
      tan1[a].add(sdir);
      tan1[b].add(sdir);
      tan1[c].add(sdir);
      tan2[a].add(tdir);
      tan2[b].add(tdir);
      tan2[c].add(tdir);
    }
    let groups = this.groups;
    if (groups.length === 0) {
      groups = [{
        start: 0,
        count: index.count
      }];
    }
    for (let i = 0, il = groups.length;i < il; ++i) {
      const group = groups[i];
      const start = group.start;
      const count3 = group.count;
      for (let j = start, jl = start + count3;j < jl; j += 3) {
        handleTriangle(index.getX(j + 0), index.getX(j + 1), index.getX(j + 2));
      }
    }
    const tmp = new Vector3, tmp2 = new Vector3;
    const n = new Vector3, n2 = new Vector3;
    function handleVertex(v) {
      n.fromBufferAttribute(normalAttribute, v);
      n2.copy(n);
      const t = tan1[v];
      tmp.copy(t);
      tmp.sub(n.multiplyScalar(n.dot(t))).normalize();
      tmp2.crossVectors(n2, t);
      const test = tmp2.dot(tan2[v]);
      const w = test < 0 ? -1 : 1;
      tangentAttribute.setXYZW(v, tmp.x, tmp.y, tmp.z, w);
    }
    for (let i = 0, il = groups.length;i < il; ++i) {
      const group = groups[i];
      const start = group.start;
      const count3 = group.count;
      for (let j = start, jl = start + count3;j < jl; j += 3) {
        handleVertex(index.getX(j + 0));
        handleVertex(index.getX(j + 1));
        handleVertex(index.getX(j + 2));
      }
    }
  }
  computeVertexNormals() {
    const index = this.index;
    const positionAttribute = this.getAttribute("position");
    if (positionAttribute !== undefined) {
      let normalAttribute = this.getAttribute("normal");
      if (normalAttribute === undefined) {
        normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
        this.setAttribute("normal", normalAttribute);
      } else {
        for (let i = 0, il = normalAttribute.count;i < il; i++) {
          normalAttribute.setXYZ(i, 0, 0, 0);
        }
      }
      const pA = new Vector3, pB = new Vector3, pC = new Vector3;
      const nA = new Vector3, nB = new Vector3, nC = new Vector3;
      const cb = new Vector3, ab = new Vector3;
      if (index) {
        for (let i = 0, il = index.count;i < il; i += 3) {
          const vA = index.getX(i + 0);
          const vB = index.getX(i + 1);
          const vC = index.getX(i + 2);
          pA.fromBufferAttribute(positionAttribute, vA);
          pB.fromBufferAttribute(positionAttribute, vB);
          pC.fromBufferAttribute(positionAttribute, vC);
          cb.subVectors(pC, pB);
          ab.subVectors(pA, pB);
          cb.cross(ab);
          nA.fromBufferAttribute(normalAttribute, vA);
          nB.fromBufferAttribute(normalAttribute, vB);
          nC.fromBufferAttribute(normalAttribute, vC);
          nA.add(cb);
          nB.add(cb);
          nC.add(cb);
          normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
          normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
          normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
        }
      } else {
        for (let i = 0, il = positionAttribute.count;i < il; i += 3) {
          pA.fromBufferAttribute(positionAttribute, i + 0);
          pB.fromBufferAttribute(positionAttribute, i + 1);
          pC.fromBufferAttribute(positionAttribute, i + 2);
          cb.subVectors(pC, pB);
          ab.subVectors(pA, pB);
          cb.cross(ab);
          normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
          normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
          normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
        }
      }
      this.normalizeNormals();
      normalAttribute.needsUpdate = true;
    }
  }
  normalizeNormals() {
    const normals = this.attributes.normal;
    for (let i = 0, il = normals.count;i < il; i++) {
      _vector$8.fromBufferAttribute(normals, i);
      _vector$8.normalize();
      normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
    }
  }
  toNonIndexed() {
    function convertBufferAttribute(attribute, indices2) {
      const array2 = attribute.array;
      const itemSize = attribute.itemSize;
      const normalized = attribute.normalized;
      const array22 = new array2.constructor(indices2.length * itemSize);
      let index = 0, index2 = 0;
      for (let i = 0, l = indices2.length;i < l; i++) {
        if (attribute.isInterleavedBufferAttribute) {
          index = indices2[i] * attribute.data.stride + attribute.offset;
        } else {
          index = indices2[i] * itemSize;
        }
        for (let j = 0;j < itemSize; j++) {
          array22[index2++] = array2[index++];
        }
      }
      return new BufferAttribute(array22, itemSize, normalized);
    }
    if (this.index === null) {
      console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.");
      return this;
    }
    const geometry2 = new BufferGeometry;
    const indices = this.index.array;
    const attributes = this.attributes;
    for (const name in attributes) {
      const attribute = attributes[name];
      const newAttribute = convertBufferAttribute(attribute, indices);
      geometry2.setAttribute(name, newAttribute);
    }
    const morphAttributes = this.morphAttributes;
    for (const name in morphAttributes) {
      const morphArray = [];
      const morphAttribute = morphAttributes[name];
      for (let i = 0, il = morphAttribute.length;i < il; i++) {
        const attribute = morphAttribute[i];
        const newAttribute = convertBufferAttribute(attribute, indices);
        morphArray.push(newAttribute);
      }
      geometry2.morphAttributes[name] = morphArray;
    }
    geometry2.morphTargetsRelative = this.morphTargetsRelative;
    const groups = this.groups;
    for (let i = 0, l = groups.length;i < l; i++) {
      const group = groups[i];
      geometry2.addGroup(group.start, group.count, group.materialIndex);
    }
    return geometry2;
  }
  toJSON() {
    const data = {
      metadata: {
        version: 4.7,
        type: "BufferGeometry",
        generator: "BufferGeometry.toJSON"
      }
    };
    data.uuid = this.uuid;
    data.type = this.type;
    if (this.name !== "")
      data.name = this.name;
    if (Object.keys(this.userData).length > 0)
      data.userData = this.userData;
    if (this.parameters !== undefined) {
      const parameters = this.parameters;
      for (const key in parameters) {
        if (parameters[key] !== undefined)
          data[key] = parameters[key];
      }
      return data;
    }
    data.data = { attributes: {} };
    const index = this.index;
    if (index !== null) {
      data.data.index = {
        type: index.array.constructor.name,
        array: Array.prototype.slice.call(index.array)
      };
    }
    const attributes = this.attributes;
    for (const key in attributes) {
      const attribute = attributes[key];
      data.data.attributes[key] = attribute.toJSON(data.data);
    }
    const morphAttributes = {};
    let hasMorphAttributes = false;
    for (const key in this.morphAttributes) {
      const attributeArray = this.morphAttributes[key];
      const array2 = [];
      for (let i = 0, il = attributeArray.length;i < il; i++) {
        const attribute = attributeArray[i];
        array2.push(attribute.toJSON(data.data));
      }
      if (array2.length > 0) {
        morphAttributes[key] = array2;
        hasMorphAttributes = true;
      }
    }
    if (hasMorphAttributes) {
      data.data.morphAttributes = morphAttributes;
      data.data.morphTargetsRelative = this.morphTargetsRelative;
    }
    const groups = this.groups;
    if (groups.length > 0) {
      data.data.groups = JSON.parse(JSON.stringify(groups));
    }
    const boundingSphere = this.boundingSphere;
    if (boundingSphere !== null) {
      data.data.boundingSphere = boundingSphere.toJSON();
    }
    return data;
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(source) {
    this.index = null;
    this.attributes = {};
    this.morphAttributes = {};
    this.groups = [];
    this.boundingBox = null;
    this.boundingSphere = null;
    const data = {};
    this.name = source.name;
    const index = source.index;
    if (index !== null) {
      this.setIndex(index.clone());
    }
    const attributes = source.attributes;
    for (const name in attributes) {
      const attribute = attributes[name];
      this.setAttribute(name, attribute.clone(data));
    }
    const morphAttributes = source.morphAttributes;
    for (const name in morphAttributes) {
      const array2 = [];
      const morphAttribute = morphAttributes[name];
      for (let i = 0, l = morphAttribute.length;i < l; i++) {
        array2.push(morphAttribute[i].clone(data));
      }
      this.morphAttributes[name] = array2;
    }
    this.morphTargetsRelative = source.morphTargetsRelative;
    const groups = source.groups;
    for (let i = 0, l = groups.length;i < l; i++) {
      const group = groups[i];
      this.addGroup(group.start, group.count, group.materialIndex);
    }
    const boundingBox = source.boundingBox;
    if (boundingBox !== null) {
      this.boundingBox = boundingBox.clone();
    }
    const boundingSphere = source.boundingSphere;
    if (boundingSphere !== null) {
      this.boundingSphere = boundingSphere.clone();
    }
    this.drawRange.start = source.drawRange.start;
    this.drawRange.count = source.drawRange.count;
    this.userData = source.userData;
    return this;
  }
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
}
var _inverseMatrix$3 = /* @__PURE__ */ new Matrix4;
var _ray$3 = /* @__PURE__ */ new Ray;
var _sphere$6 = /* @__PURE__ */ new Sphere;
var _sphereHitAt = /* @__PURE__ */ new Vector3;
var _vA$1 = /* @__PURE__ */ new Vector3;
var _vB$1 = /* @__PURE__ */ new Vector3;
var _vC$1 = /* @__PURE__ */ new Vector3;
var _tempA = /* @__PURE__ */ new Vector3;
var _morphA = /* @__PURE__ */ new Vector3;
var _intersectionPoint = /* @__PURE__ */ new Vector3;
var _intersectionPointWorld = /* @__PURE__ */ new Vector3;

class Mesh extends Object3D {
  constructor(geometry = new BufferGeometry, material = new MeshBasicMaterial) {
    super();
    this.isMesh = true;
    this.type = "Mesh";
    this.geometry = geometry;
    this.material = material;
    this.morphTargetDictionary = undefined;
    this.morphTargetInfluences = undefined;
    this.count = 1;
    this.updateMorphTargets();
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    if (source.morphTargetInfluences !== undefined) {
      this.morphTargetInfluences = source.morphTargetInfluences.slice();
    }
    if (source.morphTargetDictionary !== undefined) {
      this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
    }
    this.material = Array.isArray(source.material) ? source.material.slice() : source.material;
    this.geometry = source.geometry;
    return this;
  }
  updateMorphTargets() {
    const geometry = this.geometry;
    const morphAttributes = geometry.morphAttributes;
    const keys = Object.keys(morphAttributes);
    if (keys.length > 0) {
      const morphAttribute = morphAttributes[keys[0]];
      if (morphAttribute !== undefined) {
        this.morphTargetInfluences = [];
        this.morphTargetDictionary = {};
        for (let m = 0, ml = morphAttribute.length;m < ml; m++) {
          const name = morphAttribute[m].name || String(m);
          this.morphTargetInfluences.push(0);
          this.morphTargetDictionary[name] = m;
        }
      }
    }
  }
  getVertexPosition(index, target) {
    const geometry = this.geometry;
    const position = geometry.attributes.position;
    const morphPosition = geometry.morphAttributes.position;
    const morphTargetsRelative = geometry.morphTargetsRelative;
    target.fromBufferAttribute(position, index);
    const morphInfluences = this.morphTargetInfluences;
    if (morphPosition && morphInfluences) {
      _morphA.set(0, 0, 0);
      for (let i = 0, il = morphPosition.length;i < il; i++) {
        const influence = morphInfluences[i];
        const morphAttribute = morphPosition[i];
        if (influence === 0)
          continue;
        _tempA.fromBufferAttribute(morphAttribute, index);
        if (morphTargetsRelative) {
          _morphA.addScaledVector(_tempA, influence);
        } else {
          _morphA.addScaledVector(_tempA.sub(target), influence);
        }
      }
      target.add(_morphA);
    }
    return target;
  }
  raycast(raycaster, intersects) {
    const geometry = this.geometry;
    const material = this.material;
    const matrixWorld = this.matrixWorld;
    if (material === undefined)
      return;
    if (geometry.boundingSphere === null)
      geometry.computeBoundingSphere();
    _sphere$6.copy(geometry.boundingSphere);
    _sphere$6.applyMatrix4(matrixWorld);
    _ray$3.copy(raycaster.ray).recast(raycaster.near);
    if (_sphere$6.containsPoint(_ray$3.origin) === false) {
      if (_ray$3.intersectSphere(_sphere$6, _sphereHitAt) === null)
        return;
      if (_ray$3.origin.distanceToSquared(_sphereHitAt) > (raycaster.far - raycaster.near) ** 2)
        return;
    }
    _inverseMatrix$3.copy(matrixWorld).invert();
    _ray$3.copy(raycaster.ray).applyMatrix4(_inverseMatrix$3);
    if (geometry.boundingBox !== null) {
      if (_ray$3.intersectsBox(geometry.boundingBox) === false)
        return;
    }
    this._computeIntersections(raycaster, intersects, _ray$3);
  }
  _computeIntersections(raycaster, intersects, rayLocalSpace) {
    let intersection;
    const geometry = this.geometry;
    const material = this.material;
    const index = geometry.index;
    const position = geometry.attributes.position;
    const uv = geometry.attributes.uv;
    const uv1 = geometry.attributes.uv1;
    const normal = geometry.attributes.normal;
    const groups = geometry.groups;
    const drawRange = geometry.drawRange;
    if (index !== null) {
      if (Array.isArray(material)) {
        for (let i = 0, il = groups.length;i < il; i++) {
          const group = groups[i];
          const groupMaterial = material[group.materialIndex];
          const start = Math.max(group.start, drawRange.start);
          const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
          for (let j = start, jl = end;j < jl; j += 3) {
            const a = index.getX(j);
            const b = index.getX(j + 1);
            const c = index.getX(j + 2);
            intersection = checkGeometryIntersection(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c);
            if (intersection) {
              intersection.faceIndex = Math.floor(j / 3);
              intersection.face.materialIndex = group.materialIndex;
              intersects.push(intersection);
            }
          }
        }
      } else {
        const start = Math.max(0, drawRange.start);
        const end = Math.min(index.count, drawRange.start + drawRange.count);
        for (let i = start, il = end;i < il; i += 3) {
          const a = index.getX(i);
          const b = index.getX(i + 1);
          const c = index.getX(i + 2);
          intersection = checkGeometryIntersection(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c);
          if (intersection) {
            intersection.faceIndex = Math.floor(i / 3);
            intersects.push(intersection);
          }
        }
      }
    } else if (position !== undefined) {
      if (Array.isArray(material)) {
        for (let i = 0, il = groups.length;i < il; i++) {
          const group = groups[i];
          const groupMaterial = material[group.materialIndex];
          const start = Math.max(group.start, drawRange.start);
          const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
          for (let j = start, jl = end;j < jl; j += 3) {
            const a = j;
            const b = j + 1;
            const c = j + 2;
            intersection = checkGeometryIntersection(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c);
            if (intersection) {
              intersection.faceIndex = Math.floor(j / 3);
              intersection.face.materialIndex = group.materialIndex;
              intersects.push(intersection);
            }
          }
        }
      } else {
        const start = Math.max(0, drawRange.start);
        const end = Math.min(position.count, drawRange.start + drawRange.count);
        for (let i = start, il = end;i < il; i += 3) {
          const a = i;
          const b = i + 1;
          const c = i + 2;
          intersection = checkGeometryIntersection(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c);
          if (intersection) {
            intersection.faceIndex = Math.floor(i / 3);
            intersects.push(intersection);
          }
        }
      }
    }
  }
}
function checkIntersection$1(object, material, raycaster, ray, pA, pB, pC, point3) {
  let intersect2;
  if (material.side === BackSide) {
    intersect2 = ray.intersectTriangle(pC, pB, pA, true, point3);
  } else {
    intersect2 = ray.intersectTriangle(pA, pB, pC, material.side === FrontSide, point3);
  }
  if (intersect2 === null)
    return null;
  _intersectionPointWorld.copy(point3);
  _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  if (distance < raycaster.near || distance > raycaster.far)
    return null;
  return {
    distance,
    point: _intersectionPointWorld.clone(),
    object
  };
}
function checkGeometryIntersection(object, material, raycaster, ray, uv, uv1, normal, a, b, c) {
  object.getVertexPosition(a, _vA$1);
  object.getVertexPosition(b, _vB$1);
  object.getVertexPosition(c, _vC$1);
  const intersection = checkIntersection$1(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  if (intersection) {
    const barycoord = new Vector3;
    Triangle.getBarycoord(_intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord);
    if (uv) {
      intersection.uv = Triangle.getInterpolatedAttribute(uv, a, b, c, barycoord, new Vector2);
    }
    if (uv1) {
      intersection.uv1 = Triangle.getInterpolatedAttribute(uv1, a, b, c, barycoord, new Vector2);
    }
    if (normal) {
      intersection.normal = Triangle.getInterpolatedAttribute(normal, a, b, c, barycoord, new Vector3);
      if (intersection.normal.dot(ray.direction) > 0) {
        intersection.normal.multiplyScalar(-1);
      }
    }
    const face = {
      a,
      b,
      c,
      normal: new Vector3,
      materialIndex: 0
    };
    Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
    intersection.face = face;
    intersection.barycoord = barycoord;
  }
  return intersection;
}

class BoxGeometry extends BufferGeometry {
  constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
    super();
    this.type = "BoxGeometry";
    this.parameters = {
      width,
      height,
      depth,
      widthSegments,
      heightSegments,
      depthSegments
    };
    const scope = this;
    widthSegments = Math.floor(widthSegments);
    heightSegments = Math.floor(heightSegments);
    depthSegments = Math.floor(depthSegments);
    const indices = [];
    const vertices = [];
    const normals = [];
    const uvs = [];
    let numberOfVertices = 0;
    let groupStart = 0;
    buildPlane("z", "y", "x", -1, -1, depth, height, width, depthSegments, heightSegments, 0);
    buildPlane("z", "y", "x", 1, -1, depth, height, -width, depthSegments, heightSegments, 1);
    buildPlane("x", "z", "y", 1, 1, width, depth, height, widthSegments, depthSegments, 2);
    buildPlane("x", "z", "y", 1, -1, width, depth, -height, widthSegments, depthSegments, 3);
    buildPlane("x", "y", "z", 1, -1, width, height, depth, widthSegments, heightSegments, 4);
    buildPlane("x", "y", "z", -1, -1, width, height, -depth, widthSegments, heightSegments, 5);
    this.setIndex(indices);
    this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    this.setAttribute("normal", new Float32BufferAttribute(normals, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
    function buildPlane(u, v, w, udir, vdir, width2, height2, depth2, gridX, gridY, materialIndex) {
      const segmentWidth = width2 / gridX;
      const segmentHeight = height2 / gridY;
      const widthHalf = width2 / 2;
      const heightHalf = height2 / 2;
      const depthHalf = depth2 / 2;
      const gridX1 = gridX + 1;
      const gridY1 = gridY + 1;
      let vertexCounter = 0;
      let groupCount = 0;
      const vector = new Vector3;
      for (let iy = 0;iy < gridY1; iy++) {
        const y2 = iy * segmentHeight - heightHalf;
        for (let ix = 0;ix < gridX1; ix++) {
          const x2 = ix * segmentWidth - widthHalf;
          vector[u] = x2 * udir;
          vector[v] = y2 * vdir;
          vector[w] = depthHalf;
          vertices.push(vector.x, vector.y, vector.z);
          vector[u] = 0;
          vector[v] = 0;
          vector[w] = depth2 > 0 ? 1 : -1;
          normals.push(vector.x, vector.y, vector.z);
          uvs.push(ix / gridX);
          uvs.push(1 - iy / gridY);
          vertexCounter += 1;
        }
      }
      for (let iy = 0;iy < gridY; iy++) {
        for (let ix = 0;ix < gridX; ix++) {
          const a = numberOfVertices + ix + gridX1 * iy;
          const b = numberOfVertices + ix + gridX1 * (iy + 1);
          const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
          const d = numberOfVertices + (ix + 1) + gridX1 * iy;
          indices.push(a, b, d);
          indices.push(b, c, d);
          groupCount += 6;
        }
      }
      scope.addGroup(groupStart, groupCount, materialIndex);
      groupStart += groupCount;
      numberOfVertices += vertexCounter;
    }
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
  static fromJSON(data) {
    return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  }
}
function cloneUniforms(src) {
  const dst = {};
  for (const u in src) {
    dst[u] = {};
    for (const p in src[u]) {
      const property = src[u][p];
      if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
        if (property.isRenderTargetTexture) {
          console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().");
          dst[u][p] = null;
        } else {
          dst[u][p] = property.clone();
        }
      } else if (Array.isArray(property)) {
        dst[u][p] = property.slice();
      } else {
        dst[u][p] = property;
      }
    }
  }
  return dst;
}
function mergeUniforms(uniforms) {
  const merged = {};
  for (let u = 0;u < uniforms.length; u++) {
    const tmp = cloneUniforms(uniforms[u]);
    for (const p in tmp) {
      merged[p] = tmp[p];
    }
  }
  return merged;
}
class Group extends Object3D {
  constructor() {
    super();
    this.isGroup = true;
    this.type = "Group";
  }
}
class InterleavedBuffer {
  constructor(array2, stride) {
    this.isInterleavedBuffer = true;
    this.array = array2;
    this.stride = stride;
    this.count = array2 !== undefined ? array2.length / stride : 0;
    this.usage = StaticDrawUsage;
    this.updateRanges = [];
    this.version = 0;
    this.uuid = generateUUID();
  }
  onUploadCallback() {}
  set needsUpdate(value) {
    if (value === true)
      this.version++;
  }
  setUsage(value) {
    this.usage = value;
    return this;
  }
  addUpdateRange(start, count3) {
    this.updateRanges.push({ start, count: count3 });
  }
  clearUpdateRanges() {
    this.updateRanges.length = 0;
  }
  copy(source) {
    this.array = new source.array.constructor(source.array);
    this.count = source.count;
    this.stride = source.stride;
    this.usage = source.usage;
    return this;
  }
  copyAt(index1, interleavedBuffer, index2) {
    index1 *= this.stride;
    index2 *= interleavedBuffer.stride;
    for (let i = 0, l = this.stride;i < l; i++) {
      this.array[index1 + i] = interleavedBuffer.array[index2 + i];
    }
    return this;
  }
  set(value, offset = 0) {
    this.array.set(value, offset);
    return this;
  }
  clone(data) {
    if (data.arrayBuffers === undefined) {
      data.arrayBuffers = {};
    }
    if (this.array.buffer._uuid === undefined) {
      this.array.buffer._uuid = generateUUID();
    }
    if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
      data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
    }
    const array2 = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
    const ib = new this.constructor(array2, this.stride);
    ib.setUsage(this.usage);
    return ib;
  }
  onUpload(callback) {
    this.onUploadCallback = callback;
    return this;
  }
  toJSON(data) {
    if (data.arrayBuffers === undefined) {
      data.arrayBuffers = {};
    }
    if (this.array.buffer._uuid === undefined) {
      this.array.buffer._uuid = generateUUID();
    }
    if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
      data.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer));
    }
    return {
      uuid: this.uuid,
      buffer: this.array.buffer._uuid,
      type: this.array.constructor.name,
      stride: this.stride
    };
  }
}
var _vector$7 = /* @__PURE__ */ new Vector3;

class InterleavedBufferAttribute {
  constructor(interleavedBuffer, itemSize, offset, normalized = false) {
    this.isInterleavedBufferAttribute = true;
    this.name = "";
    this.data = interleavedBuffer;
    this.itemSize = itemSize;
    this.offset = offset;
    this.normalized = normalized;
  }
  get count() {
    return this.data.count;
  }
  get array() {
    return this.data.array;
  }
  set needsUpdate(value) {
    this.data.needsUpdate = value;
  }
  applyMatrix4(m) {
    for (let i = 0, l = this.data.count;i < l; i++) {
      _vector$7.fromBufferAttribute(this, i);
      _vector$7.applyMatrix4(m);
      this.setXYZ(i, _vector$7.x, _vector$7.y, _vector$7.z);
    }
    return this;
  }
  applyNormalMatrix(m) {
    for (let i = 0, l = this.count;i < l; i++) {
      _vector$7.fromBufferAttribute(this, i);
      _vector$7.applyNormalMatrix(m);
      this.setXYZ(i, _vector$7.x, _vector$7.y, _vector$7.z);
    }
    return this;
  }
  transformDirection(m) {
    for (let i = 0, l = this.count;i < l; i++) {
      _vector$7.fromBufferAttribute(this, i);
      _vector$7.transformDirection(m);
      this.setXYZ(i, _vector$7.x, _vector$7.y, _vector$7.z);
    }
    return this;
  }
  getComponent(index, component) {
    let value = this.array[index * this.data.stride + this.offset + component];
    if (this.normalized)
      value = denormalize(value, this.array);
    return value;
  }
  setComponent(index, component, value) {
    if (this.normalized)
      value = normalize2(value, this.array);
    this.data.array[index * this.data.stride + this.offset + component] = value;
    return this;
  }
  setX(index, x2) {
    if (this.normalized)
      x2 = normalize2(x2, this.array);
    this.data.array[index * this.data.stride + this.offset] = x2;
    return this;
  }
  setY(index, y2) {
    if (this.normalized)
      y2 = normalize2(y2, this.array);
    this.data.array[index * this.data.stride + this.offset + 1] = y2;
    return this;
  }
  setZ(index, z) {
    if (this.normalized)
      z = normalize2(z, this.array);
    this.data.array[index * this.data.stride + this.offset + 2] = z;
    return this;
  }
  setW(index, w) {
    if (this.normalized)
      w = normalize2(w, this.array);
    this.data.array[index * this.data.stride + this.offset + 3] = w;
    return this;
  }
  getX(index) {
    let x2 = this.data.array[index * this.data.stride + this.offset];
    if (this.normalized)
      x2 = denormalize(x2, this.array);
    return x2;
  }
  getY(index) {
    let y2 = this.data.array[index * this.data.stride + this.offset + 1];
    if (this.normalized)
      y2 = denormalize(y2, this.array);
    return y2;
  }
  getZ(index) {
    let z = this.data.array[index * this.data.stride + this.offset + 2];
    if (this.normalized)
      z = denormalize(z, this.array);
    return z;
  }
  getW(index) {
    let w = this.data.array[index * this.data.stride + this.offset + 3];
    if (this.normalized)
      w = denormalize(w, this.array);
    return w;
  }
  setXY(index, x2, y2) {
    index = index * this.data.stride + this.offset;
    if (this.normalized) {
      x2 = normalize2(x2, this.array);
      y2 = normalize2(y2, this.array);
    }
    this.data.array[index + 0] = x2;
    this.data.array[index + 1] = y2;
    return this;
  }
  setXYZ(index, x2, y2, z) {
    index = index * this.data.stride + this.offset;
    if (this.normalized) {
      x2 = normalize2(x2, this.array);
      y2 = normalize2(y2, this.array);
      z = normalize2(z, this.array);
    }
    this.data.array[index + 0] = x2;
    this.data.array[index + 1] = y2;
    this.data.array[index + 2] = z;
    return this;
  }
  setXYZW(index, x2, y2, z, w) {
    index = index * this.data.stride + this.offset;
    if (this.normalized) {
      x2 = normalize2(x2, this.array);
      y2 = normalize2(y2, this.array);
      z = normalize2(z, this.array);
      w = normalize2(w, this.array);
    }
    this.data.array[index + 0] = x2;
    this.data.array[index + 1] = y2;
    this.data.array[index + 2] = z;
    this.data.array[index + 3] = w;
    return this;
  }
  clone(data) {
    if (data === undefined) {
      console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");
      const array2 = [];
      for (let i = 0;i < this.count; i++) {
        const index = i * this.data.stride + this.offset;
        for (let j = 0;j < this.itemSize; j++) {
          array2.push(this.data.array[index + j]);
        }
      }
      return new BufferAttribute(new this.array.constructor(array2), this.itemSize, this.normalized);
    } else {
      if (data.interleavedBuffers === undefined) {
        data.interleavedBuffers = {};
      }
      if (data.interleavedBuffers[this.data.uuid] === undefined) {
        data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
      }
      return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
    }
  }
  toJSON(data) {
    if (data === undefined) {
      console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");
      const array2 = [];
      for (let i = 0;i < this.count; i++) {
        const index = i * this.data.stride + this.offset;
        for (let j = 0;j < this.itemSize; j++) {
          array2.push(this.data.array[index + j]);
        }
      }
      return {
        itemSize: this.itemSize,
        type: this.array.constructor.name,
        array: array2,
        normalized: this.normalized
      };
    } else {
      if (data.interleavedBuffers === undefined) {
        data.interleavedBuffers = {};
      }
      if (data.interleavedBuffers[this.data.uuid] === undefined) {
        data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
      }
      return {
        isInterleavedBufferAttribute: true,
        itemSize: this.itemSize,
        data: this.data.uuid,
        offset: this.offset,
        normalized: this.normalized
      };
    }
  }
}

class SpriteMaterial extends Material {
  constructor(parameters) {
    super();
    this.isSpriteMaterial = true;
    this.type = "SpriteMaterial";
    this.color = new Color3(16777215);
    this.map = null;
    this.alphaMap = null;
    this.rotation = 0;
    this.sizeAttenuation = true;
    this.transparent = true;
    this.fog = true;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.color.copy(source.color);
    this.map = source.map;
    this.alphaMap = source.alphaMap;
    this.rotation = source.rotation;
    this.sizeAttenuation = source.sizeAttenuation;
    this.fog = source.fog;
    return this;
  }
}
var _geometry;
var _intersectPoint = /* @__PURE__ */ new Vector3;
var _worldScale = /* @__PURE__ */ new Vector3;
var _mvPosition = /* @__PURE__ */ new Vector3;
var _alignedPosition = /* @__PURE__ */ new Vector2;
var _rotatedPosition = /* @__PURE__ */ new Vector2;
var _viewWorldMatrix = /* @__PURE__ */ new Matrix4;
var _vA = /* @__PURE__ */ new Vector3;
var _vB = /* @__PURE__ */ new Vector3;
var _vC = /* @__PURE__ */ new Vector3;
var _uvA = /* @__PURE__ */ new Vector2;
var _uvB = /* @__PURE__ */ new Vector2;
var _uvC = /* @__PURE__ */ new Vector2;

class Sprite extends Object3D {
  constructor(material = new SpriteMaterial) {
    super();
    this.isSprite = true;
    this.type = "Sprite";
    if (_geometry === undefined) {
      _geometry = new BufferGeometry;
      const float32Array = new Float32Array([
        -0.5,
        -0.5,
        0,
        0,
        0,
        0.5,
        -0.5,
        0,
        1,
        0,
        0.5,
        0.5,
        0,
        1,
        1,
        -0.5,
        0.5,
        0,
        0,
        1
      ]);
      const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
      _geometry.setIndex([0, 1, 2, 0, 2, 3]);
      _geometry.setAttribute("position", new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
      _geometry.setAttribute("uv", new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
    }
    this.geometry = _geometry;
    this.material = material;
    this.center = new Vector2(0.5, 0.5);
    this.count = 1;
  }
  raycast(raycaster, intersects) {
    if (raycaster.camera === null) {
      console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
    }
    _worldScale.setFromMatrixScale(this.matrixWorld);
    _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
    this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
    _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
    if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
      _worldScale.multiplyScalar(-_mvPosition.z);
    }
    const rotation = this.material.rotation;
    let sin2, cos2;
    if (rotation !== 0) {
      cos2 = Math.cos(rotation);
      sin2 = Math.sin(rotation);
    }
    const center = this.center;
    transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin2, cos2);
    transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin2, cos2);
    transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin2, cos2);
    _uvA.set(0, 0);
    _uvB.set(1, 0);
    _uvC.set(1, 1);
    let intersect2 = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
    if (intersect2 === null) {
      transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin2, cos2);
      _uvB.set(0, 1);
      intersect2 = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
      if (intersect2 === null) {
        return;
      }
    }
    const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
    if (distance < raycaster.near || distance > raycaster.far)
      return;
    intersects.push({
      distance,
      point: _intersectPoint.clone(),
      uv: Triangle.getInterpolation(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2),
      face: null,
      object: this
    });
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    if (source.center !== undefined)
      this.center.copy(source.center);
    this.material = source.material;
    return this;
  }
}
function transformVertex(vertexPosition, mvPosition, center, scale, sin2, cos2) {
  _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale);
  if (sin2 !== undefined) {
    _rotatedPosition.x = cos2 * _alignedPosition.x - sin2 * _alignedPosition.y;
    _rotatedPosition.y = sin2 * _alignedPosition.x + cos2 * _alignedPosition.y;
  } else {
    _rotatedPosition.copy(_alignedPosition);
  }
  vertexPosition.copy(mvPosition);
  vertexPosition.x += _rotatedPosition.x;
  vertexPosition.y += _rotatedPosition.y;
  vertexPosition.applyMatrix4(_viewWorldMatrix);
}
class LineBasicMaterial extends Material {
  constructor(parameters) {
    super();
    this.isLineBasicMaterial = true;
    this.type = "LineBasicMaterial";
    this.color = new Color3(16777215);
    this.map = null;
    this.linewidth = 1;
    this.linecap = "round";
    this.linejoin = "round";
    this.fog = true;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.color.copy(source.color);
    this.map = source.map;
    this.linewidth = source.linewidth;
    this.linecap = source.linecap;
    this.linejoin = source.linejoin;
    this.fog = source.fog;
    return this;
  }
}
var _vStart = /* @__PURE__ */ new Vector3;
var _vEnd = /* @__PURE__ */ new Vector3;
var _inverseMatrix$1 = /* @__PURE__ */ new Matrix4;
var _ray$1 = /* @__PURE__ */ new Ray;
var _sphere$1 = /* @__PURE__ */ new Sphere;
var _intersectPointOnRay = /* @__PURE__ */ new Vector3;
var _intersectPointOnSegment = /* @__PURE__ */ new Vector3;

class Line2 extends Object3D {
  constructor(geometry = new BufferGeometry, material = new LineBasicMaterial) {
    super();
    this.isLine = true;
    this.type = "Line";
    this.geometry = geometry;
    this.material = material;
    this.morphTargetDictionary = undefined;
    this.morphTargetInfluences = undefined;
    this.updateMorphTargets();
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    this.material = Array.isArray(source.material) ? source.material.slice() : source.material;
    this.geometry = source.geometry;
    return this;
  }
  computeLineDistances() {
    const geometry = this.geometry;
    if (geometry.index === null) {
      const positionAttribute = geometry.attributes.position;
      const lineDistances = [0];
      for (let i = 1, l = positionAttribute.count;i < l; i++) {
        _vStart.fromBufferAttribute(positionAttribute, i - 1);
        _vEnd.fromBufferAttribute(positionAttribute, i);
        lineDistances[i] = lineDistances[i - 1];
        lineDistances[i] += _vStart.distanceTo(_vEnd);
      }
      geometry.setAttribute("lineDistance", new Float32BufferAttribute(lineDistances, 1));
    } else {
      console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");
    }
    return this;
  }
  raycast(raycaster, intersects) {
    const geometry = this.geometry;
    const matrixWorld = this.matrixWorld;
    const threshold = raycaster.params.Line.threshold;
    const drawRange = geometry.drawRange;
    if (geometry.boundingSphere === null)
      geometry.computeBoundingSphere();
    _sphere$1.copy(geometry.boundingSphere);
    _sphere$1.applyMatrix4(matrixWorld);
    _sphere$1.radius += threshold;
    if (raycaster.ray.intersectsSphere(_sphere$1) === false)
      return;
    _inverseMatrix$1.copy(matrixWorld).invert();
    _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
    const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
    const localThresholdSq = localThreshold * localThreshold;
    const step = this.isLineSegments ? 2 : 1;
    const index = geometry.index;
    const attributes = geometry.attributes;
    const positionAttribute = attributes.position;
    if (index !== null) {
      const start = Math.max(0, drawRange.start);
      const end = Math.min(index.count, drawRange.start + drawRange.count);
      for (let i = start, l = end - 1;i < l; i += step) {
        const a = index.getX(i);
        const b = index.getX(i + 1);
        const intersect2 = checkIntersection(this, raycaster, _ray$1, localThresholdSq, a, b, i);
        if (intersect2) {
          intersects.push(intersect2);
        }
      }
      if (this.isLineLoop) {
        const a = index.getX(end - 1);
        const b = index.getX(start);
        const intersect2 = checkIntersection(this, raycaster, _ray$1, localThresholdSq, a, b, end - 1);
        if (intersect2) {
          intersects.push(intersect2);
        }
      }
    } else {
      const start = Math.max(0, drawRange.start);
      const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
      for (let i = start, l = end - 1;i < l; i += step) {
        const intersect2 = checkIntersection(this, raycaster, _ray$1, localThresholdSq, i, i + 1, i);
        if (intersect2) {
          intersects.push(intersect2);
        }
      }
      if (this.isLineLoop) {
        const intersect2 = checkIntersection(this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1);
        if (intersect2) {
          intersects.push(intersect2);
        }
      }
    }
  }
  updateMorphTargets() {
    const geometry = this.geometry;
    const morphAttributes = geometry.morphAttributes;
    const keys = Object.keys(morphAttributes);
    if (keys.length > 0) {
      const morphAttribute = morphAttributes[keys[0]];
      if (morphAttribute !== undefined) {
        this.morphTargetInfluences = [];
        this.morphTargetDictionary = {};
        for (let m = 0, ml = morphAttribute.length;m < ml; m++) {
          const name = morphAttribute[m].name || String(m);
          this.morphTargetInfluences.push(0);
          this.morphTargetDictionary[name] = m;
        }
      }
    }
  }
}
function checkIntersection(object, raycaster, ray, thresholdSq, a, b, i) {
  const positionAttribute = object.geometry.attributes.position;
  _vStart.fromBufferAttribute(positionAttribute, a);
  _vEnd.fromBufferAttribute(positionAttribute, b);
  const distSq = ray.distanceSqToSegment(_vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment);
  if (distSq > thresholdSq)
    return;
  _intersectPointOnRay.applyMatrix4(object.matrixWorld);
  const distance = raycaster.ray.origin.distanceTo(_intersectPointOnRay);
  if (distance < raycaster.near || distance > raycaster.far)
    return;
  return {
    distance,
    point: _intersectPointOnSegment.clone().applyMatrix4(object.matrixWorld),
    index: i,
    face: null,
    faceIndex: null,
    barycoord: null,
    object
  };
}
class CanvasTexture extends Texture {
  constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format2, type, anisotropy) {
    super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format2, type, anisotropy);
    this.isCanvasTexture = true;
    this.needsUpdate = true;
  }
}
class CylinderGeometry extends BufferGeometry {
  constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
    super();
    this.type = "CylinderGeometry";
    this.parameters = {
      radiusTop,
      radiusBottom,
      height,
      radialSegments,
      heightSegments,
      openEnded,
      thetaStart,
      thetaLength
    };
    const scope = this;
    radialSegments = Math.floor(radialSegments);
    heightSegments = Math.floor(heightSegments);
    const indices = [];
    const vertices = [];
    const normals = [];
    const uvs = [];
    let index = 0;
    const indexArray = [];
    const halfHeight = height / 2;
    let groupStart = 0;
    generateTorso();
    if (openEnded === false) {
      if (radiusTop > 0)
        generateCap(true);
      if (radiusBottom > 0)
        generateCap(false);
    }
    this.setIndex(indices);
    this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    this.setAttribute("normal", new Float32BufferAttribute(normals, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
    function generateTorso() {
      const normal = new Vector3;
      const vertex = new Vector3;
      let groupCount = 0;
      const slope = (radiusBottom - radiusTop) / height;
      for (let y2 = 0;y2 <= heightSegments; y2++) {
        const indexRow = [];
        const v = y2 / heightSegments;
        const radius = v * (radiusBottom - radiusTop) + radiusTop;
        for (let x2 = 0;x2 <= radialSegments; x2++) {
          const u = x2 / radialSegments;
          const theta = u * thetaLength + thetaStart;
          const sinTheta = Math.sin(theta);
          const cosTheta = Math.cos(theta);
          vertex.x = radius * sinTheta;
          vertex.y = -v * height + halfHeight;
          vertex.z = radius * cosTheta;
          vertices.push(vertex.x, vertex.y, vertex.z);
          normal.set(sinTheta, slope, cosTheta).normalize();
          normals.push(normal.x, normal.y, normal.z);
          uvs.push(u, 1 - v);
          indexRow.push(index++);
        }
        indexArray.push(indexRow);
      }
      for (let x2 = 0;x2 < radialSegments; x2++) {
        for (let y2 = 0;y2 < heightSegments; y2++) {
          const a = indexArray[y2][x2];
          const b = indexArray[y2 + 1][x2];
          const c = indexArray[y2 + 1][x2 + 1];
          const d = indexArray[y2][x2 + 1];
          if (radiusTop > 0 || y2 !== 0) {
            indices.push(a, b, d);
            groupCount += 3;
          }
          if (radiusBottom > 0 || y2 !== heightSegments - 1) {
            indices.push(b, c, d);
            groupCount += 3;
          }
        }
      }
      scope.addGroup(groupStart, groupCount, 0);
      groupStart += groupCount;
    }
    function generateCap(top) {
      const centerIndexStart = index;
      const uv = new Vector2;
      const vertex = new Vector3;
      let groupCount = 0;
      const radius = top === true ? radiusTop : radiusBottom;
      const sign2 = top === true ? 1 : -1;
      for (let x2 = 1;x2 <= radialSegments; x2++) {
        vertices.push(0, halfHeight * sign2, 0);
        normals.push(0, sign2, 0);
        uvs.push(0.5, 0.5);
        index++;
      }
      const centerIndexEnd = index;
      for (let x2 = 0;x2 <= radialSegments; x2++) {
        const u = x2 / radialSegments;
        const theta = u * thetaLength + thetaStart;
        const cosTheta = Math.cos(theta);
        const sinTheta = Math.sin(theta);
        vertex.x = radius * sinTheta;
        vertex.y = halfHeight * sign2;
        vertex.z = radius * cosTheta;
        vertices.push(vertex.x, vertex.y, vertex.z);
        normals.push(0, sign2, 0);
        uv.x = cosTheta * 0.5 + 0.5;
        uv.y = sinTheta * 0.5 * sign2 + 0.5;
        uvs.push(uv.x, uv.y);
        index++;
      }
      for (let x2 = 0;x2 < radialSegments; x2++) {
        const c = centerIndexStart + x2;
        const i = centerIndexEnd + x2;
        if (top === true) {
          indices.push(i, i + 1, c);
        } else {
          indices.push(i + 1, i, c);
        }
        groupCount += 3;
      }
      scope.addGroup(groupStart, groupCount, top === true ? 1 : 2);
      groupStart += groupCount;
    }
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
  static fromJSON(data) {
    return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  }
}
class MeshStandardMaterial extends Material {
  constructor(parameters) {
    super();
    this.isMeshStandardMaterial = true;
    this.type = "MeshStandardMaterial";
    this.defines = { STANDARD: "" };
    this.color = new Color3(16777215);
    this.roughness = 1;
    this.metalness = 0;
    this.map = null;
    this.lightMap = null;
    this.lightMapIntensity = 1;
    this.aoMap = null;
    this.aoMapIntensity = 1;
    this.emissive = new Color3(0);
    this.emissiveIntensity = 1;
    this.emissiveMap = null;
    this.bumpMap = null;
    this.bumpScale = 1;
    this.normalMap = null;
    this.normalMapType = TangentSpaceNormalMap;
    this.normalScale = new Vector2(1, 1);
    this.displacementMap = null;
    this.displacementScale = 1;
    this.displacementBias = 0;
    this.roughnessMap = null;
    this.metalnessMap = null;
    this.alphaMap = null;
    this.envMap = null;
    this.envMapRotation = new Euler;
    this.envMapIntensity = 1;
    this.wireframe = false;
    this.wireframeLinewidth = 1;
    this.wireframeLinecap = "round";
    this.wireframeLinejoin = "round";
    this.flatShading = false;
    this.fog = true;
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.defines = { STANDARD: "" };
    this.color.copy(source.color);
    this.roughness = source.roughness;
    this.metalness = source.metalness;
    this.map = source.map;
    this.lightMap = source.lightMap;
    this.lightMapIntensity = source.lightMapIntensity;
    this.aoMap = source.aoMap;
    this.aoMapIntensity = source.aoMapIntensity;
    this.emissive.copy(source.emissive);
    this.emissiveMap = source.emissiveMap;
    this.emissiveIntensity = source.emissiveIntensity;
    this.bumpMap = source.bumpMap;
    this.bumpScale = source.bumpScale;
    this.normalMap = source.normalMap;
    this.normalMapType = source.normalMapType;
    this.normalScale.copy(source.normalScale);
    this.displacementMap = source.displacementMap;
    this.displacementScale = source.displacementScale;
    this.displacementBias = source.displacementBias;
    this.roughnessMap = source.roughnessMap;
    this.metalnessMap = source.metalnessMap;
    this.alphaMap = source.alphaMap;
    this.envMap = source.envMap;
    this.envMapRotation.copy(source.envMapRotation);
    this.envMapIntensity = source.envMapIntensity;
    this.wireframe = source.wireframe;
    this.wireframeLinewidth = source.wireframeLinewidth;
    this.wireframeLinecap = source.wireframeLinecap;
    this.wireframeLinejoin = source.wireframeLinejoin;
    this.flatShading = source.flatShading;
    this.fog = source.fog;
    return this;
  }
}

class MeshPhysicalMaterial extends MeshStandardMaterial {
  constructor(parameters) {
    super();
    this.isMeshPhysicalMaterial = true;
    this.defines = {
      STANDARD: "",
      PHYSICAL: ""
    };
    this.type = "MeshPhysicalMaterial";
    this.anisotropyRotation = 0;
    this.anisotropyMap = null;
    this.clearcoatMap = null;
    this.clearcoatRoughness = 0;
    this.clearcoatRoughnessMap = null;
    this.clearcoatNormalScale = new Vector2(1, 1);
    this.clearcoatNormalMap = null;
    this.ior = 1.5;
    Object.defineProperty(this, "reflectivity", {
      get: function() {
        return clamp3(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
      },
      set: function(reflectivity) {
        this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
      }
    });
    this.iridescenceMap = null;
    this.iridescenceIOR = 1.3;
    this.iridescenceThicknessRange = [100, 400];
    this.iridescenceThicknessMap = null;
    this.sheenColor = new Color3(0);
    this.sheenColorMap = null;
    this.sheenRoughness = 1;
    this.sheenRoughnessMap = null;
    this.transmissionMap = null;
    this.thickness = 0;
    this.thicknessMap = null;
    this.attenuationDistance = Infinity;
    this.attenuationColor = new Color3(1, 1, 1);
    this.specularIntensity = 1;
    this.specularIntensityMap = null;
    this.specularColor = new Color3(1, 1, 1);
    this.specularColorMap = null;
    this._anisotropy = 0;
    this._clearcoat = 0;
    this._dispersion = 0;
    this._iridescence = 0;
    this._sheen = 0;
    this._transmission = 0;
    this.setValues(parameters);
  }
  get anisotropy() {
    return this._anisotropy;
  }
  set anisotropy(value) {
    if (this._anisotropy > 0 !== value > 0) {
      this.version++;
    }
    this._anisotropy = value;
  }
  get clearcoat() {
    return this._clearcoat;
  }
  set clearcoat(value) {
    if (this._clearcoat > 0 !== value > 0) {
      this.version++;
    }
    this._clearcoat = value;
  }
  get iridescence() {
    return this._iridescence;
  }
  set iridescence(value) {
    if (this._iridescence > 0 !== value > 0) {
      this.version++;
    }
    this._iridescence = value;
  }
  get dispersion() {
    return this._dispersion;
  }
  set dispersion(value) {
    if (this._dispersion > 0 !== value > 0) {
      this.version++;
    }
    this._dispersion = value;
  }
  get sheen() {
    return this._sheen;
  }
  set sheen(value) {
    if (this._sheen > 0 !== value > 0) {
      this.version++;
    }
    this._sheen = value;
  }
  get transmission() {
    return this._transmission;
  }
  set transmission(value) {
    if (this._transmission > 0 !== value > 0) {
      this.version++;
    }
    this._transmission = value;
  }
  copy(source) {
    super.copy(source);
    this.defines = {
      STANDARD: "",
      PHYSICAL: ""
    };
    this.anisotropy = source.anisotropy;
    this.anisotropyRotation = source.anisotropyRotation;
    this.anisotropyMap = source.anisotropyMap;
    this.clearcoat = source.clearcoat;
    this.clearcoatMap = source.clearcoatMap;
    this.clearcoatRoughness = source.clearcoatRoughness;
    this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
    this.clearcoatNormalMap = source.clearcoatNormalMap;
    this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
    this.dispersion = source.dispersion;
    this.ior = source.ior;
    this.iridescence = source.iridescence;
    this.iridescenceMap = source.iridescenceMap;
    this.iridescenceIOR = source.iridescenceIOR;
    this.iridescenceThicknessRange = [...source.iridescenceThicknessRange];
    this.iridescenceThicknessMap = source.iridescenceThicknessMap;
    this.sheen = source.sheen;
    this.sheenColor.copy(source.sheenColor);
    this.sheenColorMap = source.sheenColorMap;
    this.sheenRoughness = source.sheenRoughness;
    this.sheenRoughnessMap = source.sheenRoughnessMap;
    this.transmission = source.transmission;
    this.transmissionMap = source.transmissionMap;
    this.thickness = source.thickness;
    this.thicknessMap = source.thicknessMap;
    this.attenuationDistance = source.attenuationDistance;
    this.attenuationColor.copy(source.attenuationColor);
    this.specularIntensity = source.specularIntensity;
    this.specularIntensityMap = source.specularIntensityMap;
    this.specularColor.copy(source.specularColor);
    this.specularColorMap = source.specularColorMap;
    return this;
  }
}
function convertArray(array2, type) {
  if (!array2 || array2.constructor === type)
    return array2;
  if (typeof type.BYTES_PER_ELEMENT === "number") {
    return new type(array2);
  }
  return Array.prototype.slice.call(array2);
}
function isTypedArray(object) {
  return ArrayBuffer.isView(object) && !(object instanceof DataView);
}
class Interpolant {
  constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
    this.parameterPositions = parameterPositions;
    this._cachedIndex = 0;
    this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
    this.sampleValues = sampleValues;
    this.valueSize = sampleSize;
    this.settings = null;
    this.DefaultSettings_ = {};
  }
  evaluate(t) {
    const pp = this.parameterPositions;
    let i1 = this._cachedIndex, t1 = pp[i1], t0 = pp[i1 - 1];
    validate_interval: {
      seek: {
        let right;
        linear_scan: {
          forward_scan:
            if (!(t < t1)) {
              for (let giveUpAt = i1 + 2;; ) {
                if (t1 === undefined) {
                  if (t < t0)
                    break forward_scan;
                  i1 = pp.length;
                  this._cachedIndex = i1;
                  return this.copySampleValue_(i1 - 1);
                }
                if (i1 === giveUpAt)
                  break;
                t0 = t1;
                t1 = pp[++i1];
                if (t < t1) {
                  break seek;
                }
              }
              right = pp.length;
              break linear_scan;
            }
          if (!(t >= t0)) {
            const t1global = pp[1];
            if (t < t1global) {
              i1 = 2;
              t0 = t1global;
            }
            for (let giveUpAt = i1 - 2;; ) {
              if (t0 === undefined) {
                this._cachedIndex = 0;
                return this.copySampleValue_(0);
              }
              if (i1 === giveUpAt)
                break;
              t1 = t0;
              t0 = pp[--i1 - 1];
              if (t >= t0) {
                break seek;
              }
            }
            right = i1;
            i1 = 0;
            break linear_scan;
          }
          break validate_interval;
        }
        while (i1 < right) {
          const mid = i1 + right >>> 1;
          if (t < pp[mid]) {
            right = mid;
          } else {
            i1 = mid + 1;
          }
        }
        t1 = pp[i1];
        t0 = pp[i1 - 1];
        if (t0 === undefined) {
          this._cachedIndex = 0;
          return this.copySampleValue_(0);
        }
        if (t1 === undefined) {
          i1 = pp.length;
          this._cachedIndex = i1;
          return this.copySampleValue_(i1 - 1);
        }
      }
      this._cachedIndex = i1;
      this.intervalChanged_(i1, t0, t1);
    }
    return this.interpolate_(i1, t0, t, t1);
  }
  getSettings_() {
    return this.settings || this.DefaultSettings_;
  }
  copySampleValue_(index) {
    const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, offset = index * stride;
    for (let i = 0;i !== stride; ++i) {
      result[i] = values[offset + i];
    }
    return result;
  }
  interpolate_() {
    throw new Error("call to abstract method");
  }
  intervalChanged_() {}
}

class CubicInterpolant extends Interpolant {
  constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
    super(parameterPositions, sampleValues, sampleSize, resultBuffer);
    this._weightPrev = -0;
    this._offsetPrev = -0;
    this._weightNext = -0;
    this._offsetNext = -0;
    this.DefaultSettings_ = {
      endingStart: ZeroCurvatureEnding,
      endingEnd: ZeroCurvatureEnding
    };
  }
  intervalChanged_(i1, t0, t1) {
    const pp = this.parameterPositions;
    let iPrev = i1 - 2, iNext = i1 + 1, tPrev = pp[iPrev], tNext = pp[iNext];
    if (tPrev === undefined) {
      switch (this.getSettings_().endingStart) {
        case ZeroSlopeEnding:
          iPrev = i1;
          tPrev = 2 * t0 - t1;
          break;
        case WrapAroundEnding:
          iPrev = pp.length - 2;
          tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
          break;
        default:
          iPrev = i1;
          tPrev = t1;
      }
    }
    if (tNext === undefined) {
      switch (this.getSettings_().endingEnd) {
        case ZeroSlopeEnding:
          iNext = i1;
          tNext = 2 * t1 - t0;
          break;
        case WrapAroundEnding:
          iNext = 1;
          tNext = t1 + pp[1] - pp[0];
          break;
        default:
          iNext = i1 - 1;
          tNext = t0;
      }
    }
    const halfDt = (t1 - t0) * 0.5, stride = this.valueSize;
    this._weightPrev = halfDt / (t0 - tPrev);
    this._weightNext = halfDt / (tNext - t1);
    this._offsetPrev = iPrev * stride;
    this._offsetNext = iNext * stride;
  }
  interpolate_(i1, t0, t, t1) {
    const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, o1 = i1 * stride, o0 = o1 - stride, oP = this._offsetPrev, oN = this._offsetNext, wP = this._weightPrev, wN = this._weightNext, p = (t - t0) / (t1 - t0), pp = p * p, ppp = pp * p;
    const sP = -wP * ppp + 2 * wP * pp - wP * p;
    const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
    const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
    const sN = wN * ppp - wN * pp;
    for (let i = 0;i !== stride; ++i) {
      result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
    }
    return result;
  }
}

class LinearInterpolant extends Interpolant {
  constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
    super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  }
  interpolate_(i1, t0, t, t1) {
    const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, offset1 = i1 * stride, offset0 = offset1 - stride, weight1 = (t - t0) / (t1 - t0), weight0 = 1 - weight1;
    for (let i = 0;i !== stride; ++i) {
      result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
    }
    return result;
  }
}

class DiscreteInterpolant extends Interpolant {
  constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
    super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  }
  interpolate_(i1) {
    return this.copySampleValue_(i1 - 1);
  }
}

class KeyframeTrack {
  constructor(name, times, values, interpolation) {
    if (name === undefined)
      throw new Error("THREE.KeyframeTrack: track name is undefined");
    if (times === undefined || times.length === 0)
      throw new Error("THREE.KeyframeTrack: no keyframes in track named " + name);
    this.name = name;
    this.times = convertArray(times, this.TimeBufferType);
    this.values = convertArray(values, this.ValueBufferType);
    this.setInterpolation(interpolation || this.DefaultInterpolation);
  }
  static toJSON(track) {
    const trackType = track.constructor;
    let json;
    if (trackType.toJSON !== this.toJSON) {
      json = trackType.toJSON(track);
    } else {
      json = {
        name: track.name,
        times: convertArray(track.times, Array),
        values: convertArray(track.values, Array)
      };
      const interpolation = track.getInterpolation();
      if (interpolation !== track.DefaultInterpolation) {
        json.interpolation = interpolation;
      }
    }
    json.type = track.ValueTypeName;
    return json;
  }
  InterpolantFactoryMethodDiscrete(result) {
    return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  }
  InterpolantFactoryMethodLinear(result) {
    return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  }
  InterpolantFactoryMethodSmooth(result) {
    return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  }
  setInterpolation(interpolation) {
    let factoryMethod;
    switch (interpolation) {
      case InterpolateDiscrete:
        factoryMethod = this.InterpolantFactoryMethodDiscrete;
        break;
      case InterpolateLinear:
        factoryMethod = this.InterpolantFactoryMethodLinear;
        break;
      case InterpolateSmooth:
        factoryMethod = this.InterpolantFactoryMethodSmooth;
        break;
    }
    if (factoryMethod === undefined) {
      const message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
      if (this.createInterpolant === undefined) {
        if (interpolation !== this.DefaultInterpolation) {
          this.setInterpolation(this.DefaultInterpolation);
        } else {
          throw new Error(message);
        }
      }
      console.warn("THREE.KeyframeTrack:", message);
      return this;
    }
    this.createInterpolant = factoryMethod;
    return this;
  }
  getInterpolation() {
    switch (this.createInterpolant) {
      case this.InterpolantFactoryMethodDiscrete:
        return InterpolateDiscrete;
      case this.InterpolantFactoryMethodLinear:
        return InterpolateLinear;
      case this.InterpolantFactoryMethodSmooth:
        return InterpolateSmooth;
    }
  }
  getValueSize() {
    return this.values.length / this.times.length;
  }
  shift(timeOffset) {
    if (timeOffset !== 0) {
      const times = this.times;
      for (let i = 0, n = times.length;i !== n; ++i) {
        times[i] += timeOffset;
      }
    }
    return this;
  }
  scale(timeScale) {
    if (timeScale !== 1) {
      const times = this.times;
      for (let i = 0, n = times.length;i !== n; ++i) {
        times[i] *= timeScale;
      }
    }
    return this;
  }
  trim(startTime, endTime) {
    const times = this.times, nKeys = times.length;
    let from = 0, to = nKeys - 1;
    while (from !== nKeys && times[from] < startTime) {
      ++from;
    }
    while (to !== -1 && times[to] > endTime) {
      --to;
    }
    ++to;
    if (from !== 0 || to !== nKeys) {
      if (from >= to) {
        to = Math.max(to, 1);
        from = to - 1;
      }
      const stride = this.getValueSize();
      this.times = times.slice(from, to);
      this.values = this.values.slice(from * stride, to * stride);
    }
    return this;
  }
  validate() {
    let valid = true;
    const valueSize = this.getValueSize();
    if (valueSize - Math.floor(valueSize) !== 0) {
      console.error("THREE.KeyframeTrack: Invalid value size in track.", this);
      valid = false;
    }
    const times = this.times, values = this.values, nKeys = times.length;
    if (nKeys === 0) {
      console.error("THREE.KeyframeTrack: Track is empty.", this);
      valid = false;
    }
    let prevTime = null;
    for (let i = 0;i !== nKeys; i++) {
      const currTime = times[i];
      if (typeof currTime === "number" && isNaN(currTime)) {
        console.error("THREE.KeyframeTrack: Time is not a valid number.", this, i, currTime);
        valid = false;
        break;
      }
      if (prevTime !== null && prevTime > currTime) {
        console.error("THREE.KeyframeTrack: Out of order keys.", this, i, currTime, prevTime);
        valid = false;
        break;
      }
      prevTime = currTime;
    }
    if (values !== undefined) {
      if (isTypedArray(values)) {
        for (let i = 0, n = values.length;i !== n; ++i) {
          const value = values[i];
          if (isNaN(value)) {
            console.error("THREE.KeyframeTrack: Value is not a valid number.", this, i, value);
            valid = false;
            break;
          }
        }
      }
    }
    return valid;
  }
  optimize() {
    const times = this.times.slice(), values = this.values.slice(), stride = this.getValueSize(), smoothInterpolation = this.getInterpolation() === InterpolateSmooth, lastIndex = times.length - 1;
    let writeIndex = 1;
    for (let i = 1;i < lastIndex; ++i) {
      let keep = false;
      const time = times[i];
      const timeNext = times[i + 1];
      if (time !== timeNext && (i !== 1 || time !== times[0])) {
        if (!smoothInterpolation) {
          const offset = i * stride, offsetP = offset - stride, offsetN = offset + stride;
          for (let j = 0;j !== stride; ++j) {
            const value = values[offset + j];
            if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
              keep = true;
              break;
            }
          }
        } else {
          keep = true;
        }
      }
      if (keep) {
        if (i !== writeIndex) {
          times[writeIndex] = times[i];
          const readOffset = i * stride, writeOffset = writeIndex * stride;
          for (let j = 0;j !== stride; ++j) {
            values[writeOffset + j] = values[readOffset + j];
          }
        }
        ++writeIndex;
      }
    }
    if (lastIndex > 0) {
      times[writeIndex] = times[lastIndex];
      for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0;j !== stride; ++j) {
        values[writeOffset + j] = values[readOffset + j];
      }
      ++writeIndex;
    }
    if (writeIndex !== times.length) {
      this.times = times.slice(0, writeIndex);
      this.values = values.slice(0, writeIndex * stride);
    } else {
      this.times = times;
      this.values = values;
    }
    return this;
  }
  clone() {
    const times = this.times.slice();
    const values = this.values.slice();
    const TypedKeyframeTrack = this.constructor;
    const track = new TypedKeyframeTrack(this.name, times, values);
    track.createInterpolant = this.createInterpolant;
    return track;
  }
}
KeyframeTrack.prototype.ValueTypeName = "";
KeyframeTrack.prototype.TimeBufferType = Float32Array;
KeyframeTrack.prototype.ValueBufferType = Float32Array;
KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;

class BooleanKeyframeTrack extends KeyframeTrack {
  constructor(name, times, values) {
    super(name, times, values);
  }
}
BooleanKeyframeTrack.prototype.ValueTypeName = "bool";
BooleanKeyframeTrack.prototype.ValueBufferType = Array;
BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;

class ColorKeyframeTrack extends KeyframeTrack {
  constructor(name, times, values, interpolation) {
    super(name, times, values, interpolation);
  }
}
ColorKeyframeTrack.prototype.ValueTypeName = "color";

class NumberKeyframeTrack extends KeyframeTrack {
  constructor(name, times, values, interpolation) {
    super(name, times, values, interpolation);
  }
}
NumberKeyframeTrack.prototype.ValueTypeName = "number";

class QuaternionLinearInterpolant extends Interpolant {
  constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
    super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  }
  interpolate_(i1, t0, t, t1) {
    const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, alpha = (t - t0) / (t1 - t0);
    let offset = i1 * stride;
    for (let end = offset + stride;offset !== end; offset += 4) {
      Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
    }
    return result;
  }
}

class QuaternionKeyframeTrack extends KeyframeTrack {
  constructor(name, times, values, interpolation) {
    super(name, times, values, interpolation);
  }
  InterpolantFactoryMethodLinear(result) {
    return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  }
}
QuaternionKeyframeTrack.prototype.ValueTypeName = "quaternion";
QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;

class StringKeyframeTrack extends KeyframeTrack {
  constructor(name, times, values) {
    super(name, times, values);
  }
}
StringKeyframeTrack.prototype.ValueTypeName = "string";
StringKeyframeTrack.prototype.ValueBufferType = Array;
StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;

class VectorKeyframeTrack extends KeyframeTrack {
  constructor(name, times, values, interpolation) {
    super(name, times, values, interpolation);
  }
}
VectorKeyframeTrack.prototype.ValueTypeName = "vector";
class LoadingManager {
  constructor(onLoad, onProgress, onError) {
    const scope = this;
    let isLoading = false;
    let itemsLoaded = 0;
    let itemsTotal = 0;
    let urlModifier = undefined;
    const handlers = [];
    this.onStart = undefined;
    this.onLoad = onLoad;
    this.onProgress = onProgress;
    this.onError = onError;
    this.abortController = new AbortController;
    this.itemStart = function(url) {
      itemsTotal++;
      if (isLoading === false) {
        if (scope.onStart !== undefined) {
          scope.onStart(url, itemsLoaded, itemsTotal);
        }
      }
      isLoading = true;
    };
    this.itemEnd = function(url) {
      itemsLoaded++;
      if (scope.onProgress !== undefined) {
        scope.onProgress(url, itemsLoaded, itemsTotal);
      }
      if (itemsLoaded === itemsTotal) {
        isLoading = false;
        if (scope.onLoad !== undefined) {
          scope.onLoad();
        }
      }
    };
    this.itemError = function(url) {
      if (scope.onError !== undefined) {
        scope.onError(url);
      }
    };
    this.resolveURL = function(url) {
      if (urlModifier) {
        return urlModifier(url);
      }
      return url;
    };
    this.setURLModifier = function(transform) {
      urlModifier = transform;
      return this;
    };
    this.addHandler = function(regex, loader) {
      handlers.push(regex, loader);
      return this;
    };
    this.removeHandler = function(regex) {
      const index = handlers.indexOf(regex);
      if (index !== -1) {
        handlers.splice(index, 2);
      }
      return this;
    };
    this.getHandler = function(file) {
      for (let i = 0, l = handlers.length;i < l; i += 2) {
        const regex = handlers[i];
        const loader = handlers[i + 1];
        if (regex.global)
          regex.lastIndex = 0;
        if (regex.test(file)) {
          return loader;
        }
      }
      return null;
    };
    this.abort = function() {
      this.abortController.abort();
      this.abortController = new AbortController;
      return this;
    };
  }
}
var DefaultLoadingManager = /* @__PURE__ */ new LoadingManager;

class Loader {
  constructor(manager) {
    this.manager = manager !== undefined ? manager : DefaultLoadingManager;
    this.crossOrigin = "anonymous";
    this.withCredentials = false;
    this.path = "";
    this.resourcePath = "";
    this.requestHeader = {};
  }
  load() {}
  loadAsync(url, onProgress) {
    const scope = this;
    return new Promise(function(resolve, reject) {
      scope.load(url, resolve, onProgress, reject);
    });
  }
  parse() {}
  setCrossOrigin(crossOrigin) {
    this.crossOrigin = crossOrigin;
    return this;
  }
  setWithCredentials(value) {
    this.withCredentials = value;
    return this;
  }
  setPath(path3) {
    this.path = path3;
    return this;
  }
  setResourcePath(resourcePath) {
    this.resourcePath = resourcePath;
    return this;
  }
  setRequestHeader(requestHeader) {
    this.requestHeader = requestHeader;
    return this;
  }
  abort() {
    return this;
  }
}
Loader.DEFAULT_MATERIAL_NAME = "__DEFAULT";
var _loading = new WeakMap;
var _errorMap = new WeakMap;
var _RESERVED_CHARS_RE = "\\[\\]\\.:\\/";
var _reservedRe = new RegExp("[" + _RESERVED_CHARS_RE + "]", "g");
var _wordChar = "[^" + _RESERVED_CHARS_RE + "]";
var _wordCharOrDot = "[^" + _RESERVED_CHARS_RE.replace("\\.", "") + "]";
var _directoryRe = /* @__PURE__ */ /((?:WC+[\/:])*)/.source.replace("WC", _wordChar);
var _nodeRe = /* @__PURE__ */ /(WCOD+)?/.source.replace("WCOD", _wordCharOrDot);
var _objectRe = /* @__PURE__ */ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", _wordChar);
var _propertyRe = /* @__PURE__ */ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", _wordChar);
var _trackRe = new RegExp("" + "^" + _directoryRe + _nodeRe + _objectRe + _propertyRe + "$");
var _supportedObjectNames = ["material", "materials", "bones", "map"];

class Composite {
  constructor(targetGroup, path3, optionalParsedPath) {
    const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path3);
    this._targetGroup = targetGroup;
    this._bindings = targetGroup.subscribe_(path3, parsedPath);
  }
  getValue(array2, offset) {
    this.bind();
    const firstValidIndex = this._targetGroup.nCachedObjects_, binding = this._bindings[firstValidIndex];
    if (binding !== undefined)
      binding.getValue(array2, offset);
  }
  setValue(array2, offset) {
    const bindings = this._bindings;
    for (let i = this._targetGroup.nCachedObjects_, n = bindings.length;i !== n; ++i) {
      bindings[i].setValue(array2, offset);
    }
  }
  bind() {
    const bindings = this._bindings;
    for (let i = this._targetGroup.nCachedObjects_, n = bindings.length;i !== n; ++i) {
      bindings[i].bind();
    }
  }
  unbind() {
    const bindings = this._bindings;
    for (let i = this._targetGroup.nCachedObjects_, n = bindings.length;i !== n; ++i) {
      bindings[i].unbind();
    }
  }
}

class PropertyBinding {
  constructor(rootNode, path3, parsedPath) {
    this.path = path3;
    this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path3);
    this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName);
    this.rootNode = rootNode;
    this.getValue = this._getValue_unbound;
    this.setValue = this._setValue_unbound;
  }
  static create(root, path3, parsedPath) {
    if (!(root && root.isAnimationObjectGroup)) {
      return new PropertyBinding(root, path3, parsedPath);
    } else {
      return new PropertyBinding.Composite(root, path3, parsedPath);
    }
  }
  static sanitizeNodeName(name) {
    return name.replace(/\s/g, "_").replace(_reservedRe, "");
  }
  static parseTrackName(trackName) {
    const matches = _trackRe.exec(trackName);
    if (matches === null) {
      throw new Error("PropertyBinding: Cannot parse trackName: " + trackName);
    }
    const results = {
      nodeName: matches[2],
      objectName: matches[3],
      objectIndex: matches[4],
      propertyName: matches[5],
      propertyIndex: matches[6]
    };
    const lastDot = results.nodeName && results.nodeName.lastIndexOf(".");
    if (lastDot !== undefined && lastDot !== -1) {
      const objectName = results.nodeName.substring(lastDot + 1);
      if (_supportedObjectNames.indexOf(objectName) !== -1) {
        results.nodeName = results.nodeName.substring(0, lastDot);
        results.objectName = objectName;
      }
    }
    if (results.propertyName === null || results.propertyName.length === 0) {
      throw new Error("PropertyBinding: can not parse propertyName from trackName: " + trackName);
    }
    return results;
  }
  static findNode(root, nodeName) {
    if (nodeName === undefined || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
      return root;
    }
    if (root.skeleton) {
      const bone = root.skeleton.getBoneByName(nodeName);
      if (bone !== undefined) {
        return bone;
      }
    }
    if (root.children) {
      const searchNodeSubtree = function(children) {
        for (let i = 0;i < children.length; i++) {
          const childNode = children[i];
          if (childNode.name === nodeName || childNode.uuid === nodeName) {
            return childNode;
          }
          const result = searchNodeSubtree(childNode.children);
          if (result)
            return result;
        }
        return null;
      };
      const subTreeNode = searchNodeSubtree(root.children);
      if (subTreeNode) {
        return subTreeNode;
      }
    }
    return null;
  }
  _getValue_unavailable() {}
  _setValue_unavailable() {}
  _getValue_direct(buffer, offset) {
    buffer[offset] = this.targetObject[this.propertyName];
  }
  _getValue_array(buffer, offset) {
    const source = this.resolvedProperty;
    for (let i = 0, n = source.length;i !== n; ++i) {
      buffer[offset++] = source[i];
    }
  }
  _getValue_arrayElement(buffer, offset) {
    buffer[offset] = this.resolvedProperty[this.propertyIndex];
  }
  _getValue_toArray(buffer, offset) {
    this.resolvedProperty.toArray(buffer, offset);
  }
  _setValue_direct(buffer, offset) {
    this.targetObject[this.propertyName] = buffer[offset];
  }
  _setValue_direct_setNeedsUpdate(buffer, offset) {
    this.targetObject[this.propertyName] = buffer[offset];
    this.targetObject.needsUpdate = true;
  }
  _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
    this.targetObject[this.propertyName] = buffer[offset];
    this.targetObject.matrixWorldNeedsUpdate = true;
  }
  _setValue_array(buffer, offset) {
    const dest = this.resolvedProperty;
    for (let i = 0, n = dest.length;i !== n; ++i) {
      dest[i] = buffer[offset++];
    }
  }
  _setValue_array_setNeedsUpdate(buffer, offset) {
    const dest = this.resolvedProperty;
    for (let i = 0, n = dest.length;i !== n; ++i) {
      dest[i] = buffer[offset++];
    }
    this.targetObject.needsUpdate = true;
  }
  _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
    const dest = this.resolvedProperty;
    for (let i = 0, n = dest.length;i !== n; ++i) {
      dest[i] = buffer[offset++];
    }
    this.targetObject.matrixWorldNeedsUpdate = true;
  }
  _setValue_arrayElement(buffer, offset) {
    this.resolvedProperty[this.propertyIndex] = buffer[offset];
  }
  _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
    this.resolvedProperty[this.propertyIndex] = buffer[offset];
    this.targetObject.needsUpdate = true;
  }
  _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
    this.resolvedProperty[this.propertyIndex] = buffer[offset];
    this.targetObject.matrixWorldNeedsUpdate = true;
  }
  _setValue_fromArray(buffer, offset) {
    this.resolvedProperty.fromArray(buffer, offset);
  }
  _setValue_fromArray_setNeedsUpdate(buffer, offset) {
    this.resolvedProperty.fromArray(buffer, offset);
    this.targetObject.needsUpdate = true;
  }
  _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
    this.resolvedProperty.fromArray(buffer, offset);
    this.targetObject.matrixWorldNeedsUpdate = true;
  }
  _getValue_unbound(targetArray, offset) {
    this.bind();
    this.getValue(targetArray, offset);
  }
  _setValue_unbound(sourceArray, offset) {
    this.bind();
    this.setValue(sourceArray, offset);
  }
  bind() {
    let targetObject = this.node;
    const parsedPath = this.parsedPath;
    const objectName = parsedPath.objectName;
    const propertyName = parsedPath.propertyName;
    let propertyIndex = parsedPath.propertyIndex;
    if (!targetObject) {
      targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName);
      this.node = targetObject;
    }
    this.getValue = this._getValue_unavailable;
    this.setValue = this._setValue_unavailable;
    if (!targetObject) {
      console.warn("THREE.PropertyBinding: No target node found for track: " + this.path + ".");
      return;
    }
    if (objectName) {
      let objectIndex = parsedPath.objectIndex;
      switch (objectName) {
        case "materials":
          if (!targetObject.material) {
            console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this);
            return;
          }
          if (!targetObject.material.materials) {
            console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.", this);
            return;
          }
          targetObject = targetObject.material.materials;
          break;
        case "bones":
          if (!targetObject.skeleton) {
            console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.", this);
            return;
          }
          targetObject = targetObject.skeleton.bones;
          for (let i = 0;i < targetObject.length; i++) {
            if (targetObject[i].name === objectIndex) {
              objectIndex = i;
              break;
            }
          }
          break;
        case "map":
          if ("map" in targetObject) {
            targetObject = targetObject.map;
            break;
          }
          if (!targetObject.material) {
            console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this);
            return;
          }
          if (!targetObject.material.map) {
            console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.", this);
            return;
          }
          targetObject = targetObject.material.map;
          break;
        default:
          if (targetObject[objectName] === undefined) {
            console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.", this);
            return;
          }
          targetObject = targetObject[objectName];
      }
      if (objectIndex !== undefined) {
        if (targetObject[objectIndex] === undefined) {
          console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.", this, targetObject);
          return;
        }
        targetObject = targetObject[objectIndex];
      }
    }
    const nodeProperty = targetObject[propertyName];
    if (nodeProperty === undefined) {
      const nodeName = parsedPath.nodeName;
      console.error("THREE.PropertyBinding: Trying to update property for track: " + nodeName + "." + propertyName + " but it wasn't found.", targetObject);
      return;
    }
    let versioning = this.Versioning.None;
    this.targetObject = targetObject;
    if (targetObject.isMaterial === true) {
      versioning = this.Versioning.NeedsUpdate;
    } else if (targetObject.isObject3D === true) {
      versioning = this.Versioning.MatrixWorldNeedsUpdate;
    }
    let bindingType = this.BindingType.Direct;
    if (propertyIndex !== undefined) {
      if (propertyName === "morphTargetInfluences") {
        if (!targetObject.geometry) {
          console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.", this);
          return;
        }
        if (!targetObject.geometry.morphAttributes) {
          console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.", this);
          return;
        }
        if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
          propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
        }
      }
      bindingType = this.BindingType.ArrayElement;
      this.resolvedProperty = nodeProperty;
      this.propertyIndex = propertyIndex;
    } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
      bindingType = this.BindingType.HasFromToArray;
      this.resolvedProperty = nodeProperty;
    } else if (Array.isArray(nodeProperty)) {
      bindingType = this.BindingType.EntireArray;
      this.resolvedProperty = nodeProperty;
    } else {
      this.propertyName = propertyName;
    }
    this.getValue = this.GetterByBindingType[bindingType];
    this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  }
  unbind() {
    this.node = null;
    this.getValue = this._getValue_unbound;
    this.setValue = this._setValue_unbound;
  }
}
PropertyBinding.Composite = Composite;
PropertyBinding.prototype.BindingType = {
  Direct: 0,
  EntireArray: 1,
  ArrayElement: 2,
  HasFromToArray: 3
};
PropertyBinding.prototype.Versioning = {
  None: 0,
  NeedsUpdate: 1,
  MatrixWorldNeedsUpdate: 2
};
PropertyBinding.prototype.GetterByBindingType = [
  PropertyBinding.prototype._getValue_direct,
  PropertyBinding.prototype._getValue_array,
  PropertyBinding.prototype._getValue_arrayElement,
  PropertyBinding.prototype._getValue_toArray
];
PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  [
    PropertyBinding.prototype._setValue_direct,
    PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
    PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate
  ],
  [
    PropertyBinding.prototype._setValue_array,
    PropertyBinding.prototype._setValue_array_setNeedsUpdate,
    PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate
  ],
  [
    PropertyBinding.prototype._setValue_arrayElement,
    PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
    PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate
  ],
  [
    PropertyBinding.prototype._setValue_fromArray,
    PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
    PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate
  ]
];
var _controlInterpolantsResultBuffer = new Float32Array(1);
if (typeof __THREE_DEVTOOLS__ !== "undefined") {
  __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: {
    revision: REVISION
  } }));
}
if (typeof window !== "undefined") {
  if (window.__THREE__) {
    console.warn("WARNING: Multiple instances of Three.js being imported.");
  } else {
    window.__THREE__ = REVISION;
  }
}
// node_modules/three/build/three.module.js
var alphahash_fragment = `#ifdef USE_ALPHAHASH
	if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
#endif`;
var alphahash_pars_fragment = `#ifdef USE_ALPHAHASH
	const float ALPHA_HASH_SCALE = 0.05;
	float hash2D( vec2 value ) {
		return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
	}
	float hash3D( vec3 value ) {
		return hash2D( vec2( hash2D( value.xy ), value.z ) );
	}
	float getAlphaHashThreshold( vec3 position ) {
		float maxDeriv = max(
			length( dFdx( position.xyz ) ),
			length( dFdy( position.xyz ) )
		);
		float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
		vec2 pixScales = vec2(
			exp2( floor( log2( pixScale ) ) ),
			exp2( ceil( log2( pixScale ) ) )
		);
		vec2 alpha = vec2(
			hash3D( floor( pixScales.x * position.xyz ) ),
			hash3D( floor( pixScales.y * position.xyz ) )
		);
		float lerpFactor = fract( log2( pixScale ) );
		float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
		float a = min( lerpFactor, 1.0 - lerpFactor );
		vec3 cases = vec3(
			x * x / ( 2.0 * a * ( 1.0 - a ) ),
			( x - 0.5 * a ) / ( 1.0 - a ),
			1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
		);
		float threshold = ( x < ( 1.0 - a ) )
			? ( ( x < a ) ? cases.x : cases.y )
			: cases.z;
		return clamp( threshold , 1.0e-6, 1.0 );
	}
#endif`;
var alphamap_fragment = `#ifdef USE_ALPHAMAP
	diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
#endif`;
var alphamap_pars_fragment = `#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`;
var alphatest_fragment = `#ifdef USE_ALPHATEST
	#ifdef ALPHA_TO_COVERAGE
	diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
	if ( diffuseColor.a == 0.0 ) discard;
	#else
	if ( diffuseColor.a < alphaTest ) discard;
	#endif
#endif`;
var alphatest_pars_fragment = `#ifdef USE_ALPHATEST
	uniform float alphaTest;
#endif`;
var aomap_fragment = `#ifdef USE_AOMAP
	float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
	reflectedLight.indirectDiffuse *= ambientOcclusion;
	#if defined( USE_CLEARCOAT ) 
		clearcoatSpecularIndirect *= ambientOcclusion;
	#endif
	#if defined( USE_SHEEN ) 
		sheenSpecularIndirect *= ambientOcclusion;
	#endif
	#if defined( USE_ENVMAP ) && defined( STANDARD )
		float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
		reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
	#endif
#endif`;
var aomap_pars_fragment = `#ifdef USE_AOMAP
	uniform sampler2D aoMap;
	uniform float aoMapIntensity;
#endif`;
var batching_pars_vertex = `#ifdef USE_BATCHING
	#if ! defined( GL_ANGLE_multi_draw )
	#define gl_DrawID _gl_DrawID
	uniform int _gl_DrawID;
	#endif
	uniform highp sampler2D batchingTexture;
	uniform highp usampler2D batchingIdTexture;
	mat4 getBatchingMatrix( const in float i ) {
		int size = textureSize( batchingTexture, 0 ).x;
		int j = int( i ) * 4;
		int x = j % size;
		int y = j / size;
		vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
		vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
		vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
		vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
		return mat4( v1, v2, v3, v4 );
	}
	float getIndirectIndex( const in int i ) {
		int size = textureSize( batchingIdTexture, 0 ).x;
		int x = i % size;
		int y = i / size;
		return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );
	}
#endif
#ifdef USE_BATCHING_COLOR
	uniform sampler2D batchingColorTexture;
	vec3 getBatchingColor( const in float i ) {
		int size = textureSize( batchingColorTexture, 0 ).x;
		int j = int( i );
		int x = j % size;
		int y = j / size;
		return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;
	}
#endif`;
var batching_vertex = `#ifdef USE_BATCHING
	mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
#endif`;
var begin_vertex = `vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
	vPosition = vec3( position );
#endif`;
var beginnormal_vertex = `vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
	vec3 objectTangent = vec3( tangent.xyz );
#endif`;
var bsdfs = `float G_BlinnPhong_Implicit( ) {
	return 0.25;
}
float D_BlinnPhong( const in float shininess, const in float dotNH ) {
	return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
}
vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNH = saturate( dot( normal, halfDir ) );
	float dotVH = saturate( dot( viewDir, halfDir ) );
	vec3 F = F_Schlick( specularColor, 1.0, dotVH );
	float G = G_BlinnPhong_Implicit( );
	float D = D_BlinnPhong( shininess, dotNH );
	return F * ( G * D );
} // validated`;
var iridescence_fragment = `#ifdef USE_IRIDESCENCE
	const mat3 XYZ_TO_REC709 = mat3(
		 3.2404542, -0.9692660,  0.0556434,
		-1.5371385,  1.8760108, -0.2040259,
		-0.4985314,  0.0415560,  1.0572252
	);
	vec3 Fresnel0ToIor( vec3 fresnel0 ) {
		vec3 sqrtF0 = sqrt( fresnel0 );
		return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
	}
	vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
		return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
	}
	float IorToFresnel0( float transmittedIor, float incidentIor ) {
		return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
	}
	vec3 evalSensitivity( float OPD, vec3 shift ) {
		float phase = 2.0 * PI * OPD * 1.0e-9;
		vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
		vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
		vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
		vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
		xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );
		xyz /= 1.0685e-7;
		vec3 rgb = XYZ_TO_REC709 * xyz;
		return rgb;
	}
	vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
		vec3 I;
		float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
		float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
		float cosTheta2Sq = 1.0 - sinTheta2Sq;
		if ( cosTheta2Sq < 0.0 ) {
			return vec3( 1.0 );
		}
		float cosTheta2 = sqrt( cosTheta2Sq );
		float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
		float R12 = F_Schlick( R0, 1.0, cosTheta1 );
		float T121 = 1.0 - R12;
		float phi12 = 0.0;
		if ( iridescenceIOR < outsideIOR ) phi12 = PI;
		float phi21 = PI - phi12;
		vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );		vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
		vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
		vec3 phi23 = vec3( 0.0 );
		if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
		if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
		if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
		float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
		vec3 phi = vec3( phi21 ) + phi23;
		vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
		vec3 r123 = sqrt( R123 );
		vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
		vec3 C0 = R12 + Rs;
		I = C0;
		vec3 Cm = Rs - T121;
		for ( int m = 1; m <= 2; ++ m ) {
			Cm *= r123;
			vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
			I += Cm * Sm;
		}
		return max( I, vec3( 0.0 ) );
	}
#endif`;
var bumpmap_pars_fragment = `#ifdef USE_BUMPMAP
	uniform sampler2D bumpMap;
	uniform float bumpScale;
	vec2 dHdxy_fwd() {
		vec2 dSTdx = dFdx( vBumpMapUv );
		vec2 dSTdy = dFdy( vBumpMapUv );
		float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
		float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
		float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
		return vec2( dBx, dBy );
	}
	vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
		vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
		vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
		vec3 vN = surf_norm;
		vec3 R1 = cross( vSigmaY, vN );
		vec3 R2 = cross( vN, vSigmaX );
		float fDet = dot( vSigmaX, R1 ) * faceDirection;
		vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
		return normalize( abs( fDet ) * surf_norm - vGrad );
	}
#endif`;
var clipping_planes_fragment = `#if NUM_CLIPPING_PLANES > 0
	vec4 plane;
	#ifdef ALPHA_TO_COVERAGE
		float distanceToPlane, distanceGradient;
		float clipOpacity = 1.0;
		#pragma unroll_loop_start
		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
			plane = clippingPlanes[ i ];
			distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
			distanceGradient = fwidth( distanceToPlane ) / 2.0;
			clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
			if ( clipOpacity == 0.0 ) discard;
		}
		#pragma unroll_loop_end
		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
			float unionClipOpacity = 1.0;
			#pragma unroll_loop_start
			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
				plane = clippingPlanes[ i ];
				distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
				distanceGradient = fwidth( distanceToPlane ) / 2.0;
				unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
			}
			#pragma unroll_loop_end
			clipOpacity *= 1.0 - unionClipOpacity;
		#endif
		diffuseColor.a *= clipOpacity;
		if ( diffuseColor.a == 0.0 ) discard;
	#else
		#pragma unroll_loop_start
		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
			plane = clippingPlanes[ i ];
			if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
		}
		#pragma unroll_loop_end
		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
			bool clipped = true;
			#pragma unroll_loop_start
			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
				plane = clippingPlanes[ i ];
				clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
			}
			#pragma unroll_loop_end
			if ( clipped ) discard;
		#endif
	#endif
#endif`;
var clipping_planes_pars_fragment = `#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
	uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
#endif`;
var clipping_planes_pars_vertex = `#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
#endif`;
var clipping_planes_vertex = `#if NUM_CLIPPING_PLANES > 0
	vClipPosition = - mvPosition.xyz;
#endif`;
var color_fragment = `#if defined( USE_COLOR_ALPHA )
	diffuseColor *= vColor;
#elif defined( USE_COLOR )
	diffuseColor.rgb *= vColor;
#endif`;
var color_pars_fragment = `#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR )
	varying vec3 vColor;
#endif`;
var color_pars_vertex = `#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	varying vec3 vColor;
#endif`;
var color_vertex = `#if defined( USE_COLOR_ALPHA )
	vColor = vec4( 1.0 );
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	vColor = vec3( 1.0 );
#endif
#ifdef USE_COLOR
	vColor *= color;
#endif
#ifdef USE_INSTANCING_COLOR
	vColor.xyz *= instanceColor.xyz;
#endif
#ifdef USE_BATCHING_COLOR
	vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );
	vColor.xyz *= batchingColor.xyz;
#endif`;
var common = `#define PI 3.141592653589793
#define PI2 6.283185307179586
#define PI_HALF 1.5707963267948966
#define RECIPROCAL_PI 0.3183098861837907
#define RECIPROCAL_PI2 0.15915494309189535
#define EPSILON 1e-6
#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
#define whiteComplement( a ) ( 1.0 - saturate( a ) )
float pow2( const in float x ) { return x*x; }
vec3 pow2( const in vec3 x ) { return x*x; }
float pow3( const in float x ) { return x*x*x; }
float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
highp float rand( const in vec2 uv ) {
	const highp float a = 12.9898, b = 78.233, c = 43758.5453;
	highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
	return fract( sin( sn ) * c );
}
#ifdef HIGH_PRECISION
	float precisionSafeLength( vec3 v ) { return length( v ); }
#else
	float precisionSafeLength( vec3 v ) {
		float maxComponent = max3( abs( v ) );
		return length( v / maxComponent ) * maxComponent;
	}
#endif
struct IncidentLight {
	vec3 color;
	vec3 direction;
	bool visible;
};
struct ReflectedLight {
	vec3 directDiffuse;
	vec3 directSpecular;
	vec3 indirectDiffuse;
	vec3 indirectSpecular;
};
#ifdef USE_ALPHAHASH
	varying vec3 vPosition;
#endif
vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
}
vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
}
mat3 transposeMat3( const in mat3 m ) {
	mat3 tmp;
	tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );
	tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );
	tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );
	return tmp;
}
bool isPerspectiveMatrix( mat4 m ) {
	return m[ 2 ][ 3 ] == - 1.0;
}
vec2 equirectUv( in vec3 dir ) {
	float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
	float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
	return vec2( u, v );
}
vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
	return RECIPROCAL_PI * diffuseColor;
}
vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
}
float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
} // validated`;
var cube_uv_reflection_fragment = `#ifdef ENVMAP_TYPE_CUBE_UV
	#define cubeUV_minMipLevel 4.0
	#define cubeUV_minTileSize 16.0
	float getFace( vec3 direction ) {
		vec3 absDirection = abs( direction );
		float face = - 1.0;
		if ( absDirection.x > absDirection.z ) {
			if ( absDirection.x > absDirection.y )
				face = direction.x > 0.0 ? 0.0 : 3.0;
			else
				face = direction.y > 0.0 ? 1.0 : 4.0;
		} else {
			if ( absDirection.z > absDirection.y )
				face = direction.z > 0.0 ? 2.0 : 5.0;
			else
				face = direction.y > 0.0 ? 1.0 : 4.0;
		}
		return face;
	}
	vec2 getUV( vec3 direction, float face ) {
		vec2 uv;
		if ( face == 0.0 ) {
			uv = vec2( direction.z, direction.y ) / abs( direction.x );
		} else if ( face == 1.0 ) {
			uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
		} else if ( face == 2.0 ) {
			uv = vec2( - direction.x, direction.y ) / abs( direction.z );
		} else if ( face == 3.0 ) {
			uv = vec2( - direction.z, direction.y ) / abs( direction.x );
		} else if ( face == 4.0 ) {
			uv = vec2( - direction.x, direction.z ) / abs( direction.y );
		} else {
			uv = vec2( direction.x, direction.y ) / abs( direction.z );
		}
		return 0.5 * ( uv + 1.0 );
	}
	vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
		float face = getFace( direction );
		float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
		mipInt = max( mipInt, cubeUV_minMipLevel );
		float faceSize = exp2( mipInt );
		highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
		if ( face > 2.0 ) {
			uv.y += faceSize;
			face -= 3.0;
		}
		uv.x += face * faceSize;
		uv.x += filterInt * 3.0 * cubeUV_minTileSize;
		uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
		uv.x *= CUBEUV_TEXEL_WIDTH;
		uv.y *= CUBEUV_TEXEL_HEIGHT;
		#ifdef texture2DGradEXT
			return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
		#else
			return texture2D( envMap, uv ).rgb;
		#endif
	}
	#define cubeUV_r0 1.0
	#define cubeUV_m0 - 2.0
	#define cubeUV_r1 0.8
	#define cubeUV_m1 - 1.0
	#define cubeUV_r4 0.4
	#define cubeUV_m4 2.0
	#define cubeUV_r5 0.305
	#define cubeUV_m5 3.0
	#define cubeUV_r6 0.21
	#define cubeUV_m6 4.0
	float roughnessToMip( float roughness ) {
		float mip = 0.0;
		if ( roughness >= cubeUV_r1 ) {
			mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
		} else if ( roughness >= cubeUV_r4 ) {
			mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
		} else if ( roughness >= cubeUV_r5 ) {
			mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
		} else if ( roughness >= cubeUV_r6 ) {
			mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
		} else {
			mip = - 2.0 * log2( 1.16 * roughness );		}
		return mip;
	}
	vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
		float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
		float mipF = fract( mip );
		float mipInt = floor( mip );
		vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
		if ( mipF == 0.0 ) {
			return vec4( color0, 1.0 );
		} else {
			vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
			return vec4( mix( color0, color1, mipF ), 1.0 );
		}
	}
#endif`;
var defaultnormal_vertex = `vec3 transformedNormal = objectNormal;
#ifdef USE_TANGENT
	vec3 transformedTangent = objectTangent;
#endif
#ifdef USE_BATCHING
	mat3 bm = mat3( batchingMatrix );
	transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
	transformedNormal = bm * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = bm * transformedTangent;
	#endif
#endif
#ifdef USE_INSTANCING
	mat3 im = mat3( instanceMatrix );
	transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
	transformedNormal = im * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = im * transformedTangent;
	#endif
#endif
transformedNormal = normalMatrix * transformedNormal;
#ifdef FLIP_SIDED
	transformedNormal = - transformedNormal;
#endif
#ifdef USE_TANGENT
	transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
	#ifdef FLIP_SIDED
		transformedTangent = - transformedTangent;
	#endif
#endif`;
var displacementmap_pars_vertex = `#ifdef USE_DISPLACEMENTMAP
	uniform sampler2D displacementMap;
	uniform float displacementScale;
	uniform float displacementBias;
#endif`;
var displacementmap_vertex = `#ifdef USE_DISPLACEMENTMAP
	transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
#endif`;
var emissivemap_fragment = `#ifdef USE_EMISSIVEMAP
	vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
	#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
		emissiveColor = sRGBTransferEOTF( emissiveColor );
	#endif
	totalEmissiveRadiance *= emissiveColor.rgb;
#endif`;
var emissivemap_pars_fragment = `#ifdef USE_EMISSIVEMAP
	uniform sampler2D emissiveMap;
#endif`;
var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
var colorspace_pars_fragment = `vec4 LinearTransferOETF( in vec4 value ) {
	return value;
}
vec4 sRGBTransferEOTF( in vec4 value ) {
	return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
}
vec4 sRGBTransferOETF( in vec4 value ) {
	return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );
}`;
var envmap_fragment = `#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vec3 cameraToFrag;
		if ( isOrthographic ) {
			cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToFrag = normalize( vWorldPosition - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vec3 reflectVec = reflect( cameraToFrag, worldNormal );
		#else
			vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
		#endif
	#else
		vec3 reflectVec = vReflect;
	#endif
	#ifdef ENVMAP_TYPE_CUBE
		vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
	#else
		vec4 envColor = vec4( 0.0 );
	#endif
	#ifdef ENVMAP_BLENDING_MULTIPLY
		outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
	#elif defined( ENVMAP_BLENDING_MIX )
		outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
	#elif defined( ENVMAP_BLENDING_ADD )
		outgoingLight += envColor.xyz * specularStrength * reflectivity;
	#endif
#endif`;
var envmap_common_pars_fragment = `#ifdef USE_ENVMAP
	uniform float envMapIntensity;
	uniform float flipEnvMap;
	uniform mat3 envMapRotation;
	#ifdef ENVMAP_TYPE_CUBE
		uniform samplerCube envMap;
	#else
		uniform sampler2D envMap;
	#endif
	
#endif`;
var envmap_pars_fragment = `#ifdef USE_ENVMAP
	uniform float reflectivity;
	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
		#define ENV_WORLDPOS
	#endif
	#ifdef ENV_WORLDPOS
		varying vec3 vWorldPosition;
		uniform float refractionRatio;
	#else
		varying vec3 vReflect;
	#endif
#endif`;
var envmap_pars_vertex = `#ifdef USE_ENVMAP
	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
		#define ENV_WORLDPOS
	#endif
	#ifdef ENV_WORLDPOS
		
		varying vec3 vWorldPosition;
	#else
		varying vec3 vReflect;
		uniform float refractionRatio;
	#endif
#endif`;
var envmap_vertex = `#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vWorldPosition = worldPosition.xyz;
	#else
		vec3 cameraToVertex;
		if ( isOrthographic ) {
			cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vReflect = reflect( cameraToVertex, worldNormal );
		#else
			vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
		#endif
	#endif
#endif`;
var fog_vertex = `#ifdef USE_FOG
	vFogDepth = - mvPosition.z;
#endif`;
var fog_pars_vertex = `#ifdef USE_FOG
	varying float vFogDepth;
#endif`;
var fog_fragment = `#ifdef USE_FOG
	#ifdef FOG_EXP2
		float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
	#else
		float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
	#endif
	gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
#endif`;
var fog_pars_fragment = `#ifdef USE_FOG
	uniform vec3 fogColor;
	varying float vFogDepth;
	#ifdef FOG_EXP2
		uniform float fogDensity;
	#else
		uniform float fogNear;
		uniform float fogFar;
	#endif
#endif`;
var gradientmap_pars_fragment = `#ifdef USE_GRADIENTMAP
	uniform sampler2D gradientMap;
#endif
vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
	float dotNL = dot( normal, lightDirection );
	vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
	#ifdef USE_GRADIENTMAP
		return vec3( texture2D( gradientMap, coord ).r );
	#else
		vec2 fw = fwidth( coord ) * 0.5;
		return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
	#endif
}`;
var lightmap_pars_fragment = `#ifdef USE_LIGHTMAP
	uniform sampler2D lightMap;
	uniform float lightMapIntensity;
#endif`;
var lights_lambert_fragment = `LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularStrength = specularStrength;`;
var lights_lambert_pars_fragment = `varying vec3 vViewPosition;
struct LambertMaterial {
	vec3 diffuseColor;
	float specularStrength;
};
void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_Lambert
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Lambert`;
var lights_pars_begin = `uniform bool receiveShadow;
uniform vec3 ambientLightColor;
#if defined( USE_LIGHT_PROBES )
	uniform vec3 lightProbe[ 9 ];
#endif
vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
	float x = normal.x, y = normal.y, z = normal.z;
	vec3 result = shCoefficients[ 0 ] * 0.886227;
	result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
	result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
	result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
	result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
	result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
	result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
	result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
	result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
	return result;
}
vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
	vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
	vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
	return irradiance;
}
vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
	vec3 irradiance = ambientLightColor;
	return irradiance;
}
float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
	float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
	if ( cutoffDistance > 0.0 ) {
		distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
	}
	return distanceFalloff;
}
float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
	return smoothstep( coneCosine, penumbraCosine, angleCosine );
}
#if NUM_DIR_LIGHTS > 0
	struct DirectionalLight {
		vec3 direction;
		vec3 color;
	};
	uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
	void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
		light.color = directionalLight.color;
		light.direction = directionalLight.direction;
		light.visible = true;
	}
#endif
#if NUM_POINT_LIGHTS > 0
	struct PointLight {
		vec3 position;
		vec3 color;
		float distance;
		float decay;
	};
	uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
	void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = pointLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float lightDistance = length( lVector );
		light.color = pointLight.color;
		light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
		light.visible = ( light.color != vec3( 0.0 ) );
	}
#endif
#if NUM_SPOT_LIGHTS > 0
	struct SpotLight {
		vec3 position;
		vec3 direction;
		vec3 color;
		float distance;
		float decay;
		float coneCos;
		float penumbraCos;
	};
	uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
	void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = spotLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float angleCos = dot( light.direction, spotLight.direction );
		float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
		if ( spotAttenuation > 0.0 ) {
			float lightDistance = length( lVector );
			light.color = spotLight.color * spotAttenuation;
			light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
			light.visible = ( light.color != vec3( 0.0 ) );
		} else {
			light.color = vec3( 0.0 );
			light.visible = false;
		}
	}
#endif
#if NUM_RECT_AREA_LIGHTS > 0
	struct RectAreaLight {
		vec3 color;
		vec3 position;
		vec3 halfWidth;
		vec3 halfHeight;
	};
	uniform sampler2D ltc_1;	uniform sampler2D ltc_2;
	uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
#endif
#if NUM_HEMI_LIGHTS > 0
	struct HemisphereLight {
		vec3 direction;
		vec3 skyColor;
		vec3 groundColor;
	};
	uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
	vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
		float dotNL = dot( normal, hemiLight.direction );
		float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
		vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
		return irradiance;
	}
#endif`;
var envmap_physical_pars_fragment = `#ifdef USE_ENVMAP
	vec3 getIBLIrradiance( const in vec3 normal ) {
		#ifdef ENVMAP_TYPE_CUBE_UV
			vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );
			return PI * envMapColor.rgb * envMapIntensity;
		#else
			return vec3( 0.0 );
		#endif
	}
	vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
		#ifdef ENVMAP_TYPE_CUBE_UV
			vec3 reflectVec = reflect( - viewDir, normal );
			reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );
			reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
			return envMapColor.rgb * envMapIntensity;
		#else
			return vec3( 0.0 );
		#endif
	}
	#ifdef USE_ANISOTROPY
		vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
			#ifdef ENVMAP_TYPE_CUBE_UV
				vec3 bentNormal = cross( bitangent, viewDir );
				bentNormal = normalize( cross( bentNormal, bitangent ) );
				bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
				return getIBLRadiance( viewDir, bentNormal, roughness );
			#else
				return vec3( 0.0 );
			#endif
		}
	#endif
#endif`;
var lights_toon_fragment = `ToonMaterial material;
material.diffuseColor = diffuseColor.rgb;`;
var lights_toon_pars_fragment = `varying vec3 vViewPosition;
struct ToonMaterial {
	vec3 diffuseColor;
};
void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
	vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_Toon
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Toon`;
var lights_phong_fragment = `BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
material.specularStrength = specularStrength;`;
var lights_phong_pars_fragment = `varying vec3 vViewPosition;
struct BlinnPhongMaterial {
	vec3 diffuseColor;
	vec3 specularColor;
	float specularShininess;
	float specularStrength;
};
void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
	reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
}
void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_BlinnPhong
#define RE_IndirectDiffuse		RE_IndirectDiffuse_BlinnPhong`;
var lights_physical_fragment = `PhysicalMaterial material;
material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
material.roughness = min( material.roughness, 1.0 );
#ifdef IOR
	material.ior = ior;
	#ifdef USE_SPECULAR
		float specularIntensityFactor = specularIntensity;
		vec3 specularColorFactor = specularColor;
		#ifdef USE_SPECULAR_COLORMAP
			specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
		#endif
		#ifdef USE_SPECULAR_INTENSITYMAP
			specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
		#endif
		material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
	#else
		float specularIntensityFactor = 1.0;
		vec3 specularColorFactor = vec3( 1.0 );
		material.specularF90 = 1.0;
	#endif
	material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
#else
	material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
	material.specularF90 = 1.0;
#endif
#ifdef USE_CLEARCOAT
	material.clearcoat = clearcoat;
	material.clearcoatRoughness = clearcoatRoughness;
	material.clearcoatF0 = vec3( 0.04 );
	material.clearcoatF90 = 1.0;
	#ifdef USE_CLEARCOATMAP
		material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
	#endif
	#ifdef USE_CLEARCOAT_ROUGHNESSMAP
		material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
	#endif
	material.clearcoat = saturate( material.clearcoat );	material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
	material.clearcoatRoughness += geometryRoughness;
	material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
#endif
#ifdef USE_DISPERSION
	material.dispersion = dispersion;
#endif
#ifdef USE_IRIDESCENCE
	material.iridescence = iridescence;
	material.iridescenceIOR = iridescenceIOR;
	#ifdef USE_IRIDESCENCEMAP
		material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
	#endif
	#ifdef USE_IRIDESCENCE_THICKNESSMAP
		material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
	#else
		material.iridescenceThickness = iridescenceThicknessMaximum;
	#endif
#endif
#ifdef USE_SHEEN
	material.sheenColor = sheenColor;
	#ifdef USE_SHEEN_COLORMAP
		material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
	#endif
	material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );
	#ifdef USE_SHEEN_ROUGHNESSMAP
		material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
	#endif
#endif
#ifdef USE_ANISOTROPY
	#ifdef USE_ANISOTROPYMAP
		mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
		vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
		vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
	#else
		vec2 anisotropyV = anisotropyVector;
	#endif
	material.anisotropy = length( anisotropyV );
	if( material.anisotropy == 0.0 ) {
		anisotropyV = vec2( 1.0, 0.0 );
	} else {
		anisotropyV /= material.anisotropy;
		material.anisotropy = saturate( material.anisotropy );
	}
	material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
	material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
	material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
#endif`;
var lights_physical_pars_fragment = `struct PhysicalMaterial {
	vec3 diffuseColor;
	float roughness;
	vec3 specularColor;
	float specularF90;
	float dispersion;
	#ifdef USE_CLEARCOAT
		float clearcoat;
		float clearcoatRoughness;
		vec3 clearcoatF0;
		float clearcoatF90;
	#endif
	#ifdef USE_IRIDESCENCE
		float iridescence;
		float iridescenceIOR;
		float iridescenceThickness;
		vec3 iridescenceFresnel;
		vec3 iridescenceF0;
	#endif
	#ifdef USE_SHEEN
		vec3 sheenColor;
		float sheenRoughness;
	#endif
	#ifdef IOR
		float ior;
	#endif
	#ifdef USE_TRANSMISSION
		float transmission;
		float transmissionAlpha;
		float thickness;
		float attenuationDistance;
		vec3 attenuationColor;
	#endif
	#ifdef USE_ANISOTROPY
		float anisotropy;
		float alphaT;
		vec3 anisotropyT;
		vec3 anisotropyB;
	#endif
};
vec3 clearcoatSpecularDirect = vec3( 0.0 );
vec3 clearcoatSpecularIndirect = vec3( 0.0 );
vec3 sheenSpecularDirect = vec3( 0.0 );
vec3 sheenSpecularIndirect = vec3(0.0 );
vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
    float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
    float x2 = x * x;
    float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
    return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
}
float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
	float a2 = pow2( alpha );
	float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
	float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
	return 0.5 / max( gv + gl, EPSILON );
}
float D_GGX( const in float alpha, const in float dotNH ) {
	float a2 = pow2( alpha );
	float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
	return RECIPROCAL_PI * a2 / pow2( denom );
}
#ifdef USE_ANISOTROPY
	float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {
		float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
		float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
		float v = 0.5 / ( gv + gl );
		return saturate(v);
	}
	float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
		float a2 = alphaT * alphaB;
		highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
		highp float v2 = dot( v, v );
		float w2 = a2 / v2;
		return RECIPROCAL_PI * a2 * pow2 ( w2 );
	}
#endif
#ifdef USE_CLEARCOAT
	vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
		vec3 f0 = material.clearcoatF0;
		float f90 = material.clearcoatF90;
		float roughness = material.clearcoatRoughness;
		float alpha = pow2( roughness );
		vec3 halfDir = normalize( lightDir + viewDir );
		float dotNL = saturate( dot( normal, lightDir ) );
		float dotNV = saturate( dot( normal, viewDir ) );
		float dotNH = saturate( dot( normal, halfDir ) );
		float dotVH = saturate( dot( viewDir, halfDir ) );
		vec3 F = F_Schlick( f0, f90, dotVH );
		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
		float D = D_GGX( alpha, dotNH );
		return F * ( V * D );
	}
#endif
vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
	vec3 f0 = material.specularColor;
	float f90 = material.specularF90;
	float roughness = material.roughness;
	float alpha = pow2( roughness );
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNL = saturate( dot( normal, lightDir ) );
	float dotNV = saturate( dot( normal, viewDir ) );
	float dotNH = saturate( dot( normal, halfDir ) );
	float dotVH = saturate( dot( viewDir, halfDir ) );
	vec3 F = F_Schlick( f0, f90, dotVH );
	#ifdef USE_IRIDESCENCE
		F = mix( F, material.iridescenceFresnel, material.iridescence );
	#endif
	#ifdef USE_ANISOTROPY
		float dotTL = dot( material.anisotropyT, lightDir );
		float dotTV = dot( material.anisotropyT, viewDir );
		float dotTH = dot( material.anisotropyT, halfDir );
		float dotBL = dot( material.anisotropyB, lightDir );
		float dotBV = dot( material.anisotropyB, viewDir );
		float dotBH = dot( material.anisotropyB, halfDir );
		float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
		float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
	#else
		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
		float D = D_GGX( alpha, dotNH );
	#endif
	return F * ( V * D );
}
vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
	const float LUT_SIZE = 64.0;
	const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
	const float LUT_BIAS = 0.5 / LUT_SIZE;
	float dotNV = saturate( dot( N, V ) );
	vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
	uv = uv * LUT_SCALE + LUT_BIAS;
	return uv;
}
float LTC_ClippedSphereFormFactor( const in vec3 f ) {
	float l = length( f );
	return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
}
vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
	float x = dot( v1, v2 );
	float y = abs( x );
	float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
	float b = 3.4175940 + ( 4.1616724 + y ) * y;
	float v = a / b;
	float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
	return cross( v1, v2 ) * theta_sintheta;
}
vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
	vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
	vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
	vec3 lightNormal = cross( v1, v2 );
	if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
	vec3 T1, T2;
	T1 = normalize( V - N * dot( V, N ) );
	T2 = - cross( N, T1 );
	mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );
	vec3 coords[ 4 ];
	coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
	coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
	coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
	coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
	coords[ 0 ] = normalize( coords[ 0 ] );
	coords[ 1 ] = normalize( coords[ 1 ] );
	coords[ 2 ] = normalize( coords[ 2 ] );
	coords[ 3 ] = normalize( coords[ 3 ] );
	vec3 vectorFormFactor = vec3( 0.0 );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
	float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
	return vec3( result );
}
#if defined( USE_SHEEN )
float D_Charlie( float roughness, float dotNH ) {
	float alpha = pow2( roughness );
	float invAlpha = 1.0 / alpha;
	float cos2h = dotNH * dotNH;
	float sin2h = max( 1.0 - cos2h, 0.0078125 );
	return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
}
float V_Neubelt( float dotNV, float dotNL ) {
	return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
}
vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNL = saturate( dot( normal, lightDir ) );
	float dotNV = saturate( dot( normal, viewDir ) );
	float dotNH = saturate( dot( normal, halfDir ) );
	float D = D_Charlie( sheenRoughness, dotNH );
	float V = V_Neubelt( dotNV, dotNL );
	return sheenColor * ( D * V );
}
#endif
float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	float r2 = roughness * roughness;
	float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
	float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
	float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
	return saturate( DG * RECIPROCAL_PI );
}
vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
	const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
	vec4 r = roughness * c0 + c1;
	float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;
	vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;
	return fab;
}
vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	return specularColor * fab.x + specularF90 * fab.y;
}
#ifdef USE_IRIDESCENCE
void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#else
void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#endif
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	#ifdef USE_IRIDESCENCE
		vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
	#else
		vec3 Fr = specularColor;
	#endif
	vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
	float Ess = fab.x + fab.y;
	float Ems = 1.0 - Ess;
	vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;	vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
	singleScatter += FssEss;
	multiScatter += Fms * Ems;
}
#if NUM_RECT_AREA_LIGHTS > 0
	void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
		vec3 normal = geometryNormal;
		vec3 viewDir = geometryViewDir;
		vec3 position = geometryPosition;
		vec3 lightPos = rectAreaLight.position;
		vec3 halfWidth = rectAreaLight.halfWidth;
		vec3 halfHeight = rectAreaLight.halfHeight;
		vec3 lightColor = rectAreaLight.color;
		float roughness = material.roughness;
		vec3 rectCoords[ 4 ];
		rectCoords[ 0 ] = lightPos + halfWidth - halfHeight;		rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
		rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
		rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
		vec2 uv = LTC_Uv( normal, viewDir, roughness );
		vec4 t1 = texture2D( ltc_1, uv );
		vec4 t2 = texture2D( ltc_2, uv );
		mat3 mInv = mat3(
			vec3( t1.x, 0, t1.y ),
			vec3(    0, 1,    0 ),
			vec3( t1.z, 0, t1.w )
		);
		vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
		reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
		reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
	}
#endif
void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	#ifdef USE_CLEARCOAT
		float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
		vec3 ccIrradiance = dotNLcc * directLight.color;
		clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
	#endif
	#ifdef USE_SHEEN
		sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
	#endif
	reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {
	#ifdef USE_CLEARCOAT
		clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
	#endif
	#ifdef USE_SHEEN
		sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
	#endif
	vec3 singleScattering = vec3( 0.0 );
	vec3 multiScattering = vec3( 0.0 );
	vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
	#ifdef USE_IRIDESCENCE
		computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
	#else
		computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
	#endif
	vec3 totalScattering = singleScattering + multiScattering;
	vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
	reflectedLight.indirectSpecular += radiance * singleScattering;
	reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
	reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
}
#define RE_Direct				RE_Direct_Physical
#define RE_Direct_RectArea		RE_Direct_RectArea_Physical
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Physical
#define RE_IndirectSpecular		RE_IndirectSpecular_Physical
float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
	return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
}`;
var lights_fragment_begin = `
vec3 geometryPosition = - vViewPosition;
vec3 geometryNormal = normal;
vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
vec3 geometryClearcoatNormal = vec3( 0.0 );
#ifdef USE_CLEARCOAT
	geometryClearcoatNormal = clearcoatNormal;
#endif
#ifdef USE_IRIDESCENCE
	float dotNVi = saturate( dot( normal, geometryViewDir ) );
	if ( material.iridescenceThickness == 0.0 ) {
		material.iridescence = 0.0;
	} else {
		material.iridescence = saturate( material.iridescence );
	}
	if ( material.iridescence > 0.0 ) {
		material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
		material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
	}
#endif
IncidentLight directLight;
#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
	PointLight pointLight;
	#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
		pointLight = pointLights[ i ];
		getPointLightInfo( pointLight, geometryPosition, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
		pointLightShadow = pointLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
	SpotLight spotLight;
	vec4 spotColor;
	vec3 spotLightCoord;
	bool inSpotLightMap;
	#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
		spotLight = spotLights[ i ];
		getSpotLightInfo( spotLight, geometryPosition, directLight );
		#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
		#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
		#else
		#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#endif
		#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
			spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
			inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
			spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
			directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
		#endif
		#undef SPOT_LIGHT_MAP_INDEX
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		spotLightShadow = spotLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
	DirectionalLight directionalLight;
	#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
		directionalLight = directionalLights[ i ];
		getDirectionalLightInfo( directionalLight, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
		directionalLightShadow = directionalLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
	RectAreaLight rectAreaLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
		rectAreaLight = rectAreaLights[ i ];
		RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if defined( RE_IndirectDiffuse )
	vec3 iblIrradiance = vec3( 0.0 );
	vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
	#if defined( USE_LIGHT_PROBES )
		irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
	#endif
	#if ( NUM_HEMI_LIGHTS > 0 )
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
			irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
		}
		#pragma unroll_loop_end
	#endif
#endif
#if defined( RE_IndirectSpecular )
	vec3 radiance = vec3( 0.0 );
	vec3 clearcoatRadiance = vec3( 0.0 );
#endif`;
var lights_fragment_maps = `#if defined( RE_IndirectDiffuse )
	#ifdef USE_LIGHTMAP
		vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
		vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
		irradiance += lightMapIrradiance;
	#endif
	#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
		iblIrradiance += getIBLIrradiance( geometryNormal );
	#endif
#endif
#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
	#ifdef USE_ANISOTROPY
		radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
	#else
		radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
	#endif
	#ifdef USE_CLEARCOAT
		clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
	#endif
#endif`;
var lights_fragment_end = `#if defined( RE_IndirectDiffuse )
	RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif
#if defined( RE_IndirectSpecular )
	RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif`;
var logdepthbuf_fragment = `#if defined( USE_LOGDEPTHBUF )
	gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
#endif`;
var logdepthbuf_pars_fragment = `#if defined( USE_LOGDEPTHBUF )
	uniform float logDepthBufFC;
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`;
var logdepthbuf_pars_vertex = `#ifdef USE_LOGDEPTHBUF
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`;
var logdepthbuf_vertex = `#ifdef USE_LOGDEPTHBUF
	vFragDepth = 1.0 + gl_Position.w;
	vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
#endif`;
var map_fragment = `#ifdef USE_MAP
	vec4 sampledDiffuseColor = texture2D( map, vMapUv );
	#ifdef DECODE_VIDEO_TEXTURE
		sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
	#endif
	diffuseColor *= sampledDiffuseColor;
#endif`;
var map_pars_fragment = `#ifdef USE_MAP
	uniform sampler2D map;
#endif`;
var map_particle_fragment = `#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
	#if defined( USE_POINTS_UV )
		vec2 uv = vUv;
	#else
		vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
	#endif
#endif
#ifdef USE_MAP
	diffuseColor *= texture2D( map, uv );
#endif
#ifdef USE_ALPHAMAP
	diffuseColor.a *= texture2D( alphaMap, uv ).g;
#endif`;
var map_particle_pars_fragment = `#if defined( USE_POINTS_UV )
	varying vec2 vUv;
#else
	#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
		uniform mat3 uvTransform;
	#endif
#endif
#ifdef USE_MAP
	uniform sampler2D map;
#endif
#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`;
var metalnessmap_fragment = `float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
	vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
	metalnessFactor *= texelMetalness.b;
#endif`;
var metalnessmap_pars_fragment = `#ifdef USE_METALNESSMAP
	uniform sampler2D metalnessMap;
#endif`;
var morphinstance_vertex = `#ifdef USE_INSTANCING_MORPH
	float morphTargetInfluences[ MORPHTARGETS_COUNT ];
	float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		morphTargetInfluences[i] =  texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
	}
#endif`;
var morphcolor_vertex = `#if defined( USE_MORPHCOLORS )
	vColor *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		#if defined( USE_COLOR_ALPHA )
			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
		#elif defined( USE_COLOR )
			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
		#endif
	}
#endif`;
var morphnormal_vertex = `#ifdef USE_MORPHNORMALS
	objectNormal *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
	}
#endif`;
var morphtarget_pars_vertex = `#ifdef USE_MORPHTARGETS
	#ifndef USE_INSTANCING_MORPH
		uniform float morphTargetBaseInfluence;
		uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
	#endif
	uniform sampler2DArray morphTargetsTexture;
	uniform ivec2 morphTargetsTextureSize;
	vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
		int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
		int y = texelIndex / morphTargetsTextureSize.x;
		int x = texelIndex - y * morphTargetsTextureSize.x;
		ivec3 morphUV = ivec3( x, y, morphTargetIndex );
		return texelFetch( morphTargetsTexture, morphUV, 0 );
	}
#endif`;
var morphtarget_vertex = `#ifdef USE_MORPHTARGETS
	transformed *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
	}
#endif`;
var normal_fragment_begin = `float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
#ifdef FLAT_SHADED
	vec3 fdx = dFdx( vViewPosition );
	vec3 fdy = dFdy( vViewPosition );
	vec3 normal = normalize( cross( fdx, fdy ) );
#else
	vec3 normal = normalize( vNormal );
	#ifdef DOUBLE_SIDED
		normal *= faceDirection;
	#endif
#endif
#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
	#ifdef USE_TANGENT
		mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn = getTangentFrame( - vViewPosition, normal,
		#if defined( USE_NORMALMAP )
			vNormalMapUv
		#elif defined( USE_CLEARCOAT_NORMALMAP )
			vClearcoatNormalMapUv
		#else
			vUv
		#endif
		);
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn[0] *= faceDirection;
		tbn[1] *= faceDirection;
	#endif
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	#ifdef USE_TANGENT
		mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn2[0] *= faceDirection;
		tbn2[1] *= faceDirection;
	#endif
#endif
vec3 nonPerturbedNormal = normal;`;
var normal_fragment_maps = `#ifdef USE_NORMALMAP_OBJECTSPACE
	normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
	#ifdef FLIP_SIDED
		normal = - normal;
	#endif
	#ifdef DOUBLE_SIDED
		normal = normal * faceDirection;
	#endif
	normal = normalize( normalMatrix * normal );
#elif defined( USE_NORMALMAP_TANGENTSPACE )
	vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
	mapN.xy *= normalScale;
	normal = normalize( tbn * mapN );
#elif defined( USE_BUMPMAP )
	normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
#endif`;
var normal_pars_fragment = `#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`;
var normal_pars_vertex = `#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`;
var normal_vertex = `#ifndef FLAT_SHADED
	vNormal = normalize( transformedNormal );
	#ifdef USE_TANGENT
		vTangent = normalize( transformedTangent );
		vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
	#endif
#endif`;
var normalmap_pars_fragment = `#ifdef USE_NORMALMAP
	uniform sampler2D normalMap;
	uniform vec2 normalScale;
#endif
#ifdef USE_NORMALMAP_OBJECTSPACE
	uniform mat3 normalMatrix;
#endif
#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
	mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
		vec3 q0 = dFdx( eye_pos.xyz );
		vec3 q1 = dFdy( eye_pos.xyz );
		vec2 st0 = dFdx( uv.st );
		vec2 st1 = dFdy( uv.st );
		vec3 N = surf_norm;
		vec3 q1perp = cross( q1, N );
		vec3 q0perp = cross( N, q0 );
		vec3 T = q1perp * st0.x + q0perp * st1.x;
		vec3 B = q1perp * st0.y + q0perp * st1.y;
		float det = max( dot( T, T ), dot( B, B ) );
		float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
		return mat3( T * scale, B * scale, N );
	}
#endif`;
var clearcoat_normal_fragment_begin = `#ifdef USE_CLEARCOAT
	vec3 clearcoatNormal = nonPerturbedNormal;
#endif`;
var clearcoat_normal_fragment_maps = `#ifdef USE_CLEARCOAT_NORMALMAP
	vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
	clearcoatMapN.xy *= clearcoatNormalScale;
	clearcoatNormal = normalize( tbn2 * clearcoatMapN );
#endif`;
var clearcoat_pars_fragment = `#ifdef USE_CLEARCOATMAP
	uniform sampler2D clearcoatMap;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	uniform sampler2D clearcoatNormalMap;
	uniform vec2 clearcoatNormalScale;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	uniform sampler2D clearcoatRoughnessMap;
#endif`;
var iridescence_pars_fragment = `#ifdef USE_IRIDESCENCEMAP
	uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform sampler2D iridescenceThicknessMap;
#endif`;
var opaque_fragment = `#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
#endif
gl_FragColor = vec4( outgoingLight, diffuseColor.a );`;
var packing = `vec3 packNormalToRGB( const in vec3 normal ) {
	return normalize( normal ) * 0.5 + 0.5;
}
vec3 unpackRGBToNormal( const in vec3 rgb ) {
	return 2.0 * rgb.xyz - 1.0;
}
const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;
const float Inv255 = 1. / 255.;
const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );
const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );
const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );
const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );
vec4 packDepthToRGBA( const in float v ) {
	if( v <= 0.0 )
		return vec4( 0., 0., 0., 0. );
	if( v >= 1.0 )
		return vec4( 1., 1., 1., 1. );
	float vuf;
	float af = modf( v * PackFactors.a, vuf );
	float bf = modf( vuf * ShiftRight8, vuf );
	float gf = modf( vuf * ShiftRight8, vuf );
	return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );
}
vec3 packDepthToRGB( const in float v ) {
	if( v <= 0.0 )
		return vec3( 0., 0., 0. );
	if( v >= 1.0 )
		return vec3( 1., 1., 1. );
	float vuf;
	float bf = modf( v * PackFactors.b, vuf );
	float gf = modf( vuf * ShiftRight8, vuf );
	return vec3( vuf * Inv255, gf * PackUpscale, bf );
}
vec2 packDepthToRG( const in float v ) {
	if( v <= 0.0 )
		return vec2( 0., 0. );
	if( v >= 1.0 )
		return vec2( 1., 1. );
	float vuf;
	float gf = modf( v * 256., vuf );
	return vec2( vuf * Inv255, gf );
}
float unpackRGBAToDepth( const in vec4 v ) {
	return dot( v, UnpackFactors4 );
}
float unpackRGBToDepth( const in vec3 v ) {
	return dot( v, UnpackFactors3 );
}
float unpackRGToDepth( const in vec2 v ) {
	return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;
}
vec4 pack2HalfToRGBA( const in vec2 v ) {
	vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
	return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
}
vec2 unpackRGBATo2Half( const in vec4 v ) {
	return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
}
float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
	return ( viewZ + near ) / ( near - far );
}
float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
	return depth * ( near - far ) - near;
}
float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
	return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
}
float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
	return ( near * far ) / ( ( far - near ) * depth - far );
}`;
var premultiplied_alpha_fragment = `#ifdef PREMULTIPLIED_ALPHA
	gl_FragColor.rgb *= gl_FragColor.a;
#endif`;
var project_vertex = `vec4 mvPosition = vec4( transformed, 1.0 );
#ifdef USE_BATCHING
	mvPosition = batchingMatrix * mvPosition;
#endif
#ifdef USE_INSTANCING
	mvPosition = instanceMatrix * mvPosition;
#endif
mvPosition = modelViewMatrix * mvPosition;
gl_Position = projectionMatrix * mvPosition;`;
var dithering_fragment = `#ifdef DITHERING
	gl_FragColor.rgb = dithering( gl_FragColor.rgb );
#endif`;
var dithering_pars_fragment = `#ifdef DITHERING
	vec3 dithering( vec3 color ) {
		float grid_position = rand( gl_FragCoord.xy );
		vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
		dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
		return color + dither_shift_RGB;
	}
#endif`;
var roughnessmap_fragment = `float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
	vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
	roughnessFactor *= texelRoughness.g;
#endif`;
var roughnessmap_pars_fragment = `#ifdef USE_ROUGHNESSMAP
	uniform sampler2D roughnessMap;
#endif`;
var shadowmap_pars_fragment = `#if NUM_SPOT_LIGHT_COORDS > 0
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#if NUM_SPOT_LIGHT_MAPS > 0
	uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
		struct DirectionalLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
		uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
		struct SpotLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
		struct PointLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
			float shadowCameraNear;
			float shadowCameraFar;
		};
		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
	#endif
	float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
		float depth = unpackRGBAToDepth( texture2D( depths, uv ) );
		#ifdef USE_REVERSEDEPTHBUF
			return step( depth, compare );
		#else
			return step( compare, depth );
		#endif
	}
	vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
		return unpackRGBATo2Half( texture2D( shadow, uv ) );
	}
	float VSMShadow (sampler2D shadow, vec2 uv, float compare ){
		float occlusion = 1.0;
		vec2 distribution = texture2DDistribution( shadow, uv );
		#ifdef USE_REVERSEDEPTHBUF
			float hard_shadow = step( distribution.x, compare );
		#else
			float hard_shadow = step( compare , distribution.x );
		#endif
		if (hard_shadow != 1.0 ) {
			float distance = compare - distribution.x ;
			float variance = max( 0.00000, distribution.y * distribution.y );
			float softness_probability = variance / (variance + distance * distance );			softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );			occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );
		}
		return occlusion;
	}
	float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
		float shadow = 1.0;
		shadowCoord.xyz /= shadowCoord.w;
		shadowCoord.z += shadowBias;
		bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
		bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
		if ( frustumTest ) {
		#if defined( SHADOWMAP_TYPE_PCF )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx0 = - texelSize.x * shadowRadius;
			float dy0 = - texelSize.y * shadowRadius;
			float dx1 = + texelSize.x * shadowRadius;
			float dy1 = + texelSize.y * shadowRadius;
			float dx2 = dx0 / 2.0;
			float dy2 = dy0 / 2.0;
			float dx3 = dx1 / 2.0;
			float dy3 = dy1 / 2.0;
			shadow = (
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
			) * ( 1.0 / 17.0 );
		#elif defined( SHADOWMAP_TYPE_PCF_SOFT )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx = texelSize.x;
			float dy = texelSize.y;
			vec2 uv = shadowCoord.xy;
			vec2 f = fract( uv * shadowMapSize + 0.5 );
			uv -= f * texelSize;
			shadow = (
				texture2DCompare( shadowMap, uv, shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
						  f.x ),
					 mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
						  f.x ),
					 f.y )
			) * ( 1.0 / 9.0 );
		#elif defined( SHADOWMAP_TYPE_VSM )
			shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
		#else
			shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
		#endif
		}
		return mix( 1.0, shadow, shadowIntensity );
	}
	vec2 cubeToUV( vec3 v, float texelSizeY ) {
		vec3 absV = abs( v );
		float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
		absV *= scaleToCube;
		v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
		vec2 planar = v.xy;
		float almostATexel = 1.5 * texelSizeY;
		float almostOne = 1.0 - almostATexel;
		if ( absV.z >= almostOne ) {
			if ( v.z > 0.0 )
				planar.x = 4.0 - v.x;
		} else if ( absV.x >= almostOne ) {
			float signX = sign( v.x );
			planar.x = v.z * signX + 2.0 * signX;
		} else if ( absV.y >= almostOne ) {
			float signY = sign( v.y );
			planar.x = v.x + 2.0 * signY + 2.0;
			planar.y = v.z * signY - 2.0;
		}
		return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
	}
	float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
		float shadow = 1.0;
		vec3 lightToPosition = shadowCoord.xyz;
		
		float lightToPositionLength = length( lightToPosition );
		if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {
			float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );			dp += shadowBias;
			vec3 bd3D = normalize( lightToPosition );
			vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
			#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
				vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
				shadow = (
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
				) * ( 1.0 / 9.0 );
			#else
				shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
			#endif
		}
		return mix( 1.0, shadow, shadowIntensity );
	}
#endif`;
var shadowmap_pars_vertex = `#if NUM_SPOT_LIGHT_COORDS > 0
	uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
		struct DirectionalLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
		struct SpotLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
		struct PointLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
			float shadowCameraNear;
			float shadowCameraFar;
		};
		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
	#endif
#endif`;
var shadowmap_vertex = `#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
	vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
	vec4 shadowWorldPosition;
#endif
#if defined( USE_SHADOWMAP )
	#if NUM_DIR_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
			vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
			vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
#endif
#if NUM_SPOT_LIGHT_COORDS > 0
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
		shadowWorldPosition = worldPosition;
		#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
			shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
		#endif
		vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
	}
	#pragma unroll_loop_end
#endif`;
var shadowmask_pars_fragment = `float getShadowMask() {
	float shadow = 1.0;
	#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
		directionalLight = directionalLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
		spotLight = spotLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
		pointLight = pointLightShadows[ i ];
		shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#endif
	return shadow;
}`;
var skinbase_vertex = `#ifdef USE_SKINNING
	mat4 boneMatX = getBoneMatrix( skinIndex.x );
	mat4 boneMatY = getBoneMatrix( skinIndex.y );
	mat4 boneMatZ = getBoneMatrix( skinIndex.z );
	mat4 boneMatW = getBoneMatrix( skinIndex.w );
#endif`;
var skinning_pars_vertex = `#ifdef USE_SKINNING
	uniform mat4 bindMatrix;
	uniform mat4 bindMatrixInverse;
	uniform highp sampler2D boneTexture;
	mat4 getBoneMatrix( const in float i ) {
		int size = textureSize( boneTexture, 0 ).x;
		int j = int( i ) * 4;
		int x = j % size;
		int y = j / size;
		vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
		vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
		vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
		vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
		return mat4( v1, v2, v3, v4 );
	}
#endif`;
var skinning_vertex = `#ifdef USE_SKINNING
	vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
	vec4 skinned = vec4( 0.0 );
	skinned += boneMatX * skinVertex * skinWeight.x;
	skinned += boneMatY * skinVertex * skinWeight.y;
	skinned += boneMatZ * skinVertex * skinWeight.z;
	skinned += boneMatW * skinVertex * skinWeight.w;
	transformed = ( bindMatrixInverse * skinned ).xyz;
#endif`;
var skinnormal_vertex = `#ifdef USE_SKINNING
	mat4 skinMatrix = mat4( 0.0 );
	skinMatrix += skinWeight.x * boneMatX;
	skinMatrix += skinWeight.y * boneMatY;
	skinMatrix += skinWeight.z * boneMatZ;
	skinMatrix += skinWeight.w * boneMatW;
	skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
	objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
	#ifdef USE_TANGENT
		objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
	#endif
#endif`;
var specularmap_fragment = `float specularStrength;
#ifdef USE_SPECULARMAP
	vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
	specularStrength = texelSpecular.r;
#else
	specularStrength = 1.0;
#endif`;
var specularmap_pars_fragment = `#ifdef USE_SPECULARMAP
	uniform sampler2D specularMap;
#endif`;
var tonemapping_fragment = `#if defined( TONE_MAPPING )
	gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
#endif`;
var tonemapping_pars_fragment = `#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
uniform float toneMappingExposure;
vec3 LinearToneMapping( vec3 color ) {
	return saturate( toneMappingExposure * color );
}
vec3 ReinhardToneMapping( vec3 color ) {
	color *= toneMappingExposure;
	return saturate( color / ( vec3( 1.0 ) + color ) );
}
vec3 CineonToneMapping( vec3 color ) {
	color *= toneMappingExposure;
	color = max( vec3( 0.0 ), color - 0.004 );
	return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
}
vec3 RRTAndODTFit( vec3 v ) {
	vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
	vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
	return a / b;
}
vec3 ACESFilmicToneMapping( vec3 color ) {
	const mat3 ACESInputMat = mat3(
		vec3( 0.59719, 0.07600, 0.02840 ),		vec3( 0.35458, 0.90834, 0.13383 ),
		vec3( 0.04823, 0.01566, 0.83777 )
	);
	const mat3 ACESOutputMat = mat3(
		vec3(  1.60475, -0.10208, -0.00327 ),		vec3( -0.53108,  1.10813, -0.07276 ),
		vec3( -0.07367, -0.00605,  1.07602 )
	);
	color *= toneMappingExposure / 0.6;
	color = ACESInputMat * color;
	color = RRTAndODTFit( color );
	color = ACESOutputMat * color;
	return saturate( color );
}
const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(
	vec3( 1.6605, - 0.1246, - 0.0182 ),
	vec3( - 0.5876, 1.1329, - 0.1006 ),
	vec3( - 0.0728, - 0.0083, 1.1187 )
);
const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(
	vec3( 0.6274, 0.0691, 0.0164 ),
	vec3( 0.3293, 0.9195, 0.0880 ),
	vec3( 0.0433, 0.0113, 0.8956 )
);
vec3 agxDefaultContrastApprox( vec3 x ) {
	vec3 x2 = x * x;
	vec3 x4 = x2 * x2;
	return + 15.5 * x4 * x2
		- 40.14 * x4 * x
		+ 31.96 * x4
		- 6.868 * x2 * x
		+ 0.4298 * x2
		+ 0.1191 * x
		- 0.00232;
}
vec3 AgXToneMapping( vec3 color ) {
	const mat3 AgXInsetMatrix = mat3(
		vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),
		vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),
		vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )
	);
	const mat3 AgXOutsetMatrix = mat3(
		vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),
		vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),
		vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )
	);
	const float AgxMinEv = - 12.47393;	const float AgxMaxEv = 4.026069;
	color *= toneMappingExposure;
	color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;
	color = AgXInsetMatrix * color;
	color = max( color, 1e-10 );	color = log2( color );
	color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );
	color = clamp( color, 0.0, 1.0 );
	color = agxDefaultContrastApprox( color );
	color = AgXOutsetMatrix * color;
	color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );
	color = LINEAR_REC2020_TO_LINEAR_SRGB * color;
	color = clamp( color, 0.0, 1.0 );
	return color;
}
vec3 NeutralToneMapping( vec3 color ) {
	const float StartCompression = 0.8 - 0.04;
	const float Desaturation = 0.15;
	color *= toneMappingExposure;
	float x = min( color.r, min( color.g, color.b ) );
	float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
	color -= offset;
	float peak = max( color.r, max( color.g, color.b ) );
	if ( peak < StartCompression ) return color;
	float d = 1. - StartCompression;
	float newPeak = 1. - d * d / ( peak + d - StartCompression );
	color *= newPeak / peak;
	float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
	return mix( color, vec3( newPeak ), g );
}
vec3 CustomToneMapping( vec3 color ) { return color; }`;
var transmission_fragment = `#ifdef USE_TRANSMISSION
	material.transmission = transmission;
	material.transmissionAlpha = 1.0;
	material.thickness = thickness;
	material.attenuationDistance = attenuationDistance;
	material.attenuationColor = attenuationColor;
	#ifdef USE_TRANSMISSIONMAP
		material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
	#endif
	#ifdef USE_THICKNESSMAP
		material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
	#endif
	vec3 pos = vWorldPosition;
	vec3 v = normalize( cameraPosition - pos );
	vec3 n = inverseTransformDirection( normal, viewMatrix );
	vec4 transmitted = getIBLVolumeRefraction(
		n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
		pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,
		material.attenuationColor, material.attenuationDistance );
	material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
	totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
#endif`;
var transmission_pars_fragment = `#ifdef USE_TRANSMISSION
	uniform float transmission;
	uniform float thickness;
	uniform float attenuationDistance;
	uniform vec3 attenuationColor;
	#ifdef USE_TRANSMISSIONMAP
		uniform sampler2D transmissionMap;
	#endif
	#ifdef USE_THICKNESSMAP
		uniform sampler2D thicknessMap;
	#endif
	uniform vec2 transmissionSamplerSize;
	uniform sampler2D transmissionSamplerMap;
	uniform mat4 modelMatrix;
	uniform mat4 projectionMatrix;
	varying vec3 vWorldPosition;
	float w0( float a ) {
		return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
	}
	float w1( float a ) {
		return ( 1.0 / 6.0 ) * ( a *  a * ( 3.0 * a - 6.0 ) + 4.0 );
	}
	float w2( float a ){
		return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
	}
	float w3( float a ) {
		return ( 1.0 / 6.0 ) * ( a * a * a );
	}
	float g0( float a ) {
		return w0( a ) + w1( a );
	}
	float g1( float a ) {
		return w2( a ) + w3( a );
	}
	float h0( float a ) {
		return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
	}
	float h1( float a ) {
		return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
	}
	vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
		uv = uv * texelSize.zw + 0.5;
		vec2 iuv = floor( uv );
		vec2 fuv = fract( uv );
		float g0x = g0( fuv.x );
		float g1x = g1( fuv.x );
		float h0x = h0( fuv.x );
		float h1x = h1( fuv.x );
		float h0y = h0( fuv.y );
		float h1y = h1( fuv.y );
		vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
		vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
		vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
		vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
		return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
			g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
	}
	vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
		vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
		vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
		vec2 fLodSizeInv = 1.0 / fLodSize;
		vec2 cLodSizeInv = 1.0 / cLodSize;
		vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
		vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
		return mix( fSample, cSample, fract( lod ) );
	}
	vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
		vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
		vec3 modelScale;
		modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
		modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
		modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
		return normalize( refractionVector ) * thickness * modelScale;
	}
	float applyIorToRoughness( const in float roughness, const in float ior ) {
		return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
	}
	vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
		float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
		return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );
	}
	vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
		if ( isinf( attenuationDistance ) ) {
			return vec3( 1.0 );
		} else {
			vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
			vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );			return transmittance;
		}
	}
	vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
		const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
		const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,
		const in vec3 attenuationColor, const in float attenuationDistance ) {
		vec4 transmittedLight;
		vec3 transmittance;
		#ifdef USE_DISPERSION
			float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;
			vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );
			for ( int i = 0; i < 3; i ++ ) {
				vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );
				vec3 refractedRayExit = position + transmissionRay;
				vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
				vec2 refractionCoords = ndcPos.xy / ndcPos.w;
				refractionCoords += 1.0;
				refractionCoords /= 2.0;
				vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );
				transmittedLight[ i ] = transmissionSample[ i ];
				transmittedLight.a += transmissionSample.a;
				transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];
			}
			transmittedLight.a /= 3.0;
		#else
			vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
			vec3 refractedRayExit = position + transmissionRay;
			vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
			vec2 refractionCoords = ndcPos.xy / ndcPos.w;
			refractionCoords += 1.0;
			refractionCoords /= 2.0;
			transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
			transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
		#endif
		vec3 attenuatedColor = transmittance * transmittedLight.rgb;
		vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
		float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
		return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
	}
#endif`;
var uv_pars_fragment = `#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	varying vec2 vUv;
#endif
#ifdef USE_MAP
	varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
	varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
	varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
	varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
	varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
	varying vec2 vNormalMapUv;
#endif
#ifdef USE_EMISSIVEMAP
	varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
	varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
	varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
	varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
	varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
	varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
	varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_SPECULARMAP
	varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
	varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
	uniform mat3 transmissionMapTransform;
	varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
	uniform mat3 thicknessMapTransform;
	varying vec2 vThicknessMapUv;
#endif`;
var uv_pars_vertex = `#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	varying vec2 vUv;
#endif
#ifdef USE_MAP
	uniform mat3 mapTransform;
	varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
	uniform mat3 alphaMapTransform;
	varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
	uniform mat3 lightMapTransform;
	varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
	uniform mat3 aoMapTransform;
	varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
	uniform mat3 bumpMapTransform;
	varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
	uniform mat3 normalMapTransform;
	varying vec2 vNormalMapUv;
#endif
#ifdef USE_DISPLACEMENTMAP
	uniform mat3 displacementMapTransform;
	varying vec2 vDisplacementMapUv;
#endif
#ifdef USE_EMISSIVEMAP
	uniform mat3 emissiveMapTransform;
	varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
	uniform mat3 metalnessMapTransform;
	varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
	uniform mat3 roughnessMapTransform;
	varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
	uniform mat3 anisotropyMapTransform;
	varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
	uniform mat3 clearcoatMapTransform;
	varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	uniform mat3 clearcoatNormalMapTransform;
	varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	uniform mat3 clearcoatRoughnessMapTransform;
	varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
	uniform mat3 sheenColorMapTransform;
	varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	uniform mat3 sheenRoughnessMapTransform;
	varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
	uniform mat3 iridescenceMapTransform;
	varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform mat3 iridescenceThicknessMapTransform;
	varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SPECULARMAP
	uniform mat3 specularMapTransform;
	varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
	uniform mat3 specularColorMapTransform;
	varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	uniform mat3 specularIntensityMapTransform;
	varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
	uniform mat3 transmissionMapTransform;
	varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
	uniform mat3 thicknessMapTransform;
	varying vec2 vThicknessMapUv;
#endif`;
var uv_vertex = `#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	vUv = vec3( uv, 1 ).xy;
#endif
#ifdef USE_MAP
	vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ALPHAMAP
	vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_LIGHTMAP
	vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_AOMAP
	vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_BUMPMAP
	vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_NORMALMAP
	vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_DISPLACEMENTMAP
	vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_EMISSIVEMAP
	vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_METALNESSMAP
	vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ROUGHNESSMAP
	vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ANISOTROPYMAP
	vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOATMAP
	vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCEMAP
	vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_COLORMAP
	vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULARMAP
	vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_COLORMAP
	vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_TRANSMISSIONMAP
	vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_THICKNESSMAP
	vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
#endif`;
var worldpos_vertex = `#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
	vec4 worldPosition = vec4( transformed, 1.0 );
	#ifdef USE_BATCHING
		worldPosition = batchingMatrix * worldPosition;
	#endif
	#ifdef USE_INSTANCING
		worldPosition = instanceMatrix * worldPosition;
	#endif
	worldPosition = modelMatrix * worldPosition;
#endif`;
var vertex$h = `varying vec2 vUv;
uniform mat3 uvTransform;
void main() {
	vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
	gl_Position = vec4( position.xy, 1.0, 1.0 );
}`;
var fragment$h = `uniform sampler2D t2D;
uniform float backgroundIntensity;
varying vec2 vUv;
void main() {
	vec4 texColor = texture2D( t2D, vUv );
	#ifdef DECODE_VIDEO_TEXTURE
		texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );
	#endif
	texColor.rgb *= backgroundIntensity;
	gl_FragColor = texColor;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`;
var vertex$g = `varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`;
var fragment$g = `#ifdef ENVMAP_TYPE_CUBE
	uniform samplerCube envMap;
#elif defined( ENVMAP_TYPE_CUBE_UV )
	uniform sampler2D envMap;
#endif
uniform float flipEnvMap;
uniform float backgroundBlurriness;
uniform float backgroundIntensity;
uniform mat3 backgroundRotation;
varying vec3 vWorldDirection;
#include <cube_uv_reflection_fragment>
void main() {
	#ifdef ENVMAP_TYPE_CUBE
		vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );
	#elif defined( ENVMAP_TYPE_CUBE_UV )
		vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );
	#else
		vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
	#endif
	texColor.rgb *= backgroundIntensity;
	gl_FragColor = texColor;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`;
var vertex$f = `varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`;
var fragment$f = `uniform samplerCube tCube;
uniform float tFlip;
uniform float opacity;
varying vec3 vWorldDirection;
void main() {
	vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
	gl_FragColor = texColor;
	gl_FragColor.a *= opacity;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`;
var vertex$e = `#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
varying vec2 vHighPrecisionZW;
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <skinbase_vertex>
	#include <morphinstance_vertex>
	#ifdef USE_DISPLACEMENTMAP
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vHighPrecisionZW = gl_Position.zw;
}`;
var fragment$e = `#if DEPTH_PACKING == 3200
	uniform float opacity;
#endif
#include <common>
#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
varying vec2 vHighPrecisionZW;
void main() {
	vec4 diffuseColor = vec4( 1.0 );
	#include <clipping_planes_fragment>
	#if DEPTH_PACKING == 3200
		diffuseColor.a = opacity;
	#endif
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <logdepthbuf_fragment>
	#ifdef USE_REVERSEDEPTHBUF
		float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];
	#else
		float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;
	#endif
	#if DEPTH_PACKING == 3200
		gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
	#elif DEPTH_PACKING == 3201
		gl_FragColor = packDepthToRGBA( fragCoordZ );
	#elif DEPTH_PACKING == 3202
		gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );
	#elif DEPTH_PACKING == 3203
		gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );
	#endif
}`;
var vertex$d = `#define DISTANCE
varying vec3 vWorldPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <skinbase_vertex>
	#include <morphinstance_vertex>
	#ifdef USE_DISPLACEMENTMAP
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <worldpos_vertex>
	#include <clipping_planes_vertex>
	vWorldPosition = worldPosition.xyz;
}`;
var fragment$d = `#define DISTANCE
uniform vec3 referencePosition;
uniform float nearDistance;
uniform float farDistance;
varying vec3 vWorldPosition;
#include <common>
#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <clipping_planes_pars_fragment>
void main () {
	vec4 diffuseColor = vec4( 1.0 );
	#include <clipping_planes_fragment>
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	float dist = length( vWorldPosition - referencePosition );
	dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
	dist = saturate( dist );
	gl_FragColor = packDepthToRGBA( dist );
}`;
var vertex$c = `varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
}`;
var fragment$c = `uniform sampler2D tEquirect;
varying vec3 vWorldDirection;
#include <common>
void main() {
	vec3 direction = normalize( vWorldDirection );
	vec2 sampleUV = equirectUv( direction );
	gl_FragColor = texture2D( tEquirect, sampleUV );
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`;
var vertex$b = `uniform float scale;
attribute float lineDistance;
varying float vLineDistance;
#include <common>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	vLineDistance = scale * lineDistance;
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
}`;
var fragment$b = `uniform vec3 diffuse;
uniform float opacity;
uniform float dashSize;
uniform float totalSize;
varying float vLineDistance;
#include <common>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	if ( mod( vLineDistance, totalSize ) > dashSize ) {
		discard;
	}
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
}`;
var vertex$a = `#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinbase_vertex>
		#include <skinnormal_vertex>
		#include <defaultnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <fog_vertex>
}`;
var fragment$a = `uniform vec3 diffuse;
uniform float opacity;
#ifndef FLAT_SHADED
	varying vec3 vNormal;
#endif
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	#ifdef USE_LIGHTMAP
		vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
		reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
	#else
		reflectedLight.indirectDiffuse += vec3( 1.0 );
	#endif
	#include <aomap_fragment>
	reflectedLight.indirectDiffuse *= diffuseColor.rgb;
	vec3 outgoingLight = reflectedLight.indirectDiffuse;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`;
var vertex$9 = `#define LAMBERT
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`;
var fragment$9 = `#define LAMBERT
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_lambert_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_lambert_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`;
var vertex$8 = `#define MATCAP
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <displacementmap_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
	vViewPosition = - mvPosition.xyz;
}`;
var fragment$8 = `#define MATCAP
uniform vec3 diffuse;
uniform float opacity;
uniform sampler2D matcap;
varying vec3 vViewPosition;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	vec3 viewDir = normalize( vViewPosition );
	vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
	vec3 y = cross( viewDir, x );
	vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
	#ifdef USE_MATCAP
		vec4 matcapColor = texture2D( matcap, uv );
	#else
		vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
	#endif
	vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`;
var vertex$7 = `#define NORMAL
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	varying vec3 vViewPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	vViewPosition = - mvPosition.xyz;
#endif
}`;
var fragment$7 = `#define NORMAL
uniform float opacity;
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	varying vec3 vViewPosition;
#endif
#include <packing>
#include <uv_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );
	#ifdef OPAQUE
		gl_FragColor.a = 1.0;
	#endif
}`;
var vertex$6 = `#define PHONG
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`;
var fragment$6 = `#define PHONG
uniform vec3 diffuse;
uniform vec3 emissive;
uniform vec3 specular;
uniform float shininess;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_phong_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_phong_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`;
var vertex$5 = `#define STANDARD
varying vec3 vViewPosition;
#ifdef USE_TRANSMISSION
	varying vec3 vWorldPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
#ifdef USE_TRANSMISSION
	vWorldPosition = worldPosition.xyz;
#endif
}`;
var fragment$5 = `#define STANDARD
#ifdef PHYSICAL
	#define IOR
	#define USE_SPECULAR
#endif
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float roughness;
uniform float metalness;
uniform float opacity;
#ifdef IOR
	uniform float ior;
#endif
#ifdef USE_SPECULAR
	uniform float specularIntensity;
	uniform vec3 specularColor;
	#ifdef USE_SPECULAR_COLORMAP
		uniform sampler2D specularColorMap;
	#endif
	#ifdef USE_SPECULAR_INTENSITYMAP
		uniform sampler2D specularIntensityMap;
	#endif
#endif
#ifdef USE_CLEARCOAT
	uniform float clearcoat;
	uniform float clearcoatRoughness;
#endif
#ifdef USE_DISPERSION
	uniform float dispersion;
#endif
#ifdef USE_IRIDESCENCE
	uniform float iridescence;
	uniform float iridescenceIOR;
	uniform float iridescenceThicknessMinimum;
	uniform float iridescenceThicknessMaximum;
#endif
#ifdef USE_SHEEN
	uniform vec3 sheenColor;
	uniform float sheenRoughness;
	#ifdef USE_SHEEN_COLORMAP
		uniform sampler2D sheenColorMap;
	#endif
	#ifdef USE_SHEEN_ROUGHNESSMAP
		uniform sampler2D sheenRoughnessMap;
	#endif
#endif
#ifdef USE_ANISOTROPY
	uniform vec2 anisotropyVector;
	#ifdef USE_ANISOTROPYMAP
		uniform sampler2D anisotropyMap;
	#endif
#endif
varying vec3 vViewPosition;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <iridescence_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_physical_pars_fragment>
#include <fog_pars_fragment>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_physical_pars_fragment>
#include <transmission_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <clearcoat_pars_fragment>
#include <iridescence_pars_fragment>
#include <roughnessmap_pars_fragment>
#include <metalnessmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <roughnessmap_fragment>
	#include <metalnessmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <clearcoat_normal_fragment_begin>
	#include <clearcoat_normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_physical_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
	vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
	#include <transmission_fragment>
	vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
	#ifdef USE_SHEEN
		float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
		outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;
	#endif
	#ifdef USE_CLEARCOAT
		float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
		vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
		outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
	#endif
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`;
var vertex$4 = `#define TOON
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`;
var fragment$4 = `#define TOON
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <gradientmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_toon_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_toon_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`;
var vertex$3 = `uniform float size;
uniform float scale;
#include <common>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
#ifdef USE_POINTS_UV
	varying vec2 vUv;
	uniform mat3 uvTransform;
#endif
void main() {
	#ifdef USE_POINTS_UV
		vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
	#endif
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <project_vertex>
	gl_PointSize = size;
	#ifdef USE_SIZEATTENUATION
		bool isPerspective = isPerspectiveMatrix( projectionMatrix );
		if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
	#endif
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <worldpos_vertex>
	#include <fog_vertex>
}`;
var fragment$3 = `uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <color_pars_fragment>
#include <map_particle_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_particle_fragment>
	#include <color_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
}`;
var vertex$2 = `#include <common>
#include <batching_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <shadowmap_pars_vertex>
void main() {
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`;
var fragment$2 = `uniform vec3 color;
uniform float opacity;
#include <common>
#include <packing>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <logdepthbuf_pars_fragment>
#include <shadowmap_pars_fragment>
#include <shadowmask_pars_fragment>
void main() {
	#include <logdepthbuf_fragment>
	gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
}`;
var vertex$1 = `uniform float rotation;
uniform vec2 center;
#include <common>
#include <uv_pars_vertex>
#include <fog_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	vec4 mvPosition = modelViewMatrix[ 3 ];
	vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );
	#ifndef USE_SIZEATTENUATION
		bool isPerspective = isPerspectiveMatrix( projectionMatrix );
		if ( isPerspective ) scale *= - mvPosition.z;
	#endif
	vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
	vec2 rotatedPosition;
	rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
	rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
	mvPosition.xy += rotatedPosition;
	gl_Position = projectionMatrix * mvPosition;
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
}`;
var fragment$1 = `uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
}`;
var ShaderChunk = {
  alphahash_fragment,
  alphahash_pars_fragment,
  alphamap_fragment,
  alphamap_pars_fragment,
  alphatest_fragment,
  alphatest_pars_fragment,
  aomap_fragment,
  aomap_pars_fragment,
  batching_pars_vertex,
  batching_vertex,
  begin_vertex,
  beginnormal_vertex,
  bsdfs,
  iridescence_fragment,
  bumpmap_pars_fragment,
  clipping_planes_fragment,
  clipping_planes_pars_fragment,
  clipping_planes_pars_vertex,
  clipping_planes_vertex,
  color_fragment,
  color_pars_fragment,
  color_pars_vertex,
  color_vertex,
  common,
  cube_uv_reflection_fragment,
  defaultnormal_vertex,
  displacementmap_pars_vertex,
  displacementmap_vertex,
  emissivemap_fragment,
  emissivemap_pars_fragment,
  colorspace_fragment,
  colorspace_pars_fragment,
  envmap_fragment,
  envmap_common_pars_fragment,
  envmap_pars_fragment,
  envmap_pars_vertex,
  envmap_physical_pars_fragment,
  envmap_vertex,
  fog_vertex,
  fog_pars_vertex,
  fog_fragment,
  fog_pars_fragment,
  gradientmap_pars_fragment,
  lightmap_pars_fragment,
  lights_lambert_fragment,
  lights_lambert_pars_fragment,
  lights_pars_begin,
  lights_toon_fragment,
  lights_toon_pars_fragment,
  lights_phong_fragment,
  lights_phong_pars_fragment,
  lights_physical_fragment,
  lights_physical_pars_fragment,
  lights_fragment_begin,
  lights_fragment_maps,
  lights_fragment_end,
  logdepthbuf_fragment,
  logdepthbuf_pars_fragment,
  logdepthbuf_pars_vertex,
  logdepthbuf_vertex,
  map_fragment,
  map_pars_fragment,
  map_particle_fragment,
  map_particle_pars_fragment,
  metalnessmap_fragment,
  metalnessmap_pars_fragment,
  morphinstance_vertex,
  morphcolor_vertex,
  morphnormal_vertex,
  morphtarget_pars_vertex,
  morphtarget_vertex,
  normal_fragment_begin,
  normal_fragment_maps,
  normal_pars_fragment,
  normal_pars_vertex,
  normal_vertex,
  normalmap_pars_fragment,
  clearcoat_normal_fragment_begin,
  clearcoat_normal_fragment_maps,
  clearcoat_pars_fragment,
  iridescence_pars_fragment,
  opaque_fragment,
  packing,
  premultiplied_alpha_fragment,
  project_vertex,
  dithering_fragment,
  dithering_pars_fragment,
  roughnessmap_fragment,
  roughnessmap_pars_fragment,
  shadowmap_pars_fragment,
  shadowmap_pars_vertex,
  shadowmap_vertex,
  shadowmask_pars_fragment,
  skinbase_vertex,
  skinning_pars_vertex,
  skinning_vertex,
  skinnormal_vertex,
  specularmap_fragment,
  specularmap_pars_fragment,
  tonemapping_fragment,
  tonemapping_pars_fragment,
  transmission_fragment,
  transmission_pars_fragment,
  uv_pars_fragment,
  uv_pars_vertex,
  uv_vertex,
  worldpos_vertex,
  background_vert: vertex$h,
  background_frag: fragment$h,
  backgroundCube_vert: vertex$g,
  backgroundCube_frag: fragment$g,
  cube_vert: vertex$f,
  cube_frag: fragment$f,
  depth_vert: vertex$e,
  depth_frag: fragment$e,
  distanceRGBA_vert: vertex$d,
  distanceRGBA_frag: fragment$d,
  equirect_vert: vertex$c,
  equirect_frag: fragment$c,
  linedashed_vert: vertex$b,
  linedashed_frag: fragment$b,
  meshbasic_vert: vertex$a,
  meshbasic_frag: fragment$a,
  meshlambert_vert: vertex$9,
  meshlambert_frag: fragment$9,
  meshmatcap_vert: vertex$8,
  meshmatcap_frag: fragment$8,
  meshnormal_vert: vertex$7,
  meshnormal_frag: fragment$7,
  meshphong_vert: vertex$6,
  meshphong_frag: fragment$6,
  meshphysical_vert: vertex$5,
  meshphysical_frag: fragment$5,
  meshtoon_vert: vertex$4,
  meshtoon_frag: fragment$4,
  points_vert: vertex$3,
  points_frag: fragment$3,
  shadow_vert: vertex$2,
  shadow_frag: fragment$2,
  sprite_vert: vertex$1,
  sprite_frag: fragment$1
};
var UniformsLib = {
  common: {
    diffuse: { value: /* @__PURE__ */ new Color3(16777215) },
    opacity: { value: 1 },
    map: { value: null },
    mapTransform: { value: /* @__PURE__ */ new Matrix3 },
    alphaMap: { value: null },
    alphaMapTransform: { value: /* @__PURE__ */ new Matrix3 },
    alphaTest: { value: 0 }
  },
  specularmap: {
    specularMap: { value: null },
    specularMapTransform: { value: /* @__PURE__ */ new Matrix3 }
  },
  envmap: {
    envMap: { value: null },
    envMapRotation: { value: /* @__PURE__ */ new Matrix3 },
    flipEnvMap: { value: -1 },
    reflectivity: { value: 1 },
    ior: { value: 1.5 },
    refractionRatio: { value: 0.98 }
  },
  aomap: {
    aoMap: { value: null },
    aoMapIntensity: { value: 1 },
    aoMapTransform: { value: /* @__PURE__ */ new Matrix3 }
  },
  lightmap: {
    lightMap: { value: null },
    lightMapIntensity: { value: 1 },
    lightMapTransform: { value: /* @__PURE__ */ new Matrix3 }
  },
  bumpmap: {
    bumpMap: { value: null },
    bumpMapTransform: { value: /* @__PURE__ */ new Matrix3 },
    bumpScale: { value: 1 }
  },
  normalmap: {
    normalMap: { value: null },
    normalMapTransform: { value: /* @__PURE__ */ new Matrix3 },
    normalScale: { value: /* @__PURE__ */ new Vector2(1, 1) }
  },
  displacementmap: {
    displacementMap: { value: null },
    displacementMapTransform: { value: /* @__PURE__ */ new Matrix3 },
    displacementScale: { value: 1 },
    displacementBias: { value: 0 }
  },
  emissivemap: {
    emissiveMap: { value: null },
    emissiveMapTransform: { value: /* @__PURE__ */ new Matrix3 }
  },
  metalnessmap: {
    metalnessMap: { value: null },
    metalnessMapTransform: { value: /* @__PURE__ */ new Matrix3 }
  },
  roughnessmap: {
    roughnessMap: { value: null },
    roughnessMapTransform: { value: /* @__PURE__ */ new Matrix3 }
  },
  gradientmap: {
    gradientMap: { value: null }
  },
  fog: {
    fogDensity: { value: 0.00025 },
    fogNear: { value: 1 },
    fogFar: { value: 2000 },
    fogColor: { value: /* @__PURE__ */ new Color3(16777215) }
  },
  lights: {
    ambientLightColor: { value: [] },
    lightProbe: { value: [] },
    directionalLights: { value: [], properties: {
      direction: {},
      color: {}
    } },
    directionalLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {}
    } },
    directionalShadowMap: { value: [] },
    directionalShadowMatrix: { value: [] },
    spotLights: { value: [], properties: {
      color: {},
      position: {},
      direction: {},
      distance: {},
      coneCos: {},
      penumbraCos: {},
      decay: {}
    } },
    spotLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {}
    } },
    spotLightMap: { value: [] },
    spotShadowMap: { value: [] },
    spotLightMatrix: { value: [] },
    pointLights: { value: [], properties: {
      color: {},
      position: {},
      decay: {},
      distance: {}
    } },
    pointLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {},
      shadowCameraNear: {},
      shadowCameraFar: {}
    } },
    pointShadowMap: { value: [] },
    pointShadowMatrix: { value: [] },
    hemisphereLights: { value: [], properties: {
      direction: {},
      skyColor: {},
      groundColor: {}
    } },
    rectAreaLights: { value: [], properties: {
      color: {},
      position: {},
      width: {},
      height: {}
    } },
    ltc_1: { value: null },
    ltc_2: { value: null }
  },
  points: {
    diffuse: { value: /* @__PURE__ */ new Color3(16777215) },
    opacity: { value: 1 },
    size: { value: 1 },
    scale: { value: 1 },
    map: { value: null },
    alphaMap: { value: null },
    alphaMapTransform: { value: /* @__PURE__ */ new Matrix3 },
    alphaTest: { value: 0 },
    uvTransform: { value: /* @__PURE__ */ new Matrix3 }
  },
  sprite: {
    diffuse: { value: /* @__PURE__ */ new Color3(16777215) },
    opacity: { value: 1 },
    center: { value: /* @__PURE__ */ new Vector2(0.5, 0.5) },
    rotation: { value: 0 },
    map: { value: null },
    mapTransform: { value: /* @__PURE__ */ new Matrix3 },
    alphaMap: { value: null },
    alphaMapTransform: { value: /* @__PURE__ */ new Matrix3 },
    alphaTest: { value: 0 }
  }
};
var ShaderLib = {
  basic: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.specularmap,
      UniformsLib.envmap,
      UniformsLib.aomap,
      UniformsLib.lightmap,
      UniformsLib.fog
    ]),
    vertexShader: ShaderChunk.meshbasic_vert,
    fragmentShader: ShaderChunk.meshbasic_frag
  },
  lambert: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.specularmap,
      UniformsLib.envmap,
      UniformsLib.aomap,
      UniformsLib.lightmap,
      UniformsLib.emissivemap,
      UniformsLib.bumpmap,
      UniformsLib.normalmap,
      UniformsLib.displacementmap,
      UniformsLib.fog,
      UniformsLib.lights,
      {
        emissive: { value: /* @__PURE__ */ new Color3(0) }
      }
    ]),
    vertexShader: ShaderChunk.meshlambert_vert,
    fragmentShader: ShaderChunk.meshlambert_frag
  },
  phong: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.specularmap,
      UniformsLib.envmap,
      UniformsLib.aomap,
      UniformsLib.lightmap,
      UniformsLib.emissivemap,
      UniformsLib.bumpmap,
      UniformsLib.normalmap,
      UniformsLib.displacementmap,
      UniformsLib.fog,
      UniformsLib.lights,
      {
        emissive: { value: /* @__PURE__ */ new Color3(0) },
        specular: { value: /* @__PURE__ */ new Color3(1118481) },
        shininess: { value: 30 }
      }
    ]),
    vertexShader: ShaderChunk.meshphong_vert,
    fragmentShader: ShaderChunk.meshphong_frag
  },
  standard: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.envmap,
      UniformsLib.aomap,
      UniformsLib.lightmap,
      UniformsLib.emissivemap,
      UniformsLib.bumpmap,
      UniformsLib.normalmap,
      UniformsLib.displacementmap,
      UniformsLib.roughnessmap,
      UniformsLib.metalnessmap,
      UniformsLib.fog,
      UniformsLib.lights,
      {
        emissive: { value: /* @__PURE__ */ new Color3(0) },
        roughness: { value: 1 },
        metalness: { value: 0 },
        envMapIntensity: { value: 1 }
      }
    ]),
    vertexShader: ShaderChunk.meshphysical_vert,
    fragmentShader: ShaderChunk.meshphysical_frag
  },
  toon: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.aomap,
      UniformsLib.lightmap,
      UniformsLib.emissivemap,
      UniformsLib.bumpmap,
      UniformsLib.normalmap,
      UniformsLib.displacementmap,
      UniformsLib.gradientmap,
      UniformsLib.fog,
      UniformsLib.lights,
      {
        emissive: { value: /* @__PURE__ */ new Color3(0) }
      }
    ]),
    vertexShader: ShaderChunk.meshtoon_vert,
    fragmentShader: ShaderChunk.meshtoon_frag
  },
  matcap: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.bumpmap,
      UniformsLib.normalmap,
      UniformsLib.displacementmap,
      UniformsLib.fog,
      {
        matcap: { value: null }
      }
    ]),
    vertexShader: ShaderChunk.meshmatcap_vert,
    fragmentShader: ShaderChunk.meshmatcap_frag
  },
  points: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.points,
      UniformsLib.fog
    ]),
    vertexShader: ShaderChunk.points_vert,
    fragmentShader: ShaderChunk.points_frag
  },
  dashed: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.fog,
      {
        scale: { value: 1 },
        dashSize: { value: 1 },
        totalSize: { value: 2 }
      }
    ]),
    vertexShader: ShaderChunk.linedashed_vert,
    fragmentShader: ShaderChunk.linedashed_frag
  },
  depth: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.displacementmap
    ]),
    vertexShader: ShaderChunk.depth_vert,
    fragmentShader: ShaderChunk.depth_frag
  },
  normal: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.bumpmap,
      UniformsLib.normalmap,
      UniformsLib.displacementmap,
      {
        opacity: { value: 1 }
      }
    ]),
    vertexShader: ShaderChunk.meshnormal_vert,
    fragmentShader: ShaderChunk.meshnormal_frag
  },
  sprite: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.sprite,
      UniformsLib.fog
    ]),
    vertexShader: ShaderChunk.sprite_vert,
    fragmentShader: ShaderChunk.sprite_frag
  },
  background: {
    uniforms: {
      uvTransform: { value: /* @__PURE__ */ new Matrix3 },
      t2D: { value: null },
      backgroundIntensity: { value: 1 }
    },
    vertexShader: ShaderChunk.background_vert,
    fragmentShader: ShaderChunk.background_frag
  },
  backgroundCube: {
    uniforms: {
      envMap: { value: null },
      flipEnvMap: { value: -1 },
      backgroundBlurriness: { value: 0 },
      backgroundIntensity: { value: 1 },
      backgroundRotation: { value: /* @__PURE__ */ new Matrix3 }
    },
    vertexShader: ShaderChunk.backgroundCube_vert,
    fragmentShader: ShaderChunk.backgroundCube_frag
  },
  cube: {
    uniforms: {
      tCube: { value: null },
      tFlip: { value: -1 },
      opacity: { value: 1 }
    },
    vertexShader: ShaderChunk.cube_vert,
    fragmentShader: ShaderChunk.cube_frag
  },
  equirect: {
    uniforms: {
      tEquirect: { value: null }
    },
    vertexShader: ShaderChunk.equirect_vert,
    fragmentShader: ShaderChunk.equirect_frag
  },
  distanceRGBA: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.common,
      UniformsLib.displacementmap,
      {
        referencePosition: { value: /* @__PURE__ */ new Vector3 },
        nearDistance: { value: 1 },
        farDistance: { value: 1000 }
      }
    ]),
    vertexShader: ShaderChunk.distanceRGBA_vert,
    fragmentShader: ShaderChunk.distanceRGBA_frag
  },
  shadow: {
    uniforms: /* @__PURE__ */ mergeUniforms([
      UniformsLib.lights,
      UniformsLib.fog,
      {
        color: { value: /* @__PURE__ */ new Color3(0) },
        opacity: { value: 1 }
      }
    ]),
    vertexShader: ShaderChunk.shadow_vert,
    fragmentShader: ShaderChunk.shadow_frag
  }
};
ShaderLib.physical = {
  uniforms: /* @__PURE__ */ mergeUniforms([
    ShaderLib.standard.uniforms,
    {
      clearcoat: { value: 0 },
      clearcoatMap: { value: null },
      clearcoatMapTransform: { value: /* @__PURE__ */ new Matrix3 },
      clearcoatNormalMap: { value: null },
      clearcoatNormalMapTransform: { value: /* @__PURE__ */ new Matrix3 },
      clearcoatNormalScale: { value: /* @__PURE__ */ new Vector2(1, 1) },
      clearcoatRoughness: { value: 0 },
      clearcoatRoughnessMap: { value: null },
      clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix3 },
      dispersion: { value: 0 },
      iridescence: { value: 0 },
      iridescenceMap: { value: null },
      iridescenceMapTransform: { value: /* @__PURE__ */ new Matrix3 },
      iridescenceIOR: { value: 1.3 },
      iridescenceThicknessMinimum: { value: 100 },
      iridescenceThicknessMaximum: { value: 400 },
      iridescenceThicknessMap: { value: null },
      iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new Matrix3 },
      sheen: { value: 0 },
      sheenColor: { value: /* @__PURE__ */ new Color3(0) },
      sheenColorMap: { value: null },
      sheenColorMapTransform: { value: /* @__PURE__ */ new Matrix3 },
      sheenRoughness: { value: 1 },
      sheenRoughnessMap: { value: null },
      sheenRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix3 },
      transmission: { value: 0 },
      transmissionMap: { value: null },
      transmissionMapTransform: { value: /* @__PURE__ */ new Matrix3 },
      transmissionSamplerSize: { value: /* @__PURE__ */ new Vector2 },
      transmissionSamplerMap: { value: null },
      thickness: { value: 0 },
      thicknessMap: { value: null },
      thicknessMapTransform: { value: /* @__PURE__ */ new Matrix3 },
      attenuationDistance: { value: 0 },
      attenuationColor: { value: /* @__PURE__ */ new Color3(0) },
      specularColor: { value: /* @__PURE__ */ new Color3(1, 1, 1) },
      specularColorMap: { value: null },
      specularColorMapTransform: { value: /* @__PURE__ */ new Matrix3 },
      specularIntensity: { value: 1 },
      specularIntensityMap: { value: null },
      specularIntensityMapTransform: { value: /* @__PURE__ */ new Matrix3 },
      anisotropyVector: { value: /* @__PURE__ */ new Vector2 },
      anisotropyMap: { value: null },
      anisotropyMapTransform: { value: /* @__PURE__ */ new Matrix3 }
    }
  ]),
  vertexShader: ShaderChunk.meshphysical_vert,
  fragmentShader: ShaderChunk.meshphysical_frag
};
var PHI = (1 + Math.sqrt(5)) / 2;
var INV_PHI = 1 / PHI;
var _axisDirections = [
  /* @__PURE__ */ new Vector3(-PHI, INV_PHI, 0),
  /* @__PURE__ */ new Vector3(PHI, INV_PHI, 0),
  /* @__PURE__ */ new Vector3(-INV_PHI, 0, PHI),
  /* @__PURE__ */ new Vector3(INV_PHI, 0, PHI),
  /* @__PURE__ */ new Vector3(0, PHI, -INV_PHI),
  /* @__PURE__ */ new Vector3(0, PHI, INV_PHI),
  /* @__PURE__ */ new Vector3(-1, 1, -1),
  /* @__PURE__ */ new Vector3(1, 1, -1),
  /* @__PURE__ */ new Vector3(-1, 1, 1),
  /* @__PURE__ */ new Vector3(1, 1, 1)
];
var mat4array = new Float32Array(16);
var mat3array = new Float32Array(9);
var mat2array = new Float32Array(4);
var shaderChunkMap = new Map;
var reversedFuncs = {
  [NeverDepth]: AlwaysDepth,
  [LessDepth]: GreaterDepth,
  [EqualDepth]: NotEqualDepth,
  [LessEqualDepth]: GreaterEqualDepth,
  [AlwaysDepth]: NeverDepth,
  [GreaterDepth]: LessDepth,
  [NotEqualDepth]: EqualDepth,
  [GreaterEqualDepth]: LessEqualDepth
};

// node_modules/@oai/granola/dist/draw-utils/chart-3d/utils-3d.js
var WORLD_WIDTH = 6;
var WORLD_HEIGHT = 4;
var WORLD_DEPTH = 2.6;
var MIN_BAR_THICKNESS = 0.04;
var MIN_BAR_HEIGHT = 0.02;
var FALLBACK_COLOR = "#60a5fa";
var DRAG_ROTATE_SENS_X = Math.PI * 1.2;
var DRAG_ROTATE_SENS_Y = Math.PI * 0.9;
var MAX_DRAG_PITCH = Math.PI * 0.35;
function ensureThreeColor(input, fallback = FALLBACK_COLOR) {
  const color2 = new Color3;
  try {
    color2.set(input ?? fallback);
  } catch {
    color2.set(fallback);
  }
  if (Number.isNaN(color2.r) || Number.isNaN(color2.g) || Number.isNaN(color2.b)) {
    color2.set(fallback);
  }
  return color2;
}
function getPastelMaterial(colorHex, cache) {
  const key = (colorHex ?? FALLBACK_COLOR).toLowerCase() + "_mobile_pastel_v2";
  const cached = cache.get(key);
  if (cached)
    return cached;
  const base = ensureThreeColor(colorHex);
  const hsl2 = { h: 0, s: 0, l: 0 };
  base.getHSL(hsl2);
  const h = hsl2.h;
  let _s = hsl2.s;
  let _l = hsl2.l;
  const isRed = h < 0.03 || h > 0.97;
  const isOrange = !isRed && h >= 0.03 && h < 0.11;
  const isYellow = !isRed && h >= 0.11 && h < 0.2;
  _s = _s * 1.25 + 0.06;
  _l = _l * 0.92 + 0.04;
  if (isOrange) {
    _s = Math.min(1, _s * 1.35 + 0.08);
    _l = _l + 0.03;
  }
  if (isYellow) {
    _s = Math.min(1, _s * 1.2 + 0.06);
    _l = _l + 0.01;
  }
  if (isRed) {
    _s = Math.min(1, _s * 1.2 + 0.06);
    _l = _l - 0.12;
  }
  _l = Math.max(isRed ? 0.32 : 0.4, Math.min(0.72, _l));
  const plasticCandyMaterial = new MeshPhysicalMaterial({
    color: base,
    metalness: 0,
    roughness: 0.6,
    clearcoat: 1,
    clearcoatRoughness: 0.35,
    reflectivity: 0.5,
    emissive: base.clone().multiplyScalar(0.75),
    transmission: 0,
    thickness: 0.1,
    opacity: 1
  });
  cache.set(key, plasticCandyMaterial);
  return plasticCandyMaterial;
}
function pxToWorldScalar(pixelSpan, worldSpan) {
  return worldSpan / Math.max(pixelSpan, 1);
}

// node_modules/@oai/granola/dist/draw-utils/chart-3d/draw-bar-chart-3d.js
var import_ssf3 = __toESM(require_ssf(), 1);
var CAMERA_FIT_INCLUDE_LABELS = false;
var CAMERA_PADDING_RATIO = 0.3;
var CAMERA_VIEW_DIR = new Vector3(-0.25, 0.15, 0.8).normalize();
var CAMERA_HORIZONTAL_OFFSET = 0;
var CAMERA_PAN_OFFSET = 0;
function createTextSprite(text, opts = {}) {
  const { fontSize = 28, color: color2 = "#1f2933", backgroundColor, padding = Math.ceil(fontSize * 0.35), fontFamily = FONT_FAMILY, weight = "500", worldUnitsPerPixel = 0.004 } = opts;
  if (typeof OffscreenCanvas === "undefined") {
    throw new Error("OffscreenCanvas API is not available for chart text sprites.");
  }
  const canvas = new OffscreenCanvas(1, 1);
  const ctx = canvas.getContext("2d");
  if (!ctx) {
    throw new Error("Failed to acquire 2D context for text sprite");
  }
  ctx.font = `${weight} ${fontSize}px ${fontFamily}`;
  const metrics = ctx.measureText(text);
  const textWidth = Math.ceil(metrics.width);
  const textHeight = Math.ceil(fontSize * 1.35);
  canvas.width = Math.max(1, textWidth + padding * 2);
  canvas.height = Math.max(1, textHeight + padding * 2);
  ctx.font = `${weight} ${fontSize}px ${fontFamily}`;
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  if (backgroundColor) {
    ctx.fillStyle = backgroundColor;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
  } else {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  }
  ctx.fillStyle = color2;
  ctx.fillText(text, canvas.width / 2, canvas.height / 2 + fontSize * 0.05);
  const texture = new CanvasTexture(canvas);
  texture.anisotropy = 8;
  texture.needsUpdate = true;
  const material = new SpriteMaterial({
    map: texture,
    transparent: true
  });
  material.depthTest = false;
  material.depthWrite = false;
  const sprite = new Sprite(material);
  sprite.scale.set(canvas.width * worldUnitsPerPixel, canvas.height * worldUnitsPerPixel, 1);
  sprite.center.set(0.5, 0.5);
  return sprite;
}
function prepareBarChart3D(chart, scales, plotDims, themeMap, hiddenSeries) {
  const baseBarDepth = Math.max(WORLD_DEPTH * 0.25, MIN_BAR_THICKNESS);
  const grouping = chart.barOptions?.grouping ?? 0 /* BAR_GROUPING_UNSPECIFIED */;
  if (!isBandScale(scales.x) || chart.series.length === 0) {
    return {
      segments: [],
      bounds: { minX: 0, maxX: 0, maxHeight: 0, minHeight: 0 },
      barDepth: baseBarDepth,
      chartDepth: baseBarDepth,
      categoryCount: 0,
      seriesLanes: [],
      grouping,
      categories: []
    };
  }
  const prepared = prepareBarData(chart, hiddenSeries);
  const categories = prepared.categories;
  if (categories.length === 0) {
    return {
      segments: [],
      bounds: { minX: 0, maxX: 0, maxHeight: 0, minHeight: 0 },
      barDepth: baseBarDepth,
      chartDepth: baseBarDepth,
      categoryCount: 0,
      seriesLanes: [],
      grouping,
      categories: []
    };
  }
  const xScale = scales.x;
  const yScale = scales.y;
  const pxToWorldX = pxToWorldScalar(plotDims.width, WORLD_WIDTH);
  const pxToWorldY = pxToWorldScalar(plotDims.height, WORLD_HEIGHT);
  const pxToWorldZ = pxToWorldScalar(plotDims.width, WORLD_DEPTH);
  const zeroCandidate = yScale(0);
  const zeroRel = Number.isFinite(zeroCandidate) ? zeroCandidate - plotDims.y : plotDims.height;
  const toWorldY = (relPx) => (zeroRel - relPx) * pxToWorldY;
  const isClusteredMode = prepared.mode === "clustered";
  const placeSeriesAlongZ = grouping === 0 /* BAR_GROUPING_UNSPECIFIED */;
  const visibleSeries = prepared.visibleSeries;
  const laneCount = placeSeriesAlongZ ? Math.max(visibleSeries.length, 1) : 1;
  const totalBarWidthPx = Math.max(xScale.bandwidth(), 1);
  const gapPx = totalBarWidthPx * 0.2;
  const clusterWidthPx = Math.max(totalBarWidthPx - gapPx, totalBarWidthPx * 0.4);
  const laneGapPx = placeSeriesAlongZ ? clusterWidthPx * 0.2 : 0;
  const laneClusterWidthPx = placeSeriesAlongZ ? Math.max(clusterWidthPx - laneGapPx, clusterWidthPx * 0.5) : clusterWidthPx;
  const laneDepthPx = placeSeriesAlongZ ? laneClusterWidthPx / Math.max(laneCount, 1) : clusterWidthPx;
  const laneDepthWorld = placeSeriesAlongZ ? Math.max(laneDepthPx * pxToWorldZ, MIN_BAR_THICKNESS) : baseBarDepth;
  const laneInnerPaddingWorld = placeSeriesAlongZ && !isClusteredMode ? Math.min(Math.max(laneDepthWorld * 0.15, MIN_BAR_THICKNESS * 0.5), Math.max(laneDepthWorld - MIN_BAR_THICKNESS, 0) * 0.5) : 0;
  const effectiveLaneDepthWorld = placeSeriesAlongZ ? Math.max(laneDepthWorld - laneInnerPaddingWorld * 2, MIN_BAR_THICKNESS) : baseBarDepth;
  const laneGapWorld = placeSeriesAlongZ ? Math.max(laneGapPx * pxToWorldZ, laneDepthWorld * 0.1) : 0;
  const outerGapWorld = placeSeriesAlongZ ? laneGapWorld : 0;
  const laneCentersWorld = placeSeriesAlongZ ? visibleSeries.map((_, idx) => outerGapWorld + laneDepthWorld / 2 + idx * (laneDepthWorld + laneGapWorld)) : [laneDepthWorld / 2];
  const seriesLaneMetas = placeSeriesAlongZ ? visibleSeries.map((seriesIndex, idx) => ({
    seriesIndex,
    label: (chart.series[seriesIndex]?.name ?? "").trim() || `Series ${idx + 1}`,
    centerZ: laneCentersWorld[idx] ?? laneDepthWorld / 2
  })) : [];
  const segments = [];
  let minXWorld = Number.POSITIVE_INFINITY;
  let maxXWorld = Number.NEGATIVE_INFINITY;
  let minZWorld = Number.POSITIVE_INFINITY;
  let maxZWorld = Number.NEGATIVE_INFINITY;
  let maxHeightWorld = 0;
  let minHeightWorld = 0;
  categories.forEach((category, categoryIndex) => {
    const catPx = xScale(category);
    if (catPx === undefined)
      return;
    const localCatPx = catPx - plotDims.x;
    const segmentsForCategory = prepared.segmentsByCategory[categoryIndex] ?? [];
    const visibleSegments = segmentsForCategory.filter((segment) => {
      const series = chart.series[segment.seriesIndex];
      if (!series)
        return false;
      if (pointHasNoFill(series, categoryIndex))
        return false;
      const fillColor = getPointFillColor(series, categoryIndex, segment.seriesIndex, themeMap);
      return !!fillColor;
    });
    const segmentCount = visibleSegments.length || 1;
    const singleBarWidthPx = clusterWidthPx / Math.max(segmentCount, 1);
    visibleSegments.forEach((segment, orderIdx) => {
      const series = chart.series[segment.seriesIndex];
      if (!series)
        return;
      const fillColor = getPointFillColor(series, categoryIndex, segment.seriesIndex, themeMap);
      if (!fillColor)
        return;
      const baseLaneIndex = placeSeriesAlongZ ? Math.max(0, visibleSeries.indexOf(segment.seriesIndex)) : isClusteredMode ? orderIdx : 0;
      const barWidthPx = placeSeriesAlongZ ? clusterWidthPx : isClusteredMode ? singleBarWidthPx : totalBarWidthPx;
      const innerOffsetPx = placeSeriesAlongZ ? (totalBarWidthPx - clusterWidthPx) / 2 : isClusteredMode ? (totalBarWidthPx - clusterWidthPx) / 2 + singleBarWidthPx * baseLaneIndex : 0;
      const yStartPx = yScale(segment.start);
      const yEndPx = yScale(segment.end);
      if (!Number.isFinite(yStartPx) || !Number.isFinite(yEndPx) || !Number.isFinite(barWidthPx)) {
        return;
      }
      const relStart = yStartPx - plotDims.y;
      const relEnd = yEndPx - plotDims.y;
      const worldStart = toWorldY(relStart);
      const worldEnd = toWorldY(relEnd);
      const barHeightWorld = Math.max(Math.abs(worldEnd - worldStart), MIN_BAR_HEIGHT);
      const barCenterWorldY = (worldStart + worldEnd) / 2;
      const barCenterPxX = localCatPx + innerOffsetPx + barWidthPx / 2;
      const barCenterWorldX = barCenterPxX * pxToWorldX;
      let barWidthWorld = Math.max(barWidthPx * pxToWorldX, MIN_BAR_THICKNESS);
      let barDepthWorld = placeSeriesAlongZ ? effectiveLaneDepthWorld : laneDepthWorld;
      let barCenterWorldZ = laneCentersWorld[baseLaneIndex] ?? laneCentersWorld[0] ?? effectiveLaneDepthWorld / 2;
      if (placeSeriesAlongZ && !isClusteredMode) {
        const squareSize = Math.max(Math.min(barWidthWorld, effectiveLaneDepthWorld), MIN_BAR_THICKNESS);
        barWidthWorld = squareSize;
        barDepthWorld = squareSize;
      }
      if (!placeSeriesAlongZ) {
        if (isClusteredMode) {
          barDepthWorld = barWidthWorld;
        } else {
          barDepthWorld = baseBarDepth;
        }
        barCenterWorldZ = barDepthWorld / 2;
      }
      segments.push({
        key: `${categoryIndex}-${segment.seriesIndex}-${orderIdx}`,
        seriesIndex: segment.seriesIndex,
        position: {
          x: barCenterWorldX,
          y: barCenterWorldY,
          z: barCenterWorldZ
        },
        size: {
          width: barWidthWorld,
          height: barHeightWorld,
          depth: barDepthWorld
        },
        materialKey: fillColor
      });
      const barMinX = barCenterWorldX - barWidthWorld / 2;
      const barMaxX = barCenterWorldX + barWidthWorld / 2;
      minXWorld = Math.min(minXWorld, barMinX);
      maxXWorld = Math.max(maxXWorld, barMaxX);
      maxHeightWorld = Math.max(maxHeightWorld, barCenterWorldY + barHeightWorld / 2);
      minHeightWorld = Math.min(minHeightWorld, barCenterWorldY - barHeightWorld / 2);
      const barMinZ = barCenterWorldZ - barDepthWorld / 2;
      const barMaxZ = barCenterWorldZ + barDepthWorld / 2;
      minZWorld = Math.min(minZWorld, barMinZ);
      maxZWorld = Math.max(maxZWorld, barMaxZ);
    });
  });
  if (!Number.isFinite(minXWorld) || !Number.isFinite(maxXWorld)) {
    minXWorld = 0;
    maxXWorld = WORLD_WIDTH;
  }
  const offsetX = Number.isFinite(minXWorld) ? minXWorld : 0;
  if (offsetX !== 0) {
    segments.forEach((segment) => {
      segment.position = {
        ...segment.position,
        x: segment.position.x - offsetX
      };
    });
    minXWorld -= offsetX;
    maxXWorld -= offsetX;
  }
  if (placeSeriesAlongZ && !isClusteredMode && segments.length > 0 && Number.isFinite(minZWorld) && Number.isFinite(maxZWorld)) {
    minZWorld -= laneInnerPaddingWorld;
    maxZWorld += laneInnerPaddingWorld;
  }
  if (!Number.isFinite(minZWorld) || !Number.isFinite(maxZWorld)) {
    minZWorld = 0;
    maxZWorld = placeSeriesAlongZ ? laneCentersWorld[laneCentersWorld.length - 1] ?? effectiveLaneDepthWorld : baseBarDepth;
  }
  const offsetZ = Number.isFinite(minZWorld) ? minZWorld : 0;
  if (offsetZ !== 0) {
    segments.forEach((segment) => {
      segment.position = {
        ...segment.position,
        z: segment.position.z - offsetZ
      };
    });
    seriesLaneMetas.forEach((lane) => {
      lane.centerZ -= offsetZ;
    });
    minZWorld -= offsetZ;
    maxZWorld -= offsetZ;
  }
  const chartDepth = Number.isFinite(maxZWorld) ? Math.max(maxZWorld, MIN_BAR_THICKNESS) : baseBarDepth;
  return {
    segments,
    bounds: {
      minX: minXWorld,
      maxX: maxXWorld,
      maxHeight: Math.max(maxHeightWorld, MIN_BAR_HEIGHT),
      minHeight: Math.min(minHeightWorld, 0)
    },
    barDepth: baseBarDepth,
    chartDepth,
    categoryCount: categories.length,
    seriesLanes: seriesLaneMetas,
    grouping,
    categories
  };
}
function drawBarChart3D(threeCtx, chart, scales, plotDims, themeMap, hiddenSeries) {
  const prepared = prepareBarChart3D(chart, scales, plotDims, themeMap, hiddenSeries);
  threeCtx.clear();
  if (prepared.segments.length === 0) {
    threeCtx.renderer.setScissorTest(false);
    return;
  }
  const materialCache = new Map;
  const renderer = threeCtx.renderer;
  const camera = threeCtx.camera;
  const { width: canvasWidth, height: canvasHeight } = threeCtx.dims;
  const dpr = 1;
  const viewportW = Math.max(1, canvasWidth * dpr);
  const viewportH = Math.max(1, canvasHeight * dpr);
  const prevViewport = renderer.getViewport(new Vector4);
  const prevScissor = renderer.getScissor(new Vector4);
  const prevScissorTest = renderer.getScissorTest();
  const prevAspect = camera.aspect;
  renderer.setViewport(0, 0, viewportW, viewportH);
  renderer.setScissor(0, 0, viewportW, viewportH);
  renderer.setScissorTest(true);
  if (viewportH > 0) {
    camera.aspect = canvasWidth / Math.max(canvasHeight, 1);
    camera.updateProjectionMatrix();
  }
  const { bounds, chartDepth, seriesLanes, grouping, categories } = prepared;
  const chartWidth = Math.max(bounds.maxX - bounds.minX, MIN_BAR_THICKNESS);
  const halfChartWidth = chartWidth * 0.5;
  const axisOriginX = -halfChartWidth;
  const axisBaseZ = 0;
  const depthExtent = Math.max(chartDepth, MIN_BAR_THICKNESS);
  const chartMinY = Math.min(bounds.minHeight, 0);
  const chartMaxY = Math.max(bounds.maxHeight, MIN_BAR_HEIGHT);
  const chartHeight = chartMaxY - chartMinY || MIN_BAR_HEIGHT;
  const xScale = scales.x;
  const yScale = scales.y;
  const pxToWorldX = pxToWorldScalar(plotDims.width, WORLD_WIDTH);
  const pxToWorldY = pxToWorldScalar(plotDims.height, WORLD_HEIGHT);
  const zeroCandidate = yScale(0);
  const zeroRel = Number.isFinite(zeroCandidate) ? zeroCandidate - plotDims.y : plotDims.height;
  const toWorldYValue = (value) => {
    const px = yScale(value);
    if (!Number.isFinite(px))
      return null;
    const rel = px - plotDims.y;
    return (zeroRel - rel) * pxToWorldY;
  };
  const totalBarWidthPx = Math.max(xScale.bandwidth(), 1);
  const categoryToWorldX = (category) => {
    const catPx = xScale(category);
    if (catPx === undefined)
      return null;
    const local = catPx - plotDims.x + totalBarWidthPx / 2;
    return local * pxToWorldX - bounds.minX;
  };
  const chartBaselineY = toWorldYValue(0) ?? 0;
  const originY = (chartMinY + chartMaxY) * 0.5;
  const originZ = chartDepth * 0.5;
  const translateY = (value) => value - originY;
  const translateZ = (value) => value - originZ;
  const barsGroup = new Group;
  const gridGroup = new Group;
  const axisGroup = new Group;
  const labelGroup = new Group;
  labelGroup.renderOrder = 20;
  const xAxisStyles = getAxisStyles(chart.xAxis, themeMap);
  const yAxisStyles = getAxisStyles(chart.yAxis, themeMap);
  const drawYGrid = !!chart.yAxis?.majorGridlines?.fill?.color;
  const yGridColor = yAxisStyles.gridLineColor ?? yAxisStyles.lineColor;
  const yTickFormatter = (() => {
    const nf = chart.yAxis?.numberFormatCode;
    const fallback = format("~s");
    return (value) => {
      if (nf) {
        try {
          return import_ssf3.default.format(nf, value);
        } catch {}
      }
      return fallback(value);
    };
  })();
  const axisMaterialX = new LineBasicMaterial({
    color: new Color3(xAxisStyles.lineColor ?? "#2563eb"),
    transparent: true,
    opacity: 0.9
  });
  const axisMaterialY = new LineBasicMaterial({
    color: new Color3(yAxisStyles.lineColor ?? "#1f2937"),
    transparent: true,
    opacity: 0.9
  });
  const axisMaterialZ = new LineBasicMaterial({
    color: new Color3(xAxisStyles.lineColor ?? "#2563eb"),
    transparent: true,
    opacity: 0.9
  });
  const gridMaterialY = new LineBasicMaterial({
    color: new Color3(yGridColor ?? "#cbdcfb"),
    transparent: true,
    opacity: 0.25
  });
  const floorGridMaterial = new LineBasicMaterial({
    color: new Color3("#dbeafe"),
    transparent: true,
    opacity: 0.2
  });
  const xAxisLine = new Line2(new BufferGeometry().setFromPoints([
    new Vector3(axisOriginX, translateY(chartBaselineY), translateZ(axisBaseZ)),
    new Vector3(axisOriginX + chartWidth, translateY(chartBaselineY), translateZ(axisBaseZ))
  ]), axisMaterialX.clone());
  xAxisLine.renderOrder = 5;
  axisGroup.add(xAxisLine);
  const zAxisLine = new Line2(new BufferGeometry().setFromPoints([
    new Vector3(axisOriginX, translateY(chartBaselineY), translateZ(axisBaseZ)),
    new Vector3(axisOriginX, translateY(chartBaselineY), translateZ(axisBaseZ + depthExtent))
  ]), axisMaterialZ.clone());
  zAxisLine.renderOrder = 5;
  axisGroup.add(zAxisLine);
  const yAxisLine = new Line2(new BufferGeometry().setFromPoints([
    new Vector3(axisOriginX, translateY(chartMinY), translateZ(axisBaseZ + depthExtent)),
    new Vector3(axisOriginX, translateY(chartMaxY), translateZ(axisBaseZ + depthExtent))
  ]), axisMaterialY.clone());
  yAxisLine.renderOrder = 5;
  axisGroup.add(yAxisLine);
  const yTicks = yScale.ticks(6);
  yTicks.forEach((tick) => {
    const yWorld = toWorldYValue(tick);
    if (yWorld === null)
      return;
    const isBaseline = Math.abs(tick) < 0.000001;
    if (drawYGrid && !isBaseline) {
      const frontLine = new Line2(new BufferGeometry().setFromPoints([
        new Vector3(axisOriginX, translateY(yWorld), translateZ(axisBaseZ)),
        new Vector3(axisOriginX + chartWidth, translateY(yWorld), translateZ(axisBaseZ))
      ]), gridMaterialY.clone());
      frontLine.renderOrder = -2;
      gridGroup.add(frontLine);
      const backLine = new Line2(new BufferGeometry().setFromPoints([
        new Vector3(axisOriginX, translateY(yWorld), translateZ(axisBaseZ + depthExtent)),
        new Vector3(axisOriginX + chartWidth, translateY(yWorld), translateZ(axisBaseZ + depthExtent))
      ]), gridMaterialY.clone());
      backLine.renderOrder = -2;
      gridGroup.add(backLine);
    }
    const tickLabel = createTextSprite(yTickFormatter(tick), {
      fontSize: 26,
      color: yAxisStyles.textColor ?? "#1f2933",
      weight: "500"
    });
    tickLabel.position.set(axisOriginX - Math.max(chartWidth, depthExtent) * 0.08, translateY(yWorld), translateZ(axisBaseZ - depthExtent * 0.05));
    labelGroup.add(tickLabel);
  });
  categories.forEach((category) => {
    const centerWorld = categoryToWorldX(category);
    if (centerWorld === null)
      return;
    const worldX = axisOriginX + centerWorld;
    const floorLine = new Line2(new BufferGeometry().setFromPoints([
      new Vector3(worldX, translateY(chartBaselineY), translateZ(axisBaseZ)),
      new Vector3(worldX, translateY(chartBaselineY), translateZ(axisBaseZ + depthExtent))
    ]), floorGridMaterial.clone());
    floorLine.renderOrder = -2;
    gridGroup.add(floorLine);
    const label = createTextSprite(String(category), {
      fontSize: 26,
      color: xAxisStyles.textColor ?? "#111827"
    });
    label.position.set(worldX, translateY(chartBaselineY - Math.min(chartHeight * 0.12, 0.5)), translateZ(axisBaseZ - depthExtent * 0.06));
    labelGroup.add(label);
  });
  if (grouping === 0 /* BAR_GROUPING_UNSPECIFIED */ && seriesLanes.length) {
    const laneDepthBySeries = new Map;
    prepared.segments.forEach((segment) => {
      if (!laneDepthBySeries.has(segment.seriesIndex)) {
        laneDepthBySeries.set(segment.seriesIndex, segment.size.depth);
      }
    });
    const boundaryValues = new Set;
    seriesLanes.forEach((lane) => {
      const laneDepth = laneDepthBySeries.get(lane.seriesIndex) ?? 0;
      const worldZ = axisBaseZ + lane.centerZ;
      const label = createTextSprite(lane.label, {
        fontSize: 24,
        color: xAxisStyles.textColor ?? "#111827",
        weight: "500"
      });
      label.position.set(axisOriginX + chartWidth + Math.max(chartWidth, depthExtent) * 0.06, translateY(chartBaselineY - Math.min(chartHeight * 0.08, 0.4)), translateZ(worldZ));
      labelGroup.add(label);
      if (laneDepth > 0) {
        boundaryValues.add(worldZ - laneDepth / 2);
        boundaryValues.add(worldZ + laneDepth / 2);
      }
    });
    const laneBoundaryMaterial = floorGridMaterial.clone();
    laneBoundaryMaterial.opacity = 0.3;
    Array.from(boundaryValues).sort((a, b) => a - b).forEach((boundary) => {
      const boundaryLine = new Line2(new BufferGeometry().setFromPoints([
        new Vector3(axisOriginX, translateY(chartBaselineY), translateZ(boundary)),
        new Vector3(axisOriginX + chartWidth, translateY(chartBaselineY), translateZ(boundary))
      ]), laneBoundaryMaterial.clone());
      boundaryLine.renderOrder = -2;
      gridGroup.add(boundaryLine);
    });
  }
  prepared.segments.forEach((segment) => {
    const geometry = new BoxGeometry(segment.size.width, segment.size.height, segment.size.depth);
    const material = getPastelMaterial(segment.materialKey, materialCache);
    const mesh = new Mesh(geometry, material);
    mesh.castShadow = true;
    mesh.receiveShadow = true;
    mesh.position.set(axisOriginX + segment.position.x, translateY(segment.position.y), translateZ(axisBaseZ + segment.position.z));
    barsGroup.add(mesh);
  });
  threeCtx.chartGroup.add(gridGroup);
  threeCtx.chartGroup.add(barsGroup);
  threeCtx.chartGroup.add(axisGroup);
  threeCtx.chartGroup.add(labelGroup);
  const savedRotation = threeCtx.chartGroup.rotation.clone();
  const hasUserRotation = Math.abs(savedRotation.x) > 0.00001 || Math.abs(savedRotation.y) > 0.00001 || Math.abs(savedRotation.z) > 0.00001;
  if (hasUserRotation) {
    threeCtx.chartGroup.rotation.set(0, 0, 0);
  }
  threeCtx.chartGroup.updateMatrixWorld(true);
  const contentObject = CAMERA_FIT_INCLUDE_LABELS ? threeCtx.chartGroup : barsGroup;
  const boundingBox = new Box3().setFromObject(contentObject);
  const boxCenter = new Vector3;
  const boxSize = new Vector3;
  boundingBox.getCenter(boxCenter);
  boundingBox.getSize(boxSize);
  if (boxSize.x === 0 && boxSize.y === 0 && boxSize.z === 0) {
    boxSize.set(Math.max(chartWidth, 1), Math.max(chartHeight, 1), Math.max(depthExtent, 1));
  }
  const halfFovY = MathUtils.degToRad(camera.fov * 0.5);
  const safeHalfFovY = Math.max(0.001, halfFovY);
  const aspect = camera.aspect || 1;
  const halfFovX = Math.atan(Math.tan(safeHalfFovY) * aspect);
  const safeHalfFovX = Math.max(0.001, halfFovX);
  const tanHalfFovY = Math.max(Math.tan(safeHalfFovY), 0.0001);
  const tanHalfFovX = Math.max(Math.tan(safeHalfFovX), 0.0001);
  const halfSize = boxSize.clone().multiplyScalar(0.5);
  halfSize.x = Math.max(halfSize.x * (1 + CAMERA_PADDING_RATIO), MIN_BAR_THICKNESS);
  halfSize.y = Math.max(halfSize.y * (1 + CAMERA_PADDING_RATIO), MIN_BAR_HEIGHT);
  halfSize.z = Math.max(halfSize.z * (1 + CAMERA_PADDING_RATIO), MIN_BAR_THICKNESS);
  const target = boxCenter.clone();
  const viewDir = CAMERA_VIEW_DIR.clone().normalize();
  const lookDir = viewDir.clone().negate();
  let upHint = new Vector3(0, 1, 0);
  if (Math.abs(lookDir.dot(upHint)) > 0.99) {
    upHint = new Vector3(1, 0, 0);
  }
  let right = new Vector3().crossVectors(upHint, lookDir);
  if (right.lengthSq() < 0.000001) {
    upHint = new Vector3(0, 0, 1);
    right = new Vector3().crossVectors(upHint, lookDir);
  }
  right.normalize();
  const cameraUp = new Vector3().crossVectors(lookDir, right).normalize();
  const offsets = [];
  [-1, 1].forEach((sx) => {
    [-1, 1].forEach((sy) => {
      [-1, 1].forEach((sz) => {
        offsets.push(new Vector3(halfSize.x * sx, halfSize.y * sy, halfSize.z * sz));
      });
    });
  });
  const corners = offsets.map((offset) => target.clone().add(offset));
  const diag = halfSize.length() * 2;
  const setCameraForDistance = (dist) => {
    camera.position.copy(target).addScaledVector(viewDir, dist);
    if (CAMERA_HORIZONTAL_OFFSET !== 0) {
      camera.position.addScaledVector(right, CAMERA_HORIZONTAL_OFFSET);
    }
    if (CAMERA_PAN_OFFSET !== 0) {
      camera.position.addScaledVector(right, CAMERA_PAN_OFFSET);
    }
    const shiftedTarget = CAMERA_PAN_OFFSET ? target.clone().addScaledVector(right, CAMERA_PAN_OFFSET) : target;
    camera.up.copy(cameraUp);
    camera.near = 0.1;
    camera.far = Math.max(camera.near + 1, dist + diag * 4);
    camera.lookAt(shiftedTarget);
    camera.updateMatrixWorld(true);
    camera.updateProjectionMatrix();
  };
  const evaluateDistance = (dist) => {
    setCameraForDistance(dist);
    const shiftedTarget = CAMERA_PAN_OFFSET ? target.clone().addScaledVector(right, CAMERA_PAN_OFFSET) : target;
    camera.lookAt(shiftedTarget);
    camera.updateMatrixWorld(true);
    camera.updateProjectionMatrix();
    let maxAbsX = 0;
    let maxAbsY = 0;
    let minDepth = Number.POSITIVE_INFINITY;
    let maxDepth = 0;
    corners.forEach((corner) => {
      const ndc = corner.clone().project(camera);
      maxAbsX = Math.max(maxAbsX, Math.abs(ndc.x));
      maxAbsY = Math.max(maxAbsY, Math.abs(ndc.y));
      const cameraSpace = corner.clone().applyMatrix4(camera.matrixWorldInverse);
      const depth = -cameraSpace.z;
      minDepth = Math.min(minDepth, depth);
      maxDepth = Math.max(maxDepth, depth);
    });
    const fits = maxAbsX <= 1 && maxAbsY <= 1 && minDepth > 0;
    return { fits, maxAbsX, maxAbsY, minDepth, maxDepth };
  };
  const initialEstimate = Math.max(halfSize.x / tanHalfFovX, halfSize.y / tanHalfFovY) + halfSize.z;
  let lower = 0.1;
  let upper = Math.max(initialEstimate, lower * 4);
  let upperEval = evaluateDistance(upper);
  let expandIterations = 0;
  while (!upperEval.fits && expandIterations < 24) {
    upper *= 2;
    upperEval = evaluateDistance(upper);
    expandIterations += 1;
  }
  let bestEval = upperEval;
  for (let i = 0;i < 28; i += 1) {
    const mid = (lower + upper) * 0.5;
    const evalMid = evaluateDistance(mid);
    if (evalMid.fits) {
      upper = mid;
      bestEval = evalMid;
    } else {
      lower = mid;
    }
  }
  const distance = upper;
  setCameraForDistance(distance);
  const finalTarget = CAMERA_PAN_OFFSET ? target.clone().addScaledVector(right, CAMERA_PAN_OFFSET) : target;
  bestEval = evaluateDistance(distance);
  const near = Math.max(0.1, Math.min(bestEval.minDepth * 0.8, bestEval.minDepth - 0.05));
  const far = Math.max(near + 1, bestEval.maxDepth * 1.2);
  camera.near = near;
  camera.far = far;
  camera.lookAt(finalTarget);
  camera.updateMatrixWorld(true);
  camera.updateProjectionMatrix();
  if (hasUserRotation) {
    threeCtx.chartGroup.rotation.copy(savedRotation);
    threeCtx.chartGroup.updateMatrixWorld(true);
  }
  renderer.render(threeCtx.scene, camera);
  renderer.setViewport(prevViewport);
  renderer.setScissor(prevScissor);
  renderer.setScissorTest(prevScissorTest);
  if (!prevScissorTest) {
    renderer.setScissorTest(false);
  }
  camera.aspect = prevAspect;
  camera.updateProjectionMatrix();
}

// node_modules/@oai/granola/dist/draw-utils/chart-3d/draw-pie-3d.js
var CAMERA_PADDING_RATIO2 = 0.25;
var CAMERA_VIEW_DIR2 = new Vector3(-0.25, 0.2, 0.85).normalize();
var CAMERA_HORIZONTAL_OFFSET2 = 0;
var CAMERA_PAN_OFFSET2 = 0;
var MIN_THETA_LENGTH = 0.001;
var DEFAULT_RADIAL_SEGMENTS = 64;
function drawPieChart3D(threeCtx, chart, plotDims, themeMap, hiddenSeriesIndices) {
  const series = chart.series[0];
  if (!series) {
    clearViewport(threeCtx);
    return;
  }
  if (hiddenSeriesIndices?.has(0)) {
    clearViewport(threeCtx);
    return;
  }
  const values = series.values ?? [];
  const total = sum(values);
  if (!Number.isFinite(total) || total === 0) {
    clearViewport(threeCtx);
    return;
  }
  const radiusPx = Math.max(Math.min(plotDims.width, plotDims.height) / 2, 1);
  const diameterPx = radiusPx * 2;
  const pxToWorld = pxToWorldScalar(Math.max(diameterPx, 1), Math.min(WORLD_WIDTH, WORLD_DEPTH));
  const radiusWorld = Math.max(radiusPx * pxToWorld, MIN_BAR_THICKNESS * 2);
  const thicknessWorld = Math.max(Math.min(radiusWorld * 0.35, WORLD_HEIGHT * 0.6), MIN_BAR_THICKNESS * 2);
  const pieStartAngle = (chart.pieOptions?.firstSliceAngle ?? 0) / 360 * Math.PI * 2;
  const pieGenerator = pie_default().sort(null).startAngle(pieStartAngle).endAngle(pieStartAngle + Math.PI * 2);
  const arcs = pieGenerator(values).filter((d) => Number.isFinite(d.value) && d.value !== 0);
  if (arcs.length === 0) {
    clearViewport(threeCtx);
    return;
  }
  threeCtx.clear();
  const materialCache = new Map;
  const slicesGroup = new Group;
  slicesGroup.name = "pie3dSlices";
  arcs.forEach((arcDatum, idx) => {
    const pointIndex = arcDatum.index ?? idx;
    if (pointHasNoFill(series, pointIndex)) {
      return;
    }
    const color2 = getPointFillColor(series, pointIndex, 0, themeMap, pointIndex);
    if (!color2)
      return;
    const thetaLengthRaw = arcDatum.endAngle - arcDatum.startAngle;
    const thetaLength = Math.max(Math.abs(thetaLengthRaw), MIN_THETA_LENGTH);
    if (!Number.isFinite(thetaLength))
      return;
    const thetaStart = normalizeAngle(Math.PI / 2 - arcDatum.endAngle);
    const radialSegments = Math.max(DEFAULT_RADIAL_SEGMENTS, Math.ceil(thetaLength / (Math.PI / 32)));
    const geometry = new CylinderGeometry(radiusWorld, radiusWorld, thicknessWorld, radialSegments, 1, false, thetaStart, thetaLength);
    const material = getPastelMaterial(color2, materialCache);
    const mesh = new Mesh(geometry, material);
    mesh.castShadow = true;
    mesh.receiveShadow = true;
    slicesGroup.add(mesh);
  });
  if (slicesGroup.children.length === 0) {
    clearViewport(threeCtx);
    return;
  }
  threeCtx.chartGroup.add(slicesGroup);
  fitCameraToGroup(threeCtx, slicesGroup);
}
function normalizeAngle(angle) {
  const tau3 = Math.PI * 2;
  const normalized = angle % tau3;
  return normalized < 0 ? normalized + tau3 : normalized;
}
function clearViewport(threeCtx) {
  threeCtx.clear();
  threeCtx.renderer.setScissorTest(false);
}
function fitCameraToGroup(threeCtx, target) {
  const renderer = threeCtx.renderer;
  const camera = threeCtx.camera;
  const { width: canvasWidth, height: canvasHeight } = threeCtx.dims;
  const dpr = 1;
  const viewportW = Math.max(1, canvasWidth * dpr);
  const viewportH = Math.max(1, canvasHeight * dpr);
  const prevViewport = renderer.getViewport(new Vector4);
  const prevScissor = renderer.getScissor(new Vector4);
  const prevScissorTest = renderer.getScissorTest();
  const prevAspect = camera.aspect;
  renderer.setViewport(0, 0, viewportW, viewportH);
  renderer.setScissor(0, 0, viewportW, viewportH);
  renderer.setScissorTest(true);
  if (viewportH > 0) {
    camera.aspect = canvasWidth / Math.max(canvasHeight, 1);
    camera.updateProjectionMatrix();
  }
  const savedRotation = threeCtx.chartGroup.rotation.clone();
  const hasUserRotation = Math.abs(savedRotation.x) > 0.00001 || Math.abs(savedRotation.y) > 0.00001 || Math.abs(savedRotation.z) > 0.00001;
  if (hasUserRotation) {
    threeCtx.chartGroup.rotation.set(0, 0, 0);
  }
  threeCtx.chartGroup.updateMatrixWorld(true);
  const boundingBox = new Box3().setFromObject(target);
  const boxCenter = new Vector3;
  const boxSize = new Vector3;
  boundingBox.getCenter(boxCenter);
  boundingBox.getSize(boxSize);
  if (boxSize.x === 0 && boxSize.y === 0 && boxSize.z === 0) {
    boxSize.set(Math.max(WORLD_WIDTH * 0.5, MIN_BAR_THICKNESS), Math.max(MIN_BAR_HEIGHT, 0.2), Math.max(WORLD_DEPTH * 0.5, MIN_BAR_THICKNESS));
  }
  const halfFovY = MathUtils.degToRad(camera.fov * 0.5);
  const safeHalfFovY = Math.max(0.001, halfFovY);
  const aspect = camera.aspect || 1;
  const halfFovX = Math.atan(Math.tan(safeHalfFovY) * aspect);
  const safeHalfFovX = Math.max(0.001, halfFovX);
  const tanHalfFovY = Math.max(Math.tan(safeHalfFovY), 0.0001);
  const tanHalfFovX = Math.max(Math.tan(safeHalfFovX), 0.0001);
  const halfSize = boxSize.clone().multiplyScalar(0.5);
  halfSize.x = Math.max(halfSize.x * (1 + CAMERA_PADDING_RATIO2), MIN_BAR_THICKNESS);
  halfSize.y = Math.max(halfSize.y * (1 + CAMERA_PADDING_RATIO2), MIN_BAR_HEIGHT);
  halfSize.z = Math.max(halfSize.z * (1 + CAMERA_PADDING_RATIO2), MIN_BAR_THICKNESS);
  const targetCenter = boxCenter.clone();
  const viewDir = CAMERA_VIEW_DIR2.clone().normalize();
  const lookDir = viewDir.clone().negate();
  let upHint = new Vector3(0, 1, 0);
  if (Math.abs(lookDir.dot(upHint)) > 0.99) {
    upHint = new Vector3(1, 0, 0);
  }
  let right = new Vector3().crossVectors(upHint, lookDir);
  if (right.lengthSq() < 0.000001) {
    upHint = new Vector3(0, 0, 1);
    right = new Vector3().crossVectors(upHint, lookDir);
  }
  right.normalize();
  const cameraUp = new Vector3().crossVectors(lookDir, right).normalize();
  const offsets = [];
  [-1, 1].forEach((sx) => {
    [-1, 1].forEach((sy) => {
      [-1, 1].forEach((sz) => {
        offsets.push(new Vector3(halfSize.x * sx, halfSize.y * sy, halfSize.z * sz));
      });
    });
  });
  const corners = offsets.map((offset) => targetCenter.clone().add(offset));
  const diag = halfSize.length() * 2;
  const setCameraForDistance = (dist) => {
    camera.position.copy(targetCenter).addScaledVector(viewDir, dist);
    if (CAMERA_HORIZONTAL_OFFSET2 !== 0) {
      camera.position.addScaledVector(right, CAMERA_HORIZONTAL_OFFSET2);
    }
    if (CAMERA_PAN_OFFSET2 !== 0) {
      camera.position.addScaledVector(right, CAMERA_PAN_OFFSET2);
    }
    const shiftedTarget = CAMERA_PAN_OFFSET2 !== 0 ? targetCenter.clone().addScaledVector(right, CAMERA_PAN_OFFSET2) : targetCenter;
    camera.up.copy(cameraUp);
    camera.near = 0.1;
    camera.far = Math.max(camera.near + 1, dist + diag * 4);
    camera.lookAt(shiftedTarget);
    camera.updateMatrixWorld(true);
    camera.updateProjectionMatrix();
  };
  const evaluateDistance = (dist) => {
    setCameraForDistance(dist);
    const shiftedTarget = CAMERA_PAN_OFFSET2 !== 0 ? targetCenter.clone().addScaledVector(right, CAMERA_PAN_OFFSET2) : targetCenter;
    camera.lookAt(shiftedTarget);
    camera.updateMatrixWorld(true);
    camera.updateProjectionMatrix();
    let maxAbsX = 0;
    let maxAbsY = 0;
    let minDepth = Number.POSITIVE_INFINITY;
    let maxDepth = 0;
    corners.forEach((corner) => {
      const ndc = corner.clone().project(camera);
      maxAbsX = Math.max(maxAbsX, Math.abs(ndc.x));
      maxAbsY = Math.max(maxAbsY, Math.abs(ndc.y));
      const cameraSpace = corner.clone().applyMatrix4(camera.matrixWorldInverse);
      const depth = -cameraSpace.z;
      minDepth = Math.min(minDepth, depth);
      maxDepth = Math.max(maxDepth, depth);
    });
    const fits = maxAbsX <= 1 && maxAbsY <= 1 && minDepth > 0;
    return { fits, maxAbsX, maxAbsY, minDepth, maxDepth };
  };
  const initialEstimate = Math.max(halfSize.x / tanHalfFovX, halfSize.y / tanHalfFovY) + halfSize.z;
  let lower = 0.1;
  let upper = Math.max(initialEstimate, lower * 4);
  let upperEval = evaluateDistance(upper);
  let expandIterations = 0;
  while (!upperEval.fits && expandIterations < 24) {
    upper *= 2;
    upperEval = evaluateDistance(upper);
    expandIterations += 1;
  }
  let bestEval = upperEval;
  for (let i = 0;i < 28; i += 1) {
    const mid = (lower + upper) * 0.5;
    const evalMid = evaluateDistance(mid);
    if (evalMid.fits) {
      upper = mid;
      bestEval = evalMid;
    } else {
      lower = mid;
    }
  }
  const distance = upper;
  setCameraForDistance(distance);
  const finalTarget = CAMERA_PAN_OFFSET2 !== 0 ? targetCenter.clone().addScaledVector(right, CAMERA_PAN_OFFSET2) : targetCenter;
  bestEval = evaluateDistance(distance);
  const near = Math.max(0.1, Math.min(bestEval.minDepth * 0.8, bestEval.minDepth - 0.05));
  const far = Math.max(near + 1, bestEval.maxDepth * 1.2);
  camera.near = near;
  camera.far = far;
  camera.lookAt(finalTarget);
  camera.updateMatrixWorld(true);
  camera.updateProjectionMatrix();
  if (hasUserRotation) {
    threeCtx.chartGroup.rotation.copy(savedRotation);
    threeCtx.chartGroup.updateMatrixWorld(true);
  }
  renderer.render(threeCtx.scene, camera);
  renderer.setViewport(prevViewport);
  renderer.setScissor(prevScissor);
  renderer.setScissorTest(prevScissorTest);
  if (!prevScissorTest) {
    renderer.setScissorTest(false);
  }
  camera.aspect = prevAspect;
  camera.updateProjectionMatrix();
}

// node_modules/@oai/granola/dist/draw-utils/chart/prepare-line-data.js
function getCategories3(chart) {
  if (chart.categories.length > 0) {
    return chart.categories;
  }
  const firstSeriesCategories = chart.series[0]?.categories ?? [];
  if (firstSeriesCategories.length > 0) {
    return firstSeriesCategories;
  }
  return [];
}
function prepareLineData(chart, hiddenSeriesIndices) {
  const categories = getCategories3(chart);
  const visibleSeries = chart.series.map((_, idx) => idx).filter((idx) => !hiddenSeriesIndices?.has(idx));
  const grouping = chart.lineOptions?.grouping;
  const mode = grouping === 2 /* LINE_GROUPING_STACKED */ ? "stacked" : grouping === 3 /* LINE_GROUPING_PERCENT_STACKED */ ? "percent" : "standard";
  const layers = visibleSeries.map((seriesIndex) => ({
    seriesIndex,
    values: categories.map(() => 0),
    tuples: categories.map(() => ({ start: 0, end: 0 }))
  }));
  if (mode === "standard" || visibleSeries.length === 0) {
    categories.forEach((_, categoryIndex) => {
      visibleSeries.forEach((seriesIndex) => {
        const layer = layers.find((l) => l.seriesIndex === seriesIndex);
        if (!layer)
          return;
        const raw = chart.series[seriesIndex]?.values[categoryIndex] ?? 0;
        const value = Number.isFinite(raw) ? raw : 0;
        layer.values[categoryIndex] = value;
        layer.tuples[categoryIndex] = { start: 0, end: value };
      });
    });
    return {
      categories,
      visibleSeries,
      mode,
      layers
    };
  }
  const records = categories.map((_, categoryIndex) => {
    const record = {};
    visibleSeries.forEach((seriesIndex) => {
      const series = chart.series[seriesIndex];
      const raw = series?.values[categoryIndex] ?? 0;
      record[String(seriesIndex)] = Number.isFinite(raw) ? raw : 0;
    });
    return record;
  });
  const stackGenerator = stack_default().keys(visibleSeries.map((seriesIndex) => String(seriesIndex))).value((d, key) => d[key] ?? 0).order(none_default2);
  if (mode === "percent") {
    stackGenerator.offset(expand_default);
  } else {
    stackGenerator.offset(diverging_default);
  }
  const layerMap = new Map(layers.map((layer) => [layer.seriesIndex, layer]));
  const stacks = stackGenerator(records);
  stacks.forEach((stackLayer) => {
    const seriesIndex = Number.parseInt(stackLayer.key, 10);
    const layer = layerMap.get(seriesIndex);
    if (!layer)
      return;
    categories.forEach((_, categoryIndex) => {
      const tuple = stackLayer[categoryIndex];
      if (!tuple)
        return;
      const start = Number.isFinite(tuple[0]) ? tuple[0] : 0;
      const end = Number.isFinite(tuple[1]) ? tuple[1] : start;
      layer.tuples[categoryIndex] = { start, end };
      layer.values[categoryIndex] = end;
    });
  });
  return {
    categories,
    visibleSeries,
    mode,
    layers
  };
}

// node_modules/@oai/granola/dist/models/presentation/charts/trendline-render-cache.js
function isFiniteNumber(value) {
  return typeof value === "number" && Number.isFinite(value);
}
function formatNum(value) {
  const abs2 = Math.abs(value);
  const digits = abs2 >= 1000 ? 0 : abs2 >= 100 ? 1 : abs2 >= 10 ? 2 : 3;
  return value.toFixed(digits);
}
function computeRSquared(points, evalY) {
  if (points.length < 2)
    return;
  const ys = points.map((p) => p.y);
  const yMean = ys.reduce((a, b) => a + b, 0) / ys.length;
  let ssTot = 0;
  let ssRes = 0;
  for (const p of points) {
    const yHat = evalY(p.x);
    ssTot += (p.y - yMean) ** 2;
    ssRes += (p.y - yHat) ** 2;
  }
  if (ssTot <= 0.000000000001)
    return;
  const r2 = 1 - ssRes / ssTot;
  return Number.isFinite(r2) ? Math.max(0, Math.min(1, r2)) : undefined;
}
function fitLinear(points, intercept) {
  if (points.length < 2)
    return null;
  if (isFiniteNumber(intercept)) {
    let sumXX2 = 0;
    let sumXy = 0;
    for (const p of points) {
      sumXX2 += p.x * p.x;
      sumXy += p.x * (p.y - intercept);
    }
    if (Math.abs(sumXX2) < 0.000000000001)
      return null;
    const a2 = sumXy / sumXX2;
    const b2 = intercept;
    const evalY2 = (x2) => a2 * x2 + b2;
    const rSquared2 = computeRSquared(points, evalY2);
    return {
      evalY: evalY2,
      equation: `y = ${formatNum(a2)}x + ${formatNum(b2)}`,
      rSquared: rSquared2
    };
  }
  const n = points.length;
  let sumX = 0;
  let sumY = 0;
  let sumXX = 0;
  let sumXY = 0;
  for (const p of points) {
    sumX += p.x;
    sumY += p.y;
    sumXX += p.x * p.x;
    sumXY += p.x * p.y;
  }
  const denom = n * sumXX - sumX * sumX;
  if (Math.abs(denom) < 0.000000000001)
    return null;
  const a = (n * sumXY - sumX * sumY) / denom;
  const b = (sumY - a * sumX) / n;
  const evalY = (x2) => a * x2 + b;
  const rSquared = computeRSquared(points, evalY);
  return {
    evalY,
    equation: `y = ${formatNum(a)}x + ${formatNum(b)}`,
    rSquared
  };
}
function fitLogarithmic(points, intercept) {
  const filtered = points.filter((p) => p.x > 0);
  if (filtered.length < 2)
    return null;
  const transformed = filtered.map((p) => ({ x: Math.log(p.x), y: p.y }));
  const linear3 = fitLinear(transformed, isFiniteNumber(intercept) ? intercept : undefined);
  if (!linear3)
    return null;
  const evalY = (x2) => x2 > 0 ? linear3.evalY(Math.log(x2)) : Number.NaN;
  const rSquared = computeRSquared(filtered, evalY);
  const match = /y\s*=\s*([-\d.]+)x\s*\+\s*([-\d.]+)/.exec(linear3.equation);
  const a = match ? Number(match[1]) : undefined;
  const b = match ? Number(match[2]) : undefined;
  const eqA = isFiniteNumber(a) ? formatNum(a) : "?";
  const eqB = isFiniteNumber(b) ? formatNum(b) : "?";
  return {
    evalY,
    equation: `y = ${eqA}ln(x) + ${eqB}`,
    rSquared
  };
}
function solveLinearSystem(matrix, rhs) {
  const n = matrix.length;
  const M = matrix.map((row, i) => [...row, rhs[i]]);
  for (let i = 0;i < n; i++) {
    let pivot = i;
    for (let r = i + 1;r < n; r++) {
      if (Math.abs(M[r][i]) > Math.abs(M[pivot][i]))
        pivot = r;
    }
    if (Math.abs(M[pivot][i]) < 0.000000000001)
      return null;
    if (pivot !== i)
      [M[i], M[pivot]] = [M[pivot], M[i]];
    const div = M[i][i];
    for (let c = i;c < n + 1; c++)
      M[i][c] = M[i][c] / div;
    for (let r = 0;r < n; r++) {
      if (r === i)
        continue;
      const factor = M[r][i];
      for (let c = i;c < n + 1; c++) {
        M[r][c] = M[r][c] - factor * M[i][c];
      }
    }
  }
  return M.map((row) => row[n]);
}
function fitPolynomial(points, order, intercept) {
  const clampedOrder = Math.max(2, Math.min(6, Math.floor(order)));
  const nCoeffs = clampedOrder + 1;
  if (points.length < nCoeffs)
    return null;
  const fixedC0 = isFiniteNumber(intercept) ? intercept : undefined;
  const unknowns = fixedC0 === undefined ? nCoeffs : nCoeffs - 1;
  const A = Array.from({ length: unknowns }, () => Array(unknowns).fill(0));
  const B = Array(unknowns).fill(0);
  for (const p of points) {
    const xPows = Array(nCoeffs * 2).fill(0);
    xPows[0] = 1;
    for (let i = 1;i < xPows.length; i++)
      xPows[i] = xPows[i - 1] * p.x;
    const yAdj = fixedC0 === undefined ? p.y : p.y - fixedC0;
    for (let row = 0;row < unknowns; row++) {
      const rowA = A[row];
      for (let col = 0;col < unknowns; col++) {
        const powIdx = fixedC0 === undefined ? row + col : row + col + 2;
        rowA[col] = rowA[col] + xPows[powIdx];
      }
      const powY = fixedC0 === undefined ? row : row + 1;
      B[row] += yAdj * xPows[powY];
    }
  }
  const solved = solveLinearSystem(A, B);
  if (!solved)
    return null;
  const coeffs = fixedC0 === undefined ? solved : [fixedC0, ...solved];
  const evalY = (x2) => {
    let y2 = 0;
    let pow2 = 1;
    for (const c of coeffs) {
      y2 += c * pow2;
      pow2 *= x2;
    }
    return y2;
  };
  const rSquared = computeRSquared(points, evalY);
  const terms = [];
  coeffs.forEach((c, i) => {
    if (!Number.isFinite(c))
      return;
    if (i === 0) {
      terms.push(formatNum(c));
      return;
    }
    const sign2 = c >= 0 ? "+" : "-";
    const abs2 = Math.abs(c);
    const coef = formatNum(abs2);
    const power = i === 1 ? "x" : `x^${i}`;
    terms.push(`${sign2} ${coef}${power}`);
  });
  const equation = `y = ${terms.join(" ")}`;
  return { coeffs, evalY, equation, rSquared };
}
function computeMovingAverage(points, period) {
  const p = Math.max(2, Math.floor(period));
  const ma = [];
  for (let i = 0;i < points.length; i++) {
    const start = Math.max(0, i - p + 1);
    const window2 = points.slice(start, i + 1);
    const avg = window2.reduce((acc, pt) => acc + pt.y, 0) / window2.length;
    ma.push({ x: points[i].x, y: avg });
  }
  return ma;
}
function sampleCurve(xMin, xMax, samples, evalY) {
  const n = Math.max(2, Math.floor(samples));
  if (!Number.isFinite(xMin) || !Number.isFinite(xMax) || xMax === xMin) {
    return [];
  }
  const pts = [];
  for (let i = 0;i < n; i++) {
    const t = i / (n - 1);
    const x2 = xMin + t * (xMax - xMin);
    const y2 = evalY(x2);
    if (!Number.isFinite(x2) || !Number.isFinite(y2))
      continue;
    pts.push({ x: x2, y: y2 });
  }
  return pts;
}
function computeTrendlinePaths(args) {
  const type = args.type;
  const rawPoints = args.points.filter((p) => isFiniteNumber(p.x) && isFiniteNumber(p.y));
  if (rawPoints.length < 2)
    return null;
  const xVals = rawPoints.map((p) => p.x);
  const xDataMin = Math.min(...xVals);
  const xDataMax = Math.max(...xVals);
  const forward = isFiniteNumber(args.forecastForward) ? args.forecastForward : 0;
  const backward = isFiniteNumber(args.forecastBackward) ? args.forecastBackward : 0;
  const xMin = xDataMin - backward;
  const xMax = xDataMax + forward;
  const wantsLabel = Boolean(args.displayEquation) || Boolean(args.displayRSquared);
  if (type === "movingAverage") {
    const period = isFiniteNumber(args.movingAveragePeriod) ? args.movingAveragePeriod : 2;
    const points2 = computeMovingAverage(rawPoints, period);
    return {
      type,
      points: points2,
      label: wantsLabel ? { text: `Moving average (period = ${Math.floor(period)})` } : undefined
    };
  }
  if (type === "polynomial") {
    const order = isFiniteNumber(args.polynomialOrder) ? args.polynomialOrder : 2;
    const fit2 = fitPolynomial(rawPoints, order, args.intercept);
    if (!fit2)
      return null;
    const points2 = sampleCurve(xMin, xMax, 64, fit2.evalY);
    const label2 = wantsLabel ? {
      text: [
        args.displayEquation ? fit2.equation : undefined,
        args.displayRSquared && fit2.rSquared !== undefined ? `R^2 = ${formatNum(fit2.rSquared)}` : undefined
      ].filter((v) => typeof v === "string" && v.length > 0).join(`
`),
      rSquared: fit2.rSquared
    } : undefined;
    return { type, points: points2, label: label2 };
  }
  if (type === "logarithmic") {
    const fit2 = fitLogarithmic(rawPoints, args.intercept);
    if (!fit2)
      return null;
    const points2 = sampleCurve(xMin, xMax, 64, fit2.evalY);
    const label2 = wantsLabel ? {
      text: [
        args.displayEquation ? fit2.equation : undefined,
        args.displayRSquared && fit2.rSquared !== undefined ? `R^2 = ${formatNum(fit2.rSquared)}` : undefined
      ].filter((v) => typeof v === "string" && v.length > 0).join(`
`),
      rSquared: fit2.rSquared
    } : undefined;
    return { type, points: points2, label: label2 };
  }
  const fit = fitLinear(rawPoints, args.intercept);
  if (!fit)
    return null;
  const points = sampleCurve(xMin, xMax, 64, fit.evalY);
  const label = wantsLabel ? {
    text: [
      args.displayEquation ? fit.equation : undefined,
      args.displayRSquared && fit.rSquared !== undefined ? `R^2 = ${formatNum(fit.rSquared)}` : undefined
    ].filter((v) => typeof v === "string" && v.length > 0).join(`
`),
    rSquared: fit.rSquared
  } : undefined;
  return { type, points, label };
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-trendlines.js
function resolveTrendlineStroke(ctx, chart, series, seriesIndex, trendline, themeMap) {
  const base = getSeriesColor(series, seriesIndex, themeMap) ?? "#666666";
  const stroke = trendline?.stroke;
  const line = trendline?.line;
  const style = stroke ?? line;
  if (style) {
    applyLineStyle(ctx, style, themeMap, { color: base, widthPx: 1.25 });
    return;
  }
  ctx.strokeStyle = base;
  ctx.lineWidth = 1.25;
  ctx.setLineDash([4, 3]);
}
function shouldRenderTrendlineLabel(trendline) {
  const label = trendline?.label;
  const hasOverrideText = typeof label?.text === "string" && label.text.trim().length > 0;
  const hasOverrideRuns = (label?.textRuns?.length ?? 0) > 0;
  return Boolean(trendline?.displayEquation) || Boolean(trendline?.displayRSquared) || hasOverrideText || hasOverrideRuns;
}
function resolveLabelText(trendline, computed) {
  const label = trendline.label;
  const baseStyle = label?.textStyle;
  if (label && (label.textRuns?.length ?? 0) > 0) {
    return {
      paragraphs: [
        {
          runs: label.textRuns.map((r) => ({
            text: r.text ?? "",
            textStyle: r.textStyle ?? baseStyle
          }))
        }
      ],
      resolvedStyle: baseStyle,
      manualLayout: label.manualLayout
    };
  }
  const overrideText = label && typeof label.text === "string" ? label.text.trim() : "";
  const computedText = (trendline.displayEquation || trendline.displayRSquared) && computed?.label?.text ? computed.label.text : "";
  const text = overrideText.length > 0 ? overrideText : computedText;
  if (!text)
    return null;
  const paragraphs = text.split(/\r?\n/).filter((line) => line.trim().length > 0).map((line) => ({
    runs: [
      {
        text: line,
        textStyle: baseStyle
      }
    ]
  }));
  return {
    paragraphs,
    resolvedStyle: baseStyle,
    manualLayout: label?.manualLayout
  };
}
function resolveLabelBbox(plotDims, manualLayout) {
  const xFrac = typeof manualLayout?.x === "number" ? manualLayout.x : 0.54;
  const yFrac = typeof manualLayout?.y === "number" ? manualLayout.y : 0.06;
  const wFrac = typeof manualLayout?.w === "number" ? manualLayout.w : 0.42;
  const hFrac = typeof manualLayout?.h === "number" ? manualLayout.h : 0.28;
  const padPx = 6;
  const x2 = plotDims.x + plotDims.width * xFrac + padPx;
  const y2 = plotDims.y + plotDims.height * yFrac + padPx;
  const width = Math.max(0, plotDims.width * wFrac - padPx * 2);
  const height = Math.max(0, plotDims.height * hFrac - padPx * 2);
  return { x: x2, y: y2, width, height };
}
function drawTrendlineLabel(ctx, trendline, computed, themeMap, plotDims) {
  if (!shouldRenderTrendlineLabel(trendline))
    return;
  const resolved = resolveLabelText(trendline, computed);
  if (!resolved)
    return;
  const bbox = resolveLabelBbox(plotDims, resolved.manualLayout);
  if (bbox.width <= 0 || bbox.height <= 0)
    return;
  const label = trendline.label;
  const hasBoxStyle = Boolean(label?.fill) || Boolean(label?.stroke) || Boolean(label?.line);
  if (hasBoxStyle) {
    ctx.save();
    ctx.fillStyle = "rgba(255,255,255,0.85)";
    ctx.strokeStyle = "rgba(0,0,0,0.20)";
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.rect(bbox.x, bbox.y, bbox.width, bbox.height);
    ctx.fill();
    ctx.stroke();
    ctx.restore();
  }
  const el = {
    type: 1 /* ELEMENT_TYPE_TEXT */,
    paragraphs: resolved.paragraphs,
    textStyle: {
      ...resolved.resolvedStyle && typeof resolved.resolvedStyle === "object" ? resolved.resolvedStyle : {},
      fontSize: typeof resolved.resolvedStyle?.fontSize === "number" ? resolved.resolvedStyle.fontSize : 9,
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */
    },
    effects: [],
    children: [],
    citations: [],
    levelsStyles: [],
    id: ""
  };
  const textStyle = el.textStyle;
  if (!textStyle.fill) {
    el.textStyle["fill"] = {
      type: 1 /* FILL_TYPE_SOLID */,
      color: {
        type: 1 /* COLOR_TYPE_RGB */,
        value: "FF111111",
        transform: undefined
      },
      gradientStops: []
    };
  }
  drawText(el, ctx, themeMap, undefined, {
    bboxPx: bbox,
    resolvedStyle: el.textStyle,
    wrap: true
  });
}
function drawTrendlinesXY(ctx, chart, series, seriesIndex, points, themeMap, scales, plotDims, computedPaths) {
  if (!series.trendlines?.length)
    return;
  const finite = points.filter((p) => Number.isFinite(p.x) && Number.isFinite(p.y));
  if (finite.length < 2)
    return;
  series.trendlines.forEach((t, trendlineIndex) => {
    resolveTrendlineStroke(ctx, chart, series, seriesIndex, t, themeMap);
    const type = TRENDLINE_TYPE_FROM_PROTO_SAFE[t.type] ?? DEFAULT_TRENDLINE_TYPE;
    const computed = computedPaths?.[trendlineIndex] ?? computeTrendlinePaths({
      type,
      points: finite,
      polynomialOrder: t.order,
      movingAveragePeriod: t.period,
      forecastForward: t.forward,
      forecastBackward: t.backward,
      intercept: t.intercept,
      displayEquation: t.displayEquation,
      displayRSquared: t.displayRSquared
    });
    if (!computed || computed.points.length < 2)
      return;
    ctx.beginPath();
    let started = false;
    for (const p of computed.points) {
      const px = scales.x(p.x);
      const py = scales.y(p.y);
      if (!Number.isFinite(px) || !Number.isFinite(py))
        continue;
      if (!started) {
        ctx.moveTo(px, py);
        started = true;
      } else {
        ctx.lineTo(px, py);
      }
    }
    if (started)
      ctx.stroke();
    drawTrendlineLabel(ctx, t, computed, themeMap, plotDims);
  });
}
function drawTrendlinesCategory(ctx, chart, series, seriesIndex, categories, values, themeMap, scales, plotDims, computedPaths) {
  const pts = [];
  const centers = [];
  for (let i = 0;i < categories.length; i++) {
    const cat = categories[i];
    const cx = scales.xCenter(cat);
    if (cx !== undefined && Number.isFinite(cx)) {
      centers[i] = cx;
    }
    const v = values[i];
    if (v === undefined || !Number.isFinite(v))
      continue;
    pts.push({ x: i, y: v });
  }
  if (pts.length < 2)
    return;
  const mapX = (xIndex) => {
    const firstIdx = centers.findIndex((c) => Number.isFinite(c));
    const lastIdx = (() => {
      for (let i = centers.length - 1;i >= 0; i--) {
        if (Number.isFinite(centers[i]))
          return i;
      }
      return -1;
    })();
    const firstCenter = firstIdx >= 0 ? centers[firstIdx] : 0;
    const lastCenter = lastIdx >= 0 ? centers[lastIdx] : firstCenter;
    let step = 0;
    if (firstIdx >= 0 && lastIdx > firstIdx) {
      let sum2 = 0;
      let count3 = 0;
      for (let i = firstIdx + 1;i <= lastIdx; i++) {
        const prev = centers[i - 1];
        const cur = centers[i];
        if (!Number.isFinite(prev) || !Number.isFinite(cur))
          continue;
        const d = cur - prev;
        if (!Number.isFinite(d) || d <= 0)
          continue;
        sum2 += d;
        count3 += 1;
      }
      if (count3 > 0)
        step = sum2 / count3;
    }
    if (step > 0 && xIndex < firstIdx) {
      return firstCenter + (xIndex - firstIdx) * step;
    }
    if (step > 0 && xIndex > lastIdx) {
      return lastCenter + (xIndex - lastIdx) * step;
    }
    const i0 = Math.max(0, Math.min(categories.length - 1, Math.floor(xIndex)));
    const i1 = Math.max(0, Math.min(categories.length - 1, Math.ceil(xIndex)));
    const c0 = centers[i0] ?? firstCenter;
    const c1 = centers[i1] ?? c0;
    if (i0 === i1)
      return c0;
    const t = (xIndex - i0) / (i1 - i0);
    return c0 + (c1 - c0) * t;
  };
  if (!series.trendlines?.length)
    return;
  series.trendlines.forEach((t, trendlineIndex) => {
    resolveTrendlineStroke(ctx, chart, series, seriesIndex, t, themeMap);
    const type = TRENDLINE_TYPE_FROM_PROTO_SAFE[t.type] ?? DEFAULT_TRENDLINE_TYPE;
    const computed = computedPaths?.[trendlineIndex] ?? computeTrendlinePaths({
      type,
      points: pts,
      polynomialOrder: t.order,
      movingAveragePeriod: t.period,
      forecastForward: t.forward,
      forecastBackward: t.backward,
      intercept: t.intercept,
      displayEquation: t.displayEquation,
      displayRSquared: t.displayRSquared
    });
    if (!computed || computed.points.length < 2)
      return;
    ctx.beginPath();
    let started = false;
    for (const p of computed.points) {
      const px = mapX(p.x);
      const py = scales.y(p.y);
      if (!Number.isFinite(px) || !Number.isFinite(py))
        continue;
      if (!started) {
        ctx.moveTo(px, py);
        started = true;
      } else {
        ctx.lineTo(px, py);
      }
    }
    if (started)
      ctx.stroke();
    drawTrendlineLabel(ctx, t, computed, themeMap, plotDims);
  });
}
var DEFAULT_TRENDLINE_TYPE = "linear";
var TRENDLINE_TYPE_FROM_PROTO_SAFE = {
  [1 /* TRENDLINE_TYPE_LINEAR */]: "linear",
  [2 /* TRENDLINE_TYPE_EXPONENTIAL */]: "exponential",
  [3 /* TRENDLINE_TYPE_LOGARITHMIC */]: "logarithmic",
  [4 /* TRENDLINE_TYPE_POLYNOMIAL */]: "polynomial",
  [5 /* TRENDLINE_TYPE_POWER */]: "power",
  [6 /* TRENDLINE_TYPE_MOVING_AVERAGE */]: "movingAverage"
};

// node_modules/@oai/granola/dist/draw-utils/chart/draw-error-bars.js
function mean2(values) {
  if (values.length === 0)
    return 0;
  return values.reduce((a, b) => a + b, 0) / values.length;
}
function stddev(values) {
  if (values.length < 2)
    return 0;
  const m = mean2(values);
  const v = values.reduce((acc, x2) => acc + (x2 - m) * (x2 - m), 0) / (values.length - 1);
  return Math.sqrt(Math.max(0, v));
}
function resolveErrorAmount(errorBars, values, value) {
  const type = errorBars.type;
  if (type === "percentage") {
    const pct = typeof errorBars.value === "number" && Number.isFinite(errorBars.value) ? errorBars.value : 10;
    return Math.abs(value) * (pct / 100);
  }
  if (type === "standardDeviation") {
    return stddev(values);
  }
  if (type === "standardError") {
    const sd = stddev(values);
    return values.length > 0 ? sd / Math.sqrt(values.length) : 0;
  }
  return 0;
}
function drawErrorBarsY(ctx, series, seriesIndex, themeMap, points, scales) {
  const raw = series["errorBars"];
  if (!raw || typeof raw !== "object")
    return;
  const errorBars = raw;
  if (points.length === 0)
    return;
  const values = points.map((p) => p.value).filter((v) => Number.isFinite(v));
  if (values.length === 0)
    return;
  ctx.save();
  applyLineStyle(ctx, errorBars.line, themeMap, {
    color: "#666666",
    widthPx: 1
  });
  const capHalf = 5;
  const endStyleRaw = errorBars.endStyle;
  const shouldDrawCaps = endStyleRaw !== "noCap";
  points.forEach((p) => {
    const amount = resolveErrorAmount(errorBars, values, p.value);
    if (!Number.isFinite(amount) || amount <= 0)
      return;
    const yTop = scales.y(p.value + amount);
    const yBottom = scales.y(p.value - amount);
    if (!Number.isFinite(yTop) || !Number.isFinite(yBottom))
      return;
    ctx.beginPath();
    ctx.moveTo(p.x, yTop);
    ctx.lineTo(p.x, yBottom);
    ctx.stroke();
    if (shouldDrawCaps) {
      ctx.beginPath();
      ctx.moveTo(p.x - capHalf, yTop);
      ctx.lineTo(p.x + capHalf, yTop);
      ctx.moveTo(p.x - capHalf, yBottom);
      ctx.lineTo(p.x + capHalf, yBottom);
      ctx.stroke();
    }
  });
  ctx.restore();
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-line-chart.js
function drawLineChart(ctx, chart, plotDims, scales, themeMap, chartHoverTargets, hiddenSeriesIndices, trendlineRenderCache) {
  const { x: x2, y: y2 } = scales;
  const prepared = prepareLineData(chart, hiddenSeriesIndices);
  const categories = prepared.categories;
  prepared.layers.forEach((layer) => {
    const series = chart.series[layer.seriesIndex];
    if (!series)
      return;
    const strokeFill = series.stroke?.fill;
    const explicitNoStroke = strokeFill?.type === 0 /* FILL_TYPE_UNSPECIFIED */ && strokeFill.color === undefined;
    const strokeColor = getSeriesColor(series, layer.seriesIndex, themeMap);
    if (strokeColor) {
      ctx.strokeStyle = strokeColor;
    }
    const effectiveColor = strokeColor ?? ctx.strokeStyle;
    const strokeWidthPx = (() => {
      const raw = series.stroke?.widthEmu;
      if (raw === undefined || raw === null)
        return;
      const width = Number(raw) * EMU_TO_PX;
      return Number.isFinite(width) && width > 0 ? width : undefined;
    })();
    ctx.lineWidth = strokeWidthPx ?? 2;
    ctx.beginPath();
    let hasPoint = false;
    const points = [];
    for (let idx = 0;idx < categories.length; idx++) {
      const category = categories[idx];
      const cx = getCenter(x2, category);
      if (cx === undefined)
        continue;
      const value = layer.values[idx];
      if (value === undefined || !Number.isFinite(value))
        continue;
      const cy = y2(value);
      if (!Number.isFinite(cy))
        continue;
      if (!hasPoint) {
        ctx.moveTo(cx, cy);
        hasPoint = true;
      } else {
        ctx.lineTo(cx, cy);
      }
      points.push({ cx, cy, idx, value });
      if (chartHoverTargets) {
        const hit = 6;
        const rawValue = series.values[idx] ?? 0;
        chartHoverTargets.push({
          kind: "line-point",
          x: cx - hit / 2,
          y: cy - hit / 2,
          width: hit,
          height: hit,
          seriesName: series.name,
          category,
          value: rawValue,
          color: effectiveColor,
          anchorX: cx,
          anchorY: cy
        });
      }
    }
    if (hasPoint && !explicitNoStroke) {
      ctx.stroke();
    }
    if (series.trendlines?.length) {
      const computed = trendlineRenderCache?.bySeriesIndex.get(layer.seriesIndex);
      drawTrendlinesCategory(ctx, chart, series, layer.seriesIndex, categories, layer.values, themeMap, { y: y2, xCenter: (cat) => getCenter(x2, cat) }, plotDims, computed);
    }
    if (series["errorBars"]) {
      drawErrorBarsY(ctx, series, layer.seriesIndex, themeMap, points.map((p) => ({ x: p.cx, y: p.cy, value: p.value })), { y: y2 });
    }
    points.forEach((p) => {
      const dataLabel = resolveDataLabel(chart, series, p.idx, p.value);
      if (!dataLabel.show)
        return;
      drawDataLabel(ctx, dataLabel.text, dataLabel.position, dataLabel.positionName, dataLabel.textStyle, themeMap, { x: p.cx, y: p.cy });
    });
    const markerSymbol = series.marker?.symbol;
    const showMarkers = markerSymbol !== undefined && markerSymbol !== 1 /* MARKER_SYMBOL_NONE */ && markerSymbol !== 0 /* MARKER_SYMBOL_UNSPECIFIED */ && markerSymbol !== -1 /* UNRECOGNIZED */;
    if (!showMarkers || points.length === 0) {
      return;
    }
    const markerSizePt = series.marker?.size;
    const diameterPx = markerSizePt !== undefined && Number.isFinite(markerSizePt) ? markerSizePt * 96 / 72 : 6;
    const radius = Math.max(diameterPx / 2, 1.5);
    ctx.fillStyle = effectiveColor;
    points.forEach(({ cx, cy }) => {
      ctx.beginPath();
      ctx.arc(cx, cy, radius, 0, Math.PI * 2);
      ctx.fill();
    });
  });
}

// node_modules/@oai/granola/dist/draw-utils/chart/prepare-area-data.js
function getCategories4(chart) {
  if (chart.categories.length > 0) {
    return chart.categories;
  }
  const firstSeriesCategories = chart.series[0]?.categories;
  if (firstSeriesCategories && firstSeriesCategories.length > 0) {
    return firstSeriesCategories;
  }
  return [];
}
function prepareAreaData(chart, hiddenSeriesIndices) {
  const categories = getCategories4(chart);
  const visibleSeries = chart.series.map((_, index) => index).filter((index) => !hiddenSeriesIndices?.has(index));
  const grouping = chart.areaOptions?.grouping;
  const mode = grouping === 2 /* AREA_GROUPING_STACKED */ ? "stacked" : grouping === 3 /* AREA_GROUPING_PERCENT_STACKED */ ? "percent" : "standard";
  const layers = visibleSeries.map((seriesIndex) => ({
    seriesIndex,
    tuples: categories.map(() => ({ start: 0, end: 0 }))
  }));
  if (mode === "standard" || visibleSeries.length === 0) {
    categories.forEach((_, categoryIndex) => {
      visibleSeries.forEach((seriesIndex) => {
        const layer = layers.find((l) => l.seriesIndex === seriesIndex);
        if (!layer)
          return;
        const value = chart.series[seriesIndex]?.values[categoryIndex] ?? 0;
        layer.tuples[categoryIndex] = {
          start: 0,
          end: value
        };
      });
    });
    return {
      categories,
      visibleSeries,
      mode,
      layers
    };
  }
  const records = categories.map((_, categoryIndex) => {
    const record = {};
    visibleSeries.forEach((seriesIndex) => {
      const series = chart.series[seriesIndex];
      record[String(seriesIndex)] = series?.values[categoryIndex] ?? 0;
    });
    return record;
  });
  const stackGenerator = stack_default().keys(visibleSeries.map((seriesIndex) => String(seriesIndex))).value((d, key) => d[key] ?? 0).order(none_default2);
  if (mode === "percent") {
    stackGenerator.offset(expand_default);
  } else {
    stackGenerator.offset(diverging_default);
  }
  const stacks = stackGenerator(records);
  stacks.forEach((stackLayer) => {
    const seriesIndex = Number.parseInt(stackLayer.key, 10);
    const layer = layers.find((l) => l.seriesIndex === seriesIndex);
    if (!layer)
      return;
    categories.forEach((_, categoryIndex) => {
      const tuple = stackLayer[categoryIndex];
      if (!tuple)
        return;
      const start = Number.isFinite(tuple[0]) ? tuple[0] : 0;
      const end = Number.isFinite(tuple[1]) ? tuple[1] : 0;
      layer.tuples[categoryIndex] = { start, end };
    });
  });
  return {
    categories,
    visibleSeries,
    mode,
    layers
  };
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-area-chart.js
function drawAreaChart(ctx, chart, scales, themeMap, chartHoverTargets, hiddenSeriesIndices) {
  const x2 = scales.x;
  const y2 = scales.y;
  const prepared = prepareAreaData(chart, hiddenSeriesIndices ? new Set(hiddenSeriesIndices) : undefined);
  const categories = prepared.categories;
  prepared.layers.forEach((layer) => {
    const seriesIndex = layer.seriesIndex;
    const series = chart.series[seriesIndex];
    if (!series)
      return;
    const strokeFill = series.stroke?.fill;
    const explicitNoStroke = strokeFill?.type === 0 /* FILL_TYPE_UNSPECIFIED */ && strokeFill.color === undefined;
    const stroke = getSeriesColor(series, seriesIndex, themeMap);
    const fillColor = (() => {
      if (!stroke)
        return;
      const c = color(stroke);
      if (c) {
        return c.formatRgb();
      }
      return stroke;
    })();
    if (fillColor)
      ctx.fillStyle = fillColor;
    if (stroke)
      ctx.strokeStyle = stroke;
    ctx.lineWidth = 1;
    ctx.beginPath();
    let hasPath = false;
    for (let idx = 0;idx < categories.length; idx++) {
      const category = categories[idx];
      const cx = getCenter(x2, category);
      if (cx === undefined)
        continue;
      const tuple = layer.tuples[idx];
      const endValue = tuple?.end ?? 0;
      const cy = y2(endValue);
      if (!hasPath) {
        ctx.moveTo(cx, cy);
        hasPath = true;
      } else {
        ctx.lineTo(cx, cy);
      }
    }
    if (!hasPath) {
      ctx.closePath();
      return;
    }
    for (let idx = categories.length - 1;idx >= 0; idx--) {
      const category = categories[idx];
      const cx = getCenter(x2, category);
      if (cx === undefined)
        continue;
      const tuple = layer.tuples[idx];
      const startValue = tuple?.start ?? 0;
      const cy = y2(startValue);
      ctx.lineTo(cx, cy);
    }
    ctx.closePath();
    ctx.fill();
    if (!explicitNoStroke) {
      ctx.stroke();
    }
    if (chartHoverTargets) {
      const hit = 6;
      categories.forEach((category, idx) => {
        const cx = getCenter(x2, category);
        if (cx === undefined)
          return;
        const tuple = layer.tuples[idx];
        const endValue = tuple?.end ?? 0;
        const cy = y2(endValue);
        chartHoverTargets.push({
          kind: "area-point",
          x: cx - hit / 2,
          y: cy - hit / 2,
          width: hit,
          height: hit,
          seriesName: series.name,
          category,
          value: series.values[idx] ?? 0,
          color: stroke,
          anchorX: cx,
          anchorY: cy
        });
      });
    }
  });
}

// node_modules/@oai/granola/dist/draw-utils/chart/prepare-radar-data.js
function getCategories5(chart) {
  if (chart.categories.length > 0) {
    return chart.categories;
  }
  const firstSeriesCategories = chart.series[0]?.categories ?? [];
  if (firstSeriesCategories.length > 0) {
    return firstSeriesCategories;
  }
  return [];
}
function prepareRadarData(chart, hiddenSeriesIndices) {
  const categories = getCategories5(chart);
  const categoryCount = categories.length;
  const visibleSeries = chart.series.map((_, idx) => idx).filter((idx) => !hiddenSeriesIndices?.has(idx));
  const layers = visibleSeries.map((seriesIndex) => ({
    seriesIndex,
    values: Array.from({ length: categoryCount }, () => 0)
  }));
  let observedMin = Number.POSITIVE_INFINITY;
  let observedMax = Number.NEGATIVE_INFINITY;
  categories.forEach((_, categoryIndex) => {
    visibleSeries.forEach((seriesIndex) => {
      const series = chart.series[seriesIndex];
      const raw = series?.values[categoryIndex];
      const value = typeof raw === "number" && Number.isFinite(raw) ? raw : 0;
      const layer = layers.find((l) => l.seriesIndex === seriesIndex);
      if (!layer)
        return;
      layer.values[categoryIndex] = value;
      observedMin = Math.min(observedMin, value);
      observedMax = Math.max(observedMax, value);
    });
  });
  if (observedMin === Number.POSITIVE_INFINITY) {
    observedMin = 0;
  }
  if (observedMax === Number.NEGATIVE_INFINITY) {
    observedMax = 0;
  }
  const axisMin = chart.yAxis && chart.yAxis.min !== undefined ? Number(chart.yAxis.min) : undefined;
  const axisMax = chart.yAxis && chart.yAxis.max !== undefined ? Number(chart.yAxis.max) : undefined;
  let domainMin = axisMin !== undefined && Number.isFinite(axisMin) ? axisMin : Math.min(0, observedMin);
  let domainMax = axisMax !== undefined && Number.isFinite(axisMax) ? axisMax : observedMax;
  if (!Number.isFinite(domainMin)) {
    domainMin = 0;
  }
  if (!Number.isFinite(domainMax)) {
    domainMax = 0;
  }
  if (domainMax < observedMax && axisMax === undefined) {
    domainMax = observedMax;
  }
  if (domainMax === domainMin) {
    domainMax = domainMin + 1;
  }
  return {
    categories,
    visibleSeries,
    layers,
    domain: [domainMin, domainMax]
  };
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-radar-chart.js
var RADAR_GRIDLINE_COLOR = "#E1E1E1";
function drawRadarChart(ctx, chart, dims, themeMap, chartHoverTargets, hiddenSeriesIndices) {
  const prepared = prepareRadarData(chart, hiddenSeriesIndices);
  const categories = prepared.categories;
  if (categories.length === 0 || prepared.visibleSeries.length === 0) {
    return;
  }
  const cx = dims.x + dims.width / 2;
  const cy = dims.y + dims.height / 2;
  const radiusPadding = 12;
  const maxRadius = Math.min(dims.width, dims.height) / 2 - radiusPadding;
  if (maxRadius <= 0) {
    return;
  }
  const [domainMin, domainMax] = prepared.domain;
  const radiusScale = linear2().domain([domainMin, domainMax]).range([0, maxRadius]);
  const outerRadius = radiusScale(domainMax);
  if (!Number.isFinite(outerRadius) || outerRadius <= 0) {
    return;
  }
  const angleFor = (index) => {
    const total = categories.length;
    if (total === 0)
      return -Math.PI / 2;
    return -Math.PI / 2 + index * 2 * Math.PI / total;
  };
  const clampValue = (value) => {
    if (!Number.isFinite(value))
      return domainMin;
    if (value < domainMin)
      return domainMin;
    if (value > domainMax)
      return domainMax;
    return value;
  };
  const xAxisStyles = getAxisStyles(chart.xAxis, themeMap);
  const gridColorFromAxis = chart.yAxis?.majorGridlines?.fill?.color ? resolveColor(chart.yAxis.majorGridlines.fill.color, themeMap) : undefined;
  const gridColor = gridColorFromAxis ?? RADAR_GRIDLINE_COLOR;
  const gridLevels = Array.from(new Set([...radiusScale.ticks(5), domainMax])).filter((value) => Number.isFinite(value) && value > domainMin && value <= domainMax).sort((a, b) => a - b);
  if (gridLevels.length > 0) {
    ctx.save();
    ctx.strokeStyle = gridColor;
    ctx.lineWidth = 1;
    gridLevels.forEach((tick) => {
      const radius = radiusScale(tick);
      if (!Number.isFinite(radius) || radius <= 0)
        return;
      ctx.beginPath();
      categories.forEach((_, idx) => {
        const angle = angleFor(idx);
        const px = cx + radius * Math.cos(angle);
        const py = cy + radius * Math.sin(angle);
        if (idx === 0) {
          ctx.moveTo(px, py);
        } else {
          ctx.lineTo(px, py);
        }
      });
      ctx.closePath();
      ctx.stroke();
    });
    ctx.restore();
  }
  const radialLineColor = chart.yAxis?.line?.fill?.color ? resolveColor(chart.yAxis.line.fill.color, themeMap) : RADAR_GRIDLINE_COLOR;
  ctx.save();
  ctx.strokeStyle = radialLineColor;
  ctx.lineWidth = 1;
  categories.forEach((_, idx) => {
    const angle = angleFor(idx);
    const px = cx + outerRadius * Math.cos(angle);
    const py = cy + outerRadius * Math.sin(angle);
    ctx.beginPath();
    ctx.moveTo(cx, cy);
    ctx.lineTo(px, py);
    ctx.stroke();
  });
  ctx.restore();
  ctx.save();
  ctx.font = `${xAxisStyles.fontSize}px ${FONT_FAMILY}`;
  ctx.fillStyle = xAxisStyles.textColor;
  const labelRadius = outerRadius + Math.max(xAxisStyles.fontSize, 10);
  categories.forEach((category, idx) => {
    const angle = angleFor(idx);
    const cosA = Math.cos(angle);
    const sinA = Math.sin(angle);
    const px = cx + labelRadius * cosA;
    const py = cy + labelRadius * sinA;
    if (cosA > 0.25)
      ctx.textAlign = "left";
    else if (cosA < -0.25)
      ctx.textAlign = "right";
    else
      ctx.textAlign = "center";
    if (sinA > 0.25)
      ctx.textBaseline = "top";
    else if (sinA < -0.25)
      ctx.textBaseline = "bottom";
    else
      ctx.textBaseline = "middle";
    ctx.fillText(category, px, py);
  });
  ctx.restore();
  const style = chart.radarOptions?.style ?? 1 /* RADAR_STYLE_STANDARD */;
  prepared.layers.forEach((layer) => {
    const series = chart.series[layer.seriesIndex];
    if (!series)
      return;
    const strokeColor = getSeriesColor(series, layer.seriesIndex, themeMap);
    if (strokeColor) {
      ctx.strokeStyle = strokeColor;
    }
    ctx.lineWidth = 2;
    const points = categories.map((_, idx) => {
      const raw = layer.values[idx] ?? domainMin;
      const value = clampValue(raw);
      const radius = radiusScale(value);
      const angle = angleFor(idx);
      return {
        x: cx + radius * Math.cos(angle),
        y: cy + radius * Math.sin(angle),
        value,
        idx
      };
    });
    if (points.length === 0)
      return;
    ctx.beginPath();
    points.forEach((pt, idx) => {
      if (idx === 0) {
        ctx.moveTo(pt.x, pt.y);
      } else {
        ctx.lineTo(pt.x, pt.y);
      }
    });
    ctx.closePath();
    if (style === 3 /* RADAR_STYLE_FILLED */) {
      const fillColor = (() => {
        if (!strokeColor)
          return;
        const c = color(strokeColor);
        if (c) {
          return c.formatRgb();
        }
        return strokeColor;
      })();
      if (fillColor) {
        ctx.fillStyle = fillColor;
        ctx.fill();
      }
    }
    ctx.stroke();
    const markerSymbol = series.marker?.symbol;
    const shouldShowMarkers = style === 2 /* RADAR_STYLE_MARKER */ && markerSymbol !== undefined && markerSymbol !== 1 /* MARKER_SYMBOL_NONE */ && markerSymbol !== 0 /* MARKER_SYMBOL_UNSPECIFIED */;
    if (shouldShowMarkers) {
      const markerSizePt = series.marker?.size;
      const diameterPx = markerSizePt !== undefined && Number.isFinite(markerSizePt) ? markerSizePt * 96 / 72 : 6;
      const markerRadius = Math.max(diameterPx / 2, 1.5);
      points.forEach((pt) => {
        const pointIdx = pt.idx;
        const noFill = pointHasNoFill(series, pointIdx);
        const fillClr = getPointFillColor(series, pointIdx, layer.seriesIndex, themeMap);
        const strokeOverride = getPointStroke(series, pointIdx, themeMap);
        ctx.beginPath();
        ctx.arc(pt.x, pt.y, markerRadius, 0, Math.PI * 2);
        if (!noFill) {
          const effectiveFill = fillClr ?? strokeColor;
          if (effectiveFill) {
            ctx.fillStyle = effectiveFill;
            ctx.fill();
          }
        }
        const strokeForMarker = strokeOverride.color ?? strokeColor;
        if (strokeForMarker) {
          ctx.strokeStyle = strokeForMarker;
          ctx.lineWidth = strokeOverride.widthPx ?? 1;
          ctx.stroke();
        }
      });
    }
    if (chartHoverTargets) {
      points.forEach((pt) => {
        const category = categories[pt.idx];
        const rawValue = series.values[pt.idx] ?? 0;
        chartHoverTargets.push({
          kind: "line-point",
          x: pt.x - 3,
          y: pt.y - 3,
          width: 6,
          height: 6,
          seriesName: series.name,
          category,
          value: rawValue,
          color: strokeColor,
          anchorX: pt.x,
          anchorY: pt.y
        });
      });
    }
  });
}

// node_modules/@oai/granola/dist/draw-utils/chart/layout-title.js
var TITLE_CONTENT_GAP_PX = 6;
var TITLE_MAX_FRACTION = 0.5;
function buildTitleElement(chart, text) {
  return {
    type: 1 /* ELEMENT_TYPE_TEXT */,
    paragraphs: [
      {
        runs: [
          {
            text,
            textStyle: {
              ...chart.titleTextStyle,
              alignment: 2 /* ALIGNMENT_TYPE_CENTER */
            },
            citations: [],
            reviewMarkIds: []
          }
        ]
      }
    ],
    textStyle: {
      ...chart.titleTextStyle,
      alignment: 2 /* ALIGNMENT_TYPE_CENTER */
    },
    effects: [],
    children: [],
    citations: [],
    levelsStyles: [],
    id: ""
  };
}
function getLayoutHeight(layout) {
  return layout?.lines.reduce((sum2, line) => sum2 + line.heightPx, 0) ?? 0;
}
function buildTruncatedTitle(text, length) {
  if (length >= text.length) {
    return text;
  }
  const trimmedPrefix = text.slice(0, Math.max(0, length)).trimEnd();
  return trimmedPrefix.length > 0 ? `${trimmedPrefix}…` : "…";
}
function fitTitleText(chart, themeMap, titleBox) {
  const fullText = chart.title?.trim() ?? "";
  if (!fullText) {
    return { text: "", layoutHeight: 0 };
  }
  const measure = (text) => getLayoutHeight(layoutTextBlock(buildTitleElement(chart, text), themeMap, {
    bboxPx: titleBox
  }));
  const fullHeight = measure(fullText);
  if (fullHeight <= titleBox.height) {
    return { text: fullText, layoutHeight: fullHeight };
  }
  let low = 0;
  let high = fullText.length;
  let bestText = "…";
  let bestHeight = measure(bestText);
  while (low <= high) {
    const mid = Math.floor((low + high) / 2);
    const candidate = buildTruncatedTitle(fullText, mid);
    const candidateHeight = measure(candidate);
    if (candidateHeight <= titleBox.height) {
      bestText = candidate;
      bestHeight = candidateHeight;
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }
  return { text: bestText, layoutHeight: bestHeight };
}
function layoutTitle(chart, outerDims, themeMap, maxFraction = TITLE_MAX_FRACTION) {
  if (!chart.title || !chart.title.trim())
    return { text: "", reserved: 0, layoutHeight: 0 };
  const placement = (() => {
    const raw = chart["titlePlacement"];
    return typeof raw === "string" ? raw : undefined;
  })();
  if (placement === "none") {
    return { text: "", reserved: 0, layoutHeight: 0 };
  }
  const titleBox = {
    x: outerDims.x,
    y: outerDims.y,
    width: outerDims.width,
    height: Math.max(0, outerDims.height * maxFraction)
  };
  const fitted = fitTitleText(chart, themeMap, titleBox);
  const measured = fitted.layoutHeight;
  if (measured <= 0) {
    return { text: "", reserved: 0, layoutHeight: 0 };
  }
  const reserved = placement === "centeredOverlay" ? 0 : Math.min(titleBox.height, measured + TITLE_CONTENT_GAP_PX);
  return { text: fitted.text, reserved, layoutHeight: measured };
}

// node_modules/@oai/granola/dist/draw-utils/chart/plan-category-axis.js
var DEFAULT_ROTATION_CANDIDATES = [0, -45, -90];
var LABEL_BASE_GAP_PX = 6;
var MIN_LABEL_SEPARATION_PX = 4;
var WIDTH_SOLVER_EPSILON = 0.000001;
function planCategoryAxis(args) {
  const { ctx, axis, categories, scale, plotDims, themeMap, maxLabelBandHeightPx } = args;
  const styles = getAxisStyles(axis, themeMap);
  ctx.font = `${styles.fontSize}px ${FONT_FAMILY}`;
  const tickLabelDistancePx = getAxisTickLabelDistancePx(axis);
  const hideTickLabels = shouldHideAxisTickLabels(axis);
  const explicitStep = getExplicitTickLabelStep(axis);
  const explicitRotation = getExplicitAxisRotation(axis);
  const minimumReadableWidthPx = computeMinimumReadableWidthPx(ctx, categories);
  if (categories.length === 0 || hideTickLabels) {
    return {
      step: explicitStep ?? 1,
      rotationDeg: explicitRotation ?? 0,
      labelMaxWidthPx: 0,
      labelBandHeight: 0,
      visibleIndices: buildVisibleIndices(categories.length, explicitStep ?? 1),
      hideTickLabels,
      tickLabelDistancePx,
      autoRotation: false,
      autoStep: false
    };
  }
  const stepCandidates = explicitStep ? [explicitStep] : Array.from({ length: categories.length }, (_, index) => index + 1);
  const rotationCandidates = explicitRotation !== undefined ? [explicitRotation] : [...DEFAULT_ROTATION_CANDIDATES];
  let bestFallback;
  for (const step of stepCandidates) {
    for (const rotationDeg of rotationCandidates) {
      const candidate = evaluateCandidate2({
        ctx,
        categories,
        scale,
        plotDims,
        fontSize: styles.fontSize,
        step,
        rotationDeg,
        maxLabelBandHeightPx,
        tickLabelDistancePx,
        minimumReadableWidthPx,
        explicitRotation,
        explicitStep
      });
      if (candidate.fits) {
        return candidate;
      }
      if (!bestFallback || candidate.overflowPx < bestFallback.overflowPx) {
        bestFallback = candidate;
      }
    }
  }
  return bestFallback ?? {
    step: explicitStep ?? Math.max(1, categories.length),
    rotationDeg: explicitRotation ?? 90,
    labelMaxWidthPx: 0,
    labelBandHeight: 0,
    visibleIndices: buildVisibleIndices(categories.length, explicitStep ?? Math.max(1, categories.length)),
    hideTickLabels: false,
    tickLabelDistancePx,
    autoRotation: explicitRotation === undefined,
    autoStep: explicitStep === undefined,
    fits: false,
    overflowPx: Number.POSITIVE_INFINITY
  };
}
function evaluateCandidate2(args) {
  const { ctx, categories, scale, plotDims, fontSize, step, rotationDeg, maxLabelBandHeightPx, tickLabelDistancePx, minimumReadableWidthPx, explicitRotation, explicitStep } = args;
  const visibleIndices = buildVisibleIndices(categories.length, step);
  const minCenterGapPx = computeMinCenterGapPx(scale, categories, visibleIndices);
  const angleRad = normalizeRotationForBounds(rotationDeg);
  const labelHeightBudgetPx = Math.max(0, maxLabelBandHeightPx - LABEL_BASE_GAP_PX - tickLabelDistancePx);
  const maxWidthFromGapPx = solveWidthFromHorizontalBudget(minCenterGapPx, fontSize, angleRad);
  const maxWidthFromHeightPx = solveWidthFromVerticalBudget(labelHeightBudgetPx, fontSize, angleRad);
  const labelMaxWidthPx = clampLabelWidth(Math.min(maxWidthFromGapPx, maxWidthFromHeightPx, plotDims.width));
  let maxRenderedWidthPx = 0;
  for (const index of visibleIndices) {
    const label = ellipsize(ctx, categories[index] ?? "", labelMaxWidthPx);
    const width = ctx.measureText(label).width;
    if (width > maxRenderedWidthPx) {
      maxRenderedWidthPx = width;
    }
  }
  const bounds = rotatedRectBounds(maxRenderedWidthPx, fontSize, angleRad);
  const labelBandHeight = visibleIndices.length > 0 ? bounds.height + LABEL_BASE_GAP_PX + tickLabelDistancePx : 0;
  const readableWidthShortfallPx = shouldEnforceReadableWidth(explicitRotation, explicitStep) ? Math.max(0, minimumReadableWidthPx - labelMaxWidthPx) : 0;
  const overflowPx = Math.max(0, labelBandHeight - maxLabelBandHeightPx, readableWidthShortfallPx);
  return {
    step,
    rotationDeg,
    labelMaxWidthPx,
    labelBandHeight,
    visibleIndices,
    hideTickLabels: false,
    tickLabelDistancePx,
    autoRotation: explicitRotation === undefined,
    autoStep: explicitStep === undefined,
    fits: overflowPx <= 0,
    overflowPx
  };
}
function getExplicitTickLabelStep(axis) {
  const extras = getAxisRenderExtras(axis);
  if (extras.tickLabelInterval === undefined || !Number.isFinite(extras.tickLabelInterval)) {
    return;
  }
  return Math.max(1, Math.floor(extras.tickLabelInterval));
}
function getExplicitAxisRotation(axis) {
  const raw = axis?.textStyle?.rotation;
  if (typeof raw !== "number" || !Number.isFinite(raw) || raw === -1000) {
    return;
  }
  return getAxisRotationDegrees(axis);
}
function buildVisibleIndices(count3, step) {
  if (count3 <= 0)
    return [];
  const normalizedStep = Math.max(1, Math.floor(step));
  const visibleIndices = [];
  for (let index = 0;index < count3; index += normalizedStep) {
    visibleIndices.push(index);
  }
  return visibleIndices;
}
function computeMinCenterGapPx(scale, categories, visibleIndices) {
  let minGapPx = Number.POSITIVE_INFINITY;
  let previousCenterPx;
  for (const index of visibleIndices) {
    const centerPx = getCenter(scale, categories[index]);
    if (centerPx === undefined || !Number.isFinite(centerPx))
      continue;
    if (previousCenterPx !== undefined) {
      minGapPx = Math.min(minGapPx, centerPx - previousCenterPx);
    }
    previousCenterPx = centerPx;
  }
  if (Number.isFinite(minGapPx)) {
    return Math.max(0, minGapPx - MIN_LABEL_SEPARATION_PX);
  }
  return Number.POSITIVE_INFINITY;
}
function solveWidthFromHorizontalBudget(availableWidthPx, fontSizePx, angleRad) {
  if (!Number.isFinite(availableWidthPx)) {
    return Number.POSITIVE_INFINITY;
  }
  const cos2 = Math.abs(Math.cos(angleRad));
  const sin2 = Math.abs(Math.sin(angleRad));
  const remainingWidthPx = availableWidthPx - fontSizePx * sin2;
  if (remainingWidthPx <= 0) {
    return 0;
  }
  if (cos2 <= WIDTH_SOLVER_EPSILON) {
    return Number.POSITIVE_INFINITY;
  }
  return remainingWidthPx / cos2;
}
function solveWidthFromVerticalBudget(availableHeightPx, fontSizePx, angleRad) {
  if (!Number.isFinite(availableHeightPx)) {
    return Number.POSITIVE_INFINITY;
  }
  const cos2 = Math.abs(Math.cos(angleRad));
  const sin2 = Math.abs(Math.sin(angleRad));
  const remainingHeightPx = availableHeightPx - fontSizePx * cos2;
  if (remainingHeightPx <= 0) {
    return 0;
  }
  if (sin2 <= WIDTH_SOLVER_EPSILON) {
    return Number.POSITIVE_INFINITY;
  }
  return remainingHeightPx / sin2;
}
function clampLabelWidth(widthPx) {
  if (!Number.isFinite(widthPx)) {
    return Number.MAX_SAFE_INTEGER;
  }
  return Math.max(0, Math.floor(widthPx));
}
function normalizeRotationForBounds(rotationDeg) {
  const normalizedDeg = Math.abs(rotationDeg % 180);
  return normalizedDeg * Math.PI / 180;
}
function computeMinimumReadableWidthPx(ctx, categories) {
  const widths = categories.map((category) => ctx.measureText(category).width).filter((width) => Number.isFinite(width) && width > 0).sort((left, right) => left - right);
  if (widths.length === 0) {
    return 0;
  }
  const medianWidthPx = widths[Math.floor(widths.length / 2)] ?? widths[0] ?? 0;
  return Math.min(medianWidthPx, Math.max(ctx.measureText("0000…").width, medianWidthPx * 0.35));
}
function shouldEnforceReadableWidth(explicitRotation, explicitStep) {
  return !(explicitRotation !== undefined && explicitStep !== undefined);
}

// node_modules/@oai/granola/dist/draw-utils/chart/layout-axes-vertical.js
var AXIS_TITLE_GAP_PX2 = 8;
var DEFAULT_MAX_BOTTOM_FRAC = 0.4;
var VALUE_TICK_COUNT2 = 5;
function layoutAxesVertical(ctx, chart, plotDimsIn, themeMap, caps = {}) {
  const maxLeftFrac = caps.maxLeftFrac ?? 1;
  const maxBottomFrac = caps.maxBottomFrac ?? DEFAULT_MAX_BOTTOM_FRAC;
  const categories = chart.categories.length > 0 ? chart.categories : chart.series[0]?.categories ?? [];
  const yAxisConfig = chart.yAxis;
  const yAxisDeleted = !!yAxisConfig?.deleted;
  const yStyles = getAxisStyles(yAxisConfig, themeMap);
  ctx.font = `${yStyles.fontSize}px ${FONT_FAMILY}`;
  const grouping = chart.barOptions?.grouping;
  let yMin = 0;
  let yMax = 0;
  if (grouping === 2 /* BAR_GROUPING_STACKED */) {
    const posMax = max(categories.map((_, idx) => sum(chart.series, (s) => Math.max(0, s.values[idx] ?? 0)))) ?? 0;
    const negMin = -(max(categories.map((_, idx) => sum(chart.series, (s) => Math.max(0, -(s.values[idx] ?? 0))))) ?? 0);
    yMin = Math.min(0, negMin);
    yMax = Math.max(0, posMax);
  } else if (grouping === 3 /* BAR_GROUPING_PERCENT_STACKED */) {
    yMin = 0;
    yMax = 1;
  } else {
    const values = chart.series.flatMap((s) => s.values);
    const ex = extent(values);
    yMin = Math.min(0, ex[0] ?? 0);
    yMax = ex[1] ?? 0;
  }
  if (chart.series.some((s) => (s?.trendlines?.length ?? 0) > 0)) {
    let minYTrend = Number.POSITIVE_INFINITY;
    let maxYTrend = Number.NEGATIVE_INFINITY;
    for (const series of chart.series) {
      if (!series?.trendlines?.length)
        continue;
      const values = series.values ?? [];
      const pts = [];
      for (let i = 0;i < values.length; i++) {
        const v = values[i];
        if (v === undefined || !Number.isFinite(v))
          continue;
        pts.push({ x: i, y: v });
      }
      if (pts.length < 2)
        continue;
      for (const t of series.trendlines) {
        const type = TRENDLINE_TYPE_FROM_PROTO_SAFE2[t.type] ?? DEFAULT_TRENDLINE_TYPE2;
        const computed = computeTrendlinePaths({
          type,
          points: pts,
          polynomialOrder: t.order,
          movingAveragePeriod: t.period,
          forecastForward: t.forward,
          forecastBackward: t.backward,
          intercept: t.intercept,
          displayEquation: false,
          displayRSquared: false
        });
        if (!computed?.points?.length)
          continue;
        for (const p of computed.points) {
          if (!Number.isFinite(p.y))
            continue;
          minYTrend = Math.min(minYTrend, p.y);
          maxYTrend = Math.max(maxYTrend, p.y);
        }
      }
    }
    if (Number.isFinite(minYTrend) && Number.isFinite(maxYTrend)) {
      yMin = Math.min(yMin, minYTrend);
      yMax = Math.max(yMax, maxYTrend);
    }
  }
  const provisionalYScale = linear2().domain([yMin, yMax]).nice(VALUE_TICK_COUNT2).range([plotDimsIn.y + plotDimsIn.height, plotDimsIn.y]);
  const provisionalYAxisPlan = !yAxisDeleted ? planValueAxis({
    ctx,
    axis: yAxisConfig,
    scale: provisionalYScale,
    preferredTickCount: VALUE_TICK_COUNT2,
    themeMap
  }) : undefined;
  const yTitleMetrics = !yAxisDeleted ? measureAxisTitle(ctx, yAxisConfig?.title, yAxisConfig?.titleTextStyle, yStyles.fontSize, -90) : undefined;
  const labelBand = !yAxisDeleted ? provisionalYAxisPlan?.labelBandWidth ?? 0 : 0;
  const yTitleBand = !yAxisDeleted && yTitleMetrics ? AXIS_TITLE_GAP_PX2 + yTitleMetrics.width : 0;
  const leftCap = plotDimsIn.width * maxLeftFrac;
  const reservedLeft = yAxisDeleted ? 0 : Math.min(leftCap, labelBand + yTitleBand);
  const xStyles = getAxisStyles(chart.xAxis, themeMap);
  ctx.font = `${xStyles.fontSize}px ${FONT_FAMILY}`;
  const xAxisConfig = chart.xAxis;
  const xAxisDeleted = !!xAxisConfig?.deleted;
  const xTitleMetrics = !xAxisDeleted ? measureAxisTitle(ctx, xAxisConfig?.title, xAxisConfig?.titleTextStyle, xStyles.fontSize, 0) : undefined;
  const xTitleBand = !xAxisDeleted && xTitleMetrics ? AXIS_TITLE_GAP_PX2 + xTitleMetrics.height : 0;
  const plotDimsBeforeBottom = {
    x: plotDimsIn.x + reservedLeft,
    y: plotDimsIn.y,
    width: Math.max(0, plotDimsIn.width - reservedLeft),
    height: plotDimsIn.height
  };
  const bottomCap = plotDimsIn.height * maxBottomFrac;
  const xAxisPlan = !xAxisDeleted && plotDimsBeforeBottom.width > 0 && plotDimsBeforeBottom.height > 0 ? planCategoryAxis({
    ctx,
    axis: xAxisConfig,
    categories,
    scale: createScales(chart, plotDimsBeforeBottom).x,
    plotDims: plotDimsBeforeBottom,
    themeMap,
    maxLabelBandHeightPx: Math.max(0, bottomCap - xTitleBand)
  }) : undefined;
  const reservedBottom = xAxisDeleted ? 0 : Math.min(bottomCap, (xAxisPlan?.labelBandHeight ?? 0) + xTitleBand);
  const plotDims = {
    x: plotDimsIn.x + reservedLeft,
    y: plotDimsIn.y,
    width: Math.max(0, plotDimsIn.width - reservedLeft),
    height: Math.max(0, plotDimsIn.height - reservedBottom)
  };
  const yAxisPlan = !yAxisDeleted ? planValueAxis({
    ctx,
    axis: yAxisConfig,
    scale: linear2().domain([yMin, yMax]).nice(VALUE_TICK_COUNT2).range([plotDims.y + plotDims.height, plotDims.y]),
    preferredTickCount: VALUE_TICK_COUNT2,
    themeMap
  }) : undefined;
  return { plotDims, reservedLeft, reservedBottom, xAxisPlan, yAxisPlan };
}
var DEFAULT_TRENDLINE_TYPE2 = "linear";
var TRENDLINE_TYPE_FROM_PROTO_SAFE2 = {
  [1 /* TRENDLINE_TYPE_LINEAR */]: "linear",
  [2 /* TRENDLINE_TYPE_EXPONENTIAL */]: "exponential",
  [3 /* TRENDLINE_TYPE_LOGARITHMIC */]: "logarithmic",
  [4 /* TRENDLINE_TYPE_POLYNOMIAL */]: "polynomial",
  [5 /* TRENDLINE_TYPE_POWER */]: "power",
  [6 /* TRENDLINE_TYPE_MOVING_AVERAGE */]: "movingAverage"
};

// node_modules/@oai/granola/dist/draw-utils/chart/create-scales-xy.js
function getPreferredXYAxisTickCounts(dims) {
  return {
    xTickCount: Math.max(2, Math.floor(dims.width / 80)),
    yTickCount: Math.max(2, Math.floor(dims.height / 60))
  };
}
function expandIfFlat([min2, max3]) {
  if (!Number.isFinite(min2) || !Number.isFinite(max3)) {
    return [0, 1];
  }
  if (min2 === max3) {
    if (min2 === 0)
      return [-1, 1];
    const delta = Math.abs(min2) * 0.1 || 1;
    return [min2 - delta, max3 + delta];
  }
  return [min2, max3];
}
function createScalesXY(chart, dims, prepared) {
  const xAxis = chart.xAxis ?? chart.yAxis;
  const yAxis = chart.yAxis ?? chart.xAxis;
  const sizeExtent = prepared.extents.size;
  const xDomainRaw = [
    xAxis?.min ?? prepared.extents.x[0],
    xAxis?.max ?? prepared.extents.x[1]
  ];
  const yDomainRaw = [
    yAxis?.min ?? prepared.extents.y[0],
    yAxis?.max ?? prepared.extents.y[1]
  ];
  const xDomain = expandIfFlat(xDomainRaw);
  const yDomain = expandIfFlat(yDomainRaw);
  const xRange = [dims.x, dims.x + dims.width];
  const yRange = [dims.y + dims.height, dims.y];
  if (xAxis?.orientation === 2 /* AXIS_ORIENTATION_MAX_MIN */) {
    xRange.reverse();
  }
  if (yAxis?.orientation === 2 /* AXIS_ORIENTATION_MAX_MIN */) {
    yRange.reverse();
  }
  const { xTickCount, yTickCount } = getPreferredXYAxisTickCounts(dims);
  const x2 = linear2().domain(xDomain).range(xRange).nice(xTickCount);
  const y2 = linear2().domain(yDomain).range(yRange).nice(yTickCount);
  let r;
  if (sizeExtent) {
    const minSize = Math.max(0, sizeExtent[0]);
    const maxSize = Math.max(minSize, sizeExtent[1]);
    const [width, height] = [dims.width, dims.height];
    const maxRadius = Math.max(4, Math.min(width, height) / 12);
    const minRadius = Math.min(4, maxRadius * 0.5);
    r = sqrt().domain(expandIfFlat([minSize, maxSize])).range([minRadius, maxRadius]);
  }
  return { x: x2, y: y2, r };
}

// node_modules/@oai/granola/dist/draw-utils/chart/layout-axes-xy.js
var AXIS_TICK_GAP_PX3 = 6;
var AXIS_TITLE_GAP_PX3 = 8;
function formatAxesXYTick(value, formatCode) {
  return formatValueAxisTick(value, formatCode);
}
function getAxesXYMetrics(ctx, chart, scales, dims, themeMap) {
  const xAxis = chart.xAxis ?? chart.yAxis;
  const yAxis = chart.yAxis ?? chart.xAxis;
  const xStyles = getAxisStyles(xAxis, themeMap);
  const yStyles = getAxisStyles(yAxis, themeMap);
  const xAxisDeleted = !!xAxis?.deleted;
  const yAxisDeleted = !!yAxis?.deleted;
  const { xTickCount, yTickCount } = getPreferredXYAxisTickCounts(dims);
  const xTicks = xAxisDeleted ? [] : scales.x.ticks(xTickCount);
  const yAxisPlan = !yAxisDeleted ? planValueAxis({
    ctx,
    axis: yAxis,
    scale: scales.y,
    preferredTickCount: yTickCount,
    themeMap
  }) : undefined;
  const yTicks = yAxisPlan?.ticks ?? [];
  const showXTicks = xAxis?.majorTickMark !== undefined && xAxis.majorTickMark !== 0 /* TICK_MARK_UNSPECIFIED */ && xAxis.majorTickMark !== 1 /* TICK_MARK_NONE */;
  const showYTicks = yAxis?.majorTickMark !== undefined && yAxis.majorTickMark !== 0 /* TICK_MARK_UNSPECIFIED */ && yAxis.majorTickMark !== 1 /* TICK_MARK_NONE */;
  const drawXGrid = !!xAxis?.majorGridlines?.fill?.color;
  const drawYGrid = !!yAxis?.majorGridlines?.fill?.color;
  ctx.font = `${xStyles.fontSize}px ${FONT_FAMILY}`;
  const xLabelBand = !xAxisDeleted && xTicks.length > 0 ? xStyles.fontSize + AXIS_TICK_GAP_PX3 : 0;
  const yLabelBand = !yAxisDeleted ? yAxisPlan?.labelBandWidth ?? 0 : 0;
  const xTitleMetrics = !xAxisDeleted ? measureAxisTitle(ctx, xAxis?.title, xAxis?.titleTextStyle, xStyles.fontSize, 0) : undefined;
  const yTitleMetrics = !yAxisDeleted ? measureAxisTitle(ctx, yAxis?.title, yAxis?.titleTextStyle, yStyles.fontSize, -90) : undefined;
  return {
    xAxis,
    yAxis,
    xStyles,
    yStyles,
    xAxisDeleted,
    yAxisDeleted,
    xTicks,
    yTicks,
    yAxisPlan,
    showXTicks,
    showYTicks,
    drawXGrid,
    drawYGrid,
    xLabelBand,
    yLabelBand,
    xTitleMetrics,
    yTitleMetrics
  };
}
function layoutAxesXY(ctx, chart, scales, plotDimsIn, themeMap, caps = {}) {
  const maxLeftFrac = caps.maxLeftFrac ?? 1;
  const maxBottomFrac = caps.maxBottomFrac ?? 1;
  const metrics = getAxesXYMetrics(ctx, chart, scales, plotDimsIn, themeMap);
  const leftCap = plotDimsIn.width * maxLeftFrac;
  const bottomCap = plotDimsIn.height * maxBottomFrac;
  const reservedLeft = metrics.yAxisDeleted ? 0 : Math.min(leftCap, metrics.yLabelBand + (metrics.yTitleMetrics ? AXIS_TITLE_GAP_PX3 + metrics.yTitleMetrics.width : 0));
  const reservedBottom = metrics.xAxisDeleted ? 0 : Math.min(bottomCap, metrics.xLabelBand + (metrics.xTitleMetrics ? AXIS_TITLE_GAP_PX3 + metrics.xTitleMetrics.height : 0));
  return {
    plotDims: {
      x: plotDimsIn.x + reservedLeft,
      y: plotDimsIn.y,
      width: Math.max(0, plotDimsIn.width - reservedLeft),
      height: Math.max(0, plotDimsIn.height - reservedBottom)
    },
    reservedLeft,
    reservedBottom,
    yAxisPlan: metrics.yAxisPlan
  };
}

// node_modules/@oai/granola/dist/draw-utils/chart/layout-data-labels.js
function layoutDataLabels(chart, plotDimsIn, maxTopFrac = 0.1) {
  const dl = chart.dataLabels;
  if (!dl || !dl.showValue)
    return { reservedTop: 0 };
  const pos = dl.position;
  if (pos !== 1 /* DATA_LABEL_POSITION_OUT_END */) {
    return { reservedTop: 0 };
  }
  const fs2 = dl.textStyle?.fontSize ? dl.textStyle.fontSize / 100 * (96 / 72) : TICK_FONT_SIZE;
  const gap = 12;
  const need = fs2 + gap;
  const cap = plotDimsIn.height * maxTopFrac;
  return { reservedTop: Math.min(cap, need) };
}

// node_modules/@oai/granola/dist/draw-utils/chart/layout-data-table.js
function readDataTable(chart) {
  if (!chart || typeof chart !== "object")
    return null;
  const maybe = chart["dataTable"];
  if (!maybe || typeof maybe !== "object")
    return null;
  return maybe;
}
function layoutDataTable(chart, plotDimsIn, opts = {}) {
  const dataTable = readDataTable(chart);
  if (!dataTable?.visible) {
    return { plotDims: plotDimsIn };
  }
  const maxFrac = opts.maxHeightFrac ?? 0.3;
  const minHeightPx = opts.minHeightPx ?? 48;
  const cap = Math.max(0, plotDimsIn.height * maxFrac);
  const desired = Math.max(minHeightPx, cap);
  const h = Math.min(plotDimsIn.height, desired);
  const tableRect = {
    x: plotDimsIn.x,
    y: plotDimsIn.y + Math.max(0, plotDimsIn.height - h),
    width: plotDimsIn.width,
    height: h
  };
  const plotDims = {
    x: plotDimsIn.x,
    y: plotDimsIn.y,
    width: plotDimsIn.width,
    height: Math.max(0, plotDimsIn.height - h)
  };
  return { plotDims, tableRect };
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-data-table.js
function readDataTable2(chart) {
  const maybe = chart["dataTable"];
  if (!maybe || typeof maybe !== "object")
    return null;
  return maybe;
}
function readTextStyle(v) {
  if (!v || typeof v !== "object")
    return;
  return v;
}
function readColor(value) {
  if (!value || typeof value !== "object")
    return;
  const maybe = value;
  return typeof maybe["type"] === "number" ? value : undefined;
}
function drawDataTable(ctx, chart, rect, themeMap, hiddenSeriesIndices) {
  const dt = readDataTable2(chart);
  if (!dt?.visible)
    return;
  if (rect.width <= 0 || rect.height <= 0)
    return;
  const categories = chart.categories.length > 0 ? chart.categories : chart.series[0]?.categories ?? [];
  const visibleSeries = [];
  chart.series.forEach((s, idx) => {
    if (!s)
      return;
    if (hiddenSeriesIndices?.has(idx))
      return;
    visibleSeries.push({ series: s, idx });
  });
  if (visibleSeries.length === 0 || categories.length === 0)
    return;
  const showLegendKey = Boolean(dt.showLegendKey);
  const cols = 1 + visibleSeries.length;
  const rows = 1 + categories.length;
  const cellW = rect.width / cols;
  const cellH = rect.height / rows;
  ctx.save();
  const fill = dt.fill;
  if (fill) {
    ctx.fillStyle = resolveFillPaint(ctx, rect, fill, themeMap, "transparent");
    ctx.fillRect(rect.x, rect.y, rect.width, rect.height);
  }
  const stroke = dt.stroke;
  if (stroke) {
    applyLineStyle(ctx, stroke, themeMap, { color: "#c0c0c0", widthPx: 0.75 });
  } else {
    ctx.strokeStyle = "#c0c0c0";
    ctx.lineWidth = 0.75;
    ctx.setLineDash([]);
  }
  ctx.beginPath();
  ctx.rect(rect.x, rect.y, rect.width, rect.height);
  ctx.stroke();
  for (let c = 1;c < cols; c++) {
    const x2 = rect.x + c * cellW;
    ctx.beginPath();
    ctx.moveTo(x2, rect.y);
    ctx.lineTo(x2, rect.y + rect.height);
    ctx.stroke();
  }
  for (let r = 1;r < rows; r++) {
    const y2 = rect.y + r * cellH;
    ctx.beginPath();
    ctx.moveTo(rect.x, y2);
    ctx.lineTo(rect.x + rect.width, y2);
    ctx.stroke();
  }
  const ts = readTextStyle(dt.textStyle);
  const fs2 = ts?.fontSize ? fontSizeToPx(ts.fontSize) : TICK_FONT_SIZE;
  const textColor = resolveColor(readColor(ts?.fill?.color), themeMap, AXIS_COLOR);
  const isBold = ts?.bold ?? false;
  ctx.font = `${isBold ? "bold " : ""}${fs2}px ${FONT_FAMILY}`;
  ctx.fillStyle = textColor;
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.fillText("", rect.x + cellW / 2, rect.y + cellH / 2);
  visibleSeries.forEach(({ series, idx }, sIdx) => {
    const headerX = rect.x + (1 + sIdx) * cellW + cellW / 2;
    const headerY = rect.y + cellH / 2;
    const name = series.name?.trim() || `Series ${idx + 1}`;
    ctx.fillText(name, headerX, headerY);
    if (showLegendKey) {
      const keySize = Math.min(10, cellH - 4);
      const keyX = headerX - cellW / 2 + 4;
      const keyY = headerY - keySize / 2;
      ctx.save();
      ctx.fillStyle = getSeriesColor(series, idx, themeMap) ?? "#666666";
      ctx.fillRect(keyX, keyY, keySize, keySize);
      ctx.restore();
    }
  });
  categories.forEach((cat, rIdx) => {
    const rowY = rect.y + (1 + rIdx) * cellH + cellH / 2;
    ctx.fillText(String(cat ?? ""), rect.x + cellW / 2, rowY);
    visibleSeries.forEach(({ series, idx }, sIdx) => {
      const v = series.values?.[rIdx];
      const formatted = typeof v === "number" && Number.isFinite(v) ? formatValue(v, series.valuesFormatCode ?? undefined) : "";
      const x2 = rect.x + (1 + sIdx) * cellW + cellW / 2;
      ctx.fillText(formatted, x2, rowY);
    });
  });
  ctx.restore();
}
// node_modules/@oai/granola/dist/draw-utils/chart/treemap/draw-treemap.js
var MIN_LABEL_WIDTH = 36;
var MIN_LABEL_HEIGHT = 24;
var RECT_CORNER_RADIUS = 2;
var LABEL_PADDING = 4;
var POSITION_EPSILON = 0.5;
var BRANCH_LABEL_FONT = `700 12px ${FONT_FAMILY}`;
var BRANCH_LABEL_LINE_HEIGHT = 14;
var BRANCH_LABEL_BOTTOM_GAP = 4;
function drawTreemap(ctx, prepared, dims, opts) {
  if (prepared.leaves.length === 0)
    return;
  const formatCode = opts.chart.series[0]?.valuesFormatCode ?? undefined;
  const parentLabelTargets = collectLeafParentTargets(prepared.parents, prepared.leaves);
  ctx.save();
  ctx.beginPath();
  ctx.rect(dims.x, dims.y, dims.width, dims.height);
  ctx.clip();
  const layout = opts.chart.treemapOptions?.parentLabelLayout;
  let branchLabelInfo;
  if (layout === 3 /* PARENT_LABEL_LAYOUT_OVERLAPPING */) {
    branchLabelInfo = computeBranchLabelPlacements(ctx, parentLabelTargets, prepared.leaves);
  }
  drawLeaves(ctx, prepared.leaves, formatCode, branchLabelInfo?.byLeafKey);
  drawParentLabels(ctx, layout, branchLabelInfo);
  ctx.restore();
}
function drawLeaves(ctx, leaves, formatCode, branchPlacementsByLeafKey) {
  for (const leaf of leaves) {
    if (leaf.width <= 0 || leaf.height <= 0)
      continue;
    drawLeafRect(ctx, leaf);
    const placement = branchPlacementsByLeafKey?.get(getLeafKey(leaf));
    const labelOptions = placement ? {
      verticalAlign: "bottom",
      reservedTop: placement.reservedTop
    } : undefined;
    drawLeafLabel(ctx, leaf, formatCode, labelOptions);
  }
}
function drawLeafRect(ctx, leaf) {
  ctx.save();
  ctx.beginPath();
  roundedRectPath(ctx, leaf.x, leaf.y, leaf.width, leaf.height, RECT_CORNER_RADIUS);
  ctx.fillStyle = leaf.fill;
  ctx.fill();
  ctx.lineWidth = 0.5;
  ctx.strokeStyle = "rgba(255,255,255,0.6)";
  ctx.stroke();
  ctx.restore();
}
function drawLeafLabel(ctx, leaf, formatCode, options) {
  const availableWidth = leaf.width - LABEL_PADDING * 2;
  const reservedTop = Math.max(0, options?.reservedTop ?? 0);
  const areaTop = leaf.y + LABEL_PADDING + reservedTop;
  const areaBottom = leaf.y + leaf.height - LABEL_PADDING;
  const availableHeight = areaBottom - areaTop;
  if (availableWidth < MIN_LABEL_WIDTH || availableHeight < MIN_LABEL_HEIGHT) {
    return;
  }
  const baseColor = color(leaf.fill) ?? color("#000000");
  const textColor = pickTextColor(baseColor);
  const valueColor = textColor === "#ffffff" ? "rgba(255,255,255,0.8)" : "rgba(0,0,0,0.7)";
  const labelLines = layoutLabelLines(ctx, leaf.name, availableWidth, availableHeight);
  if (labelLines.length === 0)
    return;
  const valueLabel = formatValue(leaf.value, formatCode);
  ctx.save();
  ctx.beginPath();
  ctx.rect(leaf.x, leaf.y, leaf.width, leaf.height);
  ctx.clip();
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.font = `600 11px ${FONT_FAMILY}`;
  const alignBottom = options?.verticalAlign === "bottom";
  ctx.fillStyle = textColor;
  const lineHeight = 14;
  const maxNameLines = Math.min(labelLines.length, Math.floor(availableHeight / lineHeight) - 1);
  const linesToDraw = labelLines.slice(0, Math.max(1, maxNameLines));
  const includeValueLine = linesToDraw.length * lineHeight + lineHeight <= availableHeight;
  const contentHeight = linesToDraw.length * lineHeight + (includeValueLine ? lineHeight : 0);
  let y2 = alignBottom ? areaBottom - contentHeight : areaTop;
  for (const line of linesToDraw) {
    ctx.fillText(line, leaf.x + LABEL_PADDING, y2, availableWidth);
    y2 += lineHeight;
  }
  if (includeValueLine) {
    ctx.font = `500 10px ${FONT_FAMILY}`;
    ctx.fillStyle = valueColor;
    ctx.fillText(valueLabel, leaf.x + LABEL_PADDING, y2, availableWidth);
  }
  ctx.restore();
}
function layoutLabelLines(ctx, text, maxWidth, maxHeight, fontSpec = `600 11px ${FONT_FAMILY}`) {
  ctx.save();
  ctx.font = fontSpec;
  const words = text.split(/(?=[A-Z][a-z])|\s+/g).filter(Boolean);
  const lines = [];
  let current = "";
  const lineHeight = 14;
  let remainingHeight = maxHeight;
  for (const word of words) {
    const tentative = current ? `${current} ${word}` : word;
    const width = ctx.measureText(tentative).width;
    if (width <= maxWidth) {
      current = tentative;
      continue;
    }
    if (current) {
      lines.push(truncateLine(ctx, current, maxWidth));
      remainingHeight -= lineHeight;
      if (remainingHeight < lineHeight) {
        current = "";
        break;
      }
    }
    current = word;
  }
  if (current && remainingHeight >= lineHeight) {
    lines.push(truncateLine(ctx, current, maxWidth));
  }
  ctx.restore();
  return lines;
}
function truncateLine(ctx, text, maxWidth) {
  if (ctx.measureText(text).width <= maxWidth) {
    return text;
  }
  let truncated = text;
  while (truncated.length > 1 && ctx.measureText(`${truncated}…`).width > maxWidth) {
    truncated = truncated.slice(0, -1);
  }
  return `${truncated}…`;
}
function drawParentLabels(ctx, layout, branchLabelInfo) {
  if (!layout || layout === 1 /* PARENT_LABEL_LAYOUT_NONE */) {
    return;
  }
  switch (layout) {
    case 3 /* PARENT_LABEL_LAYOUT_OVERLAPPING */:
      drawOverlappingParentLabels(ctx, branchLabelInfo);
      break;
    case 2 /* PARENT_LABEL_LAYOUT_BANNER */:
      break;
    default:
      break;
  }
}
function drawOverlappingParentLabels(ctx, branchLabelInfo) {
  if (!branchLabelInfo || branchLabelInfo.placements.length === 0)
    return;
  ctx.save();
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  for (const placement of branchLabelInfo.placements) {
    const { leaf, lines } = placement;
    if (leaf.width <= 0 || leaf.height <= 0 || lines.length === 0)
      continue;
    const availableWidth = leaf.width - LABEL_PADDING * 2;
    if (availableWidth <= 0)
      continue;
    const baseColor = color(leaf.fill) ?? color("#000000");
    const textColor = pickTextColor(baseColor);
    ctx.save();
    ctx.beginPath();
    ctx.rect(leaf.x, leaf.y, leaf.width, leaf.height);
    ctx.clip();
    ctx.font = BRANCH_LABEL_FONT;
    ctx.fillStyle = textColor;
    let y2 = leaf.y + LABEL_PADDING;
    for (const line of lines) {
      ctx.fillText(line, leaf.x + LABEL_PADDING, y2, availableWidth);
      y2 += BRANCH_LABEL_LINE_HEIGHT;
    }
    ctx.restore();
  }
  ctx.restore();
}
function roundedRectPath(ctx, x2, y2, width, height, radius) {
  const r = Math.min(radius, width / 2, height / 2);
  ctx.moveTo(x2 + r, y2);
  ctx.lineTo(x2 + width - r, y2);
  ctx.quadraticCurveTo(x2 + width, y2, x2 + width, y2 + r);
  ctx.lineTo(x2 + width, y2 + height - r);
  ctx.quadraticCurveTo(x2 + width, y2 + height, x2 + width - r, y2 + height);
  ctx.lineTo(x2 + r, y2 + height);
  ctx.quadraticCurveTo(x2, y2 + height, x2, y2 + height - r);
  ctx.lineTo(x2, y2 + r);
  ctx.quadraticCurveTo(x2, y2, x2 + r, y2);
  ctx.closePath();
}
function pickTextColor(col) {
  if (!col)
    return "#1a1a1a";
  const rgb2 = col.rgb();
  const r = rgb2.r / 255;
  const g = rgb2.g / 255;
  const b = rgb2.b / 255;
  const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
  return luminance > 0.55 ? "#1a1a1a" : "#ffffff";
}
function computeBranchLabelPlacements(ctx, parents, leaves) {
  const placements = [];
  const byLeafKey = new Map;
  for (const parent of parents) {
    const candidateLeaves = leaves.filter((leaf) => isLeafUnderParent(leaf, parent));
    if (candidateLeaves.length === 0)
      continue;
    const targetLeaf = selectTopLeftLeaf(candidateLeaves);
    if (!targetLeaf)
      continue;
    const availableWidth = targetLeaf.width - LABEL_PADDING * 2;
    const availableHeight = targetLeaf.height - LABEL_PADDING * 2;
    if (availableWidth <= 0 || availableHeight <= MIN_LABEL_HEIGHT)
      continue;
    const maxHeight = Math.max(BRANCH_LABEL_LINE_HEIGHT, availableHeight - MIN_LABEL_HEIGHT);
    const lines = layoutLabelLines(ctx, parent.name, availableWidth, maxHeight, BRANCH_LABEL_FONT);
    if (lines.length === 0)
      continue;
    const branchHeight = lines.length * BRANCH_LABEL_LINE_HEIGHT;
    const reservedTop = branchHeight + BRANCH_LABEL_BOTTOM_GAP;
    if (availableHeight - reservedTop < MIN_LABEL_HEIGHT) {
      continue;
    }
    const placement = {
      parent,
      leaf: targetLeaf,
      lines,
      reservedTop
    };
    const key = getLeafKey(targetLeaf);
    placements.push(placement);
    byLeafKey.set(key, placement);
  }
  return { placements, byLeafKey };
}
function collectLeafParentTargets(parents, leaves) {
  return parents.filter((parent) => leaves.some((leaf) => isLeafDirectChildOfParent(leaf, parent)));
}
function getLeafKey(leaf) {
  return leaf.path.join("\x00") || leaf.name;
}
function isLeafUnderParent(leaf, parent) {
  if (leaf.path.length < parent.path.length) {
    return false;
  }
  for (let i = 0;i < parent.path.length; i += 1) {
    if (leaf.path[i] !== parent.path[i]) {
      return false;
    }
  }
  return true;
}
function isLeafDirectChildOfParent(leaf, parent) {
  return leaf.path.length === parent.path.length + 1 && isLeafUnderParent(leaf, parent);
}
function selectTopLeftLeaf(leaves) {
  if (leaves.length === 0)
    return;
  let best = leaves[0];
  for (let i = 1;i < leaves.length; i += 1) {
    const current = leaves[i];
    if (current.y < best.y - POSITION_EPSILON) {
      best = current;
      continue;
    }
    if (Math.abs(current.y - best.y) <= POSITION_EPSILON) {
      if (current.x < best.x - POSITION_EPSILON) {
        best = current;
      }
    }
  }
  return best;
}
// node_modules/@oai/granola/dist/draw-utils/chart/sunburst/prepare-sunburst.js
var PATH_DELIMITER2 = "\x00";
function prepareSunburstData(chart, dims, themeMap) {
  const aggregated = aggregateLeaves2(chart);
  const radius = Math.max(0, Math.min(dims.width, dims.height) / 2);
  if (aggregated.length === 0 || radius === 0) {
    return { arcs: [], maxDepth: 0, radius };
  }
  const builderRoot = buildTree2(aggregated);
  const rootDatum = toDatum2(builderRoot);
  const rootNode = hierarchy(rootDatum).sum((d) => typeof d.value === "number" && d.value > 0 ? d.value : 0).sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
  const partitionLayout = partition_default().size([2 * Math.PI, radius]);
  const partitionRoot = partitionLayout(rootNode);
  const colorScale = buildColorScale2(themeMap, aggregated);
  const arcs = partitionRoot.descendants().filter((node) => node.depth > 0 && (node.value ?? 0) > 0 && Number.isFinite(node.x0) && Number.isFinite(node.x1) && node.x1 > node.x0).map((node) => {
    const path3 = node.data.path;
    const topLevel = path3[0];
    const fill = colorScale(topLevel);
    return {
      name: node.data.name,
      path: path3,
      value: node.value ?? 0,
      depth: node.depth,
      startAngle: node.x0,
      endAngle: node.x1,
      innerRadius: Math.max(0, node.y0),
      outerRadius: Math.max(0, node.y1),
      fill
    };
  });
  const maxDepth = arcs.reduce((acc, arc) => Math.max(acc, arc.depth), 0);
  return { arcs, maxDepth, radius };
}
function aggregateLeaves2(chart) {
  const results = new Map;
  for (const series of chart.series) {
    const values = series.values ?? [];
    const categoryPaths = normalizePaths2(series.categoryPaths, values.length);
    const fallbackCategories = series.categories?.length ? series.categories : chart.categories;
    for (let i = 0;i < values.length; i += 1) {
      const value = values[i];
      if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
        continue;
      }
      const rawLevels = categoryPaths[i]?.levels;
      let levels = rawLevels?.filter((level) => typeof level === "string" && level.length > 0) ?? undefined;
      if (!levels || levels.length === 0) {
        const fallback = fallbackCategories?.[i];
        if (typeof fallback === "string" && fallback.length > 0) {
          levels = [fallback];
        }
      }
      if (!levels || levels.length === 0)
        continue;
      const path3 = [...levels].reverse();
      const key = path3.join(PATH_DELIMITER2);
      const existing = results.get(key);
      if (existing) {
        existing.value += value;
      } else {
        results.set(key, {
          path: path3,
          value
        });
      }
    }
  }
  return Array.from(results.values());
}
function normalizePaths2(paths, length) {
  if (!paths || paths.length === 0) {
    return new Array(length).fill(undefined);
  }
  if (paths.length >= length)
    return paths;
  const padded = paths.slice();
  while (padded.length < length) {
    padded.push({ levels: [] });
  }
  return padded;
}
function buildTree2(leaves) {
  const root = {
    name: "root",
    path: [],
    children: new Map
  };
  for (const leaf of leaves) {
    let node = root;
    leaf.path.forEach((segment, index) => {
      let child = node.children.get(segment);
      if (!child) {
        child = {
          name: segment,
          path: [...node.path, segment],
          children: new Map
        };
        node.children.set(segment, child);
      }
      node = child;
      if (index === leaf.path.length - 1) {
        node.value = (node.value ?? 0) + leaf.value;
      }
    });
  }
  return root;
}
function toDatum2(node) {
  const children = Array.from(node.children.values()).map(toDatum2);
  if (children.length === 0) {
    return {
      name: node.name,
      path: node.path,
      value: node.value ?? 0
    };
  }
  return {
    name: node.name,
    path: node.path,
    children
  };
}
function buildColorScale2(themeMap, leaves) {
  const domainSet = new Set;
  for (const leaf of leaves) {
    const candidate = leaf.path[0];
    if (candidate && candidate.length > 0) {
      domainSet.add(candidate);
    }
  }
  const domain = Array.from(domainSet.values());
  if (domain.length === 0) {
    return () => SERIES_COLORS[0] ?? "#999999";
  }
  const accentKeys = [
    "accent1",
    "accent2",
    "accent3",
    "accent4",
    "accent5",
    "accent6"
  ];
  const colorForIndex = (index) => {
    const accentKey = accentKeys[index % accentKeys.length];
    const accentColor = themeMap.colorMap[accentKey ?? ""];
    if (accentColor)
      return accentColor;
    return SERIES_COLORS[index % SERIES_COLORS.length] ?? SERIES_COLORS[0] ?? "#999999";
  };
  const colors = domain.map((_name, index) => colorForIndex(index));
  const scale = ordinal().domain(domain).range(colors);
  return (key) => {
    if (!key) {
      return SERIES_COLORS[0] ?? "#999999";
    }
    if (domainSet.has(key)) {
      return scale(key);
    }
    const idx = scale.domain().length;
    return colorForIndex(idx);
  };
}
// node_modules/@oai/granola/dist/draw-utils/chart/sunburst/draw-sunburst.js
function drawSunburst(ctx, prepared, dims, opts) {
  if (prepared.arcs.length === 0 || prepared.radius === 0)
    return;
  const padAngleMax = opts.padAngle ?? 0.005;
  const radius = prepared.radius;
  const cx = dims.x + dims.width / 2;
  const cy = dims.y + dims.height / 2;
  const arcGen = arc_default().startAngle((d) => d.startAngle).endAngle((d) => d.endAngle).padAngle((d) => Math.min((d.endAngle - d.startAngle) / 2 * 0.25, padAngleMax)).padRadius(radius * 0.5).innerRadius((d) => d.innerRadius).outerRadius((d) => Math.max(d.innerRadius, d.outerRadius - 1)).context(ctx);
  ctx.save();
  ctx.translate(cx, cy);
  for (const arcDatum of prepared.arcs) {
    ctx.beginPath();
    arcGen(arcDatum);
    ctx.fillStyle = arcDatum.fill;
    ctx.fill();
  }
  drawLabels(ctx, prepared.arcs, arcGen, opts.valueFormatCode);
  ctx.restore();
}
var MIN_ARC_LENGTH_FOR_LABEL = 28;
var MIN_RADIAL_THICKNESS_FOR_LABEL = 14;
var MIN_ARC_LENGTH_FOR_VALUE = 48;
var MIN_RADIAL_THICKNESS_FOR_VALUE = 24;
var NAME_FONT = `600 11px ${FONT_FAMILY}`;
var VALUE_FONT = `500 10px ${FONT_FAMILY}`;
var LINE_GAP = 14;
function drawLabels(ctx, arcs, arcGen, valueFormatCode) {
  for (const arc of arcs) {
    if (!arc.name)
      continue;
    const angleSpan = arc.endAngle - arc.startAngle;
    if (!Number.isFinite(angleSpan) || angleSpan <= 0)
      continue;
    const radialThickness = Math.max(0, arc.outerRadius - arc.innerRadius);
    if (radialThickness < MIN_RADIAL_THICKNESS_FOR_LABEL)
      continue;
    const midRadius = arc.innerRadius + radialThickness / 2;
    const arcLength = angleSpan * midRadius;
    if (arcLength < MIN_ARC_LENGTH_FOR_LABEL)
      continue;
    const nameWidth = measureText(ctx, NAME_FONT, arc.name);
    if (nameWidth > arcLength - 6)
      continue;
    let showValue = arc.value > 0 && radialThickness >= MIN_RADIAL_THICKNESS_FOR_VALUE && arcLength >= MIN_ARC_LENGTH_FOR_VALUE;
    let valueLabel = "";
    if (showValue) {
      valueLabel = formatValue(arc.value, valueFormatCode);
      const valueWidth = measureText(ctx, VALUE_FONT, valueLabel);
      if (valueWidth > arcLength - 6) {
        showValue = false;
      }
    }
    const [x2, y2] = arcGen.centroid(arc);
    const { primary, secondary } = pickTextColors(arc.fill);
    ctx.save();
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.font = NAME_FONT;
    ctx.fillStyle = primary;
    const nameY = showValue ? y2 - LINE_GAP / 2 : y2;
    ctx.fillText(arc.name, x2, nameY);
    if (showValue) {
      ctx.font = VALUE_FONT;
      ctx.fillStyle = secondary;
      const valueY = y2 + LINE_GAP / 2;
      ctx.fillText(valueLabel, x2, valueY);
    }
    ctx.restore();
  }
}
function measureText(ctx, font, text) {
  ctx.save();
  ctx.font = font;
  const width = ctx.measureText(text).width;
  ctx.restore();
  return width;
}
function pickTextColors(fill) {
  const base = color(fill);
  if (!base) {
    return {
      primary: "#1a1a1a",
      secondary: "rgba(0,0,0,0.7)"
    };
  }
  const rgb2 = base.rgb();
  const r = rgb2.r / 255;
  const g = rgb2.g / 255;
  const b = rgb2.b / 255;
  const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
  if (luminance > 0.55) {
    return {
      primary: "#1a1a1a",
      secondary: "rgba(0,0,0,0.6)"
    };
  }
  return {
    primary: "#ffffff",
    secondary: "rgba(255,255,255,0.8)"
  };
}
// node_modules/@oai/granola/dist/draw-utils/chart/draw-axes-xy.js
var AXIS_TITLE_GAP_PX4 = 8;
var AXIS_GRIDLINE_EPSILON_PX3 = 0.5;
function overlapsAxisLine3(a, b) {
  return Math.abs(a - b) <= AXIS_GRIDLINE_EPSILON_PX3;
}
function drawAxesXY(ctx, chart, scales, dims, themeMap) {
  const metrics = getAxesXYMetrics(ctx, chart, scales, dims, themeMap);
  const { xAxis, yAxis, xStyles, yStyles, xAxisDeleted, yAxisDeleted, xTicks, yTicks, yAxisPlan, showXTicks, showYTicks, drawXGrid, drawYGrid, xLabelBand, yLabelBand, xTitleMetrics, yTitleMetrics } = metrics;
  const baseLineY = dims.y + dims.height;
  const baseLineX = dims.x;
  ctx.save();
  ctx.lineWidth = 1;
  if (!xAxisDeleted && xAxis?.line?.fill?.color) {
    ctx.strokeStyle = xStyles.lineColor ?? AXIS_COLOR;
    ctx.beginPath();
    ctx.moveTo(dims.x, baseLineY);
    ctx.lineTo(dims.x + dims.width, baseLineY);
    ctx.stroke();
  }
  if (!yAxisDeleted && yAxis?.line?.fill?.color) {
    ctx.strokeStyle = yStyles.lineColor ?? AXIS_COLOR;
    ctx.beginPath();
    ctx.moveTo(baseLineX, dims.y);
    ctx.lineTo(baseLineX, dims.y + dims.height);
    ctx.stroke();
  }
  if (!xAxisDeleted) {
    ctx.font = `${xStyles.fontSize}px ${FONT_FAMILY}`;
    ctx.textAlign = "center";
    ctx.textBaseline = "top";
    ctx.fillStyle = xStyles.textColor;
    const xGridStrokeColor = xStyles.gridLineColor ?? xStyles.lineColor;
    xTicks.forEach((tick) => {
      const px = scales.x(tick);
      if (!Number.isFinite(px))
        return;
      if (drawXGrid && !overlapsAxisLine3(px, baseLineX)) {
        ctx.strokeStyle = xGridStrokeColor;
        ctx.beginPath();
        ctx.moveTo(px, dims.y);
        ctx.lineTo(px, dims.y + dims.height);
        ctx.stroke();
      }
      if (showXTicks) {
        ctx.strokeStyle = xStyles.lineColor;
        ctx.beginPath();
        ctx.moveTo(px, baseLineY);
        ctx.lineTo(px, baseLineY + 4);
        ctx.stroke();
      }
      const label = formatAxesXYTick(tick, xAxis?.numberFormatCode);
      ctx.fillText(label, px, baseLineY + 6);
    });
  }
  if (!yAxisDeleted) {
    ctx.font = `${yStyles.fontSize}px ${FONT_FAMILY}`;
    ctx.textAlign = "right";
    ctx.textBaseline = "middle";
    ctx.fillStyle = yStyles.textColor;
    const yGridStrokeColor = yStyles.gridLineColor ?? yStyles.lineColor;
    yTicks.forEach((tick) => {
      const py = scales.y(tick);
      if (!Number.isFinite(py))
        return;
      if (drawYGrid && !overlapsAxisLine3(py, baseLineY)) {
        ctx.strokeStyle = yGridStrokeColor;
        ctx.beginPath();
        ctx.moveTo(dims.x, py);
        ctx.lineTo(dims.x + dims.width, py);
        ctx.stroke();
      }
      if (showYTicks) {
        ctx.strokeStyle = yStyles.lineColor;
        ctx.beginPath();
        ctx.moveTo(baseLineX - 4, py);
        ctx.lineTo(baseLineX, py);
        ctx.stroke();
      }
      if (!yAxisPlan?.hideTickLabels) {
        const label = formatAxesXYTick(tick, yAxis?.numberFormatCode);
        ctx.fillText(label, baseLineX - 6, py);
      }
    });
  }
  if (xTitleMetrics) {
    const xTitleStyle = xAxis?.titleTextStyle;
    const resolvedColor = xTitleStyle?.fill?.color ? resolveColor(xTitleStyle.fill.color, themeMap) : xStyles.textColor;
    const offset = xLabelBand + AXIS_TITLE_GAP_PX4 + xTitleMetrics.height / 2;
    const titleY = baseLineY + offset;
    ctx.save();
    ctx.fillStyle = resolvedColor ?? AXIS_COLOR;
    ctx.font = `${xTitleMetrics.isBold ? "bold " : ""}${xTitleMetrics.fontPx}px ${FONT_FAMILY}`;
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.translate(dims.x + dims.width / 2, titleY);
    ctx.rotate(xTitleMetrics.rotationRad);
    ctx.fillText(xTitleMetrics.text, 0, 0);
    ctx.restore();
  }
  if (yTitleMetrics) {
    const yTitleStyle = yAxis?.titleTextStyle;
    const resolvedColor = yTitleStyle?.fill?.color ? resolveColor(yTitleStyle.fill.color, themeMap) : yStyles.textColor;
    const cx = dims.x - yLabelBand - AXIS_TITLE_GAP_PX4 - yTitleMetrics.width / 2;
    const cy = dims.y + dims.height / 2;
    ctx.save();
    ctx.fillStyle = resolvedColor ?? AXIS_COLOR;
    ctx.font = `${yTitleMetrics.isBold ? "bold " : ""}${yTitleMetrics.fontPx}px ${FONT_FAMILY}`;
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.translate(cx, cy);
    ctx.rotate(yTitleMetrics.rotationRad);
    ctx.fillText(yTitleMetrics.text, 0, 0);
    ctx.restore();
  }
  ctx.restore();
}

// node_modules/@oai/granola/dist/draw-utils/chart/prepare-xy-data.js
function coerceNumber(value) {
  if (typeof value === "number" && Number.isFinite(value))
    return value;
  if (typeof value === "string") {
    const trimmed = value.trim();
    if (trimmed.length === 0)
      return;
    const num = Number(trimmed);
    if (Number.isFinite(num))
      return num;
  }
  return;
}
function getSeriesXValues(chart, series, pointCount) {
  const values = [];
  const xValues = series.xValues ?? [];
  const categories = series.categories.length > 0 ? series.categories : chart.categories.length > 0 ? chart.categories : [];
  for (let idx = 0;idx < pointCount; idx++) {
    if (idx < xValues.length) {
      values.push(coerceNumber(xValues[idx]));
      continue;
    }
    if (idx < categories.length) {
      const coerced = coerceNumber(categories[idx]);
      if (coerced !== undefined) {
        values.push(coerced);
        continue;
      }
    }
    values.push(idx);
  }
  return values;
}
function prepareXYData(chart, opts = {}) {
  const hidden = opts.hiddenSeriesIndices ?? new Set;
  const preparedSeries = [];
  const allX = [];
  const allY = [];
  const allSizes = [];
  chart.series.forEach((series, seriesIndex) => {
    if (hidden.has(seriesIndex))
      return;
    const yValues = series.values ?? [];
    const pointCount = yValues.length;
    const xValues = getSeriesXValues(chart, series, pointCount);
    const bubbleSizes = series.bubbleSizes ?? [];
    const points = [];
    for (let idx = 0;idx < pointCount; idx++) {
      const yRaw = yValues[idx];
      const xRaw = xValues[idx];
      const y2 = coerceNumber(yRaw);
      const x2 = coerceNumber(xRaw);
      if (x2 === undefined || y2 === undefined)
        continue;
      const point3 = { idx, x: x2, y: y2 };
      if (opts.includeBubbleSize) {
        const sizeRaw = bubbleSizes[idx];
        const size = coerceNumber(sizeRaw);
        if (size !== undefined) {
          point3.size = Math.max(0, size);
          allSizes.push(point3.size);
        }
      }
      points.push(point3);
      allX.push(x2);
      allY.push(y2);
    }
    preparedSeries.push({ seriesIndex, series, points });
  });
  const xExtent = extent(allX);
  const yExtent = extent(allY);
  const xMin = Number.isFinite(xExtent[0] ?? NaN) ? xExtent[0] : 0;
  const xMax = Number.isFinite(xExtent[1] ?? NaN) ? xExtent[1] : 1;
  const yMin = Number.isFinite(yExtent[0] ?? NaN) ? yExtent[0] : 0;
  const yMax = Number.isFinite(yExtent[1] ?? NaN) ? yExtent[1] : 1;
  let sizeExtent;
  if (opts.includeBubbleSize && allSizes.length > 0) {
    const sizeExt = extent(allSizes);
    const sizeMin = Number.isFinite(sizeExt[0] ?? NaN) ? Math.max(0, sizeExt[0]) : 0;
    const sizeMax = Number.isFinite(sizeExt[1] ?? NaN) ? Math.max(sizeMin, sizeExt[1]) : sizeMin || 1;
    sizeExtent = [sizeMin, sizeMax];
  }
  return {
    series: preparedSeries,
    extents: {
      x: [xMin, xMax],
      y: [yMin, yMax],
      size: sizeExtent
    }
  };
}

// node_modules/@oai/granola/dist/draw-utils/chart/prepare-scatter-data.js
function prepareScatterData(chart, hiddenSeriesIndices) {
  return prepareXYData(chart, { hiddenSeriesIndices });
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-scatter-chart.js
function hasMarkers(style) {
  if (style === undefined)
    return true;
  return style === 3 /* SCATTER_STYLE_MARKER */ || style === 1 /* SCATTER_STYLE_LINE_MARKER */ || style === 5 /* SCATTER_STYLE_SMOOTH_MARKER */;
}
function hasLine(style) {
  if (style === undefined)
    return true;
  return style !== 3 /* SCATTER_STYLE_MARKER */;
}
function isSmooth(style) {
  return style === 4 /* SCATTER_STYLE_SMOOTH */ || style === 5 /* SCATTER_STYLE_SMOOTH_MARKER */;
}
function drawScatterChart(ctx, chart, plotDims, scales, themeMap, chartHoverTargets, hiddenSeriesIndices, preparedData, trendlineRenderCache) {
  const prepared = preparedData ?? prepareScatterData(chart, hiddenSeriesIndices);
  const style = chart.scatterOptions?.style;
  const drawLine = hasLine(style);
  const drawMarkers = hasMarkers(style);
  const smooth = isSmooth(style);
  const curve = smooth ? monotoneX : linear_default;
  prepared.series.forEach(({ series, seriesIndex, points }) => {
    if (points.length === 0) {
      return;
    }
    const strokeColor = getSeriesColor(series, seriesIndex, themeMap);
    const effectiveStroke = strokeColor ?? ctx.strokeStyle;
    if (drawLine) {
      ctx.save();
      ctx.strokeStyle = effectiveStroke;
      ctx.lineWidth = 2;
      const lineGenerator = line_default().defined((pt) => Number.isFinite(pt.x) && Number.isFinite(pt.y)).x((pt) => scales.x(pt.x)).y((pt) => scales.y(pt.y)).curve(curve).context(ctx);
      ctx.beginPath();
      lineGenerator(points);
      ctx.stroke();
      ctx.restore();
    }
    if (series.trendlines?.length) {
      const computed = trendlineRenderCache?.bySeriesIndex.get(seriesIndex);
      drawTrendlinesXY(ctx, chart, series, seriesIndex, points.map((p) => ({ x: p.x, y: p.y })), themeMap, { x: scales.x, y: scales.y }, plotDims, computed);
    }
    if (series["errorBars"]) {
      drawErrorBarsY(ctx, series, seriesIndex, themeMap, points.map((p) => {
        const cx = scales.x(p.x);
        const cy = scales.y(p.y);
        return { x: cx, y: cy, value: p.y };
      }).filter((p) => Number.isFinite(p.x) && Number.isFinite(p.y)), { y: scales.y });
    }
    if (!drawMarkers) {
      return;
    }
    const markerSymbol = series.marker?.symbol;
    const showMarkers = markerSymbol === undefined || markerSymbol === 0 /* MARKER_SYMBOL_UNSPECIFIED */ || markerSymbol !== 1 /* MARKER_SYMBOL_NONE */;
    if (!showMarkers) {
      return;
    }
    const markerSizePt = series.marker?.size;
    const baseDiameter = markerSizePt !== undefined && Number.isFinite(markerSizePt) ? markerSizePt * 96 / 72 : 6;
    const radius = Math.max(baseDiameter / 2 - 1, 2);
    points.forEach((pt) => {
      const cx = scales.x(pt.x);
      const cy = scales.y(pt.y);
      if (!Number.isFinite(cx) || !Number.isFinite(cy))
        return;
      const fill = pointHasNoFill(series, pt.idx) ? undefined : getPointFillColor(series, pt.idx, seriesIndex, themeMap);
      const stroke = getPointStroke(series, pt.idx, themeMap);
      ctx.save();
      ctx.beginPath();
      ctx.arc(cx, cy, radius, 0, Math.PI * 2);
      if (fill) {
        ctx.fillStyle = fill;
        ctx.fill();
      } else {
        ctx.fillStyle = effectiveStroke;
        ctx.fill();
      }
      const strokeColorEffective = stroke.color ?? effectiveStroke;
      const strokeWidth = stroke.widthPx !== undefined ? stroke.widthPx : Math.max(1, radius / 3);
      ctx.lineWidth = strokeWidth;
      ctx.strokeStyle = strokeColorEffective;
      ctx.stroke();
      ctx.restore();
      if (chartHoverTargets) {
        chartHoverTargets.push({
          kind: "scatter-point",
          x: cx - radius,
          y: cy - radius,
          width: radius * 2,
          height: radius * 2,
          seriesName: series.name,
          category: String(pt.x),
          value: pt.y,
          color: fill ?? strokeColor ?? effectiveStroke,
          anchorX: cx,
          anchorY: cy
        });
      }
      const dataLabel = resolveDataLabel(chart, series, pt.idx, pt.y);
      if (dataLabel.show) {
        drawDataLabel(ctx, dataLabel.text, dataLabel.position, dataLabel.positionName, dataLabel.textStyle, themeMap, { x: cx, y: cy });
      }
    });
  });
}

// node_modules/@oai/granola/dist/draw-utils/chart/prepare-bubble-data.js
function prepareBubbleData(chart, hiddenSeriesIndices) {
  return prepareXYData(chart, {
    hiddenSeriesIndices,
    includeBubbleSize: true
  });
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-bubble-chart.js
function drawBubbleChart(ctx, chart, scales, prepared, themeMap, chartHoverTargets) {
  const rScale = scales.r;
  const baseRadius = 6;
  const scaleMultiplier = chart.bubbleOptions?.scale !== undefined && Number.isFinite(chart.bubbleOptions.scale) ? chart.bubbleOptions.scale / 100 : 1;
  prepared.series.forEach(({ series, seriesIndex, points }) => {
    const seriesColor = getSeriesColor(series, seriesIndex, themeMap);
    const defaultFill = seriesColor ?? ctx.fillStyle;
    points.forEach((pt) => {
      const cx = scales.x(pt.x);
      const cy = scales.y(pt.y);
      if (!Number.isFinite(cx) || !Number.isFinite(cy))
        return;
      const rawRadius = pt.size !== undefined && rScale ? rScale(pt.size) : baseRadius;
      const radius = Math.max(2, rawRadius * Math.max(0.1, scaleMultiplier));
      const fill = pointHasNoFill(series, pt.idx) ? undefined : getPointFillColor(series, pt.idx, seriesIndex, themeMap) ?? defaultFill;
      const stroke = getPointStroke(series, pt.idx, themeMap);
      const strokeColor = stroke.color ?? defaultFill;
      const strokeWidth = stroke.widthPx !== undefined ? stroke.widthPx : Math.max(1, radius / 4);
      ctx.save();
      ctx.beginPath();
      ctx.arc(cx, cy, radius, 0, Math.PI * 2);
      ctx.fillStyle = fill ?? defaultFill;
      ctx.fill();
      ctx.lineWidth = strokeWidth;
      ctx.strokeStyle = strokeColor;
      ctx.stroke();
      ctx.restore();
      if (chartHoverTargets) {
        chartHoverTargets.push({
          kind: "bubble-point",
          x: cx - radius,
          y: cy - radius,
          width: radius * 2,
          height: radius * 2,
          seriesName: series.name,
          category: String(pt.x),
          value: pt.y,
          color: fill ?? defaultFill,
          anchorX: cx,
          anchorY: cy
        });
      }
    });
  });
}

// node_modules/@oai/granola/dist/draw-utils/chart/prepare-histogram-data.js
var HUMAN_NUMBER = format("~f");
function formatNumeric(value) {
  if (!Number.isFinite(value))
    return "";
  return HUMAN_NUMBER(value);
}
function formatBinLabel(x0, x1, index, total, intervalClosed) {
  const normalized = intervalClosed ?? 2 /* INTERVAL_CLOSED_RIGHT */;
  let leftSymbol = "[";
  let rightSymbol = ")";
  switch (normalized) {
    case 2 /* INTERVAL_CLOSED_RIGHT */:
      leftSymbol = index === 0 ? "[" : "(";
      rightSymbol = "]";
      break;
    case 1 /* INTERVAL_CLOSED_LEFT */:
      leftSymbol = "[";
      rightSymbol = index === total - 1 ? "]" : ")";
      break;
    default:
      leftSymbol = index === 0 ? "[" : "(";
      rightSymbol = index === total - 1 ? "]" : ")";
      break;
  }
  return `${leftSymbol}${formatNumeric(x0)}, ${formatNumeric(x1)}${rightSymbol}`;
}
function coerceNumber2(value) {
  if (typeof value === "number" && Number.isFinite(value)) {
    return value;
  }
  if (typeof value === "string") {
    const trimmed = value.trim();
    if (trimmed.length === 0)
      return;
    const parsed = Number(trimmed);
    if (Number.isFinite(parsed))
      return parsed;
  }
  return;
}
function parseRange(label) {
  const rangePattern = /(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)[^\d\-+eE]+(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/;
  const match = label.match(rangePattern);
  if (match) {
    const left = coerceNumber2(match[1]);
    const right = coerceNumber2(match[2]);
    if (left !== undefined && right !== undefined) {
      return left <= right ? [left, right] : [right, left];
    }
  }
  const singleValue = coerceNumber2(label);
  if (singleValue !== undefined) {
    return [singleValue, singleValue];
  }
  return;
}
function getHistogramOptions(chart) {
  return chart.histogramOptions;
}
function resolveDomain(samples, histogramOptions, chart) {
  const axisDomain = [
    coerceNumber2(chart.xAxis?.min),
    coerceNumber2(chart.xAxis?.max)
  ];
  const dataExtent = extent(samples);
  const min2 = axisDomain[0] ?? (Number.isFinite(dataExtent[0] ?? NaN) ? dataExtent[0] : 0);
  const max3 = axisDomain[1] ?? (Number.isFinite(dataExtent[1] ?? NaN) ? dataExtent[1] : min2 + 1);
  if (min2 === max3) {
    return [min2 - 0.5, max3 + 0.5];
  }
  const intervalClosed = histogramOptions?.intervalClosed;
  const inclusiveRight = intervalClosed === 2 /* INTERVAL_CLOSED_RIGHT */;
  if (!inclusiveRight) {
    return [min2, max3];
  }
  const epsilon3 = Math.max(Math.abs(max3 - min2) * 0.000000001, 0.000000001);
  return [min2, max3 + epsilon3];
}
function buildBinsFromAggregated(chart, seriesIndex, options) {
  const series = chart.series[seriesIndex];
  if (!series)
    return;
  const categories = series.categories.length > 0 ? series.categories : chart.categories.length > 0 ? chart.categories : [];
  const values = series.values ?? [];
  if (values.length === 0 || categories.length === 0) {
    return;
  }
  const bins = [];
  const numericStarts = [];
  const numericEnds = [];
  const configuredBinWidth = options?.binWidth && Number.isFinite(options.binWidth) ? Math.abs(options.binWidth) : undefined;
  categories.forEach((label, idx) => {
    const countRaw = coerceNumber2(values[idx]);
    if (!Number.isFinite(countRaw) || countRaw <= 0) {
      return;
    }
    const count3 = countRaw;
    const parsedRange = label ? parseRange(label) : undefined;
    let x0 = 0;
    let x1 = 0;
    if (parsedRange) {
      x0 = parsedRange[0];
      x1 = parsedRange[1];
      if (x0 === x1) {
        const step = configuredBinWidth ?? 1;
        x1 = x0 + step;
      }
    } else {
      const previousEnd = numericEnds.length > 0 ? numericEnds[numericEnds.length - 1] : 0;
      const step = configuredBinWidth ?? 1;
      x0 = previousEnd;
      x1 = previousEnd + step;
    }
    numericStarts.push(x0);
    numericEnds.push(x1);
    bins.push({
      x0,
      x1,
      count: count3,
      values: [],
      label
    });
  });
  if (bins.length === 0) {
    return;
  }
  const domainMin = Math.min(...numericStarts);
  const domainMax = Math.max(...numericEnds);
  const totalCount = bins.reduce((acc, bin2) => acc + bin2.count, 0);
  const maxCount = bins.reduce((acc, bin2) => Math.max(acc, bin2.count), 0);
  bins.forEach((bin2, idx) => {
    if (!bin2.label || bin2.label.trim().length === 0) {
      bin2.label = formatBinLabel(bin2.x0, bin2.x1, idx, bins.length, options?.intervalClosed ?? undefined);
    }
  });
  return {
    bins,
    extents: {
      x: [domainMin, domainMax],
      y: [0, maxCount]
    },
    totalCount,
    aggregated: true,
    seriesIndex
  };
}
function prepareHistogramData(chart, opts = {}) {
  const hidden = opts.hiddenSeriesIndices ?? new Set;
  const seriesIndex = chart.series.findIndex((_, idx) => !hidden.has(idx));
  if (seriesIndex === -1) {
    return {
      bins: [],
      extents: {
        x: [0, 1],
        y: [0, 1]
      },
      totalCount: 0,
      aggregated: false,
      seriesIndex: -1
    };
  }
  const histogramOptions = getHistogramOptions(chart);
  if (histogramOptions?.aggregated) {
    const aggregated = buildBinsFromAggregated(chart, seriesIndex, histogramOptions);
    if (aggregated)
      return aggregated;
  }
  const series = chart.series[seriesIndex];
  const rawValues = series?.values ?? [];
  const samples = rawValues.map((value) => coerceNumber2(value)).filter((value) => value !== undefined);
  if (samples.length === 0) {
    return {
      bins: [],
      extents: {
        x: [0, 1],
        y: [0, 1]
      },
      totalCount: 0,
      aggregated: false,
      seriesIndex
    };
  }
  const [domainMin, domainMax] = resolveDomain(samples, histogramOptions, chart);
  const span = Math.max(domainMax - domainMin, 1);
  const fallbackBinCount = Math.max(1, Math.ceil(Math.sqrt(samples.length)));
  const rawBinWidth = histogramOptions?.binWidth && Number.isFinite(histogramOptions.binWidth) ? Math.abs(histogramOptions.binWidth) : undefined;
  const thresholdCount = rawBinWidth && rawBinWidth > 0 ? Math.max(1, Math.floor(span / rawBinWidth)) : fallbackBinCount;
  const binner = bin().domain([domainMin, domainMax]).thresholds(thresholdCount);
  const binsRaw = binner(samples);
  const bins = binsRaw.map((bin2, idx) => {
    const x0 = bin2.x0 ?? domainMin;
    const x1 = bin2.x1 ?? domainMax;
    return {
      x0,
      x1,
      count: bin2.length,
      values: bin2.slice(),
      label: formatBinLabel(x0, x1, idx, binsRaw.length, histogramOptions?.intervalClosed ?? undefined)
    };
  });
  const totalCount = samples.length;
  const maxCount = bins.reduce((acc, bin2) => Math.max(acc, bin2.count), 0);
  const effectiveMax = domainMax > domainMin ? domainMax : domainMin + 1;
  return {
    bins,
    extents: {
      x: [domainMin, effectiveMax],
      y: [0, maxCount]
    },
    totalCount,
    aggregated: false,
    seriesIndex
  };
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-histogram-chart.js
function drawHistogramChart(ctx, chart, scales, prepared, themeMap, options = {}) {
  const seriesIndex = prepared.seriesIndex;
  if (seriesIndex < 0)
    return;
  const series = chart.series[seriesIndex];
  if (!series)
    return;
  const { chartHoverTargets } = options;
  const { x: x2, y: y2 } = scales;
  const baseline = y2(0);
  const GAP_PX = 1;
  prepared.bins.forEach((bin2, idx) => {
    if (!Number.isFinite(bin2.count) || bin2.count <= 0)
      return;
    const x0 = x2(bin2.x0);
    const x1 = x2(bin2.x1);
    if (!Number.isFinite(x0) || !Number.isFinite(x1))
      return;
    const barLeft = Math.min(x0, x1);
    const barRight = Math.max(x0, x1);
    const barWidth = Math.max(0, barRight - barLeft);
    if (barWidth <= 0)
      return;
    const barTop = y2(bin2.count);
    if (!Number.isFinite(barTop) || !Number.isFinite(baseline))
      return;
    const barHeight = Math.max(0, baseline - barTop);
    if (barHeight <= 0)
      return;
    const noFill = pointHasNoFill(series, idx);
    const fillColor = getPointFillColor(series, idx, seriesIndex, themeMap);
    if (!noFill && fillColor) {
      ctx.fillStyle = fillColor;
    }
    const strokeInfo = getPointStroke(series, idx, themeMap);
    const strokeColor = strokeInfo.color;
    const strokeWidth = strokeInfo.widthPx ?? 1;
    if (strokeColor && strokeWidth > 0) {
      ctx.strokeStyle = strokeColor;
      ctx.lineWidth = strokeWidth;
    } else {
      ctx.lineWidth = 0;
    }
    const applyGap = barWidth > GAP_PX;
    const drawLeft = applyGap ? barLeft + GAP_PX / 2 : barLeft;
    const drawWidth = applyGap ? Math.max(0, barWidth - GAP_PX) : barWidth;
    ctx.beginPath();
    ctx.rect(drawLeft, barTop, drawWidth, barHeight);
    if (!noFill && fillColor) {
      ctx.fill();
    }
    if (ctx.lineWidth > 0 && strokeColor) {
      ctx.stroke();
    }
    if (chartHoverTargets) {
      chartHoverTargets.push({
        kind: "bar-vertical",
        x: drawLeft,
        y: barTop,
        width: drawWidth,
        height: barHeight,
        seriesName: series.name ?? undefined,
        category: bin2.label ?? undefined,
        value: bin2.count,
        color: fillColor ?? undefined,
        anchorX: drawLeft + drawWidth / 2,
        anchorY: barTop,
        elementId: chart.id ?? undefined,
        seriesIndex
      });
    }
  });
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-waterfall-chart.js
var CONNECTOR_COLOR = "#c7c7c7";
var CONNECTOR_WIDTH = 1;
var ACCENT_FALLBACKS = {
  increase: "#5b9bd5",
  decrease: "#ed7d31",
  total: "#a5a5a5"
};
function getAccentColor(themeMap, kind) {
  const slot = kind === "increase" ? "accent1" : kind === "decrease" ? "accent2" : "accent3";
  const color2 = themeMap.colorMap?.[slot];
  if (color2 && color2.length > 0) {
    return color2;
  }
  return ACCENT_FALLBACKS[kind];
}
function findPointOverride2(series, pointIdx) {
  if (!series.points || series.points.length === 0)
    return;
  for (let i = 0;i < series.points.length; i++) {
    const pt = series.points[i];
    const rawIdx = pt?.idx;
    const resolvedIdx = rawIdx ?? i;
    if (resolvedIdx === pointIdx)
      return pt;
  }
  return;
}
function drawConnector(ctx, prevX, currentX, value, barWidth, yScale) {
  const y2 = yScale(value);
  ctx.save();
  ctx.strokeStyle = CONNECTOR_COLOR;
  ctx.lineWidth = CONNECTOR_WIDTH;
  ctx.beginPath();
  ctx.moveTo(prevX + barWidth, y2);
  ctx.lineTo(currentX, y2);
  ctx.stroke();
  ctx.restore();
}
function drawBar(ctx, segment, baseX, barWidth, yScale, chart, seriesIndex, themeMap) {
  const yStart = yScale(segment.start);
  const yEnd = yScale(segment.end);
  const top = Math.min(yStart, yEnd);
  const bottom = Math.max(yStart, yEnd);
  const height = Math.abs(yEnd - yStart);
  if (height === 0 || Number.isNaN(top) || Number.isNaN(bottom)) {
    return null;
  }
  const series = chart.series[seriesIndex];
  if (!series)
    return null;
  const pointOverride = findPointOverride2(series, segment.index);
  let skipFill = false;
  let fillColor;
  if (pointOverride?.fill) {
    if (pointOverride.fill.color) {
      fillColor = resolveColor(pointOverride.fill.color, themeMap);
    } else {
      skipFill = true;
    }
  }
  if (!fillColor && !skipFill && series.fill?.color) {
    fillColor = resolveColor(series.fill.color, themeMap);
  }
  if (!fillColor && !skipFill) {
    fillColor = getAccentColor(themeMap, segment.kind);
  }
  const { color: strokeColor, widthPx } = getPointStroke(series, segment.index, themeMap);
  const isPositive = segment.end >= segment.start;
  const radiusBase = Math.max(0, Math.min(BAR_CORNER_RADIUS, barWidth / 2, height));
  const roundTop = isPositive || segment.kind === "total";
  const rTop = roundTop ? radiusBase : 0;
  const rBottom = !roundTop ? radiusBase : 0;
  ctx.beginPath();
  if (isPositive) {
    ctx.moveTo(baseX, bottom);
    ctx.lineTo(baseX, top + rTop);
    ctx.arcTo(baseX, top, baseX + rTop, top, rTop);
    ctx.lineTo(baseX + barWidth - rTop, top);
    ctx.arcTo(baseX + barWidth, top, baseX + barWidth, top + rTop, rTop);
    ctx.lineTo(baseX + barWidth, bottom);
    ctx.closePath();
  } else {
    ctx.moveTo(baseX, top);
    ctx.lineTo(baseX, bottom - rBottom);
    ctx.arcTo(baseX, bottom, baseX + rBottom, bottom, rBottom);
    ctx.lineTo(baseX + barWidth - rBottom, bottom);
    ctx.arcTo(baseX + barWidth, bottom, baseX + barWidth, bottom - rBottom, rBottom);
    ctx.lineTo(baseX + barWidth, top);
    ctx.closePath();
  }
  if (fillColor) {
    ctx.fillStyle = fillColor;
    ctx.fill();
  }
  if (strokeColor) {
    ctx.strokeStyle = strokeColor;
    ctx.lineWidth = widthPx ?? 1;
    ctx.stroke();
  }
  return { top, bottom };
}
function drawDataLabel2(ctx, chart, seriesIndex, segment, rect, themeMap) {
  const series = chart.series[seriesIndex];
  if (!series)
    return;
  const dataLabel = resolveDataLabel(chart, series, segment.index, segment.labelValue);
  if (!dataLabel.show || rect.width <= 0)
    return;
  const fs2 = dataLabel.textStyle?.fontSize ? fontSizeToPx(dataLabel.textStyle.fontSize) : TICK_FONT_SIZE;
  const fillColor = dataLabel.textStyle?.fill?.color ? resolveColor(dataLabel.textStyle.fill.color, themeMap) : undefined;
  ctx.save();
  ctx.fillStyle = fillColor ?? AXIS_COLOR;
  const isBold = dataLabel.textStyle?.bold ?? true;
  ctx.font = `${isBold ? "bold " : ""}${fs2}px ${FONT_FAMILY}`;
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  const isPositive = segment.end >= segment.start;
  const centerX = rect.x + rect.width / 2;
  const height = rect.bottom - rect.top;
  let y2 = isPositive ? rect.top - 12 : rect.bottom + 12;
  switch (dataLabel.position) {
    case 2:
      y2 = isPositive ? rect.top + 12 : rect.bottom - 12;
      break;
    case 3:
      y2 = rect.top + height / 2;
      break;
    default:
      y2 = isPositive ? rect.top - 12 : rect.bottom + 12;
      break;
  }
  ctx.fillText(dataLabel.text, centerX, y2);
  ctx.restore();
}
function drawWaterfallChart(ctx, chart, scales, prepared, themeMap, opts = {}) {
  if (!isBandScale(scales.x) || prepared.seriesIndex === -1)
    return;
  const xScale = scales.x;
  const yScale = scales.y;
  const barWidth = xScale.bandwidth();
  const seriesIndex = prepared.seriesIndex;
  const series = chart.series[seriesIndex];
  if (!series)
    return;
  let prevDrawn;
  prepared.segments.forEach((segment) => {
    const x2 = xScale(segment.category);
    if (x2 === undefined)
      return;
    if (segment.kind !== "total" && prevDrawn) {
      drawConnector(ctx, prevDrawn.x, x2, segment.cumulativeBefore, barWidth, yScale);
    }
    const rect = drawBar(ctx, segment, x2, barWidth, yScale, chart, seriesIndex, themeMap);
    if (rect) {
      drawDataLabel2(ctx, chart, seriesIndex, segment, { ...rect, x: x2, width: barWidth }, themeMap);
      if (opts.chartHoverTargets) {
        opts.chartHoverTargets.push({
          kind: "bar-vertical",
          x: x2,
          y: rect.top,
          width: barWidth,
          height: rect.bottom - rect.top,
          category: segment.category,
          seriesName: series.name,
          value: segment.value,
          color: getAccentColor(themeMap, segment.kind),
          anchorX: x2,
          anchorY: rect.top
        });
      }
      prevDrawn = {
        x: x2,
        cumulativeAfter: segment.cumulativeAfter
      };
    }
  });
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-histogram-axes.js
var AXIS_GRIDLINE_EPSILON_PX4 = 0.5;
var AXIS_TICK_GAP_PX4 = 6;
var AXIS_TITLE_GAP_PX5 = 8;
function overlapsAxisLine4(a, b) {
  return Math.abs(a - b) <= AXIS_GRIDLINE_EPSILON_PX4;
}
function drawHistogramAxes(ctx, chart, scales, dims, prepared, themeMap) {
  const xAxisConfig = chart.xAxis;
  const yAxisConfig = chart.yAxis;
  const xStyles = getAxisStyles(chart.xAxis, themeMap);
  const yStyles = getAxisStyles(chart.yAxis, themeMap);
  const baselineY = dims.y + dims.height;
  const axisX = dims.x;
  ctx.save();
  ctx.lineWidth = 1;
  const xAxisDeleted = !!xAxisConfig?.deleted;
  const yAxisDeleted = !!yAxisConfig?.deleted;
  let maxYLabelWidth = 0;
  if (!xAxisDeleted && xAxisConfig?.line?.fill?.color) {
    ctx.strokeStyle = xStyles.lineColor ?? AXIS_COLOR;
    ctx.beginPath();
    ctx.moveTo(dims.x, baselineY);
    ctx.lineTo(dims.x + dims.width, baselineY);
    ctx.stroke();
  }
  if (!yAxisDeleted && yAxisConfig?.line?.fill?.color) {
    ctx.strokeStyle = yStyles.lineColor ?? AXIS_COLOR;
    ctx.beginPath();
    ctx.moveTo(axisX, dims.y);
    ctx.lineTo(axisX, dims.y + dims.height);
    ctx.stroke();
  }
  if (!yAxisDeleted) {
    const yTickCount = Math.max(2, Math.floor(dims.height / 60));
    const yAxisPlan = planValueAxis({
      ctx,
      axis: yAxisConfig,
      scale: scales.y,
      preferredTickCount: yTickCount,
      themeMap
    });
    const yTicks = yAxisPlan.ticks;
    const drawYTicks = yAxisConfig?.majorTickMark !== undefined && yAxisConfig.majorTickMark !== 0 /* TICK_MARK_UNSPECIFIED */ && yAxisConfig.majorTickMark !== 1 /* TICK_MARK_NONE */;
    const drawYGrid = !!yAxisConfig?.majorGridlines?.fill?.color;
    const yGridStrokeColor = yStyles.gridLineColor ?? yStyles.lineColor;
    ctx.font = `${yStyles.fontSize}px ${FONT_FAMILY}`;
    ctx.fillStyle = yStyles.textColor;
    ctx.textAlign = "right";
    ctx.textBaseline = "middle";
    yTicks.forEach((tick) => {
      const py = scales.y(tick);
      if (!Number.isFinite(py))
        return;
      if (drawYGrid && !overlapsAxisLine4(py, baselineY)) {
        ctx.save();
        ctx.strokeStyle = yGridStrokeColor ?? AXIS_COLOR;
        ctx.beginPath();
        ctx.moveTo(dims.x, py);
        ctx.lineTo(dims.x + dims.width, py);
        ctx.stroke();
        ctx.restore();
      }
      if (drawYTicks) {
        ctx.strokeStyle = yStyles.lineColor ?? AXIS_COLOR;
        ctx.beginPath();
        ctx.moveTo(axisX - 4, py);
        ctx.lineTo(axisX, py);
        ctx.stroke();
      }
      if (!yAxisPlan.hideTickLabels) {
        const label = formatValueAxisTick(tick, chart.yAxis?.numberFormatCode);
        ctx.fillText(label, axisX - 6, py);
      }
    });
    maxYLabelWidth = Math.max(maxYLabelWidth, Math.max(0, yAxisPlan.labelBandWidth - AXIS_TICK_GAP_PX4));
  }
  if (!xAxisDeleted) {
    const binCount = prepared.bins.length;
    const tickLength = 4;
    const labelTopY = baselineY + tickLength + 2;
    const xLabelBand = binCount > 0 ? xStyles.fontSize + AXIS_TICK_GAP_PX4 : 0;
    if (binCount > 0) {
      ctx.font = `${xStyles.fontSize}px ${FONT_FAMILY}`;
      ctx.fillStyle = xStyles.textColor;
      ctx.textAlign = "center";
      ctx.textBaseline = "top";
      prepared.bins.forEach((bin2) => {
        const left = scales.x(bin2.x0);
        const right = scales.x(bin2.x1);
        if (!Number.isFinite(left) || !Number.isFinite(right))
          return;
        const center = left + (right - left) / 2;
        const label = bin2.label ?? "";
        if (xAxisConfig?.majorTickMark !== undefined && xAxisConfig.majorTickMark !== 0 /* TICK_MARK_UNSPECIFIED */ && xAxisConfig.majorTickMark !== 1 /* TICK_MARK_NONE */) {
          ctx.strokeStyle = xStyles.lineColor ?? AXIS_COLOR;
          ctx.beginPath();
          ctx.moveTo(center, baselineY);
          ctx.lineTo(center, baselineY + tickLength);
          ctx.stroke();
        }
        ctx.fillText(label, center, labelTopY);
      });
    }
    const xTitleMetrics = measureAxisTitle(ctx, xAxisConfig?.title, xAxisConfig?.titleTextStyle, xStyles.fontSize, 0);
    if (xTitleMetrics) {
      const resolvedColor = xAxisConfig?.titleTextStyle?.fill?.color ? resolveColor(xAxisConfig.titleTextStyle.fill.color, themeMap) : chart.xAxis?.textStyle?.fill?.color ? resolveColor(chart.xAxis.textStyle.fill.color, themeMap) : xStyles.textColor;
      ctx.save();
      ctx.fillStyle = resolvedColor ?? xStyles.textColor;
      ctx.font = `${xTitleMetrics.isBold ? "bold " : ""}${xTitleMetrics.fontPx}px ${FONT_FAMILY}`;
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      ctx.translate(dims.x + dims.width / 2, baselineY + xLabelBand + AXIS_TITLE_GAP_PX5 + xTitleMetrics.height / 2);
      ctx.rotate(xTitleMetrics.rotationRad);
      ctx.fillText(xTitleMetrics.text, 0, 0);
      ctx.restore();
    }
  }
  if (!yAxisDeleted) {
    const yLabelBand = maxYLabelWidth > 0 ? maxYLabelWidth + AXIS_TICK_GAP_PX4 : 0;
    const yTitleMetrics = measureAxisTitle(ctx, yAxisConfig?.title, yAxisConfig?.titleTextStyle, yStyles.fontSize, -90);
    if (yTitleMetrics) {
      const resolvedColor = yAxisConfig?.titleTextStyle?.fill?.color ? resolveColor(yAxisConfig.titleTextStyle.fill.color, themeMap) : chart.yAxis?.textStyle?.fill?.color ? resolveColor(chart.yAxis.textStyle.fill.color, themeMap) : yStyles.textColor;
      ctx.save();
      ctx.fillStyle = resolvedColor ?? yStyles.textColor;
      ctx.font = `${yTitleMetrics.isBold ? "bold " : ""}${yTitleMetrics.fontPx}px ${FONT_FAMILY}`;
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      ctx.translate(dims.x - yLabelBand - AXIS_TITLE_GAP_PX5 - yTitleMetrics.width / 2, dims.y + dims.height / 2);
      ctx.rotate(yTitleMetrics.rotationRad);
      ctx.fillText(yTitleMetrics.text, 0, 0);
      ctx.restore();
    }
  }
  ctx.restore();
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-funnel-chart.js
function drawFunnelChart(ctx, chart, prepared, themeMap, chartHoverTargets, labelLayout) {
  if (prepared.seriesIndex === -1 || prepared.segments.length === 0) {
    return;
  }
  const series = chart.series[prepared.seriesIndex];
  if (!series)
    return;
  ctx.save();
  ctx.lineJoin = "round";
  ctx.lineCap = "round";
  const labels = [];
  prepared.segments.forEach((segment) => {
    const height = segment.y1 - segment.y0;
    if (height <= 0)
      return;
    const skipFill = pointHasNoFill(series, segment.index);
    const fillColor = skipFill ? undefined : getPointFillColor(series, segment.index, prepared.seriesIndex, themeMap);
    const { color: strokeColor, widthPx: strokeWidth } = getPointStroke(series, segment.index, themeMap);
    ctx.beginPath();
    ctx.moveTo(segment.topLeftX, segment.y0);
    ctx.lineTo(segment.topRightX, segment.y0);
    ctx.lineTo(segment.bottomRightX, segment.y1);
    ctx.lineTo(segment.bottomLeftX, segment.y1);
    ctx.closePath();
    if (fillColor) {
      ctx.fillStyle = fillColor;
      ctx.fill();
    }
    const effectiveStrokeColor = strokeColor ?? (fillColor ? fillColor : "#ffffff");
    const effectiveStrokeWidth = strokeWidth ?? (strokeColor ? 1 : 0);
    if (effectiveStrokeWidth > 0) {
      ctx.strokeStyle = effectiveStrokeColor;
      ctx.lineWidth = effectiveStrokeWidth;
      ctx.stroke();
    }
    labels.push({
      text: segment.category,
      centerY: segment.y0 + height / 2
    });
    if (chartHoverTargets) {
      const width = Math.max(segment.topRightX - segment.topLeftX, segment.bottomRightX - segment.bottomLeftX);
      const x2 = Math.min(segment.topLeftX, segment.bottomLeftX);
      const anchorX = segment.centerX;
      const anchorY = segment.y0 + height / 2;
      chartHoverTargets.push({
        kind: "bar-vertical",
        x: x2,
        y: segment.y0,
        width,
        height,
        category: segment.category,
        seriesName: series.name,
        value: segment.value,
        color: fillColor ?? strokeColor,
        anchorX,
        anchorY,
        seriesIndex: prepared.seriesIndex
      });
    }
  });
  if (labelLayout && labels.length > 0) {
    ctx.save();
    ctx.font = labelLayout.font;
    ctx.fillStyle = labelLayout.textColor;
    ctx.textAlign = "right";
    ctx.textBaseline = "middle";
    labels.forEach((label) => {
      ctx.fillText(label.text, labelLayout.labelX, label.centerY);
    });
    ctx.restore();
  }
  ctx.restore();
}

// node_modules/@oai/granola/dist/draw-utils/chart/prepare-funnel-data.js
function getCategories6(chart, seriesIndex) {
  if (chart.categories.length > 0) {
    return chart.categories;
  }
  const seriesCategories = chart.series[seriesIndex]?.categories ?? [];
  return seriesCategories.length > 0 ? seriesCategories : [];
}
function clamp4(value, minValue, maxValue) {
  return Math.min(Math.max(value, minValue), maxValue);
}
function prepareFunnelData(chart, dims, hiddenSeriesIndices) {
  const hidden = hiddenSeriesIndices ?? new Set;
  const seriesIndex = chart.series.findIndex((_, idx) => !hidden.has(idx));
  if (seriesIndex === -1) {
    return { seriesIndex: -1, segments: [] };
  }
  const series = chart.series[seriesIndex];
  const categories = getCategories6(chart, seriesIndex);
  const values = series?.values ?? [];
  const segmentCount = Math.max(categories.length, values.length);
  if (segmentCount === 0) {
    return { seriesIndex, segments: [] };
  }
  const sanitizedValues = [];
  for (let i = 0;i < segmentCount; i++) {
    const raw = values[i];
    const value = typeof raw === "number" && Number.isFinite(raw) ? Math.max(0, raw) : 0;
    sanitizedValues.push(value);
  }
  const maxValue = max(sanitizedValues) ?? 0;
  if (maxValue <= 0) {
    return { seriesIndex, segments: [] };
  }
  const gapRaw = chart.funnelOptions?.gapWidth;
  const gapRatio = typeof gapRaw === "number" && Number.isFinite(gapRaw) ? clamp4(gapRaw, 0, 0.8) : 0.06;
  const denom = segmentCount + (segmentCount > 1 ? (segmentCount - 1) * gapRatio : 0);
  const usableHeight = Math.max(0, dims.height);
  const segmentHeight = denom > 0 ? usableHeight / denom : 0;
  const gapHeight = segmentHeight * gapRatio;
  const centerX = dims.x + dims.width / 2;
  let currentY = dims.y;
  const segments = [];
  for (let i = 0;i < segmentCount; i++) {
    const value = sanitizedValues[i] ?? 0;
    const ratio = value / maxValue;
    const topWidth = dims.width * ratio;
    const bottomWidth = topWidth;
    const category = categories[i] ?? series?.categories?.[i] ?? `Step ${i + 1}`;
    const y0 = currentY;
    const y1 = y0 + segmentHeight;
    const topHalf = topWidth / 2;
    const bottomHalf = bottomWidth / 2;
    segments.push({
      index: i,
      category,
      value,
      ratio,
      y0,
      y1,
      topWidth,
      bottomWidth,
      centerX,
      topLeftX: centerX - topHalf,
      topRightX: centerX + topHalf,
      bottomLeftX: centerX - bottomHalf,
      bottomRightX: centerX + bottomHalf
    });
    currentY = y1 + gapHeight;
  }
  const totalHeight = segmentCount * segmentHeight + Math.max(0, segmentCount - 1) * gapHeight;
  const remaining = usableHeight - totalHeight;
  if (remaining > 0 && segments.length > 0) {
    const offset = remaining / 2;
    segments.forEach((seg) => {
      seg.y0 += offset;
      seg.y1 += offset;
    });
  }
  return {
    seriesIndex,
    segments
  };
}

// node_modules/@oai/granola/dist/draw-utils/chart/prepare-boxwhisker-data.js
function coerceNumber3(value) {
  if (typeof value !== "number")
    return;
  if (!Number.isFinite(value))
    return;
  return value;
}
function resolveQuartileMethod(chart) {
  if (chart.boxWhiskerOptions?.quartileMethod) {
    return chart.boxWhiskerOptions.quartileMethod;
  }
  return 2 /* QUARTILE_METHOD_EXCLUSIVE */;
}
function quantileExclusive(sorted, p) {
  const n = sorted.length;
  if (n === 0)
    return NaN;
  if (n === 1)
    return sorted[0] ?? NaN;
  const h = (n + 1) * p;
  const rank = Math.floor(h);
  const fraction = h - rank;
  if (rank <= 0)
    return sorted[0];
  if (rank >= n)
    return sorted[n - 1];
  const lower = sorted[rank - 1];
  const upper = sorted[rank];
  return lower + fraction * (upper - lower);
}
function quantile2(sorted, p, method) {
  if (sorted.length === 0)
    return NaN;
  if (method === 1 /* QUARTILE_METHOD_INCLUSIVE */) {
    return quantileSorted(sorted, p) ?? NaN;
  }
  return quantileExclusive(sorted, p);
}
function pickCategory(seriesCategories, chartCategories, index, fallback) {
  const fromSeries = seriesCategories?.[index];
  if (fromSeries && fromSeries.length > 0)
    return fromSeries;
  const fromChart = chartCategories[index];
  if (fromChart && fromChart.length > 0)
    return fromChart;
  return fallback;
}
function prepareBoxWhiskerData(chart, opts = {}) {
  if (chart.type !== 26 /* CHART_TYPE_BOX_WHISKER */) {
    throw new Error("prepareBoxWhiskerData called for non box-whisker chart");
  }
  const hidden = opts.hiddenSeriesIndices;
  const quartileMethod = resolveQuartileMethod(chart);
  const chartCategories = chart.categories ?? [];
  const categoriesInOrder = [];
  const categoriesSeen = new Set;
  const perSeries = chart.series.map((series, seriesIndex) => ({ series, seriesIndex })).filter(({ seriesIndex }) => !hidden?.has(seriesIndex)).map(({ series, seriesIndex }) => {
    const map3 = new Map;
    const valueCount = series.values?.length ?? 0;
    const fallbackPrefix = series.name && series.name.length > 0 ? series.name : `Series ${seriesIndex + 1}`;
    for (let i = 0;i < valueCount; i++) {
      const coerced = coerceNumber3(series.values?.[i]);
      if (coerced === undefined)
        continue;
      const category = pickCategory(series.categories, chartCategories, i, `${fallbackPrefix} ${i + 1}`);
      if (!categoriesSeen.has(category)) {
        categoriesSeen.add(category);
        categoriesInOrder.push(category);
      }
      const bucket = map3.get(category);
      if (bucket) {
        bucket.push(coerced);
      } else {
        map3.set(category, [coerced]);
      }
    }
    return {
      seriesIndex,
      valuesByCategory: map3
    };
  });
  if (categoriesInOrder.length === 0 && chartCategories.length > 0) {
    chartCategories.forEach((cat) => {
      if (!categoriesSeen.has(cat)) {
        categoriesSeen.add(cat);
        categoriesInOrder.push(cat);
      }
    });
  }
  const byCategory = [];
  let globalMin = Number.POSITIVE_INFINITY;
  let globalMax = Number.NEGATIVE_INFINITY;
  categoriesInOrder.forEach((categoryKey) => {
    const perSeriesStats = [];
    perSeries.forEach(({ seriesIndex, valuesByCategory }) => {
      const values = valuesByCategory.get(categoryKey);
      if (!values || values.length === 0)
        return;
      const sorted = values.slice().sort((a, b) => a - b);
      if (sorted.length === 0)
        return;
      const q1 = quantile2(sorted, 0.25, quartileMethod);
      const median = quantile2(sorted, 0.5, quartileMethod);
      const q3 = quantile2(sorted, 0.75, quartileMethod);
      const iqr = q3 - q1;
      const lowerFence = q1 - 1.5 * iqr;
      const upperFence = q3 + 1.5 * iqr;
      const outliers = [];
      const nonOutliers = [];
      sorted.forEach((val) => {
        if (val < lowerFence || val > upperFence) {
          outliers.push(val);
        } else {
          nonOutliers.push(val);
        }
      });
      const whiskerLow = nonOutliers.length > 0 ? nonOutliers[0] : sorted[0];
      const whiskerHigh = nonOutliers.length > 0 ? nonOutliers[nonOutliers.length - 1] : sorted[sorted.length - 1];
      const statMean = mean(sorted) ?? undefined;
      const stats = {
        seriesIndex,
        categoryKey,
        valuesSorted: sorted,
        q1,
        median,
        q3,
        whiskerLow,
        whiskerHigh,
        min: sorted[0],
        max: sorted[sorted.length - 1],
        iqr,
        outliers,
        nonOutliers,
        mean: statMean
      };
      globalMin = Math.min(globalMin, stats.min, stats.whiskerLow, ...stats.outliers);
      globalMax = Math.max(globalMax, stats.max, stats.whiskerHigh, ...stats.outliers);
      perSeriesStats.push(stats);
    });
    byCategory.push({
      key: categoryKey,
      series: perSeriesStats
    });
  });
  if (!Number.isFinite(globalMin)) {
    globalMin = 0;
  }
  if (!Number.isFinite(globalMax)) {
    globalMax = 1;
  }
  if (globalMin === globalMax) {
    globalMin -= 1;
    globalMax += 1;
  }
  return {
    categories: categoriesInOrder,
    seriesOrder: perSeries.map((s) => s.seriesIndex),
    byCategory,
    extents: { min: globalMin, max: globalMax }
  };
}

// node_modules/@oai/granola/dist/draw-utils/chart/create-scales-boxwhisker.js
function createScalesBoxWhisker(prepared, dims) {
  const x2 = band().domain(prepared.categories).range([dims.x, dims.x + dims.width]).paddingInner(0.3).paddingOuter(0.2);
  const bandwidth = Math.max(0, x2.bandwidth());
  const xSeries = band().domain(prepared.seriesOrder).range([0, bandwidth]).paddingInner(0.2).paddingOuter(0.1);
  const y2 = linear2().domain([prepared.extents.min, prepared.extents.max]).nice().range([dims.y + dims.height, dims.y]);
  return { x: x2, xSeries, y: y2 };
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-boxwhisker-chart.js
var MEDIAN_LINE_WIDTH = 2;
var WHISKER_CAP_RATIO = 0.6;
var OUTLIER_RADIUS_PX = 3;
var NON_OUTLIER_RADIUS_PX = 2;
var MEAN_MARKER_RADIUS_PX = 3;
function drawCircle(ctx, x2, y2, radius, fillColor, strokeColor, strokeWidth) {
  if (!Number.isFinite(x2) || !Number.isFinite(y2))
    return;
  ctx.beginPath();
  ctx.arc(x2, y2, radius, 0, Math.PI * 2);
  if (fillColor) {
    ctx.fillStyle = fillColor;
    ctx.fill();
  }
  if (strokeColor && strokeWidth > 0) {
    ctx.strokeStyle = strokeColor;
    ctx.lineWidth = strokeWidth;
    ctx.stroke();
  }
}
function getSeriesStyles(chart, stats, categoryIndex, themeMap) {
  const series = chart.series[stats.seriesIndex];
  if (!series) {
    return { strokeWidth: 1, noFill: false };
  }
  const noFill = pointHasNoFill(series, categoryIndex);
  const fillColor = getPointFillColor(series, categoryIndex, stats.seriesIndex, themeMap) ?? getSeriesColor(series, stats.seriesIndex, themeMap);
  const strokeInfo = getPointStroke(series, categoryIndex, themeMap);
  const strokeColor = strokeInfo.color ?? (fillColor ? fillColor : getSeriesColor(series, stats.seriesIndex, themeMap));
  const strokeWidth = strokeInfo.widthPx ?? 1;
  return {
    fillColor: noFill ? undefined : fillColor,
    strokeColor: strokeColor ?? undefined,
    strokeWidth: strokeWidth > 0 ? strokeWidth : 1,
    noFill
  };
}
function drawBoxWhiskerChart(ctx, chart, scales, prepared, themeMap, options = {}) {
  const { chartHoverTargets } = options;
  const showMeanMarker = chart.boxWhiskerOptions?.showMeanMarker ?? false;
  const showMeanLine = chart.boxWhiskerOptions?.showMeanLine ?? false;
  const showOutliers = chart.boxWhiskerOptions?.showOutliers ?? true;
  const showNonOutliers = chart.boxWhiskerOptions?.showNonOutliers ?? false;
  const meanPoints = new Map;
  const categoryIndexMap = new Map;
  prepared.categories.forEach((categoryKey, index) => {
    const catX = scales.x(categoryKey);
    if (catX === undefined)
      return;
    categoryIndexMap.set(categoryKey, index);
  });
  prepared.byCategory.forEach((category) => {
    const catX = scales.x(category.key);
    if (catX === undefined)
      return;
    const categoryIndex = categoryIndexMap.get(category.key) ?? 0;
    const catBandwidth = scales.x.bandwidth();
    const baseSeriesBandwidth = scales.xSeries.bandwidth();
    category.series.forEach((stats) => {
      const series = chart.series[stats.seriesIndex];
      if (!series)
        return;
      const innerOffsetRaw = scales.xSeries(stats.seriesIndex);
      const boxWidth = baseSeriesBandwidth > 0 ? baseSeriesBandwidth : Math.max(catBandwidth * 0.5, Math.min(catBandwidth, 12));
      const innerOffset = innerOffsetRaw !== undefined ? innerOffsetRaw : Math.max(0, (catBandwidth - boxWidth) / 2);
      const xLeft = catX + innerOffset;
      const xRight = xLeft + boxWidth;
      const xCenter = xLeft + boxWidth / 2;
      const yQ1 = scales.y(stats.q1);
      const yQ3 = scales.y(stats.q3);
      const yMedian = scales.y(stats.median);
      const yWhiskerLow = scales.y(stats.whiskerLow);
      const yWhiskerHigh = scales.y(stats.whiskerHigh);
      if (!Number.isFinite(yQ1) || !Number.isFinite(yQ3) || !Number.isFinite(yMedian) || !Number.isFinite(yWhiskerLow) || !Number.isFinite(yWhiskerHigh)) {
        return;
      }
      const boxTop = Math.min(yQ1, yQ3);
      const boxHeight = Math.max(Math.abs(yQ3 - yQ1), 1);
      const whiskerCap = Math.min(boxWidth * WHISKER_CAP_RATIO, boxWidth);
      const capHalf = whiskerCap / 2;
      const styles = getSeriesStyles(chart, stats, categoryIndex, themeMap);
      ctx.beginPath();
      ctx.rect(xLeft, boxTop, boxWidth, boxHeight);
      if (styles.fillColor) {
        ctx.fillStyle = styles.fillColor;
        ctx.fill();
      }
      if (styles.strokeColor) {
        ctx.strokeStyle = styles.strokeColor;
        ctx.lineWidth = styles.strokeWidth;
        ctx.stroke();
      }
      if (styles.strokeColor) {
        ctx.beginPath();
        ctx.strokeStyle = styles.strokeColor;
        ctx.lineWidth = Math.max(MEDIAN_LINE_WIDTH, styles.strokeWidth);
        ctx.moveTo(xLeft, yMedian);
        ctx.lineTo(xRight, yMedian);
        ctx.stroke();
      }
      if (styles.strokeColor) {
        ctx.beginPath();
        ctx.strokeStyle = styles.strokeColor;
        ctx.lineWidth = styles.strokeWidth;
        ctx.moveTo(xCenter, yQ3);
        ctx.lineTo(xCenter, yWhiskerHigh);
        ctx.moveTo(xCenter - capHalf, yWhiskerHigh);
        ctx.lineTo(xCenter + capHalf, yWhiskerHigh);
        ctx.moveTo(xCenter, yQ1);
        ctx.lineTo(xCenter, yWhiskerLow);
        ctx.moveTo(xCenter - capHalf, yWhiskerLow);
        ctx.lineTo(xCenter + capHalf, yWhiskerLow);
        ctx.stroke();
      }
      if (showOutliers) {
        stats.outliers.forEach((value) => {
          const yVal = scales.y(value);
          if (!Number.isFinite(yVal))
            return;
          drawCircle(ctx, xCenter, yVal, OUTLIER_RADIUS_PX, styles.strokeColor ?? styles.fillColor, styles.strokeColor, styles.strokeWidth);
          if (chartHoverTargets) {
            chartHoverTargets.push({
              kind: "scatter-point",
              anchorX: xCenter,
              anchorY: yVal,
              seriesName: series.name ?? undefined,
              category: category.key,
              value,
              color: styles.fillColor ?? styles.strokeColor ?? undefined,
              elementId: chart.id ?? undefined,
              seriesIndex: stats.seriesIndex
            });
          }
        });
      }
      if (showNonOutliers) {
        stats.nonOutliers.forEach((value) => {
          const yVal = scales.y(value);
          if (!Number.isFinite(yVal))
            return;
          drawCircle(ctx, xCenter, yVal, NON_OUTLIER_RADIUS_PX, styles.fillColor ?? styles.strokeColor, styles.strokeColor, Math.max(1, styles.strokeWidth / 2));
        });
      }
      if (showMeanMarker && stats.mean !== undefined) {
        const yMean = scales.y(stats.mean);
        if (Number.isFinite(yMean)) {
          drawCircle(ctx, xCenter, yMean, MEAN_MARKER_RADIUS_PX, styles.strokeColor ?? styles.fillColor, styles.strokeColor, styles.strokeWidth);
          if (chartHoverTargets) {
            chartHoverTargets.push({
              kind: "scatter-point",
              anchorX: xCenter,
              anchorY: yMean,
              seriesName: series.name ?? undefined,
              category: category.key,
              value: stats.mean,
              color: styles.fillColor ?? styles.strokeColor ?? undefined,
              elementId: chart.id ?? undefined,
              seriesIndex: stats.seriesIndex
            });
          }
          if (!meanPoints.has(stats.seriesIndex)) {
            meanPoints.set(stats.seriesIndex, []);
          }
          meanPoints.get(stats.seriesIndex).push({
            x: xCenter,
            y: yMean,
            categoryIndex,
            color: styles.strokeColor ?? styles.fillColor
          });
        }
      }
      if (chartHoverTargets) {
        chartHoverTargets.push({
          kind: "bar-vertical",
          x: xLeft,
          y: boxTop,
          width: boxWidth,
          height: boxHeight,
          seriesName: series.name ?? undefined,
          category: category.key,
          value: stats.median,
          color: styles.fillColor ?? styles.strokeColor ?? undefined,
          anchorX: xCenter,
          anchorY: yMedian,
          elementId: chart.id ?? undefined,
          seriesIndex: stats.seriesIndex
        });
      }
    });
  });
  if (showMeanLine) {
    meanPoints.forEach((points, seriesIndex) => {
      const sorted = points.filter((pt) => Number.isFinite(pt.x) && Number.isFinite(pt.y)).sort((a, b) => a.categoryIndex - b.categoryIndex);
      if (sorted.length < 2)
        return;
      const series = chart.series[seriesIndex];
      const fallbackColor = series ? getSeriesColor(series, seriesIndex, themeMap) : undefined;
      const strokeColor = sorted[0]?.color ?? fallbackColor ?? "#444444";
      ctx.beginPath();
      ctx.strokeStyle = strokeColor;
      ctx.lineWidth = 1.5;
      ctx.lineJoin = "round";
      sorted.forEach((pt, idx) => {
        if (idx === 0)
          ctx.moveTo(pt.x, pt.y);
        else
          ctx.lineTo(pt.x, pt.y);
      });
      ctx.stroke();
    });
  }
}

// node_modules/@oai/granola/dist/draw-utils/chart/draw-chart-background.js
function fillRect(ctx, rect, fill, themeMap) {
  const paint = resolveFillPaint(ctx, rect, fill, themeMap, "transparent");
  ctx.fillStyle = paint;
  ctx.fillRect(rect.x, rect.y, rect.width, rect.height);
}
function strokeRect(ctx, rect, line, themeMap) {
  if (!line)
    return;
  if (!line.fill?.color)
    return;
  applyLineStyle(ctx, line, themeMap, { widthPx: 0.5 });
  ctx.strokeRect(rect.x, rect.y, rect.width, rect.height);
}
function drawChartBackground(ctx, chart, outer, themeMap, opts = {}) {
  if (chart.chartFill) {
    fillRect(ctx, outer, chart.chartFill, themeMap);
  } else if (opts.excelDefaults) {
    ctx.fillStyle = "#ffffff";
    ctx.fillRect(outer.x, outer.y, outer.width, outer.height);
  }
  const chartLineFill = chart.chartLine?.fill;
  const chartLineExplicitNone = chartLineFill !== undefined && chartLineFill.type === 0 /* FILL_TYPE_UNSPECIFIED */ && chartLineFill.color === undefined;
  if (chart.chartLine?.fill?.color) {
    strokeRect(ctx, outer, chart.chartLine, themeMap);
  } else if (chartLineExplicitNone) {} else if (opts.excelDefaults) {
    ctx.save();
    ctx.strokeStyle = "#d0d0d0";
    ctx.lineWidth = 0.5;
    ctx.setLineDash([]);
    ctx.strokeRect(outer.x, outer.y, outer.width, outer.height);
    ctx.restore();
  }
}
function drawPlotAreaBackground(ctx, chart, plot, themeMap) {
  if (chart.plotAreaFill) {
    fillRect(ctx, plot, chart.plotAreaFill, themeMap);
  }
  if (chart.plotAreaLine?.fill?.color) {
    strokeRect(ctx, plot, chart.plotAreaLine, themeMap);
  }
}

// node_modules/@oai/granola/dist/draw-utils/draw-chart-reference.js
var CHART_TITLE_VERTICAL_PADDING_PX = 2;
var CHART_TOP_EXTRA_PADDING_PX = 0;
var TRENDLINE_TYPE_FROM_PROTO_SAFE3 = {
  [1 /* TRENDLINE_TYPE_LINEAR */]: "linear",
  [3 /* TRENDLINE_TYPE_LOGARITHMIC */]: "logarithmic",
  [4 /* TRENDLINE_TYPE_POLYNOMIAL */]: "polynomial",
  [6 /* TRENDLINE_TYPE_MOVING_AVERAGE */]: "movingAverage"
};
function getCenteredOverlayTitleBox(chart, plotDims, titleHeight) {
  const defaultBoxHeight = Math.max(0, titleHeight + 4);
  if (chart.type !== 8 /* CHART_TYPE_DOUGHNUT */) {
    return {
      x: plotDims.x,
      y: plotDims.y + Math.max(0, (plotDims.height - defaultBoxHeight) / 2),
      width: plotDims.width,
      height: defaultBoxHeight
    };
  }
  const centerX = plotDims.x + plotDims.width / 2;
  const centerY = plotDims.y + plotDims.height / 2;
  const radius = Math.min(plotDims.width, plotDims.height) / 2;
  const holePct = Math.max(0, Math.min(100, chart.doughnutOptions?.holeSize ?? 55));
  const innerDiameter = radius * 2 * (holePct / 100);
  const boxSize = Math.min(Math.min(plotDims.width, plotDims.height), Math.max(innerDiameter, titleHeight + 8));
  return {
    x: centerX - boxSize / 2,
    y: centerY - boxSize / 2,
    width: boxSize,
    height: boxSize
  };
}
function drawChartReference(el, ctx, pres, slide, themeMap, chartHoverTargets, hiddenSeriesIndices, mapCtx, threeCtx, on3DViewport, onMapViewport, textLayoutCollector, chartModel) {
  const dims = getBBox(el, pres, slide);
  let chart = null;
  let trendlineRenderCache;
  if (chartModel) {
    const proto = chartModel.toProto();
    if (proto) {
      normalizeChartCategories(proto);
      chart = proto;
    }
    trendlineRenderCache = chartModel.buildTrendlineRenderCache();
  } else {
    chart = getChartData(el.chartReference, pres);
  }
  if (!chart)
    return;
  const tm = themeMap ?? buildThemeMap(pres.theme, getMasterSchemeRemap(pres, slide));
  const stableElementId = el.id && el.id.length > 0 ? el.id : `${Math.round(dims.x)}:${Math.round(dims.y)}:${Math.round(dims.width)}:${Math.round(dims.height)}`;
  drawChartInternal(ctx, chart, dims, {
    themeMap: tm,
    chartHoverTargets,
    hiddenSeriesIndices,
    elementId: stableElementId,
    elementZIndex: el.zIndex ?? 0,
    mapCtx: mapCtx ?? undefined,
    threeCtx: threeCtx ?? undefined,
    on3DViewport,
    onMapViewport,
    textLayoutCollector,
    titleBlockId: chart?.id ? `chartTitle:${chart.id}` : undefined,
    trendlineRenderCache
  });
}
function drawChartStandalone(ctx, chart, dims, opts = {}) {
  const tm = opts.themeMap ?? { colorMap: {}, effectMap: {}, lineStyleMap: {} };
  drawChartInternal(ctx, chart, dims, {
    ...opts,
    themeMap: tm,
    mapCtx: opts.mapCtx ?? undefined,
    threeCtx: opts.threeCtx ?? undefined
  });
}
function drawChartInternal(ctx, chart, dims, opts) {
  ctx.save();
  const isTreemap = chart.type === 29 /* CHART_TYPE_TREEMAP */;
  const isSunburst = chart.type === 30 /* CHART_TYPE_SUNBURST */;
  const isRadar = chart.type === 17 /* CHART_TYPE_RADAR */;
  const isBar3D = chart.type === 3 /* CHART_TYPE_BAR_3D */;
  const isMap = chart.type === 23 /* CHART_TYPE_MAP */;
  const isFunnel = chart.type === 28 /* CHART_TYPE_FUNNEL */;
  const isBoxWhisker = chart.type === 26 /* CHART_TYPE_BOX_WHISKER */;
  const isXYChart = chart.type === 18 /* CHART_TYPE_SCATTER */ || chart.type === 5 /* CHART_TYPE_BUBBLE */;
  const barDir = chart.barOptions?.direction ?? chart.barDirection;
  const isHorizontalBar = (chart.type === 4 /* CHART_TYPE_BAR */ || chart.type === 3 /* CHART_TYPE_BAR_3D */) && barDir === 2 /* BAR_DIRECTION_BAR */;
  drawChartBackground(ctx, chart, dims, opts.themeMap, {
    excelDefaults: opts.excelDefaults
  });
  const contentDims = {
    x: dims.x,
    y: dims.y + CHART_TOP_EXTRA_PADDING_PX,
    width: dims.width,
    height: Math.max(0, dims.height - CHART_TOP_EXTRA_PADDING_PX)
  };
  const titleMeasure = layoutTitle(chart, contentDims, opts.themeMap, 0.5);
  let plotDims = {
    x: contentDims.x,
    y: contentDims.y + titleMeasure.reserved,
    width: contentDims.width,
    height: Math.max(0, contentDims.height - titleMeasure.reserved)
  };
  plotDims = getInnerDims(plotDims);
  let legendRect;
  let legendPosition = 1 /* LEGEND_POSITION_RIGHT */;
  if (!opts.skipLegend && chart.hasLegend) {
    const res = computeLegendLayout(ctx, chart, plotDims, opts.themeMap, {
      outerDims: dims,
      maxSideFrac: 0.28,
      sidePaddingPx: 6
    });
    plotDims = res.plotDims;
    legendRect = res.legendRect;
    legendPosition = res.legendPosition ?? legendPosition;
  }
  const hiddenSet = opts.hiddenSeriesIndices !== undefined ? new Set(opts.hiddenSeriesIndices) : undefined;
  const shouldRunAxesLayout = !isTreemap && !isSunburst && !isRadar && !isBar3D && !isMap && !isFunnel;
  const plotDimsBeforeAxes = plotDims;
  const axesLayout = shouldRunAxesLayout ? isXYChart ? (() => {
    const prepared = chart.type === 5 /* CHART_TYPE_BUBBLE */ ? prepareBubbleData(chart, hiddenSet) : prepareScatterData(chart, hiddenSet);
    const xyScales = createScalesXY(chart, plotDims, prepared);
    return layoutAxesXY(ctx, chart, xyScales, plotDims, opts.themeMap);
  })() : layoutAxesVertical(ctx, chart, plotDims, opts.themeMap) : undefined;
  const xAxisPlan = !isXYChart ? axesLayout?.xAxisPlan : undefined;
  if (axesLayout) {
    if (isHorizontalBar) {
      plotDims = {
        x: plotDimsBeforeAxes.x,
        y: axesLayout.plotDims.y,
        width: plotDimsBeforeAxes.width,
        height: Math.max(0, plotDimsBeforeAxes.height - axesLayout.reservedBottom)
      };
    } else {
      plotDims = axesLayout.plotDims;
    }
  }
  if (!isTreemap && !isSunburst && !isMap && !isFunnel) {
    const dlLayout = layoutDataLabels(chart, plotDims, 0.1);
    if (dlLayout.reservedTop > 0) {
      plotDims = {
        x: plotDims.x,
        y: plotDims.y + dlLayout.reservedTop,
        width: plotDims.width,
        height: Math.max(0, plotDims.height - dlLayout.reservedTop)
      };
    }
  }
  let dataTableRect;
  let didDrawDataTable = false;
  {
    const dtLayout = layoutDataTable(chart, plotDims, {
      maxHeightFrac: 0.32,
      minHeightPx: 56
    });
    plotDims = dtLayout.plotDims;
    dataTableRect = dtLayout.tableRect;
  }
  const titlePlacementRaw = chart["titlePlacement"];
  const titlePlacement = typeof titlePlacementRaw === "string" ? titlePlacementRaw : undefined;
  if (titleMeasure.text && titlePlacement !== "none") {
    const titleTextStyle = chart.titleTextStyle;
    const titleAnchor = titlePlacement === "centeredOverlay" ? 2 /* ANCHOR_TYPE_MIDDLE */ : titleTextStyle?.anchor;
    const titleBox = titlePlacement === "centeredOverlay" ? isPieLike(chart.type) ? getCenteredOverlayTitleBox(chart, plotDims, titleMeasure.layoutHeight) : {
      x: plotDims.x,
      y: plotDims.y + CHART_TITLE_VERTICAL_PADDING_PX,
      width: plotDims.width,
      height: Math.max(0, titleMeasure.layoutHeight + 4)
    } : {
      x: dims.x,
      y: contentDims.y,
      width: dims.width,
      height: titleMeasure.reserved
    };
    const el = {
      type: 1 /* ELEMENT_TYPE_TEXT */,
      paragraphs: [
        {
          runs: [
            {
              text: titleMeasure.text,
              textStyle: {
                ...titleTextStyle,
                alignment: 2 /* ALIGNMENT_TYPE_CENTER */,
                anchor: titleAnchor
              },
              citations: [],
              reviewMarkIds: []
            }
          ]
        }
      ],
      textStyle: {
        ...titleTextStyle,
        alignment: 2 /* ALIGNMENT_TYPE_CENTER */,
        anchor: titleAnchor
      },
      effects: [],
      children: [],
      citations: [],
      levelsStyles: [],
      id: ""
    };
    const layout = drawText(el, ctx, opts.themeMap, undefined, {
      bboxPx: titleBox,
      resolvedStyle: {
        ...titleTextStyle,
        alignment: 2 /* ALIGNMENT_TYPE_CENTER */,
        anchor: titleAnchor
      },
      paddingPx: titlePlacement === "centeredOverlay" ? { left: 0, right: 0, top: 0, bottom: 0 } : undefined
    });
    if (layout && opts.textLayoutCollector) {
      const blockId = opts.titleBlockId ?? (chart.id ? `chartTitle:${chart.id}` : `chartTitle:${opts.elementId ?? "chart"}`);
      opts.textLayoutCollector.add({
        id: blockId,
        layout,
        rotationDeg: 0,
        zIndex: opts.elementZIndex ?? 0,
        hitBox: titleBox,
        getRunText: (paraIndex, runIndex) => paraIndex === 0 && runIndex === 0 ? titleMeasure.text : ""
      });
    }
  }
  if (isHorizontalBar) {
    const categories = chart.categories.length > 0 ? chart.categories : chart.series[0]?.categories ?? [];
    plotDims = adjustDimsForYAxis(ctx, plotDims, categories, chart.yAxis, opts.themeMap, {
      maxLeftFrac: 0.35,
      sidePaddingPx: 8
    });
    drawPlotAreaBackground(ctx, chart, plotDims, opts.themeMap);
    const hScales = createScalesHorizontalBar(chart, plotDims);
    drawAxesHorizontalBar(ctx, chart, hScales, plotDims, true, opts.themeMap);
    if (legendRect)
      drawLegend(ctx, chart, legendRect, opts.themeMap, legendPosition, {
        elementId: opts.elementId,
        chartHoverTargets: opts.chartHoverTargets,
        hiddenSeriesIndices: opts.hiddenSeriesIndices
      });
    drawBarChartHorizontal(ctx, chart, hScales, opts.themeMap, opts.chartHoverTargets, hiddenSet);
    if (dataTableRect) {
      drawDataTable(ctx, chart, dataTableRect, opts.themeMap, hiddenSet);
      didDrawDataTable = true;
    }
    ctx.restore();
    return;
  }
  const scales = !isTreemap && !isSunburst && !isRadar && !isMap && !isFunnel && !isBoxWhisker ? createScales(chart, plotDims) : undefined;
  if (scales && !isPieLike(chart.type) && chart.series.some((s) => (s?.trendlines?.length ?? 0) > 0)) {
    let minY = Number.POSITIVE_INFINITY;
    let maxY = Number.NEGATIVE_INFINITY;
    chart.series.forEach((series) => {
      if (!series?.trendlines?.length)
        return;
      const values = series.values ?? [];
      const pts = [];
      for (let i = 0;i < values.length; i++) {
        const v = values[i];
        if (v === undefined || !Number.isFinite(v))
          continue;
        pts.push({ x: i, y: v });
      }
      if (pts.length < 2)
        return;
      series.trendlines.forEach((t) => {
        const type = t.type ? TRENDLINE_TYPE_FROM_PROTO_SAFE3[t.type] ?? "linear" : "linear";
        const computed = computeTrendlinePaths({
          type,
          points: pts,
          polynomialOrder: t.order,
          movingAveragePeriod: t.period,
          forecastForward: t.forward,
          forecastBackward: t.backward,
          intercept: t.intercept,
          displayEquation: false,
          displayRSquared: false
        });
        if (!computed?.points?.length)
          return;
        computed.points.forEach((p) => {
          if (!Number.isFinite(p.y))
            return;
          minY = Math.min(minY, p.y);
          maxY = Math.max(maxY, p.y);
        });
      });
    });
    if (Number.isFinite(minY) && Number.isFinite(maxY) && minY !== maxY) {
      const domain = scales.y.domain();
      const d0 = domain[0] ?? 0;
      const d1 = domain[1] ?? 0;
      const nextMin = Math.min(d0, minY);
      const nextMax = Math.max(d1, maxY);
      if (nextMin !== d0 || nextMax !== d1) {
        scales.y.domain([nextMin, nextMax]).nice();
      }
    }
  }
  if (!isTreemap && !isSunburst && isRadar) {
    drawPlotAreaBackground(ctx, chart, plotDims, opts.themeMap);
    if (legendRect)
      drawLegend(ctx, chart, legendRect, opts.themeMap, legendPosition, {
        elementId: opts.elementId,
        chartHoverTargets: opts.chartHoverTargets,
        hiddenSeriesIndices: opts.hiddenSeriesIndices
      });
    drawRadarChart(ctx, chart, plotDims, opts.themeMap, opts.chartHoverTargets, opts.hiddenSeriesIndices ? new Set(opts.hiddenSeriesIndices) : undefined);
    if (dataTableRect) {
      drawDataTable(ctx, chart, dataTableRect, opts.themeMap, hiddenSet);
      didDrawDataTable = true;
    }
  } else if (!isTreemap && !isSunburst && !isMap && !isFunnel) {
    if (isBoxWhisker) {
      const prepared = prepareBoxWhiskerData(chart, {
        hiddenSeriesIndices: hiddenSet
      });
      const bwScales = createScalesBoxWhisker(prepared, plotDims);
      drawPlotAreaBackground(ctx, chart, plotDims, opts.themeMap);
      drawAxes(ctx, chart, bwScales, plotDims, opts.themeMap, xAxisPlan);
      if (legendRect)
        drawLegend(ctx, chart, legendRect, opts.themeMap, legendPosition, {
          elementId: opts.elementId,
          chartHoverTargets: opts.chartHoverTargets,
          hiddenSeriesIndices: opts.hiddenSeriesIndices
        });
      drawBoxWhiskerChart(ctx, chart, bwScales, prepared, opts.themeMap, {
        chartHoverTargets: opts.chartHoverTargets
      });
      if (dataTableRect) {
        drawDataTable(ctx, chart, dataTableRect, opts.themeMap, hiddenSet);
        didDrawDataTable = true;
      }
    } else if (scales) {
      drawPlotAreaBackground(ctx, chart, plotDims, opts.themeMap);
      if (!isPieLike(chart.type) && !isXYChart && !isBar3D && chart.type !== 24 /* CHART_TYPE_HISTOGRAM */)
        drawAxes(ctx, chart, scales, plotDims, opts.themeMap, xAxisPlan);
      if (legendRect)
        drawLegend(ctx, chart, legendRect, opts.themeMap, legendPosition, {
          elementId: opts.elementId,
          chartHoverTargets: opts.chartHoverTargets,
          hiddenSeriesIndices: opts.hiddenSeriesIndices
        });
      switch (chart.type) {
        case 4 /* CHART_TYPE_BAR */: {
          drawBarChart(ctx, chart, scales, opts.themeMap, opts.chartHoverTargets, hiddenSet);
          const categories = chart.categories.length > 0 ? chart.categories : chart.series[0]?.categories ?? [];
          chart.series.forEach((series, seriesIndex) => {
            if (!series?.trendlines?.length)
              return;
            const computed = opts.trendlineRenderCache?.bySeriesIndex.get(seriesIndex);
            drawTrendlinesCategory(ctx, chart, series, seriesIndex, categories, series.values ?? [], opts.themeMap, {
              y: scales.y,
              xCenter: (cat) => getCenter(scales.x, cat)
            }, plotDims, computed);
          });
          break;
        }
        case 27 /* CHART_TYPE_WATERFALL */: {
          const prepared = prepareWaterfallData(chart, hiddenSet);
          drawWaterfallChart(ctx, chart, scales, prepared, opts.themeMap, {
            chartHoverTargets: opts.chartHoverTargets
          });
          break;
        }
        case 3 /* CHART_TYPE_BAR_3D */: {
          if (!opts.threeCtx) {
            if (opts.on3DViewport) {
              const maxWidth = dims.width - Math.max(0, plotDims.x - dims.x);
              const maxHeight = dims.height - Math.max(0, plotDims.y - dims.y);
              const clampedPlotDims = {
                x: plotDims.x,
                y: plotDims.y,
                width: Math.max(0, Math.min(plotDims.width, maxWidth)),
                height: Math.max(0, Math.min(plotDims.height, maxHeight))
              };
              opts.on3DViewport({
                elementId: opts.elementId ?? "",
                plotDims: clampedPlotDims
              });
            }
            ctx.restore();
            return;
          }
          const localPlotDims = {
            x: 0,
            y: 0,
            width: plotDims.width,
            height: plotDims.height
          };
          const localScales = createScales(chart, localPlotDims);
          drawBarChart3D(opts.threeCtx, chart, localScales, localPlotDims, opts.themeMap, hiddenSet);
          break;
        }
        case 13 /* CHART_TYPE_LINE */:
        case 12 /* CHART_TYPE_LINE_3D */:
          drawLineChart(ctx, chart, plotDims, scales, opts.themeMap, opts.chartHoverTargets, hiddenSet, opts.trendlineRenderCache);
          break;
        case 2 /* CHART_TYPE_AREA */:
        case 1 /* CHART_TYPE_AREA_3D */:
          drawAreaChart(ctx, chart, scales, opts.themeMap, opts.chartHoverTargets, hiddenSet);
          break;
        case 24 /* CHART_TYPE_HISTOGRAM */: {
          const preparedHistogram = prepareHistogramData(chart, hiddenSet ? { hiddenSeriesIndices: hiddenSet } : undefined);
          const xyPrepared = {
            series: [],
            extents: preparedHistogram.extents
          };
          const xyScales = createScalesXY(chart, plotDims, xyPrepared);
          drawHistogramAxes(ctx, chart, xyScales, plotDims, preparedHistogram, opts.themeMap);
          drawHistogramChart(ctx, chart, xyScales, preparedHistogram, opts.themeMap, {
            chartHoverTargets: opts.chartHoverTargets
          });
          break;
        }
        case 15 /* CHART_TYPE_PIE_3D */: {
          if (!opts.threeCtx) {
            if (opts.on3DViewport) {
              const maxWidth = dims.width - Math.max(0, plotDims.x - dims.x);
              const maxHeight = dims.height - Math.max(0, plotDims.y - dims.y);
              const clampedPlotDims = {
                x: plotDims.x,
                y: plotDims.y,
                width: Math.max(0, Math.min(plotDims.width, maxWidth)),
                height: Math.max(0, Math.min(plotDims.height, maxHeight))
              };
              opts.on3DViewport({
                elementId: opts.elementId ?? "",
                plotDims: clampedPlotDims
              });
            }
            ctx.restore();
            return;
          }
          const localPlotDims = {
            x: 0,
            y: 0,
            width: plotDims.width,
            height: plotDims.height
          };
          drawPieChart3D(opts.threeCtx, chart, localPlotDims, opts.themeMap, hiddenSet);
          break;
        }
        case 16 /* CHART_TYPE_PIE */:
        case 8 /* CHART_TYPE_DOUGHNUT */:
          drawPieChart(ctx, chart, plotDims, opts.themeMap, opts.chartHoverTargets, hiddenSet);
          break;
        case 18 /* CHART_TYPE_SCATTER */: {
          const hidden = opts.hiddenSeriesIndices !== undefined ? new Set(opts.hiddenSeriesIndices) : undefined;
          const prepared = prepareScatterData(chart, hidden);
          const xyScales = createScalesXY(chart, plotDims, prepared);
          drawAxesXY(ctx, chart, xyScales, plotDims, opts.themeMap);
          drawScatterChart(ctx, chart, plotDims, xyScales, opts.themeMap, opts.chartHoverTargets, hidden, prepared, opts.trendlineRenderCache);
          break;
        }
        case 5 /* CHART_TYPE_BUBBLE */: {
          const hidden = opts.hiddenSeriesIndices !== undefined ? new Set(opts.hiddenSeriesIndices) : undefined;
          const prepared = prepareBubbleData(chart, hidden);
          const xyScales = createScalesXY(chart, plotDims, prepared);
          drawAxesXY(ctx, chart, xyScales, plotDims, opts.themeMap);
          drawBubbleChart(ctx, chart, xyScales, prepared, opts.themeMap, opts.chartHoverTargets);
          break;
        }
        default:
          break;
      }
    }
  } else if (isFunnel) {
    if (legendRect)
      drawLegend(ctx, chart, legendRect, opts.themeMap, legendPosition, {
        elementId: opts.elementId,
        chartHoverTargets: opts.chartHoverTargets,
        hiddenSeriesIndices: opts.hiddenSeriesIndices
      });
    const initialFunnel = prepareFunnelData(chart, plotDims, hiddenSet);
    const funnelLayout = computeFunnelCategoryLayout(ctx, chart, initialFunnel, plotDims, opts.themeMap);
    const preparedFunnel = funnelLayout !== null ? prepareFunnelData(chart, funnelLayout.plotDims, hiddenSet) : initialFunnel;
    drawFunnelChart(ctx, chart, preparedFunnel, opts.themeMap, opts.chartHoverTargets, funnelLayout?.labels);
  } else if (isMap) {
    if (legendRect)
      drawLegend(ctx, chart, legendRect, opts.themeMap, legendPosition, {
        elementId: opts.elementId,
        chartHoverTargets: opts.chartHoverTargets,
        hiddenSeriesIndices: opts.hiddenSeriesIndices
      });
    const maxWidth = dims.width - Math.max(0, plotDims.x - dims.x);
    const maxHeight = dims.height - Math.max(0, plotDims.y - dims.y);
    const clampedPlotDims = {
      x: plotDims.x,
      y: plotDims.y,
      width: Math.max(0, Math.min(plotDims.width, maxWidth)),
      height: Math.max(0, Math.min(plotDims.height, maxHeight))
    };
    if (opts.onMapViewport) {
      opts.onMapViewport({
        elementId: opts.elementId ?? "",
        plotDims: clampedPlotDims
      });
    }
    if (!opts.mapCtx) {
      ctx.restore();
      return;
    }
    drawMapChart(opts.mapCtx, chart, plotDims, opts.themeMap, {
      elementId: opts.elementId,
      hiddenSeriesIndices: hiddenSet
    });
  } else if (isTreemap) {
    drawPlotAreaBackground(ctx, chart, plotDims, opts.themeMap);
    const prepared = prepareTreemapData(chart, plotDims, opts.themeMap);
    drawTreemap(ctx, prepared, plotDims, {
      chart,
      themeMap: opts.themeMap
    });
    if (legendRect)
      drawLegend(ctx, chart, legendRect, opts.themeMap, legendPosition, {
        elementId: opts.elementId,
        chartHoverTargets: opts.chartHoverTargets,
        hiddenSeriesIndices: opts.hiddenSeriesIndices
      });
  } else if (isSunburst) {
    drawPlotAreaBackground(ctx, chart, plotDims, opts.themeMap);
    const prepared = prepareSunburstData(chart, plotDims, opts.themeMap);
    drawSunburst(ctx, prepared, plotDims, {
      themeMap: opts.themeMap,
      valueFormatCode: chart.series[0]?.valuesFormatCode ?? undefined
    });
    if (legendRect)
      drawLegend(ctx, chart, legendRect, opts.themeMap, legendPosition, {
        elementId: opts.elementId,
        chartHoverTargets: opts.chartHoverTargets,
        hiddenSeriesIndices: opts.hiddenSeriesIndices
      });
  }
  if (dataTableRect && !didDrawDataTable) {
    drawDataTable(ctx, chart, dataTableRect, opts.themeMap, hiddenSet);
  }
  ctx.restore();
}
var FUNNEL_LABEL_GAP_PX = 8;
var FUNNEL_LABEL_LEFT_FRAC_CAP = 0.35;
function computeFunnelCategoryLayout(ctx, chart, prepared, plotDims, themeMap) {
  if (prepared.segments.length === 0) {
    return null;
  }
  if (plotDims.width <= 0) {
    return null;
  }
  const axisStyles = getAxisStyles(chart.yAxis, themeMap);
  const font = `${axisStyles.fontSize}px ${FONT_FAMILY}`;
  ctx.save();
  ctx.font = font;
  let maxLabelWidth = 0;
  for (const segment of prepared.segments) {
    const width = ctx.measureText(segment.category).width;
    if (width > maxLabelWidth) {
      maxLabelWidth = width;
    }
  }
  ctx.restore();
  if (!Number.isFinite(maxLabelWidth) || maxLabelWidth <= 0) {
    return null;
  }
  const reservedLeft = Math.min(plotDims.width * FUNNEL_LABEL_LEFT_FRAC_CAP, maxLabelWidth + FUNNEL_LABEL_GAP_PX);
  if (reservedLeft <= FUNNEL_LABEL_GAP_PX || reservedLeft >= plotDims.width) {
    return null;
  }
  const adjustedPlotDims = {
    x: plotDims.x + reservedLeft,
    y: plotDims.y,
    width: Math.max(0, plotDims.width - reservedLeft),
    height: plotDims.height
  };
  return {
    plotDims: adjustedPlotDims,
    labels: {
      labelX: plotDims.x + reservedLeft - FUNNEL_LABEL_GAP_PX,
      font,
      textColor: axisStyles.textColor
    }
  };
}

// node_modules/@oai/granola/dist/draw-utils/draw-sheet-charts.js
function drawSheetCharts(ctx, worksheet, workbook, colOffsets, rowOffsets, scrollX, scrollY, viewportW, viewportH, themeMap, _resolvedCharts, textLayoutCollector, chartHoverTargets, mapCtx, onMapViewport) {
  const charts = worksheet.charts.items;
  if (charts.length === 0)
    return;
  const sheetLookup = buildSheetLookup(workbook);
  for (const chartItem of charts) {
    const d = chartItem.toDrawingProto({ preferPreview: true });
    if (!d.chart || !d.fromAnchor)
      continue;
    hydrateChartData(d.chart, worksheet, sheetLookup);
    const logicalBounds = chartItem.resolveBoundsPx({
      columnOffsets: colOffsets,
      rowOffsets
    }, { preferPreview: true });
    if (!logicalBounds)
      continue;
    const x0 = ROW_HEADER_W + logicalBounds.x - scrollX;
    const y0 = COL_HEADER_H + logicalBounds.y - scrollY;
    const x1 = x0 + logicalBounds.width;
    const y1 = y0 + logicalBounds.height;
    if (x1 < 0 || y1 < 0 || x0 > viewportW || y0 > viewportH)
      continue;
    const dims = {
      x: x0,
      y: y0,
      width: logicalBounds.width,
      height: logicalBounds.height
    };
    if (dims.width <= 0 || dims.height <= 0)
      continue;
    ctx.save();
    ctx.beginPath();
    ctx.rect(dims.x, dims.y, dims.width, dims.height);
    ctx.clip();
    drawChartStandalone(ctx, d.chart, dims, {
      themeMap,
      excelDefaults: true,
      textLayoutCollector,
      chartHoverTargets,
      elementId: d.chart?.id ?? undefined,
      titleBlockId: d.chart?.id ? `chartTitle:${d.chart.id}` : undefined,
      mapCtx: mapCtx ?? undefined,
      onMapViewport
    });
    ctx.restore();
  }
}
function hydrateChartData(chart, currentSheet, sheetsByName) {
  if (!chart || !Array.isArray(chart.series))
    return;
  for (const series of chart.series) {
    if (!series)
      continue;
    if (series.formula) {
      const values = readNumericRange(series.formula, sheetsByName, currentSheet);
      if (values.length > 0) {
        series.values = values;
      }
    }
    if (series.categoryFormula) {
      const labels = readStringRange(series.categoryFormula, sheetsByName, currentSheet);
      if (labels.length > 0) {
        series.categories = labels;
      }
    }
  }
  if (chart.categories.length === 0) {
    const fallback = chart.series.find((s) => s.categories.length > 0)?.categories ?? (() => {
      const firstFormula = chart.series[0]?.categoryFormula;
      return firstFormula ? readStringRange(firstFormula, sheetsByName, currentSheet) : [];
    })();
    if (fallback.length > 0) {
      chart.categories = [...fallback];
    }
  }
}
function buildSheetLookup(workbook) {
  const map3 = new Map;
  for (const ws of workbook.sheets) {
    const key = sheetLookupKey(ws?.name);
    if (key) {
      map3.set(key, ws);
    }
  }
  return map3;
}
function sheetLookupKey(name) {
  if (!name)
    return null;
  const trimmed = name.trim();
  if (!trimmed)
    return null;
  return trimmed.toLowerCase();
}
function readNumericRange(formula, sheetsByName, fallbackSheet) {
  return collectRangeValues(formula, sheetsByName, fallbackSheet, (cell) => {
    if (!cell || cell.value == null || cell.value === "")
      return Number.NaN;
    if (typeof cell.value === "number")
      return cell.value;
    if (typeof cell.value === "string") {
      const trimmed = cell.value.trim();
      if (!trimmed)
        return Number.NaN;
      const parsed = Number(trimmed);
      return Number.isFinite(parsed) ? parsed : Number.NaN;
    }
    return Number.NaN;
  });
}
function readStringRange(formula, sheetsByName, fallbackSheet) {
  return collectRangeValues(formula, sheetsByName, fallbackSheet, (cell) => {
    if (!cell || cell.value == null)
      return "";
    if (typeof cell.value === "string")
      return cell.value;
    if (typeof cell.value === "number")
      return String(cell.value);
    return "";
  });
}
function collectRangeValues(formula, sheetsByName, fallbackSheet, project) {
  const parsed = parseA1Range(formula);
  if (!parsed)
    return [];
  const targetSheet = getSheetForRange(sheetsByName, parsed.sheetName, fallbackSheet);
  const results = [];
  for (let row = parsed.startRow;row <= parsed.endRow; row++) {
    for (let col = parsed.startCol;col <= parsed.endCol; col++) {
      results.push(project(getCellAt(targetSheet, row, col)));
    }
  }
  return results;
}
function parseA1Range(ref) {
  if (!ref)
    return null;
  let input = ref.trim();
  if (!input)
    return null;
  if (input.startsWith("="))
    input = input.slice(1);
  if (!input)
    return null;
  const [firstSegment] = input.split(",");
  if (!firstSegment)
    return null;
  let sheetSegment;
  let addrSegment = firstSegment;
  const exclIdx = firstSegment.lastIndexOf("!");
  if (exclIdx !== -1) {
    sheetSegment = firstSegment.slice(0, exclIdx);
    addrSegment = firstSegment.slice(exclIdx + 1);
  }
  addrSegment = addrSegment.trim();
  if (!addrSegment)
    return null;
  const colonIdx = addrSegment.indexOf(":");
  const startRef = colonIdx === -1 ? addrSegment : addrSegment.slice(0, colonIdx);
  const endRef = colonIdx === -1 ? addrSegment : addrSegment.slice(colonIdx + 1);
  const start = parseCellAddress(startRef);
  const end = parseCellAddress(endRef);
  if (!start || !end)
    return null;
  return {
    sheetName: normalizeSheetName(sheetSegment),
    startRow: Math.min(start.row, end.row),
    endRow: Math.max(start.row, end.row),
    startCol: Math.min(start.col, end.col),
    endCol: Math.max(start.col, end.col)
  };
}
function parseCellAddress(addr) {
  if (!addr)
    return null;
  const normalized = addr.replace(/\$/g, "").trim();
  if (!normalized)
    return null;
  const match = normalized.match(/^([A-Za-z]+)(\d+)$/);
  if (!match)
    return null;
  const [, lettersRaw, rowDigits] = match;
  if (!lettersRaw || !rowDigits)
    return null;
  const letters = lettersRaw.toUpperCase();
  const rowNumber = Number.parseInt(rowDigits, 10);
  if (!Number.isFinite(rowNumber))
    return null;
  const col = columnIndex(letters);
  const row = rowNumber - 1;
  if (col < 0 || row < 0)
    return null;
  return { row, col };
}
function normalizeSheetName(raw) {
  if (!raw)
    return;
  let name = raw.trim();
  if (!name)
    return;
  if (name.startsWith("'") && name.endsWith("'")) {
    name = name.slice(1, -1).replace(/''/g, "'");
  }
  const bracketStart = name.indexOf("[");
  const bracketEnd = name.lastIndexOf("]");
  if (bracketStart !== -1 && bracketEnd > bracketStart) {
    name = name.slice(bracketEnd + 1);
  }
  return name;
}
function getSheetForRange(sheetsByName, requestedName, fallback) {
  if (requestedName) {
    const key = sheetLookupKey(requestedName);
    if (key) {
      const hit = sheetsByName.get(key);
      if (hit)
        return hit;
    }
  }
  return fallback;
}
function getCellAt(sheet, rowIdx, colIdx) {
  return sheet.__getCell(rowIdx, colIdx);
}
// node_modules/@oai/granola/dist/draw-utils/draw-sheet-sparklines.js
var DEFAULT_SERIES_COLOR = "#4f81bd";
var DEFAULT_AXIS_COLOR = "#666666";
var CELL_PADDING_PX = 2;
var MARKER_RADIUS_PX = 2;
var clamp5 = (value, min2, max3) => Math.min(Math.max(value, min2), max3);
var toCssColor = (color2, themeMap, fallback) => {
  if (!color2)
    return fallback;
  try {
    return resolveColor(color2, themeMap, fallback);
  } catch {
    return fallback;
  }
};
function drawSparklineGroups(ctx, specs, colOffsets, rowOffsets, scrollX, scrollY, viewportW, viewportH, themeMap) {
  if (!specs || specs.length === 0)
    return;
  for (const spec of specs) {
    const colStart = colOffsets[spec.col];
    const colEnd = colOffsets[spec.col + 1];
    const rowStart = rowOffsets[spec.row];
    const rowEnd = rowOffsets[spec.row + 1];
    if (colStart === undefined || colEnd === undefined || rowStart === undefined || rowEnd === undefined) {
      continue;
    }
    const x0 = ROW_HEADER_W + colStart - scrollX;
    const y0 = COL_HEADER_H + rowStart - scrollY;
    const width = colEnd - colStart;
    const height = rowEnd - rowStart;
    const x1 = x0 + width;
    const y1 = y0 + height;
    if (x1 < 0 || y1 < 0 || x0 > viewportW || y0 > viewportH) {
      continue;
    }
    if (width <= 0 || height <= 0)
      continue;
    drawSparkline(ctx, spec, { x: x0, y: y0, width, height }, themeMap);
  }
}
function drawSparkline(ctx, spec, rect, themeMap) {
  const plotX = rect.x + CELL_PADDING_PX;
  const plotY = rect.y + CELL_PADDING_PX;
  const plotW = rect.width - CELL_PADDING_PX * 2;
  const plotH = rect.height - CELL_PADDING_PX * 2;
  if (plotW <= 0 || plotH <= 0)
    return;
  const values = spec.values;
  if (values.length === 0)
    return;
  const domainMin = spec.domain.min;
  const domainMax = spec.domain.max;
  if (!Number.isFinite(domainMin) || !Number.isFinite(domainMax)) {
    return;
  }
  const denom = domainMax - domainMin;
  if (!Number.isFinite(denom) || denom === 0) {
    return;
  }
  const seriesColor = toCssColor(spec.colors.series, themeMap, DEFAULT_SERIES_COLOR);
  const negativeColor = toCssColor(spec.colors.negative, themeMap, seriesColor);
  const axisColor = toCssColor(spec.colors.axis, themeMap, DEFAULT_AXIS_COLOR);
  const markersColor = toCssColor(spec.colors.markers, themeMap, seriesColor);
  const firstMarkerColor = toCssColor(spec.colors.first, themeMap, markersColor);
  const lastMarkerColor = toCssColor(spec.colors.last, themeMap, markersColor);
  const highMarkerColor = toCssColor(spec.colors.high, themeMap, markersColor);
  const lowMarkerColor = toCssColor(spec.colors.low, themeMap, markersColor);
  const valueToY = (value) => plotY + plotH - (value - domainMin) / denom * plotH;
  const baseline = clamp5(valueToY(0), plotY, plotY + plotH);
  switch (spec.type) {
    case "column":
    case "stacked":
      drawColumnSparkline(ctx, spec, { plotX, plotY, plotW, plotH, baseline }, {
        seriesColor,
        negativeColor,
        axisColor
      }, valueToY);
      break;
    default:
      drawLineSparkline(ctx, spec, { plotX, plotY, plotW, plotH, baseline }, {
        seriesColor,
        negativeColor,
        axisColor,
        markersColor,
        firstMarkerColor,
        lastMarkerColor,
        highMarkerColor,
        lowMarkerColor
      }, valueToY);
  }
}
function drawLineSparkline(ctx, spec, box, colors, toY) {
  const { plotX, plotW } = box;
  const count3 = spec.values.length;
  const step = count3 > 1 ? plotW / (count3 - 1) : plotW;
  const startXForIndex = (idx) => {
    const logicalIndex = spec.rightToLeft ? count3 - 1 - idx : idx;
    return plotX + logicalIndex * step;
  };
  ctx.save();
  ctx.lineWidth = spec.lineWeight ?? 1;
  ctx.strokeStyle = colors.seriesColor;
  ctx.lineJoin = "round";
  ctx.beginPath();
  let open = false;
  spec.values.forEach((value, idx) => {
    if (value === null || !Number.isFinite(value)) {
      if (!spec.connectGaps && open) {
        ctx.stroke();
        ctx.beginPath();
        open = false;
      }
      return;
    }
    const x2 = startXForIndex(idx);
    const y2 = toY(value);
    if (!open) {
      ctx.moveTo(x2, y2);
      open = true;
    } else {
      ctx.lineTo(x2, y2);
    }
  });
  if (open) {
    ctx.stroke();
  }
  ctx.restore();
  if (spec.showAxis) {
    ctx.save();
    ctx.strokeStyle = colors.axisColor;
    ctx.lineWidth = 0.5;
    ctx.beginPath();
    ctx.moveTo(plotX, box.baseline);
    ctx.lineTo(plotX + box.plotW, box.baseline);
    ctx.stroke();
    ctx.restore();
  }
  const hasMarkers2 = spec.markers.show || spec.markers.high || spec.markers.low || spec.markers.first || spec.markers.last || spec.markers.negative;
  if (!hasMarkers2) {
    return;
  }
  spec.values.forEach((value, idx) => {
    if (value === null || !Number.isFinite(value)) {
      return;
    }
    const x2 = startXForIndex(idx);
    const y2 = toY(value);
    const markerColor = pickMarkerColor(idx, value, spec, colors, spec.pointMeta);
    if (!markerColor)
      return;
    ctx.save();
    ctx.fillStyle = markerColor;
    ctx.beginPath();
    ctx.arc(x2, y2, MARKER_RADIUS_PX, 0, Math.PI * 2);
    ctx.fill();
    ctx.restore();
  });
}
function drawColumnSparkline(ctx, spec, box, colors, toY) {
  const count3 = spec.values.length;
  if (count3 === 0)
    return;
  const band2 = box.plotW / Math.max(1, count3);
  const gap = Math.min(2, band2 * 0.25);
  const barX = (idx) => {
    const logicalIndex = spec.rightToLeft ? count3 - 1 - idx : idx;
    return box.plotX + logicalIndex * band2 + gap / 2;
  };
  const barWidth = Math.max(1, band2 - gap);
  spec.values.forEach((rawValue, idx) => {
    if (rawValue === null || !Number.isFinite(rawValue)) {
      return;
    }
    const value = spec.type === "stacked" ? Math.max(-1, Math.min(1, Math.sign(rawValue))) : rawValue;
    const x2 = barX(idx);
    const y2 = toY(value);
    const top = Math.min(y2, box.baseline);
    const height = Math.abs(box.baseline - y2);
    const fillColor = value < 0 ? colors.negativeColor : colors.seriesColor;
    ctx.save();
    ctx.fillStyle = fillColor;
    ctx.fillRect(x2, top, barWidth, Math.max(1, height));
    ctx.restore();
  });
  if (spec.showAxis) {
    ctx.save();
    ctx.strokeStyle = colors.axisColor;
    ctx.lineWidth = 0.5;
    ctx.beginPath();
    ctx.moveTo(box.plotX, box.baseline);
    ctx.lineTo(box.plotX + box.plotW, box.baseline);
    ctx.stroke();
    ctx.restore();
  }
}
function pickMarkerColor(idx, value, spec, colors, meta) {
  if (!Number.isFinite(value)) {
    return null;
  }
  if (spec.markers.first && meta.firstIndex === idx && colors.firstMarkerColor) {
    return colors.firstMarkerColor;
  }
  if (spec.markers.last && meta.lastIndex === idx && colors.lastMarkerColor) {
    return colors.lastMarkerColor;
  }
  if (spec.markers.high && meta.highIndices.has(idx) && colors.highMarkerColor) {
    return colors.highMarkerColor;
  }
  if (spec.markers.low && meta.lowIndices.has(idx) && colors.lowMarkerColor) {
    return colors.lowMarkerColor;
  }
  if (spec.markers.negative && meta.negativeIndices.has(idx)) {
    return colors.negativeColor;
  }
  return colors.markersColor ?? colors.seriesColor;
}
// node_modules/@oai/granola/dist/spreadsheet/hidden-header-markers.js
function computeHiddenHeaderMarkers(params) {
  const { worksheet, rowHeights, colWidths, rowIndexRemap } = params;
  const hiddenRowActual = new Set;
  for (const row of worksheet.__getRows()) {
    const rowHidden = row.hidden === true;
    if (rowHidden)
      hiddenRowActual.add(row.index - 1);
  }
  const rowBoundaries = [];
  if (hiddenRowActual.size > 0 && rowHeights.length > 1) {
    const N = rowHeights.length;
    const visualToActual = new Array(N);
    for (let v = 0;v < N; v++) {
      const actual = rowIndexRemap && v < rowIndexRemap.length ? rowIndexRemap[v] ?? v : v;
      visualToActual[v] = actual;
    }
    let lastVisibleVisual = null;
    let lastActual = null;
    for (let v = 0;v < N; v++) {
      const height = rowHeights[v];
      if (height == null || height <= 0)
        continue;
      const actual = visualToActual[v];
      if (actual == null) {
        lastVisibleVisual = v;
        lastActual = null;
        continue;
      }
      if (lastVisibleVisual != null && lastActual != null) {
        const lo = Math.min(lastActual, actual) + 1;
        const hi = Math.max(lastActual, actual) - 1;
        if (lo <= hi) {
          for (let k = lo;k <= hi; k++) {
            if (hiddenRowActual.has(k)) {
              rowBoundaries.push(lastVisibleVisual);
              break;
            }
          }
        }
      }
      lastVisibleVisual = v;
      lastActual = actual;
    }
  }
  const hiddenCols = new Set;
  for (const colDef of worksheet.__getColumns()) {
    const colHidden = colDef.hidden === true;
    if (!colHidden)
      continue;
    const min0 = Math.max(0, (colDef.min || 1) - 1);
    const max0 = Math.max(min0, (colDef.max ?? colDef.min ?? 1) - 1);
    for (let c = min0;c <= max0; c++)
      hiddenCols.add(c);
  }
  const colBoundaries = [];
  if (hiddenCols.size > 0 && colWidths.length > 1) {
    const M = colWidths.length;
    let lastVisibleCol = null;
    for (let c = 0;c < M; c++) {
      const width = colWidths[c];
      if (width == null || width <= 0)
        continue;
      const isHidden = hiddenCols.has(c);
      if (isHidden)
        continue;
      if (lastVisibleCol != null) {
        const lo = Math.min(lastVisibleCol, c) + 1;
        const hi = Math.max(lastVisibleCol, c) - 1;
        if (lo <= hi) {
          for (let k = lo;k <= hi; k++) {
            if (hiddenCols.has(k)) {
              colBoundaries.push(lastVisibleCol);
              break;
            }
          }
        }
      }
      lastVisibleCol = c;
    }
  }
  return { rowBoundaries, colBoundaries };
}
var HIDDEN_HEADER_MARKERS_CACHE = new WeakMap;
function getHiddenHeaderMarkersCached(params) {
  const { worksheet, rowHeights, colWidths, rowIndexRemap } = params;
  const cached = HIDDEN_HEADER_MARKERS_CACHE.get(worksheet);
  if (cached && cached.rowRef === rowHeights && cached.colRef === colWidths && cached.remapRef === rowIndexRemap) {
    return cached.markers;
  }
  const markers = computeHiddenHeaderMarkers({
    worksheet,
    rowHeights,
    colWidths,
    rowIndexRemap
  });
  HIDDEN_HEADER_MARKERS_CACHE.set(worksheet, {
    rowRef: rowHeights,
    colRef: colWidths,
    remapRef: rowIndexRemap,
    markers
  });
  return markers;
}

// node_modules/@oai/granola/dist/spreadsheet/ensure-merged-anchor-caches.js
function ensureMergedAnchorCaches(cache, mergedCells) {
  if (cache.mergedAnchorsComputed && cache.mergedAnchorsSheetRef === mergedCells) {
    return;
  }
  cache.mergedRowAnchorByRow.clear();
  cache.mergedColAnchorByCol.clear();
  for (const merged of mergedCells ?? []) {
    const startAddr = merged.startAddress;
    if (!startAddr)
      continue;
    const endAddr = merged.endAddress ?? startAddr;
    const c1 = columnIndex(startAddr);
    const r1 = rowIndex(startAddr);
    const c2 = columnIndex(endAddr);
    const r2 = rowIndex(endAddr);
    const rMin = Math.min(r1, r2);
    const rMax = Math.max(r1, r2);
    const cMin = Math.min(c1, c2);
    const cMax = Math.max(c1, c2);
    for (let rr = rMin;rr <= rMax; rr++) {
      const prev = cache.mergedRowAnchorByRow.get(rr);
      if (prev == null || rMin < prev) {
        cache.mergedRowAnchorByRow.set(rr, rMin);
      }
    }
    for (let cc = cMin;cc <= cMax; cc++) {
      const prev = cache.mergedColAnchorByCol.get(cc);
      if (prev == null || cMin < prev) {
        cache.mergedColAnchorByCol.set(cc, cMin);
      }
    }
  }
  cache.mergedAnchorsComputed = true;
  cache.mergedAnchorsSheetRef = mergedCells;
}

// node_modules/@oai/granola/dist/spreadsheet/ensure-merged-range-caches.js
function pushByKey(map3, key, value) {
  const existing = map3.get(key);
  if (existing) {
    existing.push(value);
  } else {
    map3.set(key, [value]);
  }
}
function ensureMergedRangeCaches(cache, mergedCells) {
  if (cache.mergedRangesComputed && cache.mergedRangesSheetRef === mergedCells) {
    return;
  }
  cache.mergedRangesByRow.clear();
  cache.mergedHorizontalBoundariesByRow.clear();
  cache.mergedVerticalBoundariesByCol.clear();
  for (const merged of mergedCells ?? []) {
    const startAddress = merged.startAddress;
    if (!startAddress) {
      continue;
    }
    const endAddress = merged.endAddress ?? startAddress;
    const startCol = columnIndex(startAddress);
    const startRow = rowIndex(startAddress);
    const endCol = columnIndex(endAddress);
    const endRow = rowIndex(endAddress);
    const rowMin = Math.min(startRow, endRow);
    const rowMax = Math.max(startRow, endRow);
    const colMin = Math.min(startCol, endCol);
    const colMax = Math.max(startCol, endCol);
    const bounds = { rowMin, rowMax, colMin, colMax };
    for (let row = rowMin;row <= rowMax; row += 1) {
      pushByKey(cache.mergedRangesByRow, row, bounds);
    }
    for (let boundaryRow = rowMin + 1;boundaryRow <= rowMax; boundaryRow += 1) {
      pushByKey(cache.mergedHorizontalBoundariesByRow, boundaryRow, {
        colMin,
        colMax
      });
    }
    for (let boundaryCol = colMin + 1;boundaryCol <= colMax; boundaryCol += 1) {
      pushByKey(cache.mergedVerticalBoundariesByCol, boundaryCol, {
        rowMin,
        rowMax
      });
    }
  }
  cache.mergedRangesComputed = true;
  cache.mergedRangesSheetRef = mergedCells;
}

// node_modules/@oai/walnut/generated/oaiproto/coworker/xlsx/spreadsheet.ts
function createBaseWorkbook() {
  return {
    id: undefined,
    sheets: [],
    styles: undefined,
    theme: undefined,
    contentReferences: [],
    images: [],
    people: [],
    threads: [],
    notes: [],
    slicerCaches: [],
    pivotCaches: [],
    timelineCaches: [],
    definedNames: undefined,
    metadata: undefined,
    featurePropertyBags: undefined,
    textStyles: [],
    codeEnvironments: [],
    codeBlocks: []
  };
}
var Workbook = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== undefined) {
      writer.uint32(82).string(message.id);
    }
    for (const v of message.sheets) {
      Sheet.encode(v, writer.uint32(10).fork()).join();
    }
    if (message.styles !== undefined) {
      Styles.encode(message.styles, writer.uint32(18).fork()).join();
    }
    if (message.theme !== undefined) {
      Theme.encode(message.theme, writer.uint32(26).fork()).join();
    }
    for (const v of message.contentReferences) {
      ContentReference.encode(v, writer.uint32(34).fork()).join();
    }
    for (const v of message.images) {
      Image.encode(v, writer.uint32(42).fork()).join();
    }
    for (const v of message.people) {
      Person.encode(v, writer.uint32(162).fork()).join();
    }
    for (const v of message.threads) {
      Thread.encode(v, writer.uint32(170).fork()).join();
    }
    for (const v of message.notes) {
      Note.encode(v, writer.uint32(178).fork()).join();
    }
    for (const v of message.slicerCaches) {
      SlicerCache.encode(v, writer.uint32(186).fork()).join();
    }
    for (const v of message.pivotCaches) {
      PivotCache.encode(v, writer.uint32(194).fork()).join();
    }
    for (const v of message.timelineCaches) {
      TimelineCache.encode(v, writer.uint32(202).fork()).join();
    }
    if (message.definedNames !== undefined) {
      DefinedNames.encode(message.definedNames, writer.uint32(210).fork()).join();
    }
    if (message.metadata !== undefined) {
      Metadata.encode(message.metadata, writer.uint32(218).fork()).join();
    }
    if (message.featurePropertyBags !== undefined) {
      FeaturePropertyBags.encode(message.featurePropertyBags, writer.uint32(226).fork()).join();
    }
    for (const v of message.textStyles) {
      TextStyleDefinition.encode(v, writer.uint32(234).fork()).join();
    }
    for (const v of message.codeEnvironments) {
      CodeEnvironment.encode(v, writer.uint32(242).fork()).join();
    }
    for (const v of message.codeBlocks) {
      CodeBlockElement.encode(v, writer.uint32(250).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseWorkbook();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.sheets.push(Sheet.decode(reader, reader.uint32()));
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.styles = Styles.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.theme = Theme.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.contentReferences.push(ContentReference.decode(reader, reader.uint32()));
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.images.push(Image.decode(reader, reader.uint32()));
          continue;
        }
        case 20: {
          if (tag !== 162) {
            break;
          }
          message.people.push(Person.decode(reader, reader.uint32()));
          continue;
        }
        case 21: {
          if (tag !== 170) {
            break;
          }
          message.threads.push(Thread.decode(reader, reader.uint32()));
          continue;
        }
        case 22: {
          if (tag !== 178) {
            break;
          }
          message.notes.push(Note.decode(reader, reader.uint32()));
          continue;
        }
        case 23: {
          if (tag !== 186) {
            break;
          }
          message.slicerCaches.push(SlicerCache.decode(reader, reader.uint32()));
          continue;
        }
        case 24: {
          if (tag !== 194) {
            break;
          }
          message.pivotCaches.push(PivotCache.decode(reader, reader.uint32()));
          continue;
        }
        case 25: {
          if (tag !== 202) {
            break;
          }
          message.timelineCaches.push(TimelineCache.decode(reader, reader.uint32()));
          continue;
        }
        case 26: {
          if (tag !== 210) {
            break;
          }
          message.definedNames = DefinedNames.decode(reader, reader.uint32());
          continue;
        }
        case 27: {
          if (tag !== 218) {
            break;
          }
          message.metadata = Metadata.decode(reader, reader.uint32());
          continue;
        }
        case 28: {
          if (tag !== 226) {
            break;
          }
          message.featurePropertyBags = FeaturePropertyBags.decode(reader, reader.uint32());
          continue;
        }
        case 29: {
          if (tag !== 234) {
            break;
          }
          message.textStyles.push(TextStyleDefinition.decode(reader, reader.uint32()));
          continue;
        }
        case 30: {
          if (tag !== 242) {
            break;
          }
          message.codeEnvironments.push(CodeEnvironment.decode(reader, reader.uint32()));
          continue;
        }
        case 31: {
          if (tag !== 250) {
            break;
          }
          message.codeBlocks.push(CodeBlockElement.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Workbook.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseWorkbook();
    message.id = object.id ?? undefined;
    message.sheets = object.sheets?.map((e) => Sheet.fromPartial(e)) || [];
    message.styles = object.styles !== undefined && object.styles !== null ? Styles.fromPartial(object.styles) : undefined;
    message.theme = object.theme !== undefined && object.theme !== null ? Theme.fromPartial(object.theme) : undefined;
    message.contentReferences = object.contentReferences?.map((e) => ContentReference.fromPartial(e)) || [];
    message.images = object.images?.map((e) => Image.fromPartial(e)) || [];
    message.people = object.people?.map((e) => Person.fromPartial(e)) || [];
    message.threads = object.threads?.map((e) => Thread.fromPartial(e)) || [];
    message.notes = object.notes?.map((e) => Note.fromPartial(e)) || [];
    message.slicerCaches = object.slicerCaches?.map((e) => SlicerCache.fromPartial(e)) || [];
    message.pivotCaches = object.pivotCaches?.map((e) => PivotCache.fromPartial(e)) || [];
    message.timelineCaches = object.timelineCaches?.map((e) => TimelineCache.fromPartial(e)) || [];
    message.definedNames = object.definedNames !== undefined && object.definedNames !== null ? DefinedNames.fromPartial(object.definedNames) : undefined;
    message.metadata = object.metadata !== undefined && object.metadata !== null ? Metadata.fromPartial(object.metadata) : undefined;
    message.featurePropertyBags = object.featurePropertyBags !== undefined && object.featurePropertyBags !== null ? FeaturePropertyBags.fromPartial(object.featurePropertyBags) : undefined;
    message.textStyles = object.textStyles?.map((e) => TextStyleDefinition.fromPartial(e)) || [];
    message.codeEnvironments = object.codeEnvironments?.map((e) => CodeEnvironment.fromPartial(e)) || [];
    message.codeBlocks = object.codeBlocks?.map((e) => CodeBlockElement.fromPartial(e)) || [];
    return message;
  }
};
function createBaseMetadata() {
  return { metadataTypes: [], futureMetadata: [], cellMetadata: [] };
}
var Metadata = {
  encode(message, writer = new BinaryWriter) {
    for (const v of message.metadataTypes) {
      MetadataType.encode(v, writer.uint32(10).fork()).join();
    }
    for (const v of message.futureMetadata) {
      FutureMetadata.encode(v, writer.uint32(18).fork()).join();
    }
    for (const v of message.cellMetadata) {
      CellMetadata.encode(v, writer.uint32(26).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseMetadata();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.metadataTypes.push(MetadataType.decode(reader, reader.uint32()));
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.futureMetadata.push(FutureMetadata.decode(reader, reader.uint32()));
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.cellMetadata.push(CellMetadata.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Metadata.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseMetadata();
    message.metadataTypes = object.metadataTypes?.map((e) => MetadataType.fromPartial(e)) || [];
    message.futureMetadata = object.futureMetadata?.map((e) => FutureMetadata.fromPartial(e)) || [];
    message.cellMetadata = object.cellMetadata?.map((e) => CellMetadata.fromPartial(e)) || [];
    return message;
  }
};
function createBaseMetadataType() {
  return {
    name: "",
    minSupportedVersion: undefined,
    copy: undefined,
    pasteAll: undefined,
    pasteValues: undefined,
    merge: undefined,
    splitFirst: undefined,
    rowColShift: undefined,
    clearFormats: undefined,
    clearComments: undefined,
    assign: undefined,
    coerce: undefined,
    cellMeta: undefined
  };
}
var MetadataType = {
  encode(message, writer = new BinaryWriter) {
    if (message.name !== "") {
      writer.uint32(10).string(message.name);
    }
    if (message.minSupportedVersion !== undefined) {
      writer.uint32(16).int32(message.minSupportedVersion);
    }
    if (message.copy !== undefined) {
      writer.uint32(24).bool(message.copy);
    }
    if (message.pasteAll !== undefined) {
      writer.uint32(32).bool(message.pasteAll);
    }
    if (message.pasteValues !== undefined) {
      writer.uint32(40).bool(message.pasteValues);
    }
    if (message.merge !== undefined) {
      writer.uint32(48).bool(message.merge);
    }
    if (message.splitFirst !== undefined) {
      writer.uint32(56).bool(message.splitFirst);
    }
    if (message.rowColShift !== undefined) {
      writer.uint32(64).bool(message.rowColShift);
    }
    if (message.clearFormats !== undefined) {
      writer.uint32(72).bool(message.clearFormats);
    }
    if (message.clearComments !== undefined) {
      writer.uint32(80).bool(message.clearComments);
    }
    if (message.assign !== undefined) {
      writer.uint32(88).bool(message.assign);
    }
    if (message.coerce !== undefined) {
      writer.uint32(96).bool(message.coerce);
    }
    if (message.cellMeta !== undefined) {
      writer.uint32(104).bool(message.cellMeta);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseMetadataType();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.minSupportedVersion = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.copy = reader.bool();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.pasteAll = reader.bool();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.pasteValues = reader.bool();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.merge = reader.bool();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.splitFirst = reader.bool();
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.rowColShift = reader.bool();
          continue;
        }
        case 9: {
          if (tag !== 72) {
            break;
          }
          message.clearFormats = reader.bool();
          continue;
        }
        case 10: {
          if (tag !== 80) {
            break;
          }
          message.clearComments = reader.bool();
          continue;
        }
        case 11: {
          if (tag !== 88) {
            break;
          }
          message.assign = reader.bool();
          continue;
        }
        case 12: {
          if (tag !== 96) {
            break;
          }
          message.coerce = reader.bool();
          continue;
        }
        case 13: {
          if (tag !== 104) {
            break;
          }
          message.cellMeta = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return MetadataType.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseMetadataType();
    message.name = object.name ?? "";
    message.minSupportedVersion = object.minSupportedVersion ?? undefined;
    message.copy = object.copy ?? undefined;
    message.pasteAll = object.pasteAll ?? undefined;
    message.pasteValues = object.pasteValues ?? undefined;
    message.merge = object.merge ?? undefined;
    message.splitFirst = object.splitFirst ?? undefined;
    message.rowColShift = object.rowColShift ?? undefined;
    message.clearFormats = object.clearFormats ?? undefined;
    message.clearComments = object.clearComments ?? undefined;
    message.assign = object.assign ?? undefined;
    message.coerce = object.coerce ?? undefined;
    message.cellMeta = object.cellMeta ?? undefined;
    return message;
  }
};
function createBaseFutureMetadata() {
  return { name: "", count: undefined, blocks: [] };
}
var FutureMetadata = {
  encode(message, writer = new BinaryWriter) {
    if (message.name !== "") {
      writer.uint32(10).string(message.name);
    }
    if (message.count !== undefined) {
      writer.uint32(16).int32(message.count);
    }
    for (const v of message.blocks) {
      FutureMetadataBlock.encode(v, writer.uint32(26).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseFutureMetadata();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.count = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.blocks.push(FutureMetadataBlock.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return FutureMetadata.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseFutureMetadata();
    message.name = object.name ?? "";
    message.count = object.count ?? undefined;
    message.blocks = object.blocks?.map((e) => FutureMetadataBlock.fromPartial(e)) || [];
    return message;
  }
};
function createBaseFutureMetadataBlock() {
  return { extensionUri: undefined, dynamicArrayProperties: undefined };
}
var FutureMetadataBlock = {
  encode(message, writer = new BinaryWriter) {
    if (message.extensionUri !== undefined) {
      writer.uint32(10).string(message.extensionUri);
    }
    if (message.dynamicArrayProperties !== undefined) {
      DynamicArrayProperties.encode(message.dynamicArrayProperties, writer.uint32(18).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseFutureMetadataBlock();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.extensionUri = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.dynamicArrayProperties = DynamicArrayProperties.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return FutureMetadataBlock.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseFutureMetadataBlock();
    message.extensionUri = object.extensionUri ?? undefined;
    message.dynamicArrayProperties = object.dynamicArrayProperties !== undefined && object.dynamicArrayProperties !== null ? DynamicArrayProperties.fromPartial(object.dynamicArrayProperties) : undefined;
    return message;
  }
};
function createBaseDynamicArrayProperties() {
  return { isDynamic: undefined, collapsed: undefined };
}
var DynamicArrayProperties = {
  encode(message, writer = new BinaryWriter) {
    if (message.isDynamic !== undefined) {
      writer.uint32(8).bool(message.isDynamic);
    }
    if (message.collapsed !== undefined) {
      writer.uint32(16).bool(message.collapsed);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseDynamicArrayProperties();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.isDynamic = reader.bool();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.collapsed = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return DynamicArrayProperties.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseDynamicArrayProperties();
    message.isDynamic = object.isDynamic ?? undefined;
    message.collapsed = object.collapsed ?? undefined;
    return message;
  }
};
function createBaseCellMetadata() {
  return { blocks: [] };
}
var CellMetadata = {
  encode(message, writer = new BinaryWriter) {
    for (const v of message.blocks) {
      CellMetadataBlock.encode(v, writer.uint32(10).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCellMetadata();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.blocks.push(CellMetadataBlock.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CellMetadata.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCellMetadata();
    message.blocks = object.blocks?.map((e) => CellMetadataBlock.fromPartial(e)) || [];
    return message;
  }
};
function createBaseCellMetadataBlock() {
  return { entries: [] };
}
var CellMetadataBlock = {
  encode(message, writer = new BinaryWriter) {
    for (const v of message.entries) {
      CellMetadataEntry.encode(v, writer.uint32(10).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCellMetadataBlock();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.entries.push(CellMetadataEntry.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CellMetadataBlock.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCellMetadataBlock();
    message.entries = object.entries?.map((e) => CellMetadataEntry.fromPartial(e)) || [];
    return message;
  }
};
function createBaseCellMetadataEntry() {
  return { type: undefined, value: undefined };
}
var CellMetadataEntry = {
  encode(message, writer = new BinaryWriter) {
    if (message.type !== undefined) {
      writer.uint32(8).int32(message.type);
    }
    if (message.value !== undefined) {
      writer.uint32(16).int32(message.value);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCellMetadataEntry();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.type = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.value = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CellMetadataEntry.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCellMetadataEntry();
    message.type = object.type ?? undefined;
    message.value = object.value ?? undefined;
    return message;
  }
};
function createBaseFeaturePropertyBags() {
  return { count: undefined, bags: [] };
}
var FeaturePropertyBags = {
  encode(message, writer = new BinaryWriter) {
    if (message.count !== undefined) {
      writer.uint32(8).uint32(message.count);
    }
    for (const v of message.bags) {
      FeaturePropertyBag.encode(v, writer.uint32(18).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseFeaturePropertyBags();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.count = reader.uint32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.bags.push(FeaturePropertyBag.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return FeaturePropertyBags.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseFeaturePropertyBags();
    message.count = object.count ?? undefined;
    message.bags = object.bags?.map((e) => FeaturePropertyBag.fromPartial(e)) || [];
    return message;
  }
};
function createBaseFeaturePropertyBag() {
  return {
    type: 0,
    extRef: undefined,
    bagExtensionId: undefined,
    att: undefined,
    customType: undefined,
    properties: []
  };
}
var FeaturePropertyBag = {
  encode(message, writer = new BinaryWriter) {
    if (message.type !== 0) {
      writer.uint32(8).int32(message.type);
    }
    if (message.extRef !== undefined) {
      writer.uint32(18).string(message.extRef);
    }
    if (message.bagExtensionId !== undefined) {
      writer.uint32(24).uint32(message.bagExtensionId);
    }
    if (message.att !== undefined) {
      writer.uint32(34).string(message.att);
    }
    if (message.customType !== undefined) {
      writer.uint32(42).string(message.customType);
    }
    for (const v of message.properties) {
      FeatureProperty.encode(v, writer.uint32(50).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseFeaturePropertyBag();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.type = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.extRef = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.bagExtensionId = reader.uint32();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.att = reader.string();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.customType = reader.string();
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.properties.push(FeatureProperty.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return FeaturePropertyBag.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseFeaturePropertyBag();
    message.type = object.type ?? 0;
    message.extRef = object.extRef ?? undefined;
    message.bagExtensionId = object.bagExtensionId ?? undefined;
    message.att = object.att ?? undefined;
    message.customType = object.customType ?? undefined;
    message.properties = object.properties?.map((e) => FeatureProperty.fromPartial(e)) || [];
    return message;
  }
};
function createBaseFeatureProperty() {
  return {
    key: "",
    bagIdValue: undefined,
    intValue: undefined,
    decimalValue: undefined,
    stringValue: undefined,
    boolValue: undefined,
    relationshipId: undefined,
    arrayValue: undefined
  };
}
var FeatureProperty = {
  encode(message, writer = new BinaryWriter) {
    if (message.key !== "") {
      writer.uint32(10).string(message.key);
    }
    if (message.bagIdValue !== undefined) {
      writer.uint32(16).uint32(message.bagIdValue);
    }
    if (message.intValue !== undefined) {
      writer.uint32(24).int32(message.intValue);
    }
    if (message.decimalValue !== undefined) {
      writer.uint32(33).double(message.decimalValue);
    }
    if (message.stringValue !== undefined) {
      writer.uint32(42).string(message.stringValue);
    }
    if (message.boolValue !== undefined) {
      writer.uint32(48).bool(message.boolValue);
    }
    if (message.relationshipId !== undefined) {
      writer.uint32(58).string(message.relationshipId);
    }
    if (message.arrayValue !== undefined) {
      FeaturePropertyArray.encode(message.arrayValue, writer.uint32(66).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseFeatureProperty();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.key = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.bagIdValue = reader.uint32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.intValue = reader.int32();
          continue;
        }
        case 4: {
          if (tag !== 33) {
            break;
          }
          message.decimalValue = reader.double();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.stringValue = reader.string();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.boolValue = reader.bool();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.relationshipId = reader.string();
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.arrayValue = FeaturePropertyArray.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return FeatureProperty.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseFeatureProperty();
    message.key = object.key ?? "";
    message.bagIdValue = object.bagIdValue ?? undefined;
    message.intValue = object.intValue ?? undefined;
    message.decimalValue = object.decimalValue ?? undefined;
    message.stringValue = object.stringValue ?? undefined;
    message.boolValue = object.boolValue ?? undefined;
    message.relationshipId = object.relationshipId ?? undefined;
    message.arrayValue = object.arrayValue !== undefined && object.arrayValue !== null ? FeaturePropertyArray.fromPartial(object.arrayValue) : undefined;
    return message;
  }
};
function createBaseFeaturePropertyArray() {
  return { values: [] };
}
var FeaturePropertyArray = {
  encode(message, writer = new BinaryWriter) {
    for (const v of message.values) {
      FeaturePropertyArrayValue.encode(v, writer.uint32(10).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseFeaturePropertyArray();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.values.push(FeaturePropertyArrayValue.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return FeaturePropertyArray.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseFeaturePropertyArray();
    message.values = object.values?.map((e) => FeaturePropertyArrayValue.fromPartial(e)) || [];
    return message;
  }
};
function createBaseFeaturePropertyArrayValue() {
  return {
    bagIdValue: undefined,
    intValue: undefined,
    doubleValue: undefined,
    stringValue: undefined,
    boolValue: undefined,
    relationshipId: undefined
  };
}
var FeaturePropertyArrayValue = {
  encode(message, writer = new BinaryWriter) {
    if (message.bagIdValue !== undefined) {
      writer.uint32(8).uint32(message.bagIdValue);
    }
    if (message.intValue !== undefined) {
      writer.uint32(16).int32(message.intValue);
    }
    if (message.doubleValue !== undefined) {
      writer.uint32(25).double(message.doubleValue);
    }
    if (message.stringValue !== undefined) {
      writer.uint32(34).string(message.stringValue);
    }
    if (message.boolValue !== undefined) {
      writer.uint32(40).bool(message.boolValue);
    }
    if (message.relationshipId !== undefined) {
      writer.uint32(50).string(message.relationshipId);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseFeaturePropertyArrayValue();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.bagIdValue = reader.uint32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.intValue = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 25) {
            break;
          }
          message.doubleValue = reader.double();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.stringValue = reader.string();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.boolValue = reader.bool();
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.relationshipId = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return FeaturePropertyArrayValue.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseFeaturePropertyArrayValue();
    message.bagIdValue = object.bagIdValue ?? undefined;
    message.intValue = object.intValue ?? undefined;
    message.doubleValue = object.doubleValue ?? undefined;
    message.stringValue = object.stringValue ?? undefined;
    message.boolValue = object.boolValue ?? undefined;
    message.relationshipId = object.relationshipId ?? undefined;
    return message;
  }
};
function createBaseDefineName() {
  return {
    name: "",
    text: "",
    localSheetId: undefined,
    hidden: undefined,
    comment: undefined,
    description: undefined,
    customMenu: undefined,
    help: undefined,
    statusBar: undefined,
    shortcutKey: undefined,
    function: undefined,
    vbProcedure: undefined,
    functionGroupId: undefined,
    publishToServer: undefined,
    workbookParameter: undefined,
    xlm: undefined
  };
}
var DefineName = {
  encode(message, writer = new BinaryWriter) {
    if (message.name !== "") {
      writer.uint32(10).string(message.name);
    }
    if (message.text !== "") {
      writer.uint32(18).string(message.text);
    }
    if (message.localSheetId !== undefined) {
      writer.uint32(24).int32(message.localSheetId);
    }
    if (message.hidden !== undefined) {
      writer.uint32(32).bool(message.hidden);
    }
    if (message.comment !== undefined) {
      writer.uint32(42).string(message.comment);
    }
    if (message.description !== undefined) {
      writer.uint32(50).string(message.description);
    }
    if (message.customMenu !== undefined) {
      writer.uint32(58).string(message.customMenu);
    }
    if (message.help !== undefined) {
      writer.uint32(66).string(message.help);
    }
    if (message.statusBar !== undefined) {
      writer.uint32(74).string(message.statusBar);
    }
    if (message.shortcutKey !== undefined) {
      writer.uint32(82).string(message.shortcutKey);
    }
    if (message.function !== undefined) {
      writer.uint32(88).bool(message.function);
    }
    if (message.vbProcedure !== undefined) {
      writer.uint32(96).bool(message.vbProcedure);
    }
    if (message.functionGroupId !== undefined) {
      writer.uint32(104).int32(message.functionGroupId);
    }
    if (message.publishToServer !== undefined) {
      writer.uint32(112).bool(message.publishToServer);
    }
    if (message.workbookParameter !== undefined) {
      writer.uint32(120).bool(message.workbookParameter);
    }
    if (message.xlm !== undefined) {
      writer.uint32(128).bool(message.xlm);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseDefineName();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.text = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.localSheetId = reader.int32();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.hidden = reader.bool();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.comment = reader.string();
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.description = reader.string();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.customMenu = reader.string();
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.help = reader.string();
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.statusBar = reader.string();
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.shortcutKey = reader.string();
          continue;
        }
        case 11: {
          if (tag !== 88) {
            break;
          }
          message.function = reader.bool();
          continue;
        }
        case 12: {
          if (tag !== 96) {
            break;
          }
          message.vbProcedure = reader.bool();
          continue;
        }
        case 13: {
          if (tag !== 104) {
            break;
          }
          message.functionGroupId = reader.int32();
          continue;
        }
        case 14: {
          if (tag !== 112) {
            break;
          }
          message.publishToServer = reader.bool();
          continue;
        }
        case 15: {
          if (tag !== 120) {
            break;
          }
          message.workbookParameter = reader.bool();
          continue;
        }
        case 16: {
          if (tag !== 128) {
            break;
          }
          message.xlm = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return DefineName.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseDefineName();
    message.name = object.name ?? "";
    message.text = object.text ?? "";
    message.localSheetId = object.localSheetId ?? undefined;
    message.hidden = object.hidden ?? undefined;
    message.comment = object.comment ?? undefined;
    message.description = object.description ?? undefined;
    message.customMenu = object.customMenu ?? undefined;
    message.help = object.help ?? undefined;
    message.statusBar = object.statusBar ?? undefined;
    message.shortcutKey = object.shortcutKey ?? undefined;
    message.function = object.function ?? undefined;
    message.vbProcedure = object.vbProcedure ?? undefined;
    message.functionGroupId = object.functionGroupId ?? undefined;
    message.publishToServer = object.publishToServer ?? undefined;
    message.workbookParameter = object.workbookParameter ?? undefined;
    message.xlm = object.xlm ?? undefined;
    return message;
  }
};
function createBaseDefinedNames() {
  return { names: [] };
}
var DefinedNames = {
  encode(message, writer = new BinaryWriter) {
    for (const v of message.names) {
      DefineName.encode(v, writer.uint32(10).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseDefinedNames();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.names.push(DefineName.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return DefinedNames.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseDefinedNames();
    message.names = object.names?.map((e) => DefineName.fromPartial(e)) || [];
    return message;
  }
};
function createBaseAnchorMarker() {
  return { rowId: "", colId: "", colOffset: "", rowOffset: "" };
}
var AnchorMarker = {
  encode(message, writer = new BinaryWriter) {
    if (message.rowId !== "") {
      writer.uint32(10).string(message.rowId);
    }
    if (message.colId !== "") {
      writer.uint32(18).string(message.colId);
    }
    if (message.colOffset !== "") {
      writer.uint32(26).string(message.colOffset);
    }
    if (message.rowOffset !== "") {
      writer.uint32(34).string(message.rowOffset);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseAnchorMarker();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.rowId = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.colId = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.colOffset = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.rowOffset = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return AnchorMarker.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseAnchorMarker();
    message.rowId = object.rowId ?? "";
    message.colId = object.colId ?? "";
    message.colOffset = object.colOffset ?? "";
    message.rowOffset = object.rowOffset ?? "";
    return message;
  }
};
function createBaseDrawing() {
  return {
    fromAnchor: undefined,
    toAnchor: undefined,
    chart: undefined,
    imageReference: undefined,
    extentCx: undefined,
    extentCy: undefined,
    shape: undefined
  };
}
var Drawing = {
  encode(message, writer = new BinaryWriter) {
    if (message.fromAnchor !== undefined) {
      AnchorMarker.encode(message.fromAnchor, writer.uint32(10).fork()).join();
    }
    if (message.toAnchor !== undefined) {
      AnchorMarker.encode(message.toAnchor, writer.uint32(18).fork()).join();
    }
    if (message.chart !== undefined) {
      Chart.encode(message.chart, writer.uint32(26).fork()).join();
    }
    if (message.imageReference !== undefined) {
      ImageReference.encode(message.imageReference, writer.uint32(34).fork()).join();
    }
    if (message.extentCx !== undefined) {
      writer.uint32(42).string(message.extentCx);
    }
    if (message.extentCy !== undefined) {
      writer.uint32(50).string(message.extentCy);
    }
    if (message.shape !== undefined) {
      Element.encode(message.shape, writer.uint32(58).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseDrawing();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.fromAnchor = AnchorMarker.decode(reader, reader.uint32());
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.toAnchor = AnchorMarker.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.chart = Chart.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.imageReference = ImageReference.decode(reader, reader.uint32());
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.extentCx = reader.string();
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.extentCy = reader.string();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.shape = Element.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Drawing.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseDrawing();
    message.fromAnchor = object.fromAnchor !== undefined && object.fromAnchor !== null ? AnchorMarker.fromPartial(object.fromAnchor) : undefined;
    message.toAnchor = object.toAnchor !== undefined && object.toAnchor !== null ? AnchorMarker.fromPartial(object.toAnchor) : undefined;
    message.chart = object.chart !== undefined && object.chart !== null ? Chart.fromPartial(object.chart) : undefined;
    message.imageReference = object.imageReference !== undefined && object.imageReference !== null ? ImageReference.fromPartial(object.imageReference) : undefined;
    message.extentCx = object.extentCx ?? undefined;
    message.extentCy = object.extentCy ?? undefined;
    message.shape = object.shape !== undefined && object.shape !== null ? Element.fromPartial(object.shape) : undefined;
    return message;
  }
};
function createBaseSheet() {
  return {
    id: undefined,
    sheetId: undefined,
    index: 0,
    name: "",
    rows: [],
    innerXml: "",
    outerXml: "",
    columns: [],
    defaultRowHeight: 0,
    drawings: [],
    defaultColWidth: 0,
    baseColWidth: undefined,
    showGridLines: undefined,
    mergedCells: [],
    conditionalFormattings: [],
    sharedFormulas: [],
    tables: [],
    pivotTables: [],
    slicers: [],
    tabColor: undefined,
    timelines: [],
    sparklineGroups: undefined,
    dataValidations: undefined
  };
}
var Sheet = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== undefined) {
      writer.uint32(90).string(message.id);
    }
    if (message.sheetId !== undefined) {
      writer.uint32(162).string(message.sheetId);
    }
    if (message.index !== 0) {
      writer.uint32(8).int32(message.index);
    }
    if (message.name !== "") {
      writer.uint32(18).string(message.name);
    }
    for (const v of message.rows) {
      Row.encode(v, writer.uint32(26).fork()).join();
    }
    if (message.innerXml !== "") {
      writer.uint32(34).string(message.innerXml);
    }
    if (message.outerXml !== "") {
      writer.uint32(42).string(message.outerXml);
    }
    for (const v of message.columns) {
      Column.encode(v, writer.uint32(50).fork()).join();
    }
    if (message.defaultRowHeight !== 0) {
      writer.uint32(61).float(message.defaultRowHeight);
    }
    for (const v of message.drawings) {
      Drawing.encode(v, writer.uint32(66).fork()).join();
    }
    if (message.defaultColWidth !== 0) {
      writer.uint32(77).float(message.defaultColWidth);
    }
    if (message.baseColWidth !== undefined) {
      writer.uint32(173).float(message.baseColWidth);
    }
    if (message.showGridLines !== undefined) {
      writer.uint32(80).bool(message.showGridLines);
    }
    for (const v of message.mergedCells) {
      RangeTarget.encode(v, writer.uint32(98).fork()).join();
    }
    for (const v of message.conditionalFormattings) {
      ConditionalFormatting.encode(v, writer.uint32(106).fork()).join();
    }
    for (const v of message.sharedFormulas) {
      SharedFormula.encode(v, writer.uint32(114).fork()).join();
    }
    for (const v of message.tables) {
      Table.encode(v, writer.uint32(122).fork()).join();
    }
    for (const v of message.pivotTables) {
      PivotTable.encode(v, writer.uint32(130).fork()).join();
    }
    for (const v of message.slicers) {
      Slicer.encode(v, writer.uint32(138).fork()).join();
    }
    if (message.tabColor !== undefined) {
      Color.encode(message.tabColor, writer.uint32(146).fork()).join();
    }
    for (const v of message.timelines) {
      Timeline.encode(v, writer.uint32(154).fork()).join();
    }
    if (message.sparklineGroups !== undefined) {
      SparklineGroups.encode(message.sparklineGroups, writer.uint32(218).fork()).join();
    }
    if (message.dataValidations !== undefined) {
      DataValidations.encode(message.dataValidations, writer.uint32(226).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseSheet();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 11: {
          if (tag !== 90) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 20: {
          if (tag !== 162) {
            break;
          }
          message.sheetId = reader.string();
          continue;
        }
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.index = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.rows.push(Row.decode(reader, reader.uint32()));
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.innerXml = reader.string();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.outerXml = reader.string();
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.columns.push(Column.decode(reader, reader.uint32()));
          continue;
        }
        case 7: {
          if (tag !== 61) {
            break;
          }
          message.defaultRowHeight = reader.float();
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.drawings.push(Drawing.decode(reader, reader.uint32()));
          continue;
        }
        case 9: {
          if (tag !== 77) {
            break;
          }
          message.defaultColWidth = reader.float();
          continue;
        }
        case 21: {
          if (tag !== 173) {
            break;
          }
          message.baseColWidth = reader.float();
          continue;
        }
        case 10: {
          if (tag !== 80) {
            break;
          }
          message.showGridLines = reader.bool();
          continue;
        }
        case 12: {
          if (tag !== 98) {
            break;
          }
          message.mergedCells.push(RangeTarget.decode(reader, reader.uint32()));
          continue;
        }
        case 13: {
          if (tag !== 106) {
            break;
          }
          message.conditionalFormattings.push(ConditionalFormatting.decode(reader, reader.uint32()));
          continue;
        }
        case 14: {
          if (tag !== 114) {
            break;
          }
          message.sharedFormulas.push(SharedFormula.decode(reader, reader.uint32()));
          continue;
        }
        case 15: {
          if (tag !== 122) {
            break;
          }
          message.tables.push(Table.decode(reader, reader.uint32()));
          continue;
        }
        case 16: {
          if (tag !== 130) {
            break;
          }
          message.pivotTables.push(PivotTable.decode(reader, reader.uint32()));
          continue;
        }
        case 17: {
          if (tag !== 138) {
            break;
          }
          message.slicers.push(Slicer.decode(reader, reader.uint32()));
          continue;
        }
        case 18: {
          if (tag !== 146) {
            break;
          }
          message.tabColor = Color.decode(reader, reader.uint32());
          continue;
        }
        case 19: {
          if (tag !== 154) {
            break;
          }
          message.timelines.push(Timeline.decode(reader, reader.uint32()));
          continue;
        }
        case 27: {
          if (tag !== 218) {
            break;
          }
          message.sparklineGroups = SparklineGroups.decode(reader, reader.uint32());
          continue;
        }
        case 28: {
          if (tag !== 226) {
            break;
          }
          message.dataValidations = DataValidations.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Sheet.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseSheet();
    message.id = object.id ?? undefined;
    message.sheetId = object.sheetId ?? undefined;
    message.index = object.index ?? 0;
    message.name = object.name ?? "";
    message.rows = object.rows?.map((e) => Row.fromPartial(e)) || [];
    message.innerXml = object.innerXml ?? "";
    message.outerXml = object.outerXml ?? "";
    message.columns = object.columns?.map((e) => Column.fromPartial(e)) || [];
    message.defaultRowHeight = object.defaultRowHeight ?? 0;
    message.drawings = object.drawings?.map((e) => Drawing.fromPartial(e)) || [];
    message.defaultColWidth = object.defaultColWidth ?? 0;
    message.baseColWidth = object.baseColWidth ?? undefined;
    message.showGridLines = object.showGridLines ?? undefined;
    message.mergedCells = object.mergedCells?.map((e) => RangeTarget.fromPartial(e)) || [];
    message.conditionalFormattings = object.conditionalFormattings?.map((e) => ConditionalFormatting.fromPartial(e)) || [];
    message.sharedFormulas = object.sharedFormulas?.map((e) => SharedFormula.fromPartial(e)) || [];
    message.tables = object.tables?.map((e) => Table.fromPartial(e)) || [];
    message.pivotTables = object.pivotTables?.map((e) => PivotTable.fromPartial(e)) || [];
    message.slicers = object.slicers?.map((e) => Slicer.fromPartial(e)) || [];
    message.tabColor = object.tabColor !== undefined && object.tabColor !== null ? Color.fromPartial(object.tabColor) : undefined;
    message.timelines = object.timelines?.map((e) => Timeline.fromPartial(e)) || [];
    message.sparklineGroups = object.sparklineGroups !== undefined && object.sparklineGroups !== null ? SparklineGroups.fromPartial(object.sparklineGroups) : undefined;
    message.dataValidations = object.dataValidations !== undefined && object.dataValidations !== null ? DataValidations.fromPartial(object.dataValidations) : undefined;
    return message;
  }
};
function createBaseSparklineGroups() {
  return { groups: [] };
}
var SparklineGroups = {
  encode(message, writer = new BinaryWriter) {
    for (const v of message.groups) {
      SparklineGroup.encode(v, writer.uint32(10).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseSparklineGroups();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.groups.push(SparklineGroup.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return SparklineGroups.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseSparklineGroups();
    message.groups = object.groups?.map((e) => SparklineGroup.fromPartial(e)) || [];
    return message;
  }
};
function createBaseSparkline() {
  return { formula: undefined, reference: undefined };
}
var Sparkline = {
  encode(message, writer = new BinaryWriter) {
    if (message.formula !== undefined) {
      writer.uint32(10).string(message.formula);
    }
    if (message.reference !== undefined) {
      writer.uint32(18).string(message.reference);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseSparkline();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.formula = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.reference = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Sparkline.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseSparkline();
    message.formula = object.formula ?? undefined;
    message.reference = object.reference ?? undefined;
    return message;
  }
};
function createBaseSparklineGroup() {
  return {
    uid: undefined,
    manualMax: undefined,
    manualMin: undefined,
    lineWeight: undefined,
    type: undefined,
    dateAxis: undefined,
    displayEmptyCellsAs: undefined,
    markers: undefined,
    high: undefined,
    low: undefined,
    first: undefined,
    last: undefined,
    negative: undefined,
    displayXAxis: undefined,
    displayHidden: undefined,
    minAxisType: undefined,
    maxAxisType: undefined,
    rightToLeft: undefined,
    seriesColor: undefined,
    negativeColor: undefined,
    axisColor: undefined,
    markersColor: undefined,
    firstMarkerColor: undefined,
    lastMarkerColor: undefined,
    highMarkerColor: undefined,
    lowMarkerColor: undefined,
    formula: undefined,
    sparklines: []
  };
}
var SparklineGroup = {
  encode(message, writer = new BinaryWriter) {
    if (message.uid !== undefined) {
      writer.uint32(10).string(message.uid);
    }
    if (message.manualMax !== undefined) {
      writer.uint32(17).double(message.manualMax);
    }
    if (message.manualMin !== undefined) {
      writer.uint32(25).double(message.manualMin);
    }
    if (message.lineWeight !== undefined) {
      writer.uint32(33).double(message.lineWeight);
    }
    if (message.type !== undefined) {
      writer.uint32(40).int32(message.type);
    }
    if (message.dateAxis !== undefined) {
      writer.uint32(48).bool(message.dateAxis);
    }
    if (message.displayEmptyCellsAs !== undefined) {
      writer.uint32(56).int32(message.displayEmptyCellsAs);
    }
    if (message.markers !== undefined) {
      writer.uint32(64).bool(message.markers);
    }
    if (message.high !== undefined) {
      writer.uint32(72).bool(message.high);
    }
    if (message.low !== undefined) {
      writer.uint32(80).bool(message.low);
    }
    if (message.first !== undefined) {
      writer.uint32(88).bool(message.first);
    }
    if (message.last !== undefined) {
      writer.uint32(96).bool(message.last);
    }
    if (message.negative !== undefined) {
      writer.uint32(104).bool(message.negative);
    }
    if (message.displayXAxis !== undefined) {
      writer.uint32(112).bool(message.displayXAxis);
    }
    if (message.displayHidden !== undefined) {
      writer.uint32(120).bool(message.displayHidden);
    }
    if (message.minAxisType !== undefined) {
      writer.uint32(128).int32(message.minAxisType);
    }
    if (message.maxAxisType !== undefined) {
      writer.uint32(136).int32(message.maxAxisType);
    }
    if (message.rightToLeft !== undefined) {
      writer.uint32(144).bool(message.rightToLeft);
    }
    if (message.seriesColor !== undefined) {
      Color.encode(message.seriesColor, writer.uint32(154).fork()).join();
    }
    if (message.negativeColor !== undefined) {
      Color.encode(message.negativeColor, writer.uint32(162).fork()).join();
    }
    if (message.axisColor !== undefined) {
      Color.encode(message.axisColor, writer.uint32(170).fork()).join();
    }
    if (message.markersColor !== undefined) {
      Color.encode(message.markersColor, writer.uint32(178).fork()).join();
    }
    if (message.firstMarkerColor !== undefined) {
      Color.encode(message.firstMarkerColor, writer.uint32(186).fork()).join();
    }
    if (message.lastMarkerColor !== undefined) {
      Color.encode(message.lastMarkerColor, writer.uint32(194).fork()).join();
    }
    if (message.highMarkerColor !== undefined) {
      Color.encode(message.highMarkerColor, writer.uint32(202).fork()).join();
    }
    if (message.lowMarkerColor !== undefined) {
      Color.encode(message.lowMarkerColor, writer.uint32(210).fork()).join();
    }
    if (message.formula !== undefined) {
      writer.uint32(218).string(message.formula);
    }
    for (const v of message.sparklines) {
      Sparkline.encode(v, writer.uint32(226).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseSparklineGroup();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.uid = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 17) {
            break;
          }
          message.manualMax = reader.double();
          continue;
        }
        case 3: {
          if (tag !== 25) {
            break;
          }
          message.manualMin = reader.double();
          continue;
        }
        case 4: {
          if (tag !== 33) {
            break;
          }
          message.lineWeight = reader.double();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.type = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.dateAxis = reader.bool();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.displayEmptyCellsAs = reader.int32();
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.markers = reader.bool();
          continue;
        }
        case 9: {
          if (tag !== 72) {
            break;
          }
          message.high = reader.bool();
          continue;
        }
        case 10: {
          if (tag !== 80) {
            break;
          }
          message.low = reader.bool();
          continue;
        }
        case 11: {
          if (tag !== 88) {
            break;
          }
          message.first = reader.bool();
          continue;
        }
        case 12: {
          if (tag !== 96) {
            break;
          }
          message.last = reader.bool();
          continue;
        }
        case 13: {
          if (tag !== 104) {
            break;
          }
          message.negative = reader.bool();
          continue;
        }
        case 14: {
          if (tag !== 112) {
            break;
          }
          message.displayXAxis = reader.bool();
          continue;
        }
        case 15: {
          if (tag !== 120) {
            break;
          }
          message.displayHidden = reader.bool();
          continue;
        }
        case 16: {
          if (tag !== 128) {
            break;
          }
          message.minAxisType = reader.int32();
          continue;
        }
        case 17: {
          if (tag !== 136) {
            break;
          }
          message.maxAxisType = reader.int32();
          continue;
        }
        case 18: {
          if (tag !== 144) {
            break;
          }
          message.rightToLeft = reader.bool();
          continue;
        }
        case 19: {
          if (tag !== 154) {
            break;
          }
          message.seriesColor = Color.decode(reader, reader.uint32());
          continue;
        }
        case 20: {
          if (tag !== 162) {
            break;
          }
          message.negativeColor = Color.decode(reader, reader.uint32());
          continue;
        }
        case 21: {
          if (tag !== 170) {
            break;
          }
          message.axisColor = Color.decode(reader, reader.uint32());
          continue;
        }
        case 22: {
          if (tag !== 178) {
            break;
          }
          message.markersColor = Color.decode(reader, reader.uint32());
          continue;
        }
        case 23: {
          if (tag !== 186) {
            break;
          }
          message.firstMarkerColor = Color.decode(reader, reader.uint32());
          continue;
        }
        case 24: {
          if (tag !== 194) {
            break;
          }
          message.lastMarkerColor = Color.decode(reader, reader.uint32());
          continue;
        }
        case 25: {
          if (tag !== 202) {
            break;
          }
          message.highMarkerColor = Color.decode(reader, reader.uint32());
          continue;
        }
        case 26: {
          if (tag !== 210) {
            break;
          }
          message.lowMarkerColor = Color.decode(reader, reader.uint32());
          continue;
        }
        case 27: {
          if (tag !== 218) {
            break;
          }
          message.formula = reader.string();
          continue;
        }
        case 28: {
          if (tag !== 226) {
            break;
          }
          message.sparklines.push(Sparkline.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return SparklineGroup.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseSparklineGroup();
    message.uid = object.uid ?? undefined;
    message.manualMax = object.manualMax ?? undefined;
    message.manualMin = object.manualMin ?? undefined;
    message.lineWeight = object.lineWeight ?? undefined;
    message.type = object.type ?? undefined;
    message.dateAxis = object.dateAxis ?? undefined;
    message.displayEmptyCellsAs = object.displayEmptyCellsAs ?? undefined;
    message.markers = object.markers ?? undefined;
    message.high = object.high ?? undefined;
    message.low = object.low ?? undefined;
    message.first = object.first ?? undefined;
    message.last = object.last ?? undefined;
    message.negative = object.negative ?? undefined;
    message.displayXAxis = object.displayXAxis ?? undefined;
    message.displayHidden = object.displayHidden ?? undefined;
    message.minAxisType = object.minAxisType ?? undefined;
    message.maxAxisType = object.maxAxisType ?? undefined;
    message.rightToLeft = object.rightToLeft ?? undefined;
    message.seriesColor = object.seriesColor !== undefined && object.seriesColor !== null ? Color.fromPartial(object.seriesColor) : undefined;
    message.negativeColor = object.negativeColor !== undefined && object.negativeColor !== null ? Color.fromPartial(object.negativeColor) : undefined;
    message.axisColor = object.axisColor !== undefined && object.axisColor !== null ? Color.fromPartial(object.axisColor) : undefined;
    message.markersColor = object.markersColor !== undefined && object.markersColor !== null ? Color.fromPartial(object.markersColor) : undefined;
    message.firstMarkerColor = object.firstMarkerColor !== undefined && object.firstMarkerColor !== null ? Color.fromPartial(object.firstMarkerColor) : undefined;
    message.lastMarkerColor = object.lastMarkerColor !== undefined && object.lastMarkerColor !== null ? Color.fromPartial(object.lastMarkerColor) : undefined;
    message.highMarkerColor = object.highMarkerColor !== undefined && object.highMarkerColor !== null ? Color.fromPartial(object.highMarkerColor) : undefined;
    message.lowMarkerColor = object.lowMarkerColor !== undefined && object.lowMarkerColor !== null ? Color.fromPartial(object.lowMarkerColor) : undefined;
    message.formula = object.formula ?? undefined;
    message.sparklines = object.sparklines?.map((e) => Sparkline.fromPartial(e)) || [];
    return message;
  }
};
function createBaseDataValidations() {
  return { items: [] };
}
var DataValidations = {
  encode(message, writer = new BinaryWriter) {
    for (const v of message.items) {
      DataValidation.encode(v, writer.uint32(10).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseDataValidations();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.items.push(DataValidation.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return DataValidations.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseDataValidations();
    message.items = object.items?.map((e) => DataValidation.fromPartial(e)) || [];
    return message;
  }
};
function createBaseDataValidation() {
  return {
    sqref: "",
    type: undefined,
    errorStyle: undefined,
    imeMode: undefined,
    operator: undefined,
    allowBlank: undefined,
    showDropDown: undefined,
    showInputMessage: undefined,
    showErrorMessage: undefined,
    errorTitle: undefined,
    errorMessage: undefined,
    promptTitle: undefined,
    promptMessage: undefined,
    formula1: undefined,
    formula2: undefined,
    uid: undefined
  };
}
var DataValidation = {
  encode(message, writer = new BinaryWriter) {
    if (message.sqref !== "") {
      writer.uint32(10).string(message.sqref);
    }
    if (message.type !== undefined) {
      writer.uint32(16).int32(message.type);
    }
    if (message.errorStyle !== undefined) {
      writer.uint32(24).int32(message.errorStyle);
    }
    if (message.imeMode !== undefined) {
      writer.uint32(32).int32(message.imeMode);
    }
    if (message.operator !== undefined) {
      writer.uint32(40).int32(message.operator);
    }
    if (message.allowBlank !== undefined) {
      writer.uint32(48).bool(message.allowBlank);
    }
    if (message.showDropDown !== undefined) {
      writer.uint32(56).bool(message.showDropDown);
    }
    if (message.showInputMessage !== undefined) {
      writer.uint32(64).bool(message.showInputMessage);
    }
    if (message.showErrorMessage !== undefined) {
      writer.uint32(72).bool(message.showErrorMessage);
    }
    if (message.errorTitle !== undefined) {
      writer.uint32(82).string(message.errorTitle);
    }
    if (message.errorMessage !== undefined) {
      writer.uint32(90).string(message.errorMessage);
    }
    if (message.promptTitle !== undefined) {
      writer.uint32(98).string(message.promptTitle);
    }
    if (message.promptMessage !== undefined) {
      writer.uint32(106).string(message.promptMessage);
    }
    if (message.formula1 !== undefined) {
      writer.uint32(114).string(message.formula1);
    }
    if (message.formula2 !== undefined) {
      writer.uint32(122).string(message.formula2);
    }
    if (message.uid !== undefined) {
      writer.uint32(130).string(message.uid);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseDataValidation();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.sqref = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.type = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.errorStyle = reader.int32();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.imeMode = reader.int32();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.operator = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.allowBlank = reader.bool();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.showDropDown = reader.bool();
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.showInputMessage = reader.bool();
          continue;
        }
        case 9: {
          if (tag !== 72) {
            break;
          }
          message.showErrorMessage = reader.bool();
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.errorTitle = reader.string();
          continue;
        }
        case 11: {
          if (tag !== 90) {
            break;
          }
          message.errorMessage = reader.string();
          continue;
        }
        case 12: {
          if (tag !== 98) {
            break;
          }
          message.promptTitle = reader.string();
          continue;
        }
        case 13: {
          if (tag !== 106) {
            break;
          }
          message.promptMessage = reader.string();
          continue;
        }
        case 14: {
          if (tag !== 114) {
            break;
          }
          message.formula1 = reader.string();
          continue;
        }
        case 15: {
          if (tag !== 122) {
            break;
          }
          message.formula2 = reader.string();
          continue;
        }
        case 16: {
          if (tag !== 130) {
            break;
          }
          message.uid = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return DataValidation.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseDataValidation();
    message.sqref = object.sqref ?? "";
    message.type = object.type ?? undefined;
    message.errorStyle = object.errorStyle ?? undefined;
    message.imeMode = object.imeMode ?? undefined;
    message.operator = object.operator ?? undefined;
    message.allowBlank = object.allowBlank ?? undefined;
    message.showDropDown = object.showDropDown ?? undefined;
    message.showInputMessage = object.showInputMessage ?? undefined;
    message.showErrorMessage = object.showErrorMessage ?? undefined;
    message.errorTitle = object.errorTitle ?? undefined;
    message.errorMessage = object.errorMessage ?? undefined;
    message.promptTitle = object.promptTitle ?? undefined;
    message.promptMessage = object.promptMessage ?? undefined;
    message.formula1 = object.formula1 ?? undefined;
    message.formula2 = object.formula2 ?? undefined;
    message.uid = object.uid ?? undefined;
    return message;
  }
};
function createBaseRow() {
  return { index: 0, cells: [], height: 0, customHeight: false, styleIndex: undefined, hidden: undefined };
}
var Row = {
  encode(message, writer = new BinaryWriter) {
    if (message.index !== 0) {
      writer.uint32(8).int32(message.index);
    }
    for (const v of message.cells) {
      Cell.encode(v, writer.uint32(18).fork()).join();
    }
    if (message.height !== 0) {
      writer.uint32(29).float(message.height);
    }
    if (message.customHeight !== false) {
      writer.uint32(32).bool(message.customHeight);
    }
    if (message.styleIndex !== undefined) {
      writer.uint32(40).int32(message.styleIndex);
    }
    if (message.hidden !== undefined) {
      writer.uint32(48).bool(message.hidden);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseRow();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.index = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.cells.push(Cell.decode(reader, reader.uint32()));
          continue;
        }
        case 3: {
          if (tag !== 29) {
            break;
          }
          message.height = reader.float();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.customHeight = reader.bool();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.styleIndex = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.hidden = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Row.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseRow();
    message.index = object.index ?? 0;
    message.cells = object.cells?.map((e) => Cell.fromPartial(e)) || [];
    message.height = object.height ?? 0;
    message.customHeight = object.customHeight ?? false;
    message.styleIndex = object.styleIndex ?? undefined;
    message.hidden = object.hidden ?? undefined;
    return message;
  }
};
function createBaseCell() {
  return {
    address: "",
    value: undefined,
    formula: undefined,
    dataType: 0,
    styleIndex: undefined,
    paragraphs: [],
    textStyle: undefined,
    sharedFormulaSi: undefined,
    formulaType: undefined,
    formulaRef: undefined,
    formulaAlwaysCalculateArray: undefined,
    cellMetadataIndex: undefined,
    dataTableRowInput: undefined,
    dataTableColumnInput: undefined,
    dataTableRowOriented: undefined,
    dataTableTwoVariable: undefined
  };
}
var Cell = {
  encode(message, writer = new BinaryWriter) {
    if (message.address !== "") {
      writer.uint32(10).string(message.address);
    }
    if (message.value !== undefined) {
      writer.uint32(18).string(message.value);
    }
    if (message.formula !== undefined) {
      writer.uint32(26).string(message.formula);
    }
    if (message.dataType !== 0) {
      writer.uint32(32).int32(message.dataType);
    }
    if (message.styleIndex !== undefined) {
      writer.uint32(40).int32(message.styleIndex);
    }
    for (const v of message.paragraphs) {
      Paragraph.encode(v, writer.uint32(50).fork()).join();
    }
    if (message.textStyle !== undefined) {
      TextStyle.encode(message.textStyle, writer.uint32(58).fork()).join();
    }
    if (message.sharedFormulaSi !== undefined) {
      writer.uint32(64).int32(message.sharedFormulaSi);
    }
    if (message.formulaType !== undefined) {
      writer.uint32(72).int32(message.formulaType);
    }
    if (message.formulaRef !== undefined) {
      writer.uint32(82).string(message.formulaRef);
    }
    if (message.formulaAlwaysCalculateArray !== undefined) {
      writer.uint32(88).bool(message.formulaAlwaysCalculateArray);
    }
    if (message.cellMetadataIndex !== undefined) {
      writer.uint32(96).int32(message.cellMetadataIndex);
    }
    if (message.dataTableRowInput !== undefined) {
      writer.uint32(106).string(message.dataTableRowInput);
    }
    if (message.dataTableColumnInput !== undefined) {
      writer.uint32(114).string(message.dataTableColumnInput);
    }
    if (message.dataTableRowOriented !== undefined) {
      writer.uint32(120).bool(message.dataTableRowOriented);
    }
    if (message.dataTableTwoVariable !== undefined) {
      writer.uint32(128).bool(message.dataTableTwoVariable);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCell();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.address = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.value = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.formula = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.dataType = reader.int32();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.styleIndex = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.paragraphs.push(Paragraph.decode(reader, reader.uint32()));
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.textStyle = TextStyle.decode(reader, reader.uint32());
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.sharedFormulaSi = reader.int32();
          continue;
        }
        case 9: {
          if (tag !== 72) {
            break;
          }
          message.formulaType = reader.int32();
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.formulaRef = reader.string();
          continue;
        }
        case 11: {
          if (tag !== 88) {
            break;
          }
          message.formulaAlwaysCalculateArray = reader.bool();
          continue;
        }
        case 12: {
          if (tag !== 96) {
            break;
          }
          message.cellMetadataIndex = reader.int32();
          continue;
        }
        case 13: {
          if (tag !== 106) {
            break;
          }
          message.dataTableRowInput = reader.string();
          continue;
        }
        case 14: {
          if (tag !== 114) {
            break;
          }
          message.dataTableColumnInput = reader.string();
          continue;
        }
        case 15: {
          if (tag !== 120) {
            break;
          }
          message.dataTableRowOriented = reader.bool();
          continue;
        }
        case 16: {
          if (tag !== 128) {
            break;
          }
          message.dataTableTwoVariable = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Cell.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCell();
    message.address = object.address ?? "";
    message.value = object.value ?? undefined;
    message.formula = object.formula ?? undefined;
    message.dataType = object.dataType ?? 0;
    message.styleIndex = object.styleIndex ?? undefined;
    message.paragraphs = object.paragraphs?.map((e) => Paragraph.fromPartial(e)) || [];
    message.textStyle = object.textStyle !== undefined && object.textStyle !== null ? TextStyle.fromPartial(object.textStyle) : undefined;
    message.sharedFormulaSi = object.sharedFormulaSi ?? undefined;
    message.formulaType = object.formulaType ?? undefined;
    message.formulaRef = object.formulaRef ?? undefined;
    message.formulaAlwaysCalculateArray = object.formulaAlwaysCalculateArray ?? undefined;
    message.cellMetadataIndex = object.cellMetadataIndex ?? undefined;
    message.dataTableRowInput = object.dataTableRowInput ?? undefined;
    message.dataTableColumnInput = object.dataTableColumnInput ?? undefined;
    message.dataTableRowOriented = object.dataTableRowOriented ?? undefined;
    message.dataTableTwoVariable = object.dataTableTwoVariable ?? undefined;
    return message;
  }
};
function createBaseSharedFormula() {
  return { si: 0, base: "", anchor: "" };
}
var SharedFormula = {
  encode(message, writer = new BinaryWriter) {
    if (message.si !== 0) {
      writer.uint32(8).int32(message.si);
    }
    if (message.base !== "") {
      writer.uint32(18).string(message.base);
    }
    if (message.anchor !== "") {
      writer.uint32(26).string(message.anchor);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseSharedFormula();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.si = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.base = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.anchor = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return SharedFormula.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseSharedFormula();
    message.si = object.si ?? 0;
    message.base = object.base ?? "";
    message.anchor = object.anchor ?? "";
    return message;
  }
};
function createBaseColumn() {
  return { min: 0, max: 0, width: 0, customWidth: false, styleIndex: undefined, hidden: undefined };
}
var Column = {
  encode(message, writer = new BinaryWriter) {
    if (message.min !== 0) {
      writer.uint32(8).int32(message.min);
    }
    if (message.max !== 0) {
      writer.uint32(16).int32(message.max);
    }
    if (message.width !== 0) {
      writer.uint32(29).float(message.width);
    }
    if (message.customWidth !== false) {
      writer.uint32(32).bool(message.customWidth);
    }
    if (message.styleIndex !== undefined) {
      writer.uint32(40).int32(message.styleIndex);
    }
    if (message.hidden !== undefined) {
      writer.uint32(48).bool(message.hidden);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseColumn();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.min = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.max = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 29) {
            break;
          }
          message.width = reader.float();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.customWidth = reader.bool();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.styleIndex = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.hidden = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Column.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseColumn();
    message.min = object.min ?? 0;
    message.max = object.max ?? 0;
    message.width = object.width ?? 0;
    message.customWidth = object.customWidth ?? false;
    message.styleIndex = object.styleIndex ?? undefined;
    message.hidden = object.hidden ?? undefined;
    return message;
  }
};
function createBaseBorderLine() {
  return { style: "", color: undefined, indexedColorId: undefined };
}
var BorderLine = {
  encode(message, writer = new BinaryWriter) {
    if (message.style !== "") {
      writer.uint32(10).string(message.style);
    }
    if (message.color !== undefined) {
      Color.encode(message.color, writer.uint32(18).fork()).join();
    }
    if (message.indexedColorId !== undefined) {
      writer.uint32(24).int32(message.indexedColorId);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseBorderLine();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.style = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.color = Color.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.indexedColorId = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return BorderLine.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseBorderLine();
    message.style = object.style ?? "";
    message.color = object.color !== undefined && object.color !== null ? Color.fromPartial(object.color) : undefined;
    message.indexedColorId = object.indexedColorId ?? undefined;
    return message;
  }
};
function createBaseBorder() {
  return {
    left: undefined,
    right: undefined,
    top: undefined,
    bottom: undefined,
    diagonal: undefined,
    diagonalUp: undefined,
    diagonalDown: undefined
  };
}
var Border = {
  encode(message, writer = new BinaryWriter) {
    if (message.left !== undefined) {
      BorderLine.encode(message.left, writer.uint32(10).fork()).join();
    }
    if (message.right !== undefined) {
      BorderLine.encode(message.right, writer.uint32(18).fork()).join();
    }
    if (message.top !== undefined) {
      BorderLine.encode(message.top, writer.uint32(26).fork()).join();
    }
    if (message.bottom !== undefined) {
      BorderLine.encode(message.bottom, writer.uint32(34).fork()).join();
    }
    if (message.diagonal !== undefined) {
      BorderLine.encode(message.diagonal, writer.uint32(42).fork()).join();
    }
    if (message.diagonalUp !== undefined) {
      writer.uint32(48).bool(message.diagonalUp);
    }
    if (message.diagonalDown !== undefined) {
      writer.uint32(56).bool(message.diagonalDown);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseBorder();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.left = BorderLine.decode(reader, reader.uint32());
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.right = BorderLine.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.top = BorderLine.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.bottom = BorderLine.decode(reader, reader.uint32());
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.diagonal = BorderLine.decode(reader, reader.uint32());
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.diagonalUp = reader.bool();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.diagonalDown = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Border.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseBorder();
    message.left = object.left !== undefined && object.left !== null ? BorderLine.fromPartial(object.left) : undefined;
    message.right = object.right !== undefined && object.right !== null ? BorderLine.fromPartial(object.right) : undefined;
    message.top = object.top !== undefined && object.top !== null ? BorderLine.fromPartial(object.top) : undefined;
    message.bottom = object.bottom !== undefined && object.bottom !== null ? BorderLine.fromPartial(object.bottom) : undefined;
    message.diagonal = object.diagonal !== undefined && object.diagonal !== null ? BorderLine.fromPartial(object.diagonal) : undefined;
    message.diagonalUp = object.diagonalUp ?? undefined;
    message.diagonalDown = object.diagonalDown ?? undefined;
    return message;
  }
};
function createBaseNumberFormat() {
  return { id: 0, formatCode: "" };
}
var NumberFormat = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== 0) {
      writer.uint32(8).int32(message.id);
    }
    if (message.formatCode !== "") {
      writer.uint32(18).string(message.formatCode);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseNumberFormat();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.id = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.formatCode = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return NumberFormat.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseNumberFormat();
    message.id = object.id ?? 0;
    message.formatCode = object.formatCode ?? "";
    return message;
  }
};
function createBaseCellFormat() {
  return {
    numFmtId: undefined,
    fontId: undefined,
    fillId: undefined,
    borderId: undefined,
    xfId: undefined,
    applyFill: undefined,
    applyFont: undefined,
    applyBorder: undefined,
    applyAlignment: undefined,
    horizontalAlignment: undefined,
    verticalAlignment: undefined,
    applyNumberFormat: undefined,
    applyProtection: undefined,
    wrapText: undefined,
    shrinkToFit: undefined,
    featurePropertyBagIndex: undefined
  };
}
var CellFormat = {
  encode(message, writer = new BinaryWriter) {
    if (message.numFmtId !== undefined) {
      writer.uint32(8).int32(message.numFmtId);
    }
    if (message.fontId !== undefined) {
      writer.uint32(16).int32(message.fontId);
    }
    if (message.fillId !== undefined) {
      writer.uint32(24).int32(message.fillId);
    }
    if (message.borderId !== undefined) {
      writer.uint32(32).int32(message.borderId);
    }
    if (message.xfId !== undefined) {
      writer.uint32(40).int32(message.xfId);
    }
    if (message.applyFill !== undefined) {
      writer.uint32(48).bool(message.applyFill);
    }
    if (message.applyFont !== undefined) {
      writer.uint32(56).bool(message.applyFont);
    }
    if (message.applyBorder !== undefined) {
      writer.uint32(64).bool(message.applyBorder);
    }
    if (message.applyAlignment !== undefined) {
      writer.uint32(72).bool(message.applyAlignment);
    }
    if (message.horizontalAlignment !== undefined) {
      writer.uint32(82).string(message.horizontalAlignment);
    }
    if (message.verticalAlignment !== undefined) {
      writer.uint32(90).string(message.verticalAlignment);
    }
    if (message.applyNumberFormat !== undefined) {
      writer.uint32(96).bool(message.applyNumberFormat);
    }
    if (message.applyProtection !== undefined) {
      writer.uint32(104).bool(message.applyProtection);
    }
    if (message.wrapText !== undefined) {
      writer.uint32(112).bool(message.wrapText);
    }
    if (message.shrinkToFit !== undefined) {
      writer.uint32(120).bool(message.shrinkToFit);
    }
    if (message.featurePropertyBagIndex !== undefined) {
      writer.uint32(128).uint32(message.featurePropertyBagIndex);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCellFormat();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.numFmtId = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.fontId = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.fillId = reader.int32();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.borderId = reader.int32();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.xfId = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.applyFill = reader.bool();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.applyFont = reader.bool();
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.applyBorder = reader.bool();
          continue;
        }
        case 9: {
          if (tag !== 72) {
            break;
          }
          message.applyAlignment = reader.bool();
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.horizontalAlignment = reader.string();
          continue;
        }
        case 11: {
          if (tag !== 90) {
            break;
          }
          message.verticalAlignment = reader.string();
          continue;
        }
        case 12: {
          if (tag !== 96) {
            break;
          }
          message.applyNumberFormat = reader.bool();
          continue;
        }
        case 13: {
          if (tag !== 104) {
            break;
          }
          message.applyProtection = reader.bool();
          continue;
        }
        case 14: {
          if (tag !== 112) {
            break;
          }
          message.wrapText = reader.bool();
          continue;
        }
        case 15: {
          if (tag !== 120) {
            break;
          }
          message.shrinkToFit = reader.bool();
          continue;
        }
        case 16: {
          if (tag !== 128) {
            break;
          }
          message.featurePropertyBagIndex = reader.uint32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CellFormat.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCellFormat();
    message.numFmtId = object.numFmtId ?? undefined;
    message.fontId = object.fontId ?? undefined;
    message.fillId = object.fillId ?? undefined;
    message.borderId = object.borderId ?? undefined;
    message.xfId = object.xfId ?? undefined;
    message.applyFill = object.applyFill ?? undefined;
    message.applyFont = object.applyFont ?? undefined;
    message.applyBorder = object.applyBorder ?? undefined;
    message.applyAlignment = object.applyAlignment ?? undefined;
    message.horizontalAlignment = object.horizontalAlignment ?? undefined;
    message.verticalAlignment = object.verticalAlignment ?? undefined;
    message.applyNumberFormat = object.applyNumberFormat ?? undefined;
    message.applyProtection = object.applyProtection ?? undefined;
    message.wrapText = object.wrapText ?? undefined;
    message.shrinkToFit = object.shrinkToFit ?? undefined;
    message.featurePropertyBagIndex = object.featurePropertyBagIndex ?? undefined;
    return message;
  }
};
function createBaseCellStyleFormat() {
  return { index: 0, format: undefined };
}
var CellStyleFormat = {
  encode(message, writer = new BinaryWriter) {
    if (message.index !== 0) {
      writer.uint32(8).int32(message.index);
    }
    if (message.format !== undefined) {
      CellFormat.encode(message.format, writer.uint32(18).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCellStyleFormat();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.index = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.format = CellFormat.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CellStyleFormat.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCellStyleFormat();
    message.index = object.index ?? 0;
    message.format = object.format !== undefined && object.format !== null ? CellFormat.fromPartial(object.format) : undefined;
    return message;
  }
};
function createBaseCellStyle() {
  return { index: 0, name: "", builtinId: "", xfId: undefined };
}
var CellStyle = {
  encode(message, writer = new BinaryWriter) {
    if (message.index !== 0) {
      writer.uint32(8).int32(message.index);
    }
    if (message.name !== "") {
      writer.uint32(18).string(message.name);
    }
    if (message.builtinId !== "") {
      writer.uint32(26).string(message.builtinId);
    }
    if (message.xfId !== undefined) {
      writer.uint32(32).int32(message.xfId);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCellStyle();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.index = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.builtinId = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.xfId = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CellStyle.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCellStyle();
    message.index = object.index ?? 0;
    message.name = object.name ?? "";
    message.builtinId = object.builtinId ?? "";
    message.xfId = object.xfId ?? undefined;
    return message;
  }
};
function createBaseStyles() {
  return {
    fonts: [],
    fills: [],
    cellXfs: [],
    borders: [],
    cellStyles: [],
    cellStyleXfs: [],
    numberFormats: [],
    dxfs: [],
    indexedColors: [],
    mruColors: []
  };
}
var Styles = {
  encode(message, writer = new BinaryWriter) {
    for (const v of message.fonts) {
      TextStyle.encode(v, writer.uint32(10).fork()).join();
    }
    for (const v of message.fills) {
      Fill.encode(v, writer.uint32(18).fork()).join();
    }
    for (const v of message.cellXfs) {
      CellFormat.encode(v, writer.uint32(26).fork()).join();
    }
    for (const v of message.borders) {
      Border.encode(v, writer.uint32(34).fork()).join();
    }
    for (const v of message.cellStyles) {
      CellStyle.encode(v, writer.uint32(42).fork()).join();
    }
    for (const v of message.cellStyleXfs) {
      CellStyleFormat.encode(v, writer.uint32(50).fork()).join();
    }
    for (const v of message.numberFormats) {
      NumberFormat.encode(v, writer.uint32(58).fork()).join();
    }
    for (const v of message.dxfs) {
      DifferentialFormat.encode(v, writer.uint32(66).fork()).join();
    }
    for (const v of message.indexedColors) {
      Color.encode(v, writer.uint32(74).fork()).join();
    }
    for (const v of message.mruColors) {
      Color.encode(v, writer.uint32(82).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseStyles();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.fonts.push(TextStyle.decode(reader, reader.uint32()));
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.fills.push(Fill.decode(reader, reader.uint32()));
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.cellXfs.push(CellFormat.decode(reader, reader.uint32()));
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.borders.push(Border.decode(reader, reader.uint32()));
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.cellStyles.push(CellStyle.decode(reader, reader.uint32()));
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.cellStyleXfs.push(CellStyleFormat.decode(reader, reader.uint32()));
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.numberFormats.push(NumberFormat.decode(reader, reader.uint32()));
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.dxfs.push(DifferentialFormat.decode(reader, reader.uint32()));
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.indexedColors.push(Color.decode(reader, reader.uint32()));
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.mruColors.push(Color.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Styles.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseStyles();
    message.fonts = object.fonts?.map((e) => TextStyle.fromPartial(e)) || [];
    message.fills = object.fills?.map((e) => Fill.fromPartial(e)) || [];
    message.cellXfs = object.cellXfs?.map((e) => CellFormat.fromPartial(e)) || [];
    message.borders = object.borders?.map((e) => Border.fromPartial(e)) || [];
    message.cellStyles = object.cellStyles?.map((e) => CellStyle.fromPartial(e)) || [];
    message.cellStyleXfs = object.cellStyleXfs?.map((e) => CellStyleFormat.fromPartial(e)) || [];
    message.numberFormats = object.numberFormats?.map((e) => NumberFormat.fromPartial(e)) || [];
    message.dxfs = object.dxfs?.map((e) => DifferentialFormat.fromPartial(e)) || [];
    message.indexedColors = object.indexedColors?.map((e) => Color.fromPartial(e)) || [];
    message.mruColors = object.mruColors?.map((e) => Color.fromPartial(e)) || [];
    return message;
  }
};
function createBaseDifferentialFormat() {
  return { font: undefined, fill: undefined, border: undefined, numberFormat: undefined };
}
var DifferentialFormat = {
  encode(message, writer = new BinaryWriter) {
    if (message.font !== undefined) {
      TextStyle.encode(message.font, writer.uint32(10).fork()).join();
    }
    if (message.fill !== undefined) {
      Fill.encode(message.fill, writer.uint32(18).fork()).join();
    }
    if (message.border !== undefined) {
      Border.encode(message.border, writer.uint32(26).fork()).join();
    }
    if (message.numberFormat !== undefined) {
      NumberFormat.encode(message.numberFormat, writer.uint32(34).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseDifferentialFormat();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.font = TextStyle.decode(reader, reader.uint32());
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.fill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.border = Border.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.numberFormat = NumberFormat.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return DifferentialFormat.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseDifferentialFormat();
    message.font = object.font !== undefined && object.font !== null ? TextStyle.fromPartial(object.font) : undefined;
    message.fill = object.fill !== undefined && object.fill !== null ? Fill.fromPartial(object.fill) : undefined;
    message.border = object.border !== undefined && object.border !== null ? Border.fromPartial(object.border) : undefined;
    message.numberFormat = object.numberFormat !== undefined && object.numberFormat !== null ? NumberFormat.fromPartial(object.numberFormat) : undefined;
    return message;
  }
};
function createBaseTextBody2() {
  return { plainText: "" };
}
var TextBody2 = {
  encode(message, writer = new BinaryWriter) {
    if (message.plainText !== "") {
      writer.uint32(10).string(message.plainText);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTextBody2();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.plainText = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TextBody2.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTextBody2();
    message.plainText = object.plainText ?? "";
    return message;
  }
};
function createBaseCellTarget() {
  return { sheetName: "", sheetId: undefined, address: "" };
}
var CellTarget = {
  encode(message, writer = new BinaryWriter) {
    if (message.sheetName !== "") {
      writer.uint32(10).string(message.sheetName);
    }
    if (message.sheetId !== undefined) {
      writer.uint32(18).string(message.sheetId);
    }
    if (message.address !== "") {
      writer.uint32(26).string(message.address);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCellTarget();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.sheetName = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.sheetId = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.address = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CellTarget.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCellTarget();
    message.sheetName = object.sheetName ?? "";
    message.sheetId = object.sheetId ?? undefined;
    message.address = object.address ?? "";
    return message;
  }
};
function createBaseRangeTarget() {
  return { sheetName: "", sheetId: undefined, startAddress: "", endAddress: "" };
}
var RangeTarget = {
  encode(message, writer = new BinaryWriter) {
    if (message.sheetName !== "") {
      writer.uint32(10).string(message.sheetName);
    }
    if (message.sheetId !== undefined) {
      writer.uint32(18).string(message.sheetId);
    }
    if (message.startAddress !== "") {
      writer.uint32(26).string(message.startAddress);
    }
    if (message.endAddress !== "") {
      writer.uint32(34).string(message.endAddress);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseRangeTarget();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.sheetName = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.sheetId = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.startAddress = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.endAddress = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return RangeTarget.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseRangeTarget();
    message.sheetName = object.sheetName ?? "";
    message.sheetId = object.sheetId ?? undefined;
    message.startAddress = object.startAddress ?? "";
    message.endAddress = object.endAddress ?? "";
    return message;
  }
};
function createBaseAnnotationTarget2() {
  return { cell: undefined, range: undefined };
}
var AnnotationTarget2 = {
  encode(message, writer = new BinaryWriter) {
    if (message.cell !== undefined) {
      CellTarget.encode(message.cell, writer.uint32(10).fork()).join();
    }
    if (message.range !== undefined) {
      RangeTarget.encode(message.range, writer.uint32(18).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseAnnotationTarget2();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.cell = CellTarget.decode(reader, reader.uint32());
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.range = RangeTarget.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return AnnotationTarget2.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseAnnotationTarget2();
    message.cell = object.cell !== undefined && object.cell !== null ? CellTarget.fromPartial(object.cell) : undefined;
    message.range = object.range !== undefined && object.range !== null ? RangeTarget.fromPartial(object.range) : undefined;
    return message;
  }
};
function createBaseNote() {
  return { id: "", target: undefined, authorId: "", createdAt: "", body: undefined };
}
var Note = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== "") {
      writer.uint32(10).string(message.id);
    }
    if (message.target !== undefined) {
      AnnotationTarget2.encode(message.target, writer.uint32(18).fork()).join();
    }
    if (message.authorId !== "") {
      writer.uint32(26).string(message.authorId);
    }
    if (message.createdAt !== "") {
      writer.uint32(34).string(message.createdAt);
    }
    if (message.body !== undefined) {
      TextBody2.encode(message.body, writer.uint32(42).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseNote();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.id = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.target = AnnotationTarget2.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.authorId = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.createdAt = reader.string();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.body = TextBody2.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Note.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseNote();
    message.id = object.id ?? "";
    message.target = object.target !== undefined && object.target !== null ? AnnotationTarget2.fromPartial(object.target) : undefined;
    message.authorId = object.authorId ?? "";
    message.createdAt = object.createdAt ?? "";
    message.body = object.body !== undefined && object.body !== null ? TextBody2.fromPartial(object.body) : undefined;
    return message;
  }
};
function createBaseCfvo() {
  return { type: "", val: undefined, gte: undefined };
}
var Cfvo = {
  encode(message, writer = new BinaryWriter) {
    if (message.type !== "") {
      writer.uint32(10).string(message.type);
    }
    if (message.val !== undefined) {
      writer.uint32(18).string(message.val);
    }
    if (message.gte !== undefined) {
      writer.uint32(24).bool(message.gte);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCfvo();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.type = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.val = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.gte = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Cfvo.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCfvo();
    message.type = object.type ?? "";
    message.val = object.val ?? undefined;
    message.gte = object.gte ?? undefined;
    return message;
  }
};
function createBaseColorScale2() {
  return { cfvos: [], colors: [] };
}
var ColorScale2 = {
  encode(message, writer = new BinaryWriter) {
    for (const v of message.cfvos) {
      Cfvo.encode(v, writer.uint32(10).fork()).join();
    }
    for (const v of message.colors) {
      Color.encode(v, writer.uint32(18).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseColorScale2();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.cfvos.push(Cfvo.decode(reader, reader.uint32()));
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.colors.push(Color.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ColorScale2.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseColorScale2();
    message.cfvos = object.cfvos?.map((e) => Cfvo.fromPartial(e)) || [];
    message.colors = object.colors?.map((e) => Color.fromPartial(e)) || [];
    return message;
  }
};
function createBaseDataBar() {
  return {
    cfvos: [],
    color: undefined,
    gradient: undefined,
    minLength: undefined,
    maxLength: undefined,
    showValue: undefined,
    border: undefined,
    negativeBarColorSameAsPositive: undefined,
    negativeBarBorderColorSameAsPositive: undefined,
    direction: undefined,
    axisPosition: undefined,
    borderColor: undefined,
    negativeFillColor: undefined,
    negativeBorderColor: undefined,
    axisColor: undefined
  };
}
var DataBar = {
  encode(message, writer = new BinaryWriter) {
    for (const v of message.cfvos) {
      Cfvo.encode(v, writer.uint32(10).fork()).join();
    }
    if (message.color !== undefined) {
      Color.encode(message.color, writer.uint32(18).fork()).join();
    }
    if (message.gradient !== undefined) {
      writer.uint32(24).bool(message.gradient);
    }
    if (message.minLength !== undefined) {
      writer.uint32(32).uint32(message.minLength);
    }
    if (message.maxLength !== undefined) {
      writer.uint32(40).uint32(message.maxLength);
    }
    if (message.showValue !== undefined) {
      writer.uint32(48).bool(message.showValue);
    }
    if (message.border !== undefined) {
      writer.uint32(56).bool(message.border);
    }
    if (message.negativeBarColorSameAsPositive !== undefined) {
      writer.uint32(64).bool(message.negativeBarColorSameAsPositive);
    }
    if (message.negativeBarBorderColorSameAsPositive !== undefined) {
      writer.uint32(72).bool(message.negativeBarBorderColorSameAsPositive);
    }
    if (message.direction !== undefined) {
      writer.uint32(82).string(message.direction);
    }
    if (message.axisPosition !== undefined) {
      writer.uint32(90).string(message.axisPosition);
    }
    if (message.borderColor !== undefined) {
      Color.encode(message.borderColor, writer.uint32(98).fork()).join();
    }
    if (message.negativeFillColor !== undefined) {
      Color.encode(message.negativeFillColor, writer.uint32(106).fork()).join();
    }
    if (message.negativeBorderColor !== undefined) {
      Color.encode(message.negativeBorderColor, writer.uint32(114).fork()).join();
    }
    if (message.axisColor !== undefined) {
      Color.encode(message.axisColor, writer.uint32(122).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseDataBar();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.cfvos.push(Cfvo.decode(reader, reader.uint32()));
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.color = Color.decode(reader, reader.uint32());
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.gradient = reader.bool();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.minLength = reader.uint32();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.maxLength = reader.uint32();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.showValue = reader.bool();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.border = reader.bool();
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.negativeBarColorSameAsPositive = reader.bool();
          continue;
        }
        case 9: {
          if (tag !== 72) {
            break;
          }
          message.negativeBarBorderColorSameAsPositive = reader.bool();
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.direction = reader.string();
          continue;
        }
        case 11: {
          if (tag !== 90) {
            break;
          }
          message.axisPosition = reader.string();
          continue;
        }
        case 12: {
          if (tag !== 98) {
            break;
          }
          message.borderColor = Color.decode(reader, reader.uint32());
          continue;
        }
        case 13: {
          if (tag !== 106) {
            break;
          }
          message.negativeFillColor = Color.decode(reader, reader.uint32());
          continue;
        }
        case 14: {
          if (tag !== 114) {
            break;
          }
          message.negativeBorderColor = Color.decode(reader, reader.uint32());
          continue;
        }
        case 15: {
          if (tag !== 122) {
            break;
          }
          message.axisColor = Color.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return DataBar.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseDataBar();
    message.cfvos = object.cfvos?.map((e) => Cfvo.fromPartial(e)) || [];
    message.color = object.color !== undefined && object.color !== null ? Color.fromPartial(object.color) : undefined;
    message.gradient = object.gradient ?? undefined;
    message.minLength = object.minLength ?? undefined;
    message.maxLength = object.maxLength ?? undefined;
    message.showValue = object.showValue ?? undefined;
    message.border = object.border ?? undefined;
    message.negativeBarColorSameAsPositive = object.negativeBarColorSameAsPositive ?? undefined;
    message.negativeBarBorderColorSameAsPositive = object.negativeBarBorderColorSameAsPositive ?? undefined;
    message.direction = object.direction ?? undefined;
    message.axisPosition = object.axisPosition ?? undefined;
    message.borderColor = object.borderColor !== undefined && object.borderColor !== null ? Color.fromPartial(object.borderColor) : undefined;
    message.negativeFillColor = object.negativeFillColor !== undefined && object.negativeFillColor !== null ? Color.fromPartial(object.negativeFillColor) : undefined;
    message.negativeBorderColor = object.negativeBorderColor !== undefined && object.negativeBorderColor !== null ? Color.fromPartial(object.negativeBorderColor) : undefined;
    message.axisColor = object.axisColor !== undefined && object.axisColor !== null ? Color.fromPartial(object.axisColor) : undefined;
    return message;
  }
};
function createBaseIconSet() {
  return { iconSet: "", showValue: undefined, reverse: undefined, custom: undefined, cfvos: [], percent: undefined };
}
var IconSet = {
  encode(message, writer = new BinaryWriter) {
    if (message.iconSet !== "") {
      writer.uint32(10).string(message.iconSet);
    }
    if (message.showValue !== undefined) {
      writer.uint32(16).bool(message.showValue);
    }
    if (message.reverse !== undefined) {
      writer.uint32(24).bool(message.reverse);
    }
    if (message.custom !== undefined) {
      writer.uint32(32).bool(message.custom);
    }
    for (const v of message.cfvos) {
      Cfvo.encode(v, writer.uint32(42).fork()).join();
    }
    if (message.percent !== undefined) {
      writer.uint32(48).bool(message.percent);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseIconSet();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.iconSet = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.showValue = reader.bool();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.reverse = reader.bool();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.custom = reader.bool();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.cfvos.push(Cfvo.decode(reader, reader.uint32()));
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.percent = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return IconSet.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseIconSet();
    message.iconSet = object.iconSet ?? "";
    message.showValue = object.showValue ?? undefined;
    message.reverse = object.reverse ?? undefined;
    message.custom = object.custom ?? undefined;
    message.cfvos = object.cfvos?.map((e) => Cfvo.fromPartial(e)) || [];
    message.percent = object.percent ?? undefined;
    return message;
  }
};
function createBaseCfRule() {
  return {
    type: "",
    priority: undefined,
    dxfId: undefined,
    operator: undefined,
    formula: [],
    colorScale: undefined,
    dataBar: undefined,
    iconSet: undefined,
    stopIfTrue: undefined,
    aboveAverage: undefined,
    percent: undefined,
    bottom: undefined,
    text: undefined,
    timePeriod: undefined,
    rank: undefined,
    stdDev: undefined,
    equalAverage: undefined,
    id: undefined
  };
}
var CfRule = {
  encode(message, writer = new BinaryWriter) {
    if (message.type !== "") {
      writer.uint32(10).string(message.type);
    }
    if (message.priority !== undefined) {
      writer.uint32(16).int32(message.priority);
    }
    if (message.dxfId !== undefined) {
      writer.uint32(24).int32(message.dxfId);
    }
    if (message.operator !== undefined) {
      writer.uint32(34).string(message.operator);
    }
    for (const v of message.formula) {
      writer.uint32(42).string(v);
    }
    if (message.colorScale !== undefined) {
      ColorScale2.encode(message.colorScale, writer.uint32(82).fork()).join();
    }
    if (message.dataBar !== undefined) {
      DataBar.encode(message.dataBar, writer.uint32(90).fork()).join();
    }
    if (message.iconSet !== undefined) {
      IconSet.encode(message.iconSet, writer.uint32(98).fork()).join();
    }
    if (message.stopIfTrue !== undefined) {
      writer.uint32(48).bool(message.stopIfTrue);
    }
    if (message.aboveAverage !== undefined) {
      writer.uint32(56).bool(message.aboveAverage);
    }
    if (message.percent !== undefined) {
      writer.uint32(64).bool(message.percent);
    }
    if (message.bottom !== undefined) {
      writer.uint32(72).bool(message.bottom);
    }
    if (message.text !== undefined) {
      writer.uint32(106).string(message.text);
    }
    if (message.timePeriod !== undefined) {
      writer.uint32(114).string(message.timePeriod);
    }
    if (message.rank !== undefined) {
      writer.uint32(120).int32(message.rank);
    }
    if (message.stdDev !== undefined) {
      writer.uint32(128).int32(message.stdDev);
    }
    if (message.equalAverage !== undefined) {
      writer.uint32(136).bool(message.equalAverage);
    }
    if (message.id !== undefined) {
      writer.uint32(146).string(message.id);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCfRule();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.type = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.priority = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.dxfId = reader.int32();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.operator = reader.string();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.formula.push(reader.string());
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.colorScale = ColorScale2.decode(reader, reader.uint32());
          continue;
        }
        case 11: {
          if (tag !== 90) {
            break;
          }
          message.dataBar = DataBar.decode(reader, reader.uint32());
          continue;
        }
        case 12: {
          if (tag !== 98) {
            break;
          }
          message.iconSet = IconSet.decode(reader, reader.uint32());
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.stopIfTrue = reader.bool();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.aboveAverage = reader.bool();
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.percent = reader.bool();
          continue;
        }
        case 9: {
          if (tag !== 72) {
            break;
          }
          message.bottom = reader.bool();
          continue;
        }
        case 13: {
          if (tag !== 106) {
            break;
          }
          message.text = reader.string();
          continue;
        }
        case 14: {
          if (tag !== 114) {
            break;
          }
          message.timePeriod = reader.string();
          continue;
        }
        case 15: {
          if (tag !== 120) {
            break;
          }
          message.rank = reader.int32();
          continue;
        }
        case 16: {
          if (tag !== 128) {
            break;
          }
          message.stdDev = reader.int32();
          continue;
        }
        case 17: {
          if (tag !== 136) {
            break;
          }
          message.equalAverage = reader.bool();
          continue;
        }
        case 18: {
          if (tag !== 146) {
            break;
          }
          message.id = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CfRule.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCfRule();
    message.type = object.type ?? "";
    message.priority = object.priority ?? undefined;
    message.dxfId = object.dxfId ?? undefined;
    message.operator = object.operator ?? undefined;
    message.formula = object.formula?.map((e) => e) || [];
    message.colorScale = object.colorScale !== undefined && object.colorScale !== null ? ColorScale2.fromPartial(object.colorScale) : undefined;
    message.dataBar = object.dataBar !== undefined && object.dataBar !== null ? DataBar.fromPartial(object.dataBar) : undefined;
    message.iconSet = object.iconSet !== undefined && object.iconSet !== null ? IconSet.fromPartial(object.iconSet) : undefined;
    message.stopIfTrue = object.stopIfTrue ?? undefined;
    message.aboveAverage = object.aboveAverage ?? undefined;
    message.percent = object.percent ?? undefined;
    message.bottom = object.bottom ?? undefined;
    message.text = object.text ?? undefined;
    message.timePeriod = object.timePeriod ?? undefined;
    message.rank = object.rank ?? undefined;
    message.stdDev = object.stdDev ?? undefined;
    message.equalAverage = object.equalAverage ?? undefined;
    message.id = object.id ?? undefined;
    return message;
  }
};
function createBaseConditionalFormatting() {
  return { ranges: [], rules: [] };
}
var ConditionalFormatting = {
  encode(message, writer = new BinaryWriter) {
    for (const v of message.ranges) {
      RangeTarget.encode(v, writer.uint32(10).fork()).join();
    }
    for (const v of message.rules) {
      CfRule.encode(v, writer.uint32(18).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseConditionalFormatting();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.ranges.push(RangeTarget.decode(reader, reader.uint32()));
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.rules.push(CfRule.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return ConditionalFormatting.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseConditionalFormatting();
    message.ranges = object.ranges?.map((e) => RangeTarget.fromPartial(e)) || [];
    message.rules = object.rules?.map((e) => CfRule.fromPartial(e)) || [];
    return message;
  }
};
function createBaseTableColumn() {
  return { id: 0, name: "", totalsRowLabel: undefined, totalsRowFunction: undefined, dataDxfId: undefined };
}
var TableColumn = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== 0) {
      writer.uint32(8).int32(message.id);
    }
    if (message.name !== "") {
      writer.uint32(18).string(message.name);
    }
    if (message.totalsRowLabel !== undefined) {
      writer.uint32(26).string(message.totalsRowLabel);
    }
    if (message.totalsRowFunction !== undefined) {
      writer.uint32(34).string(message.totalsRowFunction);
    }
    if (message.dataDxfId !== undefined) {
      writer.uint32(40).int32(message.dataDxfId);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTableColumn();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.id = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.totalsRowLabel = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.totalsRowFunction = reader.string();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.dataDxfId = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TableColumn.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTableColumn();
    message.id = object.id ?? 0;
    message.name = object.name ?? "";
    message.totalsRowLabel = object.totalsRowLabel ?? undefined;
    message.totalsRowFunction = object.totalsRowFunction ?? undefined;
    message.dataDxfId = object.dataDxfId ?? undefined;
    return message;
  }
};
function createBaseTableStyleInfo() {
  return {
    name: "",
    showFirstColumn: undefined,
    showLastColumn: undefined,
    showRowStripes: undefined,
    showColumnStripes: undefined
  };
}
var TableStyleInfo = {
  encode(message, writer = new BinaryWriter) {
    if (message.name !== "") {
      writer.uint32(10).string(message.name);
    }
    if (message.showFirstColumn !== undefined) {
      writer.uint32(16).bool(message.showFirstColumn);
    }
    if (message.showLastColumn !== undefined) {
      writer.uint32(24).bool(message.showLastColumn);
    }
    if (message.showRowStripes !== undefined) {
      writer.uint32(32).bool(message.showRowStripes);
    }
    if (message.showColumnStripes !== undefined) {
      writer.uint32(40).bool(message.showColumnStripes);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTableStyleInfo();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.showFirstColumn = reader.bool();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.showLastColumn = reader.bool();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.showRowStripes = reader.bool();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.showColumnStripes = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TableStyleInfo.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTableStyleInfo();
    message.name = object.name ?? "";
    message.showFirstColumn = object.showFirstColumn ?? undefined;
    message.showLastColumn = object.showLastColumn ?? undefined;
    message.showRowStripes = object.showRowStripes ?? undefined;
    message.showColumnStripes = object.showColumnStripes ?? undefined;
    return message;
  }
};
function createBaseFilterValues() {
  return { values: [], blank: undefined };
}
var FilterValues = {
  encode(message, writer = new BinaryWriter) {
    for (const v of message.values) {
      writer.uint32(10).string(v);
    }
    if (message.blank !== undefined) {
      writer.uint32(16).bool(message.blank);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseFilterValues();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.values.push(reader.string());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.blank = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return FilterValues.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseFilterValues();
    message.values = object.values?.map((e) => e) || [];
    message.blank = object.blank ?? undefined;
    return message;
  }
};
function createBaseFilterColumn() {
  return { colId: 0, type: "", filters: undefined };
}
var FilterColumn = {
  encode(message, writer = new BinaryWriter) {
    if (message.colId !== 0) {
      writer.uint32(8).int32(message.colId);
    }
    if (message.type !== "") {
      writer.uint32(18).string(message.type);
    }
    if (message.filters !== undefined) {
      FilterValues.encode(message.filters, writer.uint32(26).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseFilterColumn();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.colId = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.type = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.filters = FilterValues.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return FilterColumn.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseFilterColumn();
    message.colId = object.colId ?? 0;
    message.type = object.type ?? "";
    message.filters = object.filters !== undefined && object.filters !== null ? FilterValues.fromPartial(object.filters) : undefined;
    return message;
  }
};
function createBaseAutoFilter() {
  return { ref: "", columns: [] };
}
var AutoFilter = {
  encode(message, writer = new BinaryWriter) {
    if (message.ref !== "") {
      writer.uint32(10).string(message.ref);
    }
    for (const v of message.columns) {
      FilterColumn.encode(v, writer.uint32(18).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseAutoFilter();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.ref = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.columns.push(FilterColumn.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return AutoFilter.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseAutoFilter();
    message.ref = object.ref ?? "";
    message.columns = object.columns?.map((e) => FilterColumn.fromPartial(e)) || [];
    return message;
  }
};
function createBaseTable() {
  return {
    id: 0,
    name: "",
    displayName: "",
    ref: "",
    columns: [],
    style: undefined,
    totalsRowShown: undefined,
    headerRowCount: undefined,
    totalsRowCount: undefined,
    autoFilter: undefined,
    dataDxfId: undefined,
    headerRowCellStyle: undefined
  };
}
var Table = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== 0) {
      writer.uint32(8).int32(message.id);
    }
    if (message.name !== "") {
      writer.uint32(18).string(message.name);
    }
    if (message.displayName !== "") {
      writer.uint32(26).string(message.displayName);
    }
    if (message.ref !== "") {
      writer.uint32(34).string(message.ref);
    }
    for (const v of message.columns) {
      TableColumn.encode(v, writer.uint32(42).fork()).join();
    }
    if (message.style !== undefined) {
      TableStyleInfo.encode(message.style, writer.uint32(50).fork()).join();
    }
    if (message.totalsRowShown !== undefined) {
      writer.uint32(56).bool(message.totalsRowShown);
    }
    if (message.headerRowCount !== undefined) {
      writer.uint32(64).int32(message.headerRowCount);
    }
    if (message.totalsRowCount !== undefined) {
      writer.uint32(72).int32(message.totalsRowCount);
    }
    if (message.autoFilter !== undefined) {
      AutoFilter.encode(message.autoFilter, writer.uint32(82).fork()).join();
    }
    if (message.dataDxfId !== undefined) {
      writer.uint32(88).int32(message.dataDxfId);
    }
    if (message.headerRowCellStyle !== undefined) {
      writer.uint32(98).string(message.headerRowCellStyle);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTable();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.id = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.displayName = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.ref = reader.string();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.columns.push(TableColumn.decode(reader, reader.uint32()));
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.style = TableStyleInfo.decode(reader, reader.uint32());
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.totalsRowShown = reader.bool();
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.headerRowCount = reader.int32();
          continue;
        }
        case 9: {
          if (tag !== 72) {
            break;
          }
          message.totalsRowCount = reader.int32();
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.autoFilter = AutoFilter.decode(reader, reader.uint32());
          continue;
        }
        case 11: {
          if (tag !== 88) {
            break;
          }
          message.dataDxfId = reader.int32();
          continue;
        }
        case 12: {
          if (tag !== 98) {
            break;
          }
          message.headerRowCellStyle = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Table.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTable();
    message.id = object.id ?? 0;
    message.name = object.name ?? "";
    message.displayName = object.displayName ?? "";
    message.ref = object.ref ?? "";
    message.columns = object.columns?.map((e) => TableColumn.fromPartial(e)) || [];
    message.style = object.style !== undefined && object.style !== null ? TableStyleInfo.fromPartial(object.style) : undefined;
    message.totalsRowShown = object.totalsRowShown ?? undefined;
    message.headerRowCount = object.headerRowCount ?? undefined;
    message.totalsRowCount = object.totalsRowCount ?? undefined;
    message.autoFilter = object.autoFilter !== undefined && object.autoFilter !== null ? AutoFilter.fromPartial(object.autoFilter) : undefined;
    message.dataDxfId = object.dataDxfId ?? undefined;
    message.headerRowCellStyle = object.headerRowCellStyle ?? undefined;
    return message;
  }
};
function createBaseTimeline() {
  return {
    name: "",
    caption: "",
    cache: "",
    fromAnchor: undefined,
    toAnchor: undefined,
    cacheId: undefined,
    width: undefined,
    height: undefined,
    fill: undefined,
    line: undefined
  };
}
var Timeline = {
  encode(message, writer = new BinaryWriter) {
    if (message.name !== "") {
      writer.uint32(10).string(message.name);
    }
    if (message.caption !== "") {
      writer.uint32(18).string(message.caption);
    }
    if (message.cache !== "") {
      writer.uint32(26).string(message.cache);
    }
    if (message.fromAnchor !== undefined) {
      AnchorMarker.encode(message.fromAnchor, writer.uint32(34).fork()).join();
    }
    if (message.toAnchor !== undefined) {
      AnchorMarker.encode(message.toAnchor, writer.uint32(42).fork()).join();
    }
    if (message.cacheId !== undefined) {
      writer.uint32(48).int32(message.cacheId);
    }
    if (message.width !== undefined) {
      writer.uint32(57).double(message.width);
    }
    if (message.height !== undefined) {
      writer.uint32(65).double(message.height);
    }
    if (message.fill !== undefined) {
      Fill.encode(message.fill, writer.uint32(74).fork()).join();
    }
    if (message.line !== undefined) {
      Line.encode(message.line, writer.uint32(82).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTimeline();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.caption = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.cache = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.fromAnchor = AnchorMarker.decode(reader, reader.uint32());
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.toAnchor = AnchorMarker.decode(reader, reader.uint32());
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.cacheId = reader.int32();
          continue;
        }
        case 7: {
          if (tag !== 57) {
            break;
          }
          message.width = reader.double();
          continue;
        }
        case 8: {
          if (tag !== 65) {
            break;
          }
          message.height = reader.double();
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.fill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.line = Line.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Timeline.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTimeline();
    message.name = object.name ?? "";
    message.caption = object.caption ?? "";
    message.cache = object.cache ?? "";
    message.fromAnchor = object.fromAnchor !== undefined && object.fromAnchor !== null ? AnchorMarker.fromPartial(object.fromAnchor) : undefined;
    message.toAnchor = object.toAnchor !== undefined && object.toAnchor !== null ? AnchorMarker.fromPartial(object.toAnchor) : undefined;
    message.cacheId = object.cacheId ?? undefined;
    message.width = object.width ?? undefined;
    message.height = object.height ?? undefined;
    message.fill = object.fill !== undefined && object.fill !== null ? Fill.fromPartial(object.fill) : undefined;
    message.line = object.line !== undefined && object.line !== null ? Line.fromPartial(object.line) : undefined;
    return message;
  }
};
function createBaseTimelineCacheItem() {
  return { index: undefined, value: "", selected: undefined };
}
var TimelineCacheItem = {
  encode(message, writer = new BinaryWriter) {
    if (message.index !== undefined) {
      writer.uint32(8).int32(message.index);
    }
    if (message.value !== "") {
      writer.uint32(18).string(message.value);
    }
    if (message.selected !== undefined) {
      writer.uint32(24).bool(message.selected);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTimelineCacheItem();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.index = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.value = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.selected = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TimelineCacheItem.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTimelineCacheItem();
    message.index = object.index ?? undefined;
    message.value = object.value ?? "";
    message.selected = object.selected ?? undefined;
    return message;
  }
};
function createBaseTimelineCache() {
  return { name: "", caption: undefined, pivotCacheId: undefined, pivotTableIds: [], columnName: undefined, items: [] };
}
var TimelineCache = {
  encode(message, writer = new BinaryWriter) {
    if (message.name !== "") {
      writer.uint32(10).string(message.name);
    }
    if (message.caption !== undefined) {
      writer.uint32(18).string(message.caption);
    }
    if (message.pivotCacheId !== undefined) {
      writer.uint32(24).int32(message.pivotCacheId);
    }
    writer.uint32(34).fork();
    for (const v of message.pivotTableIds) {
      writer.int32(v);
    }
    writer.join();
    if (message.columnName !== undefined) {
      writer.uint32(42).string(message.columnName);
    }
    for (const v of message.items) {
      TimelineCacheItem.encode(v, writer.uint32(50).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseTimelineCache();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.caption = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.pivotCacheId = reader.int32();
          continue;
        }
        case 4: {
          if (tag === 32) {
            message.pivotTableIds.push(reader.int32());
            continue;
          }
          if (tag === 34) {
            const end2 = reader.uint32() + reader.pos;
            while (reader.pos < end2) {
              message.pivotTableIds.push(reader.int32());
            }
            continue;
          }
          break;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.columnName = reader.string();
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.items.push(TimelineCacheItem.decode(reader, reader.uint32()));
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return TimelineCache.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseTimelineCache();
    message.name = object.name ?? "";
    message.caption = object.caption ?? undefined;
    message.pivotCacheId = object.pivotCacheId ?? undefined;
    message.pivotTableIds = object.pivotTableIds?.map((e) => e) || [];
    message.columnName = object.columnName ?? undefined;
    message.items = object.items?.map((e) => TimelineCacheItem.fromPartial(e)) || [];
    return message;
  }
};
function createBasePivotTableLocation() {
  return {
    reference: "",
    firstHeaderRow: undefined,
    firstDataRow: undefined,
    firstHeaderColumn: undefined,
    firstDataColumn: undefined,
    rowPageCount: undefined,
    columnPageCount: undefined
  };
}
var PivotTableLocation = {
  encode(message, writer = new BinaryWriter) {
    if (message.reference !== "") {
      writer.uint32(10).string(message.reference);
    }
    if (message.firstHeaderRow !== undefined) {
      writer.uint32(16).int32(message.firstHeaderRow);
    }
    if (message.firstDataRow !== undefined) {
      writer.uint32(24).int32(message.firstDataRow);
    }
    if (message.firstHeaderColumn !== undefined) {
      writer.uint32(32).int32(message.firstHeaderColumn);
    }
    if (message.firstDataColumn !== undefined) {
      writer.uint32(40).int32(message.firstDataColumn);
    }
    if (message.rowPageCount !== undefined) {
      writer.uint32(48).int32(message.rowPageCount);
    }
    if (message.columnPageCount !== undefined) {
      writer.uint32(56).int32(message.columnPageCount);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePivotTableLocation();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.reference = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.firstHeaderRow = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.firstDataRow = reader.int32();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.firstHeaderColumn = reader.int32();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.firstDataColumn = reader.int32();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.rowPageCount = reader.int32();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.columnPageCount = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PivotTableLocation.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePivotTableLocation();
    message.reference = object.reference ?? "";
    message.firstHeaderRow = object.firstHeaderRow ?? undefined;
    message.firstDataRow = object.firstDataRow ?? undefined;
    message.firstHeaderColumn = object.firstHeaderColumn ?? undefined;
    message.firstDataColumn = object.firstDataColumn ?? undefined;
    message.rowPageCount = object.rowPageCount ?? undefined;
    message.columnPageCount = object.columnPageCount ?? undefined;
    return message;
  }
};
function createBasePivotFieldItem() {
  return {
    type: undefined,
    index: undefined,
    hidden: undefined,
    calculated: undefined,
    missing: undefined,
    repeatedItemCount: undefined,
    dataFieldIndex: undefined
  };
}
var PivotFieldItem = {
  encode(message, writer = new BinaryWriter) {
    if (message.type !== undefined) {
      writer.uint32(10).string(message.type);
    }
    if (message.index !== undefined) {
      writer.uint32(16).int32(message.index);
    }
    if (message.hidden !== undefined) {
      writer.uint32(24).bool(message.hidden);
    }
    if (message.calculated !== undefined) {
      writer.uint32(32).bool(message.calculated);
    }
    if (message.missing !== undefined) {
      writer.uint32(40).bool(message.missing);
    }
    if (message.repeatedItemCount !== undefined) {
      writer.uint32(48).int32(message.repeatedItemCount);
    }
    if (message.dataFieldIndex !== undefined) {
      writer.uint32(56).int32(message.dataFieldIndex);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePivotFieldItem();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.type = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.index = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.hidden = reader.bool();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.calculated = reader.bool();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.missing = reader.bool();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.repeatedItemCount = reader.int32();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.dataFieldIndex = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PivotFieldItem.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePivotFieldItem();
    message.type = object.type ?? undefined;
    message.index = object.index ?? undefined;
    message.hidden = object.hidden ?? undefined;
    message.calculated = object.calculated ?? undefined;
    message.missing = object.missing ?? undefined;
    message.repeatedItemCount = object.repeatedItemCount ?? undefined;
    message.dataFieldIndex = object.dataFieldIndex ?? undefined;
    return message;
  }
};
function createBasePivotField() {
  return {
    index: 0,
    name: "",
    axis: undefined,
    dataField: undefined,
    showAll: undefined,
    subtotalTop: undefined,
    items: [],
    numberFormatId: undefined,
    sortType: undefined,
    multipleItemSelectionAllowed: undefined,
    axisEnum: undefined,
    sortTypeEnum: undefined
  };
}
var PivotField = {
  encode(message, writer = new BinaryWriter) {
    if (message.index !== 0) {
      writer.uint32(8).int32(message.index);
    }
    if (message.name !== "") {
      writer.uint32(18).string(message.name);
    }
    if (message.axis !== undefined) {
      writer.uint32(26).string(message.axis);
    }
    if (message.dataField !== undefined) {
      writer.uint32(32).bool(message.dataField);
    }
    if (message.showAll !== undefined) {
      writer.uint32(40).bool(message.showAll);
    }
    if (message.subtotalTop !== undefined) {
      writer.uint32(48).bool(message.subtotalTop);
    }
    for (const v of message.items) {
      PivotFieldItem.encode(v, writer.uint32(58).fork()).join();
    }
    if (message.numberFormatId !== undefined) {
      writer.uint32(64).uint32(message.numberFormatId);
    }
    if (message.sortType !== undefined) {
      writer.uint32(74).string(message.sortType);
    }
    if (message.multipleItemSelectionAllowed !== undefined) {
      writer.uint32(80).bool(message.multipleItemSelectionAllowed);
    }
    if (message.axisEnum !== undefined) {
      writer.uint32(240).int32(message.axisEnum);
    }
    if (message.sortTypeEnum !== undefined) {
      writer.uint32(248).int32(message.sortTypeEnum);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePivotField();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.index = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.axis = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.dataField = reader.bool();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.showAll = reader.bool();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.subtotalTop = reader.bool();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.items.push(PivotFieldItem.decode(reader, reader.uint32()));
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.numberFormatId = reader.uint32();
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.sortType = reader.string();
          continue;
        }
        case 10: {
          if (tag !== 80) {
            break;
          }
          message.multipleItemSelectionAllowed = reader.bool();
          continue;
        }
        case 30: {
          if (tag !== 240) {
            break;
          }
          message.axisEnum = reader.int32();
          continue;
        }
        case 31: {
          if (tag !== 248) {
            break;
          }
          message.sortTypeEnum = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PivotField.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePivotField();
    message.index = object.index ?? 0;
    message.name = object.name ?? "";
    message.axis = object.axis ?? undefined;
    message.dataField = object.dataField ?? undefined;
    message.showAll = object.showAll ?? undefined;
    message.subtotalTop = object.subtotalTop ?? undefined;
    message.items = object.items?.map((e) => PivotFieldItem.fromPartial(e)) || [];
    message.numberFormatId = object.numberFormatId ?? undefined;
    message.sortType = object.sortType ?? undefined;
    message.multipleItemSelectionAllowed = object.multipleItemSelectionAllowed ?? undefined;
    message.axisEnum = object.axisEnum ?? undefined;
    message.sortTypeEnum = object.sortTypeEnum ?? undefined;
    return message;
  }
};
function createBasePivotPageField() {
  return { field: 0, item: undefined, name: undefined, hierarchy: undefined };
}
var PivotPageField = {
  encode(message, writer = new BinaryWriter) {
    if (message.field !== 0) {
      writer.uint32(8).int32(message.field);
    }
    if (message.item !== undefined) {
      writer.uint32(16).int32(message.item);
    }
    if (message.name !== undefined) {
      writer.uint32(26).string(message.name);
    }
    if (message.hierarchy !== undefined) {
      writer.uint32(32).int32(message.hierarchy);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePivotPageField();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.field = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.item = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.hierarchy = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PivotPageField.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePivotPageField();
    message.field = object.field ?? 0;
    message.item = object.item ?? undefined;
    message.name = object.name ?? undefined;
    message.hierarchy = object.hierarchy ?? undefined;
    return message;
  }
};
function createBasePivotDataField() {
  return {
    field: 0,
    name: undefined,
    subtotal: undefined,
    numberFormatId: undefined,
    showAs: undefined,
    baseField: undefined,
    baseItem: undefined,
    subtotalEnum: undefined
  };
}
var PivotDataField = {
  encode(message, writer = new BinaryWriter) {
    if (message.field !== 0) {
      writer.uint32(8).int32(message.field);
    }
    if (message.name !== undefined) {
      writer.uint32(18).string(message.name);
    }
    if (message.subtotal !== undefined) {
      writer.uint32(26).string(message.subtotal);
    }
    if (message.numberFormatId !== undefined) {
      writer.uint32(32).uint32(message.numberFormatId);
    }
    if (message.showAs !== undefined) {
      writer.uint32(42).string(message.showAs);
    }
    if (message.baseField !== undefined) {
      writer.uint32(48).int32(message.baseField);
    }
    if (message.baseItem !== undefined) {
      writer.uint32(56).int32(message.baseItem);
    }
    if (message.subtotalEnum !== undefined) {
      writer.uint32(240).int32(message.subtotalEnum);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePivotDataField();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.field = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.subtotal = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.numberFormatId = reader.uint32();
          continue;
        }
        case 5: {
          if (tag !== 42) {
            break;
          }
          message.showAs = reader.string();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.baseField = reader.int32();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.baseItem = reader.int32();
          continue;
        }
        case 30: {
          if (tag !== 240) {
            break;
          }
          message.subtotalEnum = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PivotDataField.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePivotDataField();
    message.field = object.field ?? 0;
    message.name = object.name ?? undefined;
    message.subtotal = object.subtotal ?? undefined;
    message.numberFormatId = object.numberFormatId ?? undefined;
    message.showAs = object.showAs ?? undefined;
    message.baseField = object.baseField ?? undefined;
    message.baseItem = object.baseItem ?? undefined;
    message.subtotalEnum = object.subtotalEnum ?? undefined;
    return message;
  }
};
function createBasePivotFilter() {
  return { field: 0, type: "", name: undefined, description: undefined, typeEnum: undefined };
}
var PivotFilter = {
  encode(message, writer = new BinaryWriter) {
    if (message.field !== 0) {
      writer.uint32(8).int32(message.field);
    }
    if (message.type !== "") {
      writer.uint32(18).string(message.type);
    }
    if (message.name !== undefined) {
      writer.uint32(26).string(message.name);
    }
    if (message.description !== undefined) {
      writer.uint32(34).string(message.description);
    }
    if (message.typeEnum !== undefined) {
      writer.uint32(240).int32(message.typeEnum);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePivotFilter();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.field = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.type = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.description = reader.string();
          continue;
        }
        case 30: {
          if (tag !== 240) {
            break;
          }
          message.typeEnum = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PivotFilter.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePivotFilter();
    message.field = object.field ?? 0;
    message.type = object.type ?? "";
    message.name = object.name ?? undefined;
    message.description = object.description ?? undefined;
    message.typeEnum = object.typeEnum ?? undefined;
    return message;
  }
};
function createBasePivotTable() {
  return {
    name: "",
    cacheId: 0,
    location: undefined,
    dataOnRows: undefined,
    rowGrandTotals: undefined,
    columnGrandTotals: undefined,
    pivotFields: [],
    rowFields: [],
    columnFields: [],
    pageFields: [],
    dataFields: [],
    filters: [],
    compact: undefined,
    outline: undefined,
    showDrill: undefined,
    styleName: undefined,
    rowItems: [],
    columnItems: [],
    showRowHeaders: undefined,
    showColHeaders: undefined,
    showRowStripes: undefined,
    showColStripes: undefined,
    showLastColumn: undefined,
    applyNumberFormats: undefined,
    applyBorderFormats: undefined,
    applyFontFormats: undefined,
    applyPatternFormats: undefined,
    applyAlignmentFormats: undefined,
    applyWidthHeightFormats: undefined,
    dataCaption: undefined,
    updatedVersion: undefined,
    minRefreshableVersion: undefined,
    useAutoFormatting: undefined,
    itemPrintTitles: undefined,
    createdVersion: undefined,
    indent: undefined,
    outlineData: undefined,
    multipleFieldFilters: undefined,
    chartFormat: undefined,
    extensionListXml: undefined
  };
}
var PivotTable = {
  encode(message, writer = new BinaryWriter) {
    if (message.name !== "") {
      writer.uint32(10).string(message.name);
    }
    if (message.cacheId !== 0) {
      writer.uint32(16).int32(message.cacheId);
    }
    if (message.location !== undefined) {
      PivotTableLocation.encode(message.location, writer.uint32(26).fork()).join();
    }
    if (message.dataOnRows !== undefined) {
      writer.uint32(32).bool(message.dataOnRows);
    }
    if (message.rowGrandTotals !== undefined) {
      writer.uint32(40).bool(message.rowGrandTotals);
    }
    if (message.columnGrandTotals !== undefined) {
      writer.uint32(48).bool(message.columnGrandTotals);
    }
    for (const v of message.pivotFields) {
      PivotField.encode(v, writer.uint32(58).fork()).join();
    }
    writer.uint32(66).fork();
    for (const v of message.rowFields) {
      writer.int32(v);
    }
    writer.join();
    writer.uint32(74).fork();
    for (const v of message.columnFields) {
      writer.int32(v);
    }
    writer.join();
    for (const v of message.pageFields) {
      PivotPageField.encode(v, writer.uint32(82).fork()).join();
    }
    for (const v of message.dataFields) {
      PivotDataField.encode(v, writer.uint32(90).fork()).join();
    }
    for (const v of message.filters) {
      PivotFilter.encode(v, writer.uint32(98).fork()).join();
    }
    if (message.compact !== undefined) {
      writer.uint32(104).bool(message.compact);
    }
    if (message.outline !== undefined) {
      writer.uint32(112).bool(message.outline);
    }
    if (message.showDrill !== undefined) {
      writer.uint32(120).bool(message.showDrill);
    }
    if (message.styleName !== undefined) {
      writer.uint32(130).string(message.styleName);
    }
    for (const v of message.rowItems) {
      PivotFieldItem.encode(v, writer.uint32(138).fork()).join();
    }
    for (const v of message.columnItems) {
      PivotFieldItem.encode(v, writer.uint32(146).fork()).join();
    }
    if (message.showRowHeaders !== undefined) {
      writer.uint32(152).bool(message.showRowHeaders);
    }
    if (message.showColHeaders !== undefined) {
      writer.uint32(160).bool(message.showColHeaders);
    }
    if (message.showRowStripes !== undefined) {
      writer.uint32(168).bool(message.showRowStripes);
    }
    if (message.showColStripes !== undefined) {
      writer.uint32(176).bool(message.showColStripes);
    }
    if (message.showLastColumn !== undefined) {
      writer.uint32(184).bool(message.showLastColumn);
    }
    if (message.applyNumberFormats !== undefined) {
      writer.uint32(192).bool(message.applyNumberFormats);
    }
    if (message.applyBorderFormats !== undefined) {
      writer.uint32(200).bool(message.applyBorderFormats);
    }
    if (message.applyFontFormats !== undefined) {
      writer.uint32(208).bool(message.applyFontFormats);
    }
    if (message.applyPatternFormats !== undefined) {
      writer.uint32(216).bool(message.applyPatternFormats);
    }
    if (message.applyAlignmentFormats !== undefined) {
      writer.uint32(224).bool(message.applyAlignmentFormats);
    }
    if (message.applyWidthHeightFormats !== undefined) {
      writer.uint32(232).bool(message.applyWidthHeightFormats);
    }
    if (message.dataCaption !== undefined) {
      writer.uint32(242).string(message.dataCaption);
    }
    if (message.updatedVersion !== undefined) {
      writer.uint32(248).uint32(message.updatedVersion);
    }
    if (message.minRefreshableVersion !== undefined) {
      writer.uint32(256).uint32(message.minRefreshableVersion);
    }
    if (message.useAutoFormatting !== undefined) {
      writer.uint32(264).bool(message.useAutoFormatting);
    }
    if (message.itemPrintTitles !== undefined) {
      writer.uint32(272).bool(message.itemPrintTitles);
    }
    if (message.createdVersion !== undefined) {
      writer.uint32(280).uint32(message.createdVersion);
    }
    if (message.indent !== undefined) {
      writer.uint32(289).double(message.indent);
    }
    if (message.outlineData !== undefined) {
      writer.uint32(296).bool(message.outlineData);
    }
    if (message.multipleFieldFilters !== undefined) {
      writer.uint32(304).bool(message.multipleFieldFilters);
    }
    if (message.chartFormat !== undefined) {
      writer.uint32(312).uint32(message.chartFormat);
    }
    if (message.extensionListXml !== undefined) {
      writer.uint32(322).string(message.extensionListXml);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePivotTable();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.cacheId = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.location = PivotTableLocation.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.dataOnRows = reader.bool();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.rowGrandTotals = reader.bool();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.columnGrandTotals = reader.bool();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.pivotFields.push(PivotField.decode(reader, reader.uint32()));
          continue;
        }
        case 8: {
          if (tag === 64) {
            message.rowFields.push(reader.int32());
            continue;
          }
          if (tag === 66) {
            const end2 = reader.uint32() + reader.pos;
            while (reader.pos < end2) {
              message.rowFields.push(reader.int32());
            }
            continue;
          }
          break;
        }
        case 9: {
          if (tag === 72) {
            message.columnFields.push(reader.int32());
            continue;
          }
          if (tag === 74) {
            const end2 = reader.uint32() + reader.pos;
            while (reader.pos < end2) {
              message.columnFields.push(reader.int32());
            }
            continue;
          }
          break;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.pageFields.push(PivotPageField.decode(reader, reader.uint32()));
          continue;
        }
        case 11: {
          if (tag !== 90) {
            break;
          }
          message.dataFields.push(PivotDataField.decode(reader, reader.uint32()));
          continue;
        }
        case 12: {
          if (tag !== 98) {
            break;
          }
          message.filters.push(PivotFilter.decode(reader, reader.uint32()));
          continue;
        }
        case 13: {
          if (tag !== 104) {
            break;
          }
          message.compact = reader.bool();
          continue;
        }
        case 14: {
          if (tag !== 112) {
            break;
          }
          message.outline = reader.bool();
          continue;
        }
        case 15: {
          if (tag !== 120) {
            break;
          }
          message.showDrill = reader.bool();
          continue;
        }
        case 16: {
          if (tag !== 130) {
            break;
          }
          message.styleName = reader.string();
          continue;
        }
        case 17: {
          if (tag !== 138) {
            break;
          }
          message.rowItems.push(PivotFieldItem.decode(reader, reader.uint32()));
          continue;
        }
        case 18: {
          if (tag !== 146) {
            break;
          }
          message.columnItems.push(PivotFieldItem.decode(reader, reader.uint32()));
          continue;
        }
        case 19: {
          if (tag !== 152) {
            break;
          }
          message.showRowHeaders = reader.bool();
          continue;
        }
        case 20: {
          if (tag !== 160) {
            break;
          }
          message.showColHeaders = reader.bool();
          continue;
        }
        case 21: {
          if (tag !== 168) {
            break;
          }
          message.showRowStripes = reader.bool();
          continue;
        }
        case 22: {
          if (tag !== 176) {
            break;
          }
          message.showColStripes = reader.bool();
          continue;
        }
        case 23: {
          if (tag !== 184) {
            break;
          }
          message.showLastColumn = reader.bool();
          continue;
        }
        case 24: {
          if (tag !== 192) {
            break;
          }
          message.applyNumberFormats = reader.bool();
          continue;
        }
        case 25: {
          if (tag !== 200) {
            break;
          }
          message.applyBorderFormats = reader.bool();
          continue;
        }
        case 26: {
          if (tag !== 208) {
            break;
          }
          message.applyFontFormats = reader.bool();
          continue;
        }
        case 27: {
          if (tag !== 216) {
            break;
          }
          message.applyPatternFormats = reader.bool();
          continue;
        }
        case 28: {
          if (tag !== 224) {
            break;
          }
          message.applyAlignmentFormats = reader.bool();
          continue;
        }
        case 29: {
          if (tag !== 232) {
            break;
          }
          message.applyWidthHeightFormats = reader.bool();
          continue;
        }
        case 30: {
          if (tag !== 242) {
            break;
          }
          message.dataCaption = reader.string();
          continue;
        }
        case 31: {
          if (tag !== 248) {
            break;
          }
          message.updatedVersion = reader.uint32();
          continue;
        }
        case 32: {
          if (tag !== 256) {
            break;
          }
          message.minRefreshableVersion = reader.uint32();
          continue;
        }
        case 33: {
          if (tag !== 264) {
            break;
          }
          message.useAutoFormatting = reader.bool();
          continue;
        }
        case 34: {
          if (tag !== 272) {
            break;
          }
          message.itemPrintTitles = reader.bool();
          continue;
        }
        case 35: {
          if (tag !== 280) {
            break;
          }
          message.createdVersion = reader.uint32();
          continue;
        }
        case 36: {
          if (tag !== 289) {
            break;
          }
          message.indent = reader.double();
          continue;
        }
        case 37: {
          if (tag !== 296) {
            break;
          }
          message.outlineData = reader.bool();
          continue;
        }
        case 38: {
          if (tag !== 304) {
            break;
          }
          message.multipleFieldFilters = reader.bool();
          continue;
        }
        case 39: {
          if (tag !== 312) {
            break;
          }
          message.chartFormat = reader.uint32();
          continue;
        }
        case 40: {
          if (tag !== 322) {
            break;
          }
          message.extensionListXml = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PivotTable.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePivotTable();
    message.name = object.name ?? "";
    message.cacheId = object.cacheId ?? 0;
    message.location = object.location !== undefined && object.location !== null ? PivotTableLocation.fromPartial(object.location) : undefined;
    message.dataOnRows = object.dataOnRows ?? undefined;
    message.rowGrandTotals = object.rowGrandTotals ?? undefined;
    message.columnGrandTotals = object.columnGrandTotals ?? undefined;
    message.pivotFields = object.pivotFields?.map((e) => PivotField.fromPartial(e)) || [];
    message.rowFields = object.rowFields?.map((e) => e) || [];
    message.columnFields = object.columnFields?.map((e) => e) || [];
    message.pageFields = object.pageFields?.map((e) => PivotPageField.fromPartial(e)) || [];
    message.dataFields = object.dataFields?.map((e) => PivotDataField.fromPartial(e)) || [];
    message.filters = object.filters?.map((e) => PivotFilter.fromPartial(e)) || [];
    message.compact = object.compact ?? undefined;
    message.outline = object.outline ?? undefined;
    message.showDrill = object.showDrill ?? undefined;
    message.styleName = object.styleName ?? undefined;
    message.rowItems = object.rowItems?.map((e) => PivotFieldItem.fromPartial(e)) || [];
    message.columnItems = object.columnItems?.map((e) => PivotFieldItem.fromPartial(e)) || [];
    message.showRowHeaders = object.showRowHeaders ?? undefined;
    message.showColHeaders = object.showColHeaders ?? undefined;
    message.showRowStripes = object.showRowStripes ?? undefined;
    message.showColStripes = object.showColStripes ?? undefined;
    message.showLastColumn = object.showLastColumn ?? undefined;
    message.applyNumberFormats = object.applyNumberFormats ?? undefined;
    message.applyBorderFormats = object.applyBorderFormats ?? undefined;
    message.applyFontFormats = object.applyFontFormats ?? undefined;
    message.applyPatternFormats = object.applyPatternFormats ?? undefined;
    message.applyAlignmentFormats = object.applyAlignmentFormats ?? undefined;
    message.applyWidthHeightFormats = object.applyWidthHeightFormats ?? undefined;
    message.dataCaption = object.dataCaption ?? undefined;
    message.updatedVersion = object.updatedVersion ?? undefined;
    message.minRefreshableVersion = object.minRefreshableVersion ?? undefined;
    message.useAutoFormatting = object.useAutoFormatting ?? undefined;
    message.itemPrintTitles = object.itemPrintTitles ?? undefined;
    message.createdVersion = object.createdVersion ?? undefined;
    message.indent = object.indent ?? undefined;
    message.outlineData = object.outlineData ?? undefined;
    message.multipleFieldFilters = object.multipleFieldFilters ?? undefined;
    message.chartFormat = object.chartFormat ?? undefined;
    message.extensionListXml = object.extensionListXml ?? undefined;
    return message;
  }
};
function createBaseSlicer() {
  return {
    name: "",
    caption: "",
    cache: "",
    lockedPosition: undefined,
    displayHeader: undefined,
    showNoDataItems: undefined,
    sortBy: undefined,
    style: undefined,
    fromAnchor: undefined,
    toAnchor: undefined,
    cacheId: undefined,
    width: undefined,
    height: undefined,
    isMultiSelect: undefined,
    fill: undefined,
    line: undefined,
    headerTextStyle: undefined,
    sortByEnum: undefined
  };
}
var Slicer = {
  encode(message, writer = new BinaryWriter) {
    if (message.name !== "") {
      writer.uint32(10).string(message.name);
    }
    if (message.caption !== "") {
      writer.uint32(18).string(message.caption);
    }
    if (message.cache !== "") {
      writer.uint32(26).string(message.cache);
    }
    if (message.lockedPosition !== undefined) {
      writer.uint32(32).bool(message.lockedPosition);
    }
    if (message.displayHeader !== undefined) {
      writer.uint32(40).bool(message.displayHeader);
    }
    if (message.showNoDataItems !== undefined) {
      writer.uint32(48).bool(message.showNoDataItems);
    }
    if (message.sortBy !== undefined) {
      writer.uint32(58).string(message.sortBy);
    }
    if (message.style !== undefined) {
      writer.uint32(66).string(message.style);
    }
    if (message.fromAnchor !== undefined) {
      AnchorMarker.encode(message.fromAnchor, writer.uint32(74).fork()).join();
    }
    if (message.toAnchor !== undefined) {
      AnchorMarker.encode(message.toAnchor, writer.uint32(82).fork()).join();
    }
    if (message.cacheId !== undefined) {
      writer.uint32(88).int32(message.cacheId);
    }
    if (message.width !== undefined) {
      writer.uint32(97).double(message.width);
    }
    if (message.height !== undefined) {
      writer.uint32(105).double(message.height);
    }
    if (message.isMultiSelect !== undefined) {
      writer.uint32(112).bool(message.isMultiSelect);
    }
    if (message.fill !== undefined) {
      Fill.encode(message.fill, writer.uint32(122).fork()).join();
    }
    if (message.line !== undefined) {
      Line.encode(message.line, writer.uint32(130).fork()).join();
    }
    if (message.headerTextStyle !== undefined) {
      TextStyle.encode(message.headerTextStyle, writer.uint32(138).fork()).join();
    }
    if (message.sortByEnum !== undefined) {
      writer.uint32(144).int32(message.sortByEnum);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseSlicer();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.caption = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.cache = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.lockedPosition = reader.bool();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.displayHeader = reader.bool();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.showNoDataItems = reader.bool();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.sortBy = reader.string();
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.style = reader.string();
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.fromAnchor = AnchorMarker.decode(reader, reader.uint32());
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.toAnchor = AnchorMarker.decode(reader, reader.uint32());
          continue;
        }
        case 11: {
          if (tag !== 88) {
            break;
          }
          message.cacheId = reader.int32();
          continue;
        }
        case 12: {
          if (tag !== 97) {
            break;
          }
          message.width = reader.double();
          continue;
        }
        case 13: {
          if (tag !== 105) {
            break;
          }
          message.height = reader.double();
          continue;
        }
        case 14: {
          if (tag !== 112) {
            break;
          }
          message.isMultiSelect = reader.bool();
          continue;
        }
        case 15: {
          if (tag !== 122) {
            break;
          }
          message.fill = Fill.decode(reader, reader.uint32());
          continue;
        }
        case 16: {
          if (tag !== 130) {
            break;
          }
          message.line = Line.decode(reader, reader.uint32());
          continue;
        }
        case 17: {
          if (tag !== 138) {
            break;
          }
          message.headerTextStyle = TextStyle.decode(reader, reader.uint32());
          continue;
        }
        case 18: {
          if (tag !== 144) {
            break;
          }
          message.sortByEnum = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return Slicer.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseSlicer();
    message.name = object.name ?? "";
    message.caption = object.caption ?? "";
    message.cache = object.cache ?? "";
    message.lockedPosition = object.lockedPosition ?? undefined;
    message.displayHeader = object.displayHeader ?? undefined;
    message.showNoDataItems = object.showNoDataItems ?? undefined;
    message.sortBy = object.sortBy ?? undefined;
    message.style = object.style ?? undefined;
    message.fromAnchor = object.fromAnchor !== undefined && object.fromAnchor !== null ? AnchorMarker.fromPartial(object.fromAnchor) : undefined;
    message.toAnchor = object.toAnchor !== undefined && object.toAnchor !== null ? AnchorMarker.fromPartial(object.toAnchor) : undefined;
    message.cacheId = object.cacheId ?? undefined;
    message.width = object.width ?? undefined;
    message.height = object.height ?? undefined;
    message.isMultiSelect = object.isMultiSelect ?? undefined;
    message.fill = object.fill !== undefined && object.fill !== null ? Fill.fromPartial(object.fill) : undefined;
    message.line = object.line !== undefined && object.line !== null ? Line.fromPartial(object.line) : undefined;
    message.headerTextStyle = object.headerTextStyle !== undefined && object.headerTextStyle !== null ? TextStyle.fromPartial(object.headerTextStyle) : undefined;
    message.sortByEnum = object.sortByEnum ?? undefined;
    return message;
  }
};
function createBaseSlicerCacheItem() {
  return { index: undefined, value: "", selected: undefined, hasData: undefined, hidden: undefined };
}
var SlicerCacheItem = {
  encode(message, writer = new BinaryWriter) {
    if (message.index !== undefined) {
      writer.uint32(8).int32(message.index);
    }
    if (message.value !== "") {
      writer.uint32(18).string(message.value);
    }
    if (message.selected !== undefined) {
      writer.uint32(24).bool(message.selected);
    }
    if (message.hasData !== undefined) {
      writer.uint32(32).bool(message.hasData);
    }
    if (message.hidden !== undefined) {
      writer.uint32(40).bool(message.hidden);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseSlicerCacheItem();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.index = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.value = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.selected = reader.bool();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.hasData = reader.bool();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.hidden = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return SlicerCacheItem.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseSlicerCacheItem();
    message.index = object.index ?? undefined;
    message.value = object.value ?? "";
    message.selected = object.selected ?? undefined;
    message.hasData = object.hasData ?? undefined;
    message.hidden = object.hidden ?? undefined;
    return message;
  }
};
function createBaseSlicerCache() {
  return {
    name: "",
    caption: undefined,
    sourceName: undefined,
    type: undefined,
    pivotCacheId: undefined,
    pivotTableIds: [],
    tableId: undefined,
    tableName: undefined,
    columnName: undefined,
    crossFilter: undefined,
    sortOrder: undefined,
    items: [],
    typeEnum: undefined,
    crossFilterEnum: undefined
  };
}
var SlicerCache = {
  encode(message, writer = new BinaryWriter) {
    if (message.name !== "") {
      writer.uint32(10).string(message.name);
    }
    if (message.caption !== undefined) {
      writer.uint32(18).string(message.caption);
    }
    if (message.sourceName !== undefined) {
      writer.uint32(26).string(message.sourceName);
    }
    if (message.type !== undefined) {
      writer.uint32(34).string(message.type);
    }
    if (message.pivotCacheId !== undefined) {
      writer.uint32(40).int32(message.pivotCacheId);
    }
    writer.uint32(50).fork();
    for (const v of message.pivotTableIds) {
      writer.int32(v);
    }
    writer.join();
    if (message.tableId !== undefined) {
      writer.uint32(56).int32(message.tableId);
    }
    if (message.tableName !== undefined) {
      writer.uint32(66).string(message.tableName);
    }
    if (message.columnName !== undefined) {
      writer.uint32(74).string(message.columnName);
    }
    if (message.crossFilter !== undefined) {
      writer.uint32(82).string(message.crossFilter);
    }
    if (message.sortOrder !== undefined) {
      writer.uint32(90).string(message.sortOrder);
    }
    for (const v of message.items) {
      SlicerCacheItem.encode(v, writer.uint32(98).fork()).join();
    }
    if (message.typeEnum !== undefined) {
      writer.uint32(104).int32(message.typeEnum);
    }
    if (message.crossFilterEnum !== undefined) {
      writer.uint32(112).int32(message.crossFilterEnum);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseSlicerCache();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.caption = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.sourceName = reader.string();
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.type = reader.string();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.pivotCacheId = reader.int32();
          continue;
        }
        case 6: {
          if (tag === 48) {
            message.pivotTableIds.push(reader.int32());
            continue;
          }
          if (tag === 50) {
            const end2 = reader.uint32() + reader.pos;
            while (reader.pos < end2) {
              message.pivotTableIds.push(reader.int32());
            }
            continue;
          }
          break;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.tableId = reader.int32();
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.tableName = reader.string();
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.columnName = reader.string();
          continue;
        }
        case 10: {
          if (tag !== 82) {
            break;
          }
          message.crossFilter = reader.string();
          continue;
        }
        case 11: {
          if (tag !== 90) {
            break;
          }
          message.sortOrder = reader.string();
          continue;
        }
        case 12: {
          if (tag !== 98) {
            break;
          }
          message.items.push(SlicerCacheItem.decode(reader, reader.uint32()));
          continue;
        }
        case 13: {
          if (tag !== 104) {
            break;
          }
          message.typeEnum = reader.int32();
          continue;
        }
        case 14: {
          if (tag !== 112) {
            break;
          }
          message.crossFilterEnum = reader.int32();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return SlicerCache.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseSlicerCache();
    message.name = object.name ?? "";
    message.caption = object.caption ?? undefined;
    message.sourceName = object.sourceName ?? undefined;
    message.type = object.type ?? undefined;
    message.pivotCacheId = object.pivotCacheId ?? undefined;
    message.pivotTableIds = object.pivotTableIds?.map((e) => e) || [];
    message.tableId = object.tableId ?? undefined;
    message.tableName = object.tableName ?? undefined;
    message.columnName = object.columnName ?? undefined;
    message.crossFilter = object.crossFilter ?? undefined;
    message.sortOrder = object.sortOrder ?? undefined;
    message.items = object.items?.map((e) => SlicerCacheItem.fromPartial(e)) || [];
    message.typeEnum = object.typeEnum ?? undefined;
    message.crossFilterEnum = object.crossFilterEnum ?? undefined;
    return message;
  }
};
function createBasePivotCache() {
  return {
    id: 0,
    name: undefined,
    fields: [],
    worksheetSourceReference: undefined,
    worksheetSourceSheet: undefined,
    refreshedBy: undefined,
    refreshedDate: undefined,
    createdVersion: undefined,
    refreshedVersion: undefined,
    minRefreshableVersion: undefined,
    recordCount: undefined,
    extensionListXml: undefined
  };
}
var PivotCache = {
  encode(message, writer = new BinaryWriter) {
    if (message.id !== 0) {
      writer.uint32(8).int32(message.id);
    }
    if (message.name !== undefined) {
      writer.uint32(18).string(message.name);
    }
    for (const v of message.fields) {
      CacheField.encode(v, writer.uint32(26).fork()).join();
    }
    if (message.worksheetSourceReference !== undefined) {
      writer.uint32(50).string(message.worksheetSourceReference);
    }
    if (message.worksheetSourceSheet !== undefined) {
      writer.uint32(58).string(message.worksheetSourceSheet);
    }
    if (message.refreshedBy !== undefined) {
      writer.uint32(66).string(message.refreshedBy);
    }
    if (message.refreshedDate !== undefined) {
      writer.uint32(74).string(message.refreshedDate);
    }
    if (message.createdVersion !== undefined) {
      writer.uint32(80).uint32(message.createdVersion);
    }
    if (message.refreshedVersion !== undefined) {
      writer.uint32(88).uint32(message.refreshedVersion);
    }
    if (message.minRefreshableVersion !== undefined) {
      writer.uint32(96).uint32(message.minRefreshableVersion);
    }
    if (message.recordCount !== undefined) {
      writer.uint32(104).uint32(message.recordCount);
    }
    if (message.extensionListXml !== undefined) {
      writer.uint32(114).string(message.extensionListXml);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBasePivotCache();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.id = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.fields.push(CacheField.decode(reader, reader.uint32()));
          continue;
        }
        case 6: {
          if (tag !== 50) {
            break;
          }
          message.worksheetSourceReference = reader.string();
          continue;
        }
        case 7: {
          if (tag !== 58) {
            break;
          }
          message.worksheetSourceSheet = reader.string();
          continue;
        }
        case 8: {
          if (tag !== 66) {
            break;
          }
          message.refreshedBy = reader.string();
          continue;
        }
        case 9: {
          if (tag !== 74) {
            break;
          }
          message.refreshedDate = reader.string();
          continue;
        }
        case 10: {
          if (tag !== 80) {
            break;
          }
          message.createdVersion = reader.uint32();
          continue;
        }
        case 11: {
          if (tag !== 88) {
            break;
          }
          message.refreshedVersion = reader.uint32();
          continue;
        }
        case 12: {
          if (tag !== 96) {
            break;
          }
          message.minRefreshableVersion = reader.uint32();
          continue;
        }
        case 13: {
          if (tag !== 104) {
            break;
          }
          message.recordCount = reader.uint32();
          continue;
        }
        case 14: {
          if (tag !== 114) {
            break;
          }
          message.extensionListXml = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return PivotCache.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBasePivotCache();
    message.id = object.id ?? 0;
    message.name = object.name ?? undefined;
    message.fields = object.fields?.map((e) => CacheField.fromPartial(e)) || [];
    message.worksheetSourceReference = object.worksheetSourceReference ?? undefined;
    message.worksheetSourceSheet = object.worksheetSourceSheet ?? undefined;
    message.refreshedBy = object.refreshedBy ?? undefined;
    message.refreshedDate = object.refreshedDate ?? undefined;
    message.createdVersion = object.createdVersion ?? undefined;
    message.refreshedVersion = object.refreshedVersion ?? undefined;
    message.minRefreshableVersion = object.minRefreshableVersion ?? undefined;
    message.recordCount = object.recordCount ?? undefined;
    message.extensionListXml = object.extensionListXml ?? undefined;
    return message;
  }
};
function createBaseFieldGroup() {
  return { parent: undefined, base: undefined, rangePr: undefined, groupItems: [] };
}
var FieldGroup = {
  encode(message, writer = new BinaryWriter) {
    if (message.parent !== undefined) {
      writer.uint32(8).int32(message.parent);
    }
    if (message.base !== undefined) {
      writer.uint32(16).int32(message.base);
    }
    if (message.rangePr !== undefined) {
      RangePr.encode(message.rangePr, writer.uint32(26).fork()).join();
    }
    for (const v of message.groupItems) {
      writer.uint32(34).string(v);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseFieldGroup();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 8) {
            break;
          }
          message.parent = reader.int32();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.base = reader.int32();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.rangePr = RangePr.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.groupItems.push(reader.string());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return FieldGroup.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseFieldGroup();
    message.parent = object.parent ?? undefined;
    message.base = object.base ?? undefined;
    message.rangePr = object.rangePr !== undefined && object.rangePr !== null ? RangePr.fromPartial(object.rangePr) : undefined;
    message.groupItems = object.groupItems?.map((e) => e) || [];
    return message;
  }
};
function createBaseRangePr() {
  return { groupBy: "", startDate: "", endDate: "" };
}
var RangePr = {
  encode(message, writer = new BinaryWriter) {
    if (message.groupBy !== "") {
      writer.uint32(10).string(message.groupBy);
    }
    if (message.startDate !== "") {
      writer.uint32(18).string(message.startDate);
    }
    if (message.endDate !== "") {
      writer.uint32(26).string(message.endDate);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseRangePr();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.groupBy = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 18) {
            break;
          }
          message.startDate = reader.string();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.endDate = reader.string();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return RangePr.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseRangePr();
    message.groupBy = object.groupBy ?? "";
    message.startDate = object.startDate ?? "";
    message.endDate = object.endDate ?? "";
    return message;
  }
};
function createBaseCacheField() {
  return { name: "", numFmtId: undefined, sharedItems: undefined, fieldGroup: undefined };
}
var CacheField = {
  encode(message, writer = new BinaryWriter) {
    if (message.name !== "") {
      writer.uint32(10).string(message.name);
    }
    if (message.numFmtId !== undefined) {
      writer.uint32(16).uint32(message.numFmtId);
    }
    if (message.sharedItems !== undefined) {
      SharedItems.encode(message.sharedItems, writer.uint32(26).fork()).join();
    }
    if (message.fieldGroup !== undefined) {
      FieldGroup.encode(message.fieldGroup, writer.uint32(34).fork()).join();
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseCacheField();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.name = reader.string();
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.numFmtId = reader.uint32();
          continue;
        }
        case 3: {
          if (tag !== 26) {
            break;
          }
          message.sharedItems = SharedItems.decode(reader, reader.uint32());
          continue;
        }
        case 4: {
          if (tag !== 34) {
            break;
          }
          message.fieldGroup = FieldGroup.decode(reader, reader.uint32());
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return CacheField.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseCacheField();
    message.name = object.name ?? "";
    message.numFmtId = object.numFmtId ?? undefined;
    message.sharedItems = object.sharedItems !== undefined && object.sharedItems !== null ? SharedItems.fromPartial(object.sharedItems) : undefined;
    message.fieldGroup = object.fieldGroup !== undefined && object.fieldGroup !== null ? FieldGroup.fromPartial(object.fieldGroup) : undefined;
    return message;
  }
};
function createBaseSharedItems() {
  return {
    values: [],
    containsBlank: undefined,
    containsDate: undefined,
    containsNumeric: undefined,
    containsString: undefined,
    containsSemiMixedTypes: undefined,
    containsNonDate: undefined,
    containsInteger: undefined,
    minValue: undefined,
    maxValue: undefined,
    minDate: undefined,
    maxDate: undefined,
    count: undefined,
    containsMixedTypes: undefined
  };
}
var SharedItems = {
  encode(message, writer = new BinaryWriter) {
    for (const v of message.values) {
      writer.uint32(10).string(v);
    }
    if (message.containsBlank !== undefined) {
      writer.uint32(16).bool(message.containsBlank);
    }
    if (message.containsDate !== undefined) {
      writer.uint32(24).bool(message.containsDate);
    }
    if (message.containsNumeric !== undefined) {
      writer.uint32(32).bool(message.containsNumeric);
    }
    if (message.containsString !== undefined) {
      writer.uint32(40).bool(message.containsString);
    }
    if (message.containsSemiMixedTypes !== undefined) {
      writer.uint32(48).bool(message.containsSemiMixedTypes);
    }
    if (message.containsNonDate !== undefined) {
      writer.uint32(56).bool(message.containsNonDate);
    }
    if (message.containsInteger !== undefined) {
      writer.uint32(64).bool(message.containsInteger);
    }
    if (message.minValue !== undefined) {
      writer.uint32(73).double(message.minValue);
    }
    if (message.maxValue !== undefined) {
      writer.uint32(81).double(message.maxValue);
    }
    if (message.minDate !== undefined) {
      writer.uint32(90).string(message.minDate);
    }
    if (message.maxDate !== undefined) {
      writer.uint32(98).string(message.maxDate);
    }
    if (message.count !== undefined) {
      writer.uint32(104).uint32(message.count);
    }
    if (message.containsMixedTypes !== undefined) {
      writer.uint32(112).bool(message.containsMixedTypes);
    }
    return writer;
  },
  decode(input, length) {
    const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
    let end = length === undefined ? reader.len : reader.pos + length;
    const message = createBaseSharedItems();
    while (reader.pos < end) {
      const tag = reader.uint32();
      switch (tag >>> 3) {
        case 1: {
          if (tag !== 10) {
            break;
          }
          message.values.push(reader.string());
          continue;
        }
        case 2: {
          if (tag !== 16) {
            break;
          }
          message.containsBlank = reader.bool();
          continue;
        }
        case 3: {
          if (tag !== 24) {
            break;
          }
          message.containsDate = reader.bool();
          continue;
        }
        case 4: {
          if (tag !== 32) {
            break;
          }
          message.containsNumeric = reader.bool();
          continue;
        }
        case 5: {
          if (tag !== 40) {
            break;
          }
          message.containsString = reader.bool();
          continue;
        }
        case 6: {
          if (tag !== 48) {
            break;
          }
          message.containsSemiMixedTypes = reader.bool();
          continue;
        }
        case 7: {
          if (tag !== 56) {
            break;
          }
          message.containsNonDate = reader.bool();
          continue;
        }
        case 8: {
          if (tag !== 64) {
            break;
          }
          message.containsInteger = reader.bool();
          continue;
        }
        case 9: {
          if (tag !== 73) {
            break;
          }
          message.minValue = reader.double();
          continue;
        }
        case 10: {
          if (tag !== 81) {
            break;
          }
          message.maxValue = reader.double();
          continue;
        }
        case 11: {
          if (tag !== 90) {
            break;
          }
          message.minDate = reader.string();
          continue;
        }
        case 12: {
          if (tag !== 98) {
            break;
          }
          message.maxDate = reader.string();
          continue;
        }
        case 13: {
          if (tag !== 104) {
            break;
          }
          message.count = reader.uint32();
          continue;
        }
        case 14: {
          if (tag !== 112) {
            break;
          }
          message.containsMixedTypes = reader.bool();
          continue;
        }
      }
      if ((tag & 7) === 4 || tag === 0) {
        break;
      }
      reader.skip(tag & 7);
    }
    return message;
  },
  create(base) {
    return SharedItems.fromPartial(base ?? {});
  },
  fromPartial(object) {
    const message = createBaseSharedItems();
    message.values = object.values?.map((e) => e) || [];
    message.containsBlank = object.containsBlank ?? undefined;
    message.containsDate = object.containsDate ?? undefined;
    message.containsNumeric = object.containsNumeric ?? undefined;
    message.containsString = object.containsString ?? undefined;
    message.containsSemiMixedTypes = object.containsSemiMixedTypes ?? undefined;
    message.containsNonDate = object.containsNonDate ?? undefined;
    message.containsInteger = object.containsInteger ?? undefined;
    message.minValue = object.minValue ?? undefined;
    message.maxValue = object.maxValue ?? undefined;
    message.minDate = object.minDate ?? undefined;
    message.maxDate = object.maxDate ?? undefined;
    message.count = object.count ?? undefined;
    message.containsMixedTypes = object.containsMixedTypes ?? undefined;
    return message;
  }
};

// node_modules/@oai/granola/dist/spreadsheet/format-cell.js
var import_ssf4 = __toESM(require_ssf(), 1);
function normalizeFormatCodeForSSF(formatCode) {
  return formatCode.replace(/([0#?])((?:,+))\.([0#?]+)/g, (_match, lastIntDigit, scaleCommas, fracDigits) => `${lastIntDigit}.${fracDigits}${scaleCommas}`);
}
function formatCell(cell, styleInfos, cache, styleIndexOverride) {
  if (cell.value === "" || cell.value == null) {
    return "";
  }
  const resolvedStyleIndex = styleIndexOverride ?? cell.styleIndex ?? 0;
  const style = styleInfos[resolvedStyleIndex] ?? {};
  const formatToken = style.numberFormatCode ?? (style.numberFormatId != null ? `#${style.numberFormatId}` : "");
  const cacheKey = cache ? `${cell.value}||${formatToken}` : undefined;
  if (cacheKey && cache?.has(cacheKey))
    return cache.get(cacheKey) ?? "";
  let result = cell.value;
  const formatTokenForSSF = style.numberFormatCode ?? style.numberFormatId;
  if (formatTokenForSSF !== undefined && formatTokenForSSF !== null) {
    const num = Number(cell.value);
    if (!Number.isNaN(num)) {
      try {
        const normalizedToken = typeof formatTokenForSSF === "string" ? normalizeFormatCodeForSSF(formatTokenForSSF) : formatTokenForSSF;
        result = import_ssf4.default.format(normalizedToken, num);
      } catch {
        result = cell.value;
      }
    }
  }
  if (cacheKey)
    cache?.set(cacheKey, result);
  return result;
}

// node_modules/@oai/granola/dist/spreadsheet/apply-stroke-for-border.js
function applyStrokeForBorder(ctx, styleName, color2) {
  ctx.save();
  if (color2)
    ctx.strokeStyle = color2;
  ctx.lineWidth = 1;
  ctx.setLineDash([]);
  switch (styleName) {
    case "thin":
      ctx.lineWidth = 1;
      break;
    case "medium":
      ctx.lineWidth = 2;
      break;
    case "thick":
      ctx.lineWidth = 3;
      break;
    case "dashed":
    case "mediumDashed":
      ctx.lineWidth = styleName === "mediumDashed" ? 2 : 1;
      ctx.setLineDash([6, 3]);
      break;
    case "dashDot":
      ctx.setLineDash([6, 3, 1, 3]);
      break;
    case "dashDotDot":
      ctx.setLineDash([6, 3, 1, 3, 1, 3]);
      break;
    case "slantDashDot":
      ctx.setLineDash([]);
      break;
    case "double":
      break;
    default:
      ctx.lineWidth = 1;
      break;
  }
}

// node_modules/@oai/granola/dist/spreadsheet/draw-checkbox.js
var CHECKBOX_SIZE_PX = 16;
var CHECKBOX_RADIUS_PX = 2;
function getCheckboxRenderInfo({ cell, isCheckbox, x: x2, y: y2, w, h, zoom }) {
  if (!isCheckbox)
    return null;
  const maxSize = Math.max(0, Math.min(w, h));
  const size = Math.min(CHECKBOX_SIZE_PX, maxSize);
  if (size <= 0)
    return null;
  const boxX = x2 + (w - size) / 2;
  const boxY = y2 + (h - size) / 2;
  const checked = cell.dataType === 4 /* CELL_DATA_TYPE_BOOLEAN */ && (cell.value === "1" || cell.value === "TRUE");
  return {
    checked,
    boxRect: { x: boxX, y: boxY, size },
    cssBounds: {
      x: boxX * zoom,
      y: boxY * zoom,
      width: size * zoom,
      height: size * zoom
    }
  };
}
function drawCheckbox(ctx, info, { accentColor, darkMode }) {
  const { x: x2, y: y2, size } = info.boxRect;
  const borderColor = darkMode ? "#E5E7EB" : "#6B7280";
  const fillColor = darkMode ? "#0F172A" : "#FFFFFF";
  const checkColor = accentColor ?? (darkMode ? "#93C5FD" : "#2563EB");
  const borderWidth = Math.max(1, Math.round(size * 0.08));
  ctx.save();
  ctx.lineWidth = borderWidth;
  ctx.strokeStyle = borderColor;
  ctx.fillStyle = fillColor;
  ctx.beginPath();
  drawRoundedRectPath(ctx, x2, y2, size, size, CHECKBOX_RADIUS_PX);
  ctx.fill();
  ctx.stroke();
  if (info.checked) {
    ctx.lineWidth = Math.max(borderWidth, Math.round(size * 0.12));
    ctx.strokeStyle = checkColor;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
    ctx.beginPath();
    ctx.moveTo(x2 + size * 0.2, y2 + size * 0.55);
    ctx.lineTo(x2 + size * 0.45, y2 + size * 0.75);
    ctx.lineTo(x2 + size * 0.8, y2 + size * 0.28);
    ctx.stroke();
  }
  ctx.restore();
}
function drawRoundedRectPath(ctx, x2, y2, w, h, radius) {
  const r = Math.max(0, Math.min(radius, Math.min(w, h) / 2));
  ctx.moveTo(x2 + r, y2);
  ctx.arcTo(x2 + w, y2, x2 + w, y2 + h, r);
  ctx.arcTo(x2 + w, y2 + h, x2, y2 + h, r);
  ctx.arcTo(x2, y2 + h, x2, y2, r);
  ctx.arcTo(x2, y2, x2 + w, y2, r);
  ctx.closePath();
}

// node_modules/@oai/granola/dist/models/spreadsheet/conditional-formatting-icon-sets.js
var DEFAULT_CONDITIONAL_FORMATTING_ICON_SET_NAME = "3TrafficLights1";
var ICON_SET_DEFINITIONS = {
  "3Arrows": { name: "3Arrows", iconCount: 3, slotAspectRatio: 0.95 },
  "3Triangles": { name: "3Triangles", iconCount: 3, slotAspectRatio: 0.95 },
  "4Arrows": { name: "4Arrows", iconCount: 4, slotAspectRatio: 0.95 },
  "5Arrows": { name: "5Arrows", iconCount: 5, slotAspectRatio: 0.95 },
  "3ArrowsGray": {
    name: "3ArrowsGray",
    iconCount: 3,
    slotAspectRatio: 0.95
  },
  "4ArrowsGray": {
    name: "4ArrowsGray",
    iconCount: 4,
    slotAspectRatio: 0.95
  },
  "5ArrowsGray": {
    name: "5ArrowsGray",
    iconCount: 5,
    slotAspectRatio: 0.95
  },
  "3TrafficLights1": {
    name: "3TrafficLights1",
    iconCount: 3,
    slotAspectRatio: 0.82
  },
  "3Signs": { name: "3Signs", iconCount: 3, slotAspectRatio: 0.9 },
  "4RedToBlack": {
    name: "4RedToBlack",
    iconCount: 4,
    slotAspectRatio: 0.9
  },
  "3TrafficLights2": {
    name: "3TrafficLights2",
    iconCount: 3,
    slotAspectRatio: 0.82
  },
  "4TrafficLights": {
    name: "4TrafficLights",
    iconCount: 4,
    slotAspectRatio: 0.82
  },
  "3Symbols": { name: "3Symbols", iconCount: 3, slotAspectRatio: 1.1 },
  "3Flags": { name: "3Flags", iconCount: 3, slotAspectRatio: 1.05 },
  "3Symbols2": { name: "3Symbols2", iconCount: 3, slotAspectRatio: 1.05 },
  "3Stars": { name: "3Stars", iconCount: 3, slotAspectRatio: 0.95 },
  "5Quarters": { name: "5Quarters", iconCount: 5, slotAspectRatio: 0.95 },
  "5Boxes": { name: "5Boxes", iconCount: 5, slotAspectRatio: 1.05 },
  "4Rating": { name: "4Rating", iconCount: 4, slotAspectRatio: 1.35 },
  "5Rating": { name: "5Rating", iconCount: 5, slotAspectRatio: 1.35 }
};
var SUPPORTED_CONDITIONAL_FORMATTING_ICON_SETS = Object.freeze(Object.keys(ICON_SET_DEFINITIONS));
function normalizeConditionalFormattingIconSetName(iconSetName) {
  const trimmed = iconSetName?.trim();
  return trimmed && trimmed.length > 0 ? trimmed : DEFAULT_CONDITIONAL_FORMATTING_ICON_SET_NAME;
}
function getConditionalFormattingIconSetDefinition(iconSetName) {
  const normalized = normalizeConditionalFormattingIconSetName(iconSetName);
  return ICON_SET_DEFINITIONS[normalized] ?? null;
}
function getConditionalFormattingIconSetThresholdCount(options) {
  const definition = getConditionalFormattingIconSetDefinition(options.iconSetName);
  if (definition) {
    return definition.iconCount;
  }
  const fallback = options.fallbackThresholdCount;
  if (fallback === 4 || fallback === 5) {
    return fallback;
  }
  return 3;
}
function getDefaultConditionalFormattingIconSetThresholdPercents(count3) {
  if (count3 >= 5) {
    return [0, 20, 40, 60, 80];
  }
  if (count3 === 4) {
    return [0, 25, 50, 75];
  }
  return [0, 33, 67];
}

// node_modules/@oai/granola/dist/spreadsheet/draw-conditional-format-icon.js
var GREEN = "#4CAF50";
var GREEN_DARK = "#2E7D32";
var YELLOW = "#F4C542";
var YELLOW_DARK = "#B88700";
var ORANGE = "#F28C38";
var ORANGE_DARK = "#B85A00";
var RED = "#D64541";
var RED_DARK = "#8D2B2A";
var BLUE = "#3F83F8";
var BLUE_DARK = "#1D4ED8";
var BLACK = "#2F2F2F";
var OFF_WHITE = "#FAFAFA";
function getConditionalFormattingIconLayout(options) {
  const definition = getConditionalFormattingIconSetDefinition(options.iconSetName);
  if (!definition) {
    return null;
  }
  const maxWidth = Math.max(0, options.width - 4);
  const maxHeight = Math.max(0, options.height - 4);
  if (maxWidth <= 0 || maxHeight <= 0) {
    return null;
  }
  const baseHeight = Math.max(8, options.fontSizePx * 0.96);
  const height = Math.min(maxHeight, baseHeight);
  const width = Math.min(maxWidth, height * definition.slotAspectRatio);
  if (width <= 0 || height <= 0) {
    return null;
  }
  const gap = options.showValue ? Math.max(2, Math.min(6, height * 0.22)) : 0;
  const insetLeft = Math.max(2, Math.min(6, options.fontSizePx * 0.18));
  const x2 = options.showValue ? options.x + insetLeft : options.x + (options.width - width) / 2;
  const y2 = options.y + (options.height - height) / 2;
  return {
    x: x2,
    y: y2,
    width,
    height,
    reservedWidth: options.showValue ? insetLeft + width + gap : 0
  };
}
function drawConditionalFormattingIcon(ctx, options) {
  const definition = getConditionalFormattingIconSetDefinition(options.iconSetName);
  if (!definition) {
    return;
  }
  const clampedIndex = Math.max(0, Math.min(definition.iconCount - 1, Math.round(options.iconIndex)));
  ctx.save();
  switch (definition.name) {
    case "3Arrows":
    case "3ArrowsGray":
    case "4Arrows":
    case "4ArrowsGray":
    case "5Arrows":
    case "5ArrowsGray":
      drawArrowFamily(ctx, definition.name, clampedIndex, options);
      break;
    case "3Triangles":
      drawTriangleFamily(ctx, clampedIndex, options);
      break;
    case "3TrafficLights1":
    case "3TrafficLights2":
    case "4TrafficLights":
      drawTrafficLights(ctx, definition.name, clampedIndex, options);
      break;
    case "3Signs":
      drawSigns(ctx, clampedIndex, options);
      break;
    case "4RedToBlack":
      drawRedToBlack(ctx, clampedIndex, options);
      break;
    case "3Symbols":
      drawSymbolSet(ctx, "symbols", clampedIndex, options);
      break;
    case "3Symbols2":
      drawSymbolSet(ctx, "symbols2", clampedIndex, options);
      break;
    case "3Flags":
      drawFlags(ctx, clampedIndex, options);
      break;
    case "3Stars":
      drawStarState(ctx, clampedIndex, options);
      break;
    case "5Quarters":
      drawQuarterSet(ctx, clampedIndex, options);
      break;
    case "5Boxes":
      drawBoxSet(ctx, clampedIndex, options);
      break;
    case "4Rating":
      drawBarRating(ctx, 4, clampedIndex + 1, options);
      break;
    case "5Rating":
      drawBarRating(ctx, 4, clampedIndex, options);
      break;
  }
  ctx.restore();
}
function drawArrowFamily(ctx, name, iconIndex, bounds) {
  const grayFamily = name.includes("Gray");
  const colors = grayFamily ? ["#D7DCE3", "#B6BEC8", "#8F98A3", "#697380", "#47505C"] : name === "5Arrows" ? [RED, ORANGE, YELLOW, YELLOW, GREEN] : name === "4Arrows" ? [RED, YELLOW, "#93C54B", GREEN] : [RED, YELLOW, GREEN];
  const strokes = grayFamily ? ["#9EA7B2", "#7F8995", "#5F6875", "#434B57", "#2F3640"] : name === "5Arrows" ? [RED_DARK, ORANGE_DARK, YELLOW_DARK, YELLOW_DARK, GREEN_DARK] : name === "4Arrows" ? [RED_DARK, YELLOW_DARK, "#5E8D2A", GREEN_DARK] : [RED_DARK, YELLOW_DARK, GREEN_DARK];
  const directions = name === "4Arrows" || name === "4ArrowsGray" ? ["down", "diagDown", "diagUp", "up"] : name === "5Arrows" || name === "5ArrowsGray" ? ["down", "diagDown", "right", "diagUp", "up"] : ["down", "right", "up"];
  const direction = directions[iconIndex] ?? "right";
  drawArrow(ctx, bounds, direction, colors[iconIndex] ?? colors[colors.length - 1] ?? GREEN, strokes[iconIndex] ?? strokes[strokes.length - 1] ?? GREEN_DARK);
}
function drawTriangleFamily(ctx, iconIndex, bounds) {
  if (iconIndex === 1) {
    const rectWidth = bounds.width * 0.72;
    const rectHeight = bounds.height * 0.3;
    const rectX = bounds.x + (bounds.width - rectWidth) / 2;
    const rectY = bounds.y + (bounds.height - rectHeight) / 2;
    ctx.fillStyle = YELLOW;
    ctx.fillRect(rectX, rectY, rectWidth, rectHeight);
    ctx.lineWidth = Math.max(1, Math.min(rectWidth, rectHeight) * 0.14);
    ctx.strokeStyle = YELLOW_DARK;
    ctx.strokeRect(rectX, rectY, rectWidth, rectHeight);
    return;
  }
  drawTriangle(ctx, bounds, iconIndex === 0 ? "down" : "up", iconIndex === 0 ? RED : GREEN, iconIndex === 0 ? RED_DARK : GREEN_DARK);
}
function drawTrafficLights(ctx, name, iconIndex, bounds) {
  const colors = name === "4TrafficLights" ? [RED, ORANGE, YELLOW, GREEN] : [RED, YELLOW, GREEN];
  const fill = colors[iconIndex] ?? YELLOW;
  const stroke = name === "4TrafficLights" && iconIndex === 1 ? ORANGE_DARK : iconIndex === 0 ? RED_DARK : iconIndex === colors.length - 1 ? GREEN_DARK : YELLOW_DARK;
  const rimmed = name !== "3TrafficLights1";
  const centerX = bounds.x + bounds.width / 2;
  const centerY = bounds.y + bounds.height / 2;
  const radius = Math.min(bounds.width, bounds.height) * 0.34;
  if (rimmed) {
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius * 1.18, 0, Math.PI * 2);
    ctx.fillStyle = "rgba(17, 24, 39, 0.1)";
    ctx.fill();
    ctx.lineWidth = Math.max(1, radius * 0.22);
    ctx.strokeStyle = BLACK;
    ctx.stroke();
  }
  ctx.beginPath();
  ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
  ctx.fillStyle = fill;
  ctx.fill();
  ctx.lineWidth = Math.max(1, radius * 0.12);
  ctx.strokeStyle = stroke;
  ctx.stroke();
  ctx.beginPath();
  ctx.arc(centerX - radius * 0.22, centerY - radius * 0.22, radius * 0.3, 0, Math.PI * 2);
  ctx.fillStyle = "rgba(255,255,255,0.28)";
  ctx.fill();
}
function drawSigns(ctx, iconIndex, bounds) {
  if (iconIndex === 2) {
    drawDiamond(ctx, bounds, GREEN, GREEN_DARK);
    return;
  }
  if (iconIndex === 1) {
    drawTriangle(ctx, bounds, "up", YELLOW, YELLOW_DARK);
    return;
  }
  drawCircleBadge(ctx, bounds, RED, RED_DARK);
}
function drawRedToBlack(ctx, iconIndex, bounds) {
  const fills = ["#E05555", "#B91C1C", "#5B4C4C", BLACK];
  const strokes = ["#8D2B2A", "#7F1D1D", "#3F3A3A", "#111111"];
  drawCircleBadge(ctx, bounds, fills[iconIndex] ?? BLACK, strokes[iconIndex] ?? BLACK);
}
function drawSymbolSet(ctx, kind, iconIndex, bounds) {
  const centerX = bounds.x + bounds.width / 2;
  const centerY = bounds.y + bounds.height / 2;
  const radius = Math.min(bounds.width, bounds.height) * (kind === "symbols2" ? 0.52 : 0.42);
  const accentColors = [RED, YELLOW_DARK, GREEN];
  if (kind !== "symbols2") {
    const backgrounds = [RED, YELLOW, GREEN];
    const strokes = [RED_DARK, YELLOW_DARK, GREEN_DARK];
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
    ctx.fillStyle = backgrounds[iconIndex] ?? YELLOW;
    ctx.fill();
    ctx.lineWidth = Math.max(1, radius * 0.12);
    ctx.strokeStyle = strokes[iconIndex] ?? YELLOW_DARK;
    ctx.stroke();
  }
  ctx.strokeStyle = kind === "symbols2" ? accentColors[iconIndex] ?? YELLOW_DARK : OFF_WHITE;
  ctx.fillStyle = kind === "symbols2" ? accentColors[iconIndex] ?? YELLOW_DARK : OFF_WHITE;
  ctx.lineWidth = Math.max(1.2, radius * (kind === "symbols2" ? 0.24 : 0.18));
  ctx.lineCap = "round";
  ctx.lineJoin = "round";
  if (iconIndex === 2) {
    ctx.beginPath();
    ctx.moveTo(centerX - radius * 0.52, centerY + radius * 0.04);
    ctx.lineTo(centerX - radius * 0.16, centerY + radius * 0.4);
    ctx.lineTo(centerX + radius * 0.54, centerY - radius * 0.36);
    ctx.stroke();
    return;
  }
  if (iconIndex === 1) {
    ctx.beginPath();
    ctx.moveTo(centerX, centerY - radius * 0.52);
    ctx.lineTo(centerX, centerY + radius * 0.16);
    ctx.stroke();
    ctx.beginPath();
    ctx.arc(centerX, centerY + radius * 0.42, radius * 0.1, 0, Math.PI * 2);
    ctx.fill();
    return;
  }
  if (kind === "symbols2") {
    ctx.beginPath();
    ctx.moveTo(centerX - radius * 0.42, centerY - radius * 0.42);
    ctx.lineTo(centerX + radius * 0.42, centerY + radius * 0.42);
    ctx.moveTo(centerX + radius * 0.42, centerY - radius * 0.42);
    ctx.lineTo(centerX - radius * 0.42, centerY + radius * 0.42);
    ctx.stroke();
    return;
  }
  ctx.beginPath();
  ctx.moveTo(centerX - radius * 0.28, centerY - radius * 0.28);
  ctx.lineTo(centerX + radius * 0.28, centerY + radius * 0.28);
  ctx.moveTo(centerX + radius * 0.28, centerY - radius * 0.28);
  ctx.lineTo(centerX - radius * 0.28, centerY + radius * 0.28);
  ctx.stroke();
}
function drawFlags(ctx, iconIndex, bounds) {
  const fills = [RED, YELLOW, GREEN];
  const strokes = [RED_DARK, YELLOW_DARK, GREEN_DARK];
  const poleX = bounds.x + bounds.width * 0.26;
  const poleTop = bounds.y + bounds.height * 0.14;
  const poleBottom = bounds.y + bounds.height * 0.86;
  ctx.lineWidth = Math.max(1, bounds.width * 0.07);
  ctx.strokeStyle = "#4B5563";
  ctx.beginPath();
  ctx.moveTo(poleX, poleTop);
  ctx.lineTo(poleX, poleBottom);
  ctx.stroke();
  ctx.beginPath();
  ctx.moveTo(poleX, poleTop + bounds.height * 0.03);
  ctx.lineTo(bounds.x + bounds.width * 0.82, bounds.y + bounds.height * 0.24);
  ctx.lineTo(poleX, bounds.y + bounds.height * 0.46);
  ctx.closePath();
  ctx.fillStyle = fills[iconIndex] ?? YELLOW;
  ctx.fill();
  ctx.lineWidth = Math.max(1, bounds.width * 0.06);
  ctx.strokeStyle = strokes[iconIndex] ?? YELLOW_DARK;
  ctx.stroke();
}
function drawStarState(ctx, iconIndex, bounds) {
  const fillFractions = [0, 0.5, 1];
  const fraction = fillFractions[iconIndex] ?? 0;
  withTransform(ctx, bounds, () => {
    traceStarPathNormalized(ctx);
    ctx.fillStyle = "rgba(203, 213, 225, 0.65)";
    ctx.fill();
    if (fraction > 0) {
      ctx.save();
      traceStarPathNormalized(ctx);
      ctx.clip();
      ctx.fillStyle = YELLOW;
      ctx.fillRect(0, 0, fraction, 1);
      ctx.restore();
    }
    traceStarPathNormalized(ctx);
    ctx.lineWidth = 0.08;
    ctx.strokeStyle = fraction > 0 ? YELLOW_DARK : "rgba(107, 114, 128, 0.75)";
    ctx.lineJoin = "round";
    ctx.stroke();
  });
}
function drawQuarterSet(ctx, iconIndex, bounds) {
  const centerX = bounds.x + bounds.width / 2;
  const centerY = bounds.y + bounds.height / 2;
  const radius = Math.min(bounds.width, bounds.height) * 0.42;
  const fillFraction = [0, 0.25, 0.5, 0.75, 1][iconIndex] ?? 0;
  ctx.beginPath();
  ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
  ctx.fillStyle = OFF_WHITE;
  ctx.fill();
  if (fillFraction >= 1) {
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
    ctx.fillStyle = BLACK;
    ctx.fill();
  } else if (fillFraction > 0) {
    ctx.beginPath();
    ctx.moveTo(centerX, centerY);
    ctx.arc(centerX, centerY, radius, -Math.PI / 2, -Math.PI / 2 + Math.PI * 2 * fillFraction);
    ctx.closePath();
    ctx.fillStyle = BLACK;
    ctx.fill();
  }
  ctx.lineWidth = Math.max(1, radius * 0.12);
  ctx.strokeStyle = BLACK;
  ctx.beginPath();
  ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
  ctx.stroke();
}
function drawBoxSet(ctx, iconIndex, bounds) {
  const states = [
    [false, false, false, false],
    [false, false, true, false],
    [false, false, true, true],
    [true, false, true, true],
    [true, true, true, true]
  ];
  const fillState = states[iconIndex] ?? states[0] ?? [false, false, false, false];
  const gap = 1;
  const boxSize = Math.min((bounds.width - gap) / 2, (bounds.height - gap) / 2);
  const gridWidth = boxSize * 2 + gap;
  const gridHeight = boxSize * 2 + gap;
  const startX = bounds.x + (bounds.width - gridWidth) / 2;
  const startY = bounds.y + (bounds.height - gridHeight) / 2;
  const positions = [
    { x: startX, y: startY },
    { x: startX + boxSize + gap, y: startY },
    { x: startX, y: startY + boxSize + gap },
    { x: startX + boxSize + gap, y: startY + boxSize + gap }
  ];
  for (let index = 0;index < positions.length; index += 1) {
    const box = positions[index];
    if (!box) {
      continue;
    }
    ctx.fillStyle = fillState[index] ? BLUE : "rgba(203, 213, 225, 0.58)";
    ctx.strokeStyle = BLUE_DARK;
    ctx.lineWidth = Math.max(1, boxSize * 0.1);
    ctx.fillRect(box.x, box.y, boxSize, boxSize);
    ctx.strokeRect(box.x, box.y, boxSize, boxSize);
  }
}
function drawBarRating(ctx, totalBars, filledBars, bounds) {
  const gap = totalBars > 1 ? 2 : 0;
  const barWidth = (bounds.width - gap * (totalBars - 1)) / totalBars;
  for (let index = 0;index < totalBars; index += 1) {
    const fill = index < filledBars;
    const height = bounds.height * (0.34 + (index + 1) / totalBars * 0.56);
    const x2 = bounds.x + index * (barWidth + gap);
    const y2 = bounds.y + bounds.height - height;
    ctx.fillStyle = fill ? GREEN : "rgba(203, 213, 225, 0.42)";
    ctx.strokeStyle = fill ? GREEN_DARK : "rgba(107, 114, 128, 0.55)";
    ctx.lineWidth = Math.max(1, barWidth * 0.18);
    roundRect(ctx, x2, y2, barWidth, height, barWidth * 0.25);
    ctx.fill();
    ctx.stroke();
  }
}
function drawArrow(ctx, bounds, direction, fill, stroke) {
  withTransform(ctx, bounds, () => {
    rotateForDirection(ctx, direction);
    ctx.beginPath();
    ctx.moveTo(0.5, 0.06);
    ctx.lineTo(0.9, 0.46);
    ctx.lineTo(0.68, 0.46);
    ctx.lineTo(0.68, 0.94);
    ctx.lineTo(0.32, 0.94);
    ctx.lineTo(0.32, 0.46);
    ctx.lineTo(0.1, 0.46);
    ctx.closePath();
    ctx.fillStyle = fill;
    ctx.fill();
    ctx.lineWidth = 0.08;
    ctx.strokeStyle = stroke;
    ctx.lineJoin = "round";
    ctx.stroke();
  });
}
function drawTriangle(ctx, bounds, direction, fill, stroke) {
  withTransform(ctx, bounds, () => {
    if (direction === "down") {
      ctx.translate(0.5, 0.5);
      ctx.rotate(Math.PI);
      ctx.translate(-0.5, -0.5);
    } else if (direction === "right") {
      ctx.translate(0.5, 0.5);
      ctx.rotate(Math.PI / 2);
      ctx.translate(-0.5, -0.5);
    }
    ctx.beginPath();
    ctx.moveTo(0.5, 0.08);
    ctx.lineTo(0.9, 0.84);
    ctx.lineTo(0.1, 0.84);
    ctx.closePath();
    ctx.fillStyle = fill;
    ctx.fill();
    ctx.lineWidth = 0.08;
    ctx.strokeStyle = stroke;
    ctx.lineJoin = "round";
    ctx.stroke();
  });
}
function drawDiamond(ctx, bounds, fill, stroke) {
  withTransform(ctx, bounds, () => {
    ctx.beginPath();
    ctx.moveTo(0.5, 0.05);
    ctx.lineTo(0.94, 0.5);
    ctx.lineTo(0.5, 0.95);
    ctx.lineTo(0.06, 0.5);
    ctx.closePath();
    ctx.fillStyle = fill;
    ctx.fill();
    ctx.lineWidth = 0.08;
    ctx.strokeStyle = stroke;
    ctx.stroke();
  });
}
function drawCircleBadge(ctx, bounds, fill, stroke) {
  const centerX = bounds.x + bounds.width / 2;
  const centerY = bounds.y + bounds.height / 2;
  const radius = Math.min(bounds.width, bounds.height) * 0.42;
  ctx.beginPath();
  ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
  ctx.fillStyle = fill;
  ctx.fill();
  ctx.lineWidth = Math.max(1, radius * 0.12);
  ctx.strokeStyle = stroke;
  ctx.stroke();
}
function roundRect(ctx, x2, y2, width, height, radius) {
  const clamped = Math.max(0, Math.min(radius, Math.min(width, height) / 2));
  ctx.beginPath();
  ctx.moveTo(x2 + clamped, y2);
  ctx.arcTo(x2 + width, y2, x2 + width, y2 + height, clamped);
  ctx.arcTo(x2 + width, y2 + height, x2, y2 + height, clamped);
  ctx.arcTo(x2, y2 + height, x2, y2, clamped);
  ctx.arcTo(x2, y2, x2 + width, y2, clamped);
  ctx.closePath();
}
function withTransform(ctx, bounds, draw) {
  ctx.save();
  ctx.translate(bounds.x, bounds.y);
  ctx.scale(bounds.width, bounds.height);
  draw();
  ctx.restore();
}
function traceStarPathNormalized(ctx) {
  const points = 5;
  const outer = 0.46;
  const inner = 0.2;
  ctx.beginPath();
  for (let index = 0;index < points * 2; index += 1) {
    const radius = index % 2 === 0 ? outer : inner;
    const angle = -Math.PI / 2 + Math.PI * index / points;
    const px = 0.5 + Math.cos(angle) * radius;
    const py = 0.5 + Math.sin(angle) * radius;
    if (index === 0) {
      ctx.moveTo(px, py);
    } else {
      ctx.lineTo(px, py);
    }
  }
  ctx.closePath();
}
function rotateForDirection(ctx, direction) {
  ctx.translate(0.5, 0.5);
  switch (direction) {
    case "down":
      ctx.rotate(Math.PI);
      break;
    case "right":
      ctx.rotate(Math.PI / 2);
      break;
    case "diagUp":
      ctx.rotate(Math.PI / 4);
      break;
    case "diagDown":
      ctx.rotate(Math.PI * 3 / 4);
      break;
    default:
      break;
  }
  ctx.translate(-0.5, -0.5);
}

// node_modules/@oai/granola/dist/spreadsheet/draw-double-border.js
function drawDoubleBorder(ctx, edge, color2, x2, y2, w, h) {
  ctx.save();
  ctx.strokeStyle = color2;
  ctx.setLineDash([]);
  ctx.lineWidth = 1;
  const gap = 2;
  if (edge === "top") {
    ctx.beginPath();
    ctx.moveTo(x2, y2);
    ctx.lineTo(x2 + w, y2);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(x2, y2 + gap);
    ctx.lineTo(x2 + w, y2 + gap);
    ctx.stroke();
  } else if (edge === "bottom") {
    ctx.beginPath();
    ctx.moveTo(x2, y2 + h);
    ctx.lineTo(x2 + w, y2 + h);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(x2, y2 + h - gap);
    ctx.lineTo(x2 + w, y2 + h - gap);
    ctx.stroke();
  } else if (edge === "left") {
    ctx.beginPath();
    ctx.moveTo(x2, y2);
    ctx.lineTo(x2, y2 + h);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(x2 + gap, y2);
    ctx.lineTo(x2 + gap, y2 + h);
    ctx.stroke();
  } else if (edge === "right") {
    ctx.beginPath();
    ctx.moveTo(x2 + w, y2);
    ctx.lineTo(x2 + w, y2 + h);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(x2 + w - gap, y2);
    ctx.lineTo(x2 + w - gap, y2 + h);
    ctx.stroke();
  }
  ctx.restore();
}

// node_modules/@oai/granola/dist/spreadsheet/draw-slant-dash-dot.js
function drawSlantDashDot(ctx, edge, color2, x2, y2, w, h) {
  ctx.save();
  ctx.strokeStyle = color2;
  ctx.setLineDash([]);
  ctx.lineWidth = 2;
  ctx.beginPath();
  if (edge === "top") {
    ctx.moveTo(x2, y2);
    ctx.lineTo(x2 + w, y2);
  } else if (edge === "bottom") {
    ctx.moveTo(x2, y2 + h);
    ctx.lineTo(x2 + w, y2 + h);
  } else if (edge === "left") {
    ctx.moveTo(x2, y2);
    ctx.lineTo(x2, y2 + h);
  } else if (edge === "right") {
    ctx.moveTo(x2 + w, y2);
    ctx.lineTo(x2 + w, y2 + h);
  }
  ctx.stroke();
  ctx.save();
  ctx.globalAlpha = 0.5;
  ctx.strokeStyle = "#ffffff";
  ctx.lineWidth = 1;
  const spacing = 8;
  const len = 6;
  if (edge === "left" || edge === "right") {
    const xEdge = edge === "right" ? x2 + w : x2;
    const inward = edge === "right" ? -len : len;
    for (let yy = y2;yy <= y2 + h; yy += spacing) {
      ctx.beginPath();
      ctx.moveTo(xEdge + inward, yy);
      ctx.lineTo(xEdge, yy + len);
      ctx.stroke();
    }
  } else {
    const yEdge = edge === "bottom" ? y2 + h : y2;
    const inward = edge === "bottom" ? -len : len;
    for (let xx = x2;xx <= x2 + w; xx += spacing) {
      ctx.beginPath();
      ctx.moveTo(xx, yEdge + inward);
      ctx.lineTo(xx + len, yEdge);
      ctx.stroke();
    }
  }
  ctx.restore();
  ctx.restore();
}

// node_modules/@oai/granola/dist/spreadsheet/normalize-family-name.js
var normalizeFamilyName2 = (n) => {
  if (!n)
    return;
  let out = n.replace(/\s*\(Body\)\s*$/i, "");
  out = out.replace(/\s+Regular$/i, "");
  out = out.replace(/\s+Bold$/i, "");
  out = out.replace(/\s+Italic$/i, "");
  return out.trim();
};

// node_modules/@oai/granola/dist/spreadsheet/rgba-to-rgb.js
function rgbaToRgb(css) {
  const m = css.match(/^rgba?\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\)$/i);
  if (!m)
    return null;
  const [, r, g, b] = m;
  if (!r || !g || !b)
    return null;
  return [parseInt(r, 10), parseInt(g, 10), parseInt(b, 10)];
}
// node_modules/@oai/granola/dist/draw-utils/get-bitmap.js
var bitmapCache = new Map;
function ensureUint8Array(view) {
  if (view.buffer instanceof ArrayBuffer) {
    return view;
  }
  const copy2 = new Uint8Array(view.byteLength);
  copy2.set(view);
  return copy2;
}
function addSvgIntrinsicSize(text, w, h) {
  if (/\bwidth\s*=|\bheight\s*=/.test(text)) {
    return new Blob([text], { type: "image/svg+xml" });
  }
  const patched = text.replace(/<svg\b([^>]*)>/, `<svg$1 width="${w}" height="${h}">`);
  return new Blob([patched], { type: "image/svg+xml" });
}
function getDevicePixelRatio() {
  if (typeof window !== "undefined") {
    return window.devicePixelRatio || 1;
  }
  return globalThis.devicePixelRatio || 1;
}
function getDomImageConstructor() {
  const globalImage = globalThis.Image;
  if (globalImage) {
    return globalImage;
  }
  return typeof window !== "undefined" ? window.Image : undefined;
}
async function createBitmapFromDomImage(blob, options) {
  const DomImage = getDomImageConstructor();
  if (!DomImage || typeof URL === "undefined" || typeof URL.createObjectURL !== "function") {
    return;
  }
  const url = URL.createObjectURL(blob);
  try {
    const img = new DomImage;
    const loaded = new Promise((resolve, reject) => {
      img.onload = () => resolve();
      img.onerror = () => reject(new Error("Failed to decode SVG image payload."));
    });
    img.src = url;
    if (typeof img.decode === "function") {
      await img.decode();
    } else {
      await loaded;
    }
    return await createImageBitmap(img, options);
  } finally {
    if (typeof URL.revokeObjectURL === "function") {
      URL.revokeObjectURL(url);
    }
  }
}
async function createBitmapFromSvgBlob(blob, options) {
  try {
    const domBitmap = await createBitmapFromDomImage(blob, options);
    if (domBitmap) {
      return domBitmap;
    }
  } catch {}
  return createImageBitmap(blob, options);
}
async function getBitmapFromImage(image, slideWidth, slideHeight) {
  const key = `${image.data.byteLength}_${image.contentType}`;
  const existing = bitmapCache.get(key);
  if (existing)
    return existing;
  if (image.contentType === "image/svg+xml") {
    const width = Math.round(slideWidth ?? 1);
    const height = Math.round(slideHeight ?? 1);
    const dpr = getDevicePixelRatio();
    const newBlob = addSvgIntrinsicSize(new TextDecoder().decode(image.data), width, height);
    const bitmap = createBitmapFromSvgBlob(newBlob, {
      resizeWidth: width * dpr,
      resizeHeight: height * dpr
    });
    bitmapCache.set(key, bitmap);
    return bitmap;
  } else {
    const blob = new Blob([ensureUint8Array(image.data)], {
      type: image.contentType
    });
    const bitmap = createImageBitmap(blob);
    bitmapCache.set(key, bitmap);
    return bitmap;
  }
}

// node_modules/@oai/granola/dist/draw-utils/draw-sheet-images.js
var loadedBitmapById = new Map;
var pendingById = new Map;
function ensureUint8ArrayFromBase64(data) {
  const bin2 = atob(data);
  const bytes = new Uint8Array(bin2.length);
  for (let i = 0;i < bin2.length; i++)
    bytes[i] = bin2.charCodeAt(i);
  return bytes;
}
function resolveWorkbookImage(workbook, imageId) {
  if (!imageId)
    return null;
  const imgs = workbook.images;
  if (!imgs || imgs.length === 0)
    return null;
  const found = imgs.find((i) => i.id === imageId);
  if (!found)
    return null;
  const bytes = typeof found.data === "string" ? ensureUint8ArrayFromBase64(found.data) : found.data;
  return { id: found.id, contentType: found.contentType, data: bytes };
}
function drawSheetImages(ctx, worksheet, workbook, colOffsets, rowOffsets, scrollX, scrollY, viewportW, viewportH, addImageTarget, zoom = 1) {
  const images = worksheet.images.items;
  if (images.length === 0)
    return;
  for (const image of images) {
    const d = image.toDrawingProto({ preferPreview: true });
    const imgId = d.imageReference?.id;
    if (!imgId)
      continue;
    const logicalBounds = image.resolveBoundsPx({
      columnOffsets: colOffsets,
      rowOffsets
    }, { preferPreview: true });
    if (!logicalBounds)
      continue;
    const x0 = ROW_HEADER_W + logicalBounds.x - scrollX;
    const y0 = COL_HEADER_H + logicalBounds.y - scrollY;
    let destW = logicalBounds.width;
    let destH = logicalBounds.height;
    addImageTarget?.({
      id: image.id,
      logicalBounds: { x: x0, y: y0, width: destW, height: destH },
      cssBounds: {
        x: x0 * zoom,
        y: y0 * zoom,
        width: destW * zoom,
        height: destH * zoom
      },
      drawing: d,
      usesTwoCellAnchor: Boolean(d.toAnchor)
    });
    if (destW <= 0 || destH <= 0) {
      const from = d.fromAnchor;
      if (!from)
        continue;
      const fromCol = Number(from.colId);
      const fromRow = Number(from.rowId);
      const prevColOffset = colOffsets[fromCol] ?? 0;
      const nextColOffset = colOffsets[fromCol + 1] ?? prevColOffset;
      const prevRowTop = rowOffsets[fromRow - 1] ?? 0;
      const curRowBottom = rowOffsets[fromRow] ?? prevRowTop;
      const cellW = Math.max(0, nextColOffset - prevColOffset);
      const cellH = Math.max(0, curRowBottom - prevRowTop);
      const img2 = resolveWorkbookImage(workbook, imgId);
      if (!img2)
        continue;
      const ready = loadedBitmapById.get(img2.id);
      if (!ready) {
        if (!pendingById.has(img2.id)) {
          const p = getBitmapFromImage(img2, viewportW, viewportH).then((bmp) => {
            loadedBitmapById.set(img2.id, bmp);
            return bmp;
          });
          pendingById.set(img2.id, p);
        }
        continue;
      }
      const bmpW = ready.width;
      const bmpH = ready.height;
      if (bmpW <= 0 || bmpH <= 0 || cellW <= 0 || cellH <= 0)
        continue;
      const scale = Math.min(cellW / bmpW, cellH / bmpH);
      destW = Math.max(0, Math.floor(bmpW * scale));
      destH = Math.max(0, Math.floor(bmpH * scale));
      const dx = (cellW - destW) / 2;
      const dy = (cellH - destH) / 2;
      ctx.drawImage(ready, 0, 0, bmpW, bmpH, x0 + dx, y0 + dy, destW, destH);
      continue;
    }
    if (x0 + destW < 0 || y0 + destH < 0 || x0 > viewportW || y0 > viewportH)
      continue;
    const img = resolveWorkbookImage(workbook, imgId);
    if (!img)
      continue;
    const cached = loadedBitmapById.get(img.id);
    if (cached) {
      ctx.drawImage(cached, 0, 0, cached.width, cached.height, x0, y0, destW, destH);
      continue;
    }
    if (!pendingById.has(img.id)) {
      const p = getBitmapFromImage(img, viewportW, viewportH).then((bmp) => {
        loadedBitmapById.set(img.id, bmp);
        return bmp;
      });
      pendingById.set(img.id, p);
    }
  }
}
// node_modules/@oai/granola/dist/draw-utils/transform-utils.js
var EMUS_PER_DEGREE = 60000;
function emuRotationToDegrees(rotEmu) {
  if (rotEmu === undefined || rotEmu === null) {
    return;
  }
  return rotEmu / EMUS_PER_DEGREE;
}
function degreesToEmuRotation(degrees) {
  if (degrees === undefined || degrees === null || Number.isNaN(degrees)) {
    return;
  }
  return Math.round(degrees * EMUS_PER_DEGREE);
}
function emuRotationToRadians(rotEmu) {
  const deg = emuRotationToDegrees(rotEmu);
  if (!deg)
    return 0;
  return deg * Math.PI / 180;
}
function pushElementTransform(ctx, el, pres, slide) {
  const { x: x2, y: y2, width, height } = getBBox(el, pres, slide);
  const flipH = !!el.bbox?.horizontalFlip;
  const flipV = !!el.bbox?.verticalFlip;
  const theta = emuRotationToRadians(el.bbox?.rotation ?? 0);
  const halfW = width / 2;
  const halfH = height / 2;
  const sx = flipH ? -1 : 1;
  const sy = flipV ? -1 : 1;
  ctx.save();
  ctx.translate(x2 + halfW, y2 + halfH);
  if (theta !== 0)
    ctx.rotate(theta);
  if (sx === -1 || sy === -1)
    ctx.scale(sx, sy);
  ctx.translate(-halfW, -halfH);
}

// node_modules/@oai/granola/dist/plugins/registry.js
var workbookHelpProvider = null;
var workbookExportProvider = null;
var presentationHelpProvider = null;
var googleSheetsProvider = null;
function registerWorkbookHelpProvider(provider) {
  workbookHelpProvider = provider;
}
function registerWorkbookExportProvider(provider) {
  workbookExportProvider = provider;
}
function getWorkbookHelpProviderOrThrow() {
  if (!workbookHelpProvider) {
    throw new Error([
      "Workbook help plugin is not installed.",
      "Load it with:",
      "  const { installWorkbookHelp } = await import('@oai/granola/plugins/workbook-help');",
      "  installWorkbookHelp();"
    ].join(`
`));
  }
  return workbookHelpProvider;
}
function getWorkbookExportProviderOrThrow() {
  if (!workbookExportProvider) {
    throw new Error([
      "Workbook export plugin is not installed.",
      "Load it with:",
      "  const { installWorkbookExport } = await import('@oai/granola/plugins/workbook-export');",
      "  installWorkbookExport();"
    ].join(`
`));
  }
  return workbookExportProvider;
}
function getPresentationHelpProviderOrThrow() {
  if (!presentationHelpProvider) {
    throw new Error([
      "Presentation help plugin is not installed.",
      "Load it with:",
      "  const { installPresentationHelp } = await import('@oai/granola/plugins/presentation-help');",
      "  installPresentationHelp();"
    ].join(`
`));
  }
  return presentationHelpProvider;
}
function getGoogleSheetsProviderOrThrow() {
  if (!googleSheetsProvider) {
    throw new Error([
      "Google Sheets plugin is not installed.",
      "Load it with:",
      "  const { installGoogleSheetsPlugin } = await import('@oai/granola/plugins/google-sheets');",
      "  installGoogleSheetsPlugin();"
    ].join(`
`));
  }
  return googleSheetsProvider;
}
var presetShapeDefinitions = null;
var presetShapeDefinitionsWarned = false;
function registerPresetShapeDefinitions(definitions) {
  presetShapeDefinitions = definitions;
}
function getPresetShapeDefinition(geometry) {
  if (!presetShapeDefinitions) {
    if (!presetShapeDefinitionsWarned) {
      presetShapeDefinitionsWarned = true;
      console.warn([
        "Preset shape definitions are not installed.",
        "Some shapes will not render until you load:",
        "  const { installPresetShapeDefinitions } = await import('@oai/granola/plugins/preset-shape-definitions');",
        "  installPresetShapeDefinitions();"
      ].join(`
`));
    }
    return;
  }
  const lookup = presetShapeDefinitions;
  return lookup[geometry];
}

// node_modules/@oai/granola/dist/draw-utils/apply-line-style.js
function applyLineStyle2(ctx, style, widthPx) {
  switch (style) {
    case 1 /* LINE_STYLE_SOLID */:
    case 0 /* LINE_STYLE_UNSPECIFIED */:
      ctx.setLineDash([]);
      break;
    case 2 /* LINE_STYLE_DASHED */:
      ctx.setLineDash([4 * widthPx, 4 * widthPx]);
      break;
    case 6 /* LINE_STYLE_LARGE_DASH */:
      ctx.setLineDash([8 * widthPx, 4 * widthPx]);
      break;
    case 7 /* LINE_STYLE_SYSTEM_DASH */:
      ctx.setLineDash([3 * widthPx, 3 * widthPx]);
      break;
    case 3 /* LINE_STYLE_DOTTED */:
      ctx.lineCap = "round";
      ctx.setLineDash([widthPx, 2 * widthPx]);
      break;
    case 4 /* LINE_STYLE_DASH_DOT */:
      ctx.lineCap = "round";
      ctx.setLineDash([4 * widthPx, 2 * widthPx, widthPx, 2 * widthPx]);
      break;
    case 8 /* LINE_STYLE_SYSTEM_DOT */:
      ctx.lineCap = "round";
      ctx.setLineDash([widthPx, 2 * widthPx]);
      break;
    case 5 /* LINE_STYLE_DASH_DOT_DOT */:
      ctx.lineCap = "round";
      ctx.setLineDash([
        4 * widthPx,
        2 * widthPx,
        widthPx,
        2 * widthPx,
        widthPx,
        2 * widthPx
      ]);
      break;
    case 9 /* LINE_STYLE_LARGE_DASH_DOT */:
      ctx.lineCap = "butt";
      ctx.setLineDash([8 * widthPx, 3 * widthPx, widthPx, 3 * widthPx]);
      break;
    case 10 /* LINE_STYLE_SYSTEM_DASH_DOT */:
      ctx.lineCap = "butt";
      ctx.setLineDash([3 * widthPx, 2 * widthPx, widthPx, 2 * widthPx]);
      break;
    case 11 /* LINE_STYLE_LARGE_DASH_DOT_DOT */:
      ctx.lineCap = "butt";
      ctx.setLineDash([
        8 * widthPx,
        3 * widthPx,
        widthPx,
        2 * widthPx,
        widthPx,
        3 * widthPx
      ]);
      break;
    case 12 /* LINE_STYLE_SYSTEM_DASH_DOT_DOT */:
      ctx.lineCap = "butt";
      ctx.setLineDash([
        3 * widthPx,
        2 * widthPx,
        widthPx,
        2 * widthPx,
        widthPx,
        2 * widthPx
      ]);
      break;
    default:
      ctx.setLineDash([]);
  }
}

// node_modules/@oai/granola/dist/shapes/eval-formula.js
var ANGLE_UNIT = 60000;
function degToRad2(deg) {
  return deg * Math.PI / 180;
}
function ooxmlAngleToRad(v) {
  return degToRad2(v / ANGLE_UNIT);
}
var ANG_CONST = {
  cd4: 90 * ANGLE_UNIT,
  cd2: 180 * ANGLE_UNIT,
  "3cd4": 270 * ANGLE_UNIT,
  "5cd4": 450 * ANGLE_UNIT,
  "7cd4": 630 * ANGLE_UNIT,
  "3cd2": 540 * ANGLE_UNIT,
  cd: 360 * ANGLE_UNIT
};
function toNumber(token, env) {
  if (token in env)
    return env[token];
  if (token in ANG_CONST)
    return ANG_CONST[token];
  if (/^-?\d+$/.test(token))
    return parseInt(token, 10);
  return Number.NaN;
}
var Ops = {
  val: (a) => a,
  "+-": (a, b, c) => a + b - c,
  "*/": (a, b, c) => a * b / (c || 1),
  sum: (...xs) => xs.reduce((p, x2) => p + x2, 0),
  prod: (...xs) => xs.reduce((p, x2) => p * x2, 1),
  min: (...xs) => Math.min(...xs),
  max: (...xs) => Math.max(...xs),
  abs: (a) => Math.abs(a),
  mid: (a, b) => (a + b) / 2,
  mod: (...xs) => {
    if (xs.length === 0)
      return Number.NaN;
    return Math.hypot(...xs);
  },
  sqrt: (a) => Math.sqrt(Math.max(a, 0)),
  sin: (r, ang) => ang === undefined ? Math.sin(ooxmlAngleToRad(r)) : r * Math.sin(ooxmlAngleToRad(ang)),
  cos: (r, ang) => ang === undefined ? Math.cos(ooxmlAngleToRad(r)) : r * Math.cos(ooxmlAngleToRad(ang)),
  tan: (r, ang) => ang === undefined ? Math.tan(ooxmlAngleToRad(r)) : r * Math.tan(ooxmlAngleToRad(ang)),
  at2: (x2, y2) => {
    const rad = Math.atan2(y2, x2);
    const deg = rad * 180 / Math.PI;
    return deg * ANGLE_UNIT;
  },
  cat2: (x2, y2, z) => x2 * Math.cos(Math.atan2(z, y2)),
  sat2: (x2, y2, z) => x2 * Math.sin(Math.atan2(z, y2)),
  pin: (...args) => {
    if (args.length !== 3)
      throw new Error("pin expects 3 arguments");
    {
      const [mn, x2, mx] = args;
      if (typeof mn === "number" && typeof x2 === "number" && typeof mx === "number" && !Number.isNaN(x2) && !Number.isNaN(mn) && !Number.isNaN(mx)) {
        const lo = Math.min(mn, mx), hi = Math.max(mn, mx);
        return Math.min(Math.max(x2, lo), hi);
      }
    }
    {
      const [x2, mn, mx] = args;
      if (typeof x2 === "number" && typeof mn === "number" && typeof mx === "number") {
        const lo = Math.min(mn, mx), hi = Math.max(mn, mx);
        return Math.min(Math.max(x2, lo), hi);
      }
    }
    return Number.NaN;
  },
  "?:": (cond, whenTrue, whenFalse) => cond > 0 ? whenTrue : whenFalse,
  "+/": (...args) => {
    if (args.length === 0)
      return Number.NaN;
    const denom = (args.length >= 2 ? args[args.length - 1] : 2) || 2;
    const numer = (args.length >= 2 ? args.slice(0, -1) : args).reduce((p, x2) => p + x2, 0);
    return numer / denom;
  }
};
function evalFmla(fmla, env) {
  const parts = fmla.trim().split(/\s+/);
  const op = parts[0];
  if (!op)
    return Number.NaN;
  if (Ops[op]) {
    const args = parts.slice(1).map((t) => toNumber(t, env));
    if (args.some((x2) => typeof x2 !== "number" || Number.isNaN(x2))) {
      return Number.NaN;
    }
    return Ops[op](...args);
  }
  if (parts.length === 1 && parts[0]) {
    const val = toNumber(parts[0], env);
    return typeof val === "number" && !Number.isNaN(val) ? val : Number.NaN;
  }
  throw new Error(`Unsupported formula: ${fmla}`);
}
function resolve(expr, env) {
  if (!expr)
    return Number.NaN;
  if (/^(val|\+-|\*\/|\+\/|sum|prod|min|max|abs|mid|mod|sqrt|sin|cos|tan|at2|cat2|sat2|pin|\?:)(?:\s|$)/.test(expr))
    return evalFmla(expr, env);
  if (expr in env) {
    const v = env[expr];
    return typeof v === "number" && !Number.isNaN(v) ? v : Number.NaN;
  }
  if (expr in ANG_CONST) {
    const v = ANG_CONST[expr];
    return typeof v === "number" && !Number.isNaN(v) ? v : Number.NaN;
  }
  if (/^-?\d+$/.test(expr))
    return parseInt(expr, 10);
  return Number.NaN;
}

// node_modules/@oai/granola/dist/shapes/build-env.js
var ADJUSTMENT_ALIAS = {
  adj1: "a1",
  adj2: "a2",
  adj3: "a3",
  adj4: "a4",
  adj5: "a5",
  adj6: "a6",
  adj7: "a7",
  adj8: "a8"
};
function buildEnv(preset, w, h, instanceAdj = {}) {
  const env = createBaseEnv(w, h);
  const adjustments = preset.avLst ?? {};
  for (const [name, formula] of Object.entries(adjustments)) {
    const expr = instanceAdj[name] ?? formula;
    env[name] = evalFmla(expr, env);
    if (ADJUSTMENT_ALIAS[name]) {
      const alias = ADJUSTMENT_ALIAS[name];
      env[alias] = env[name];
    }
  }
  const guides = preset.gdLst ?? {};
  const pendingGuides = [];
  for (const [name, formula] of Object.entries(guides)) {
    const value = evalFmla(formula, env);
    if (Number.isNaN(value)) {
      pendingGuides.push([name, formula]);
      continue;
    }
    env[name] = value;
  }
  for (const [name, formula] of pendingGuides) {
    env[name] = evalFmla(formula, env);
  }
  return env;
}
function createBaseEnv(w, h) {
  const ss = Math.min(w, h);
  const base = {
    w,
    h,
    l: 0,
    t: 0,
    r: w,
    b: h,
    hc: w / 2,
    vc: h / 2,
    ss,
    wd2: w / 2,
    wd3: w / 3,
    wd4: w / 4,
    wd5: w / 5,
    wd6: w / 6,
    wd8: w / 8,
    wd10: w / 10,
    wd12: w / 12,
    wd32: w / 32,
    hd2: h / 2,
    hd3: h / 3,
    hd4: h / 4,
    hd5: h / 5,
    hd6: h / 6,
    hd8: h / 8,
    hd10: h / 10,
    ssd2: ss / 2,
    ssd6: ss / 6,
    ssd8: ss / 8,
    ssd16: ss / 16,
    ssd32: ss / 32
  };
  return base;
}

// node_modules/@oai/granola/dist/shapes/draw-preset-shape.js
var TAU = Math.PI * 2;
var DEG_PER_RAD = 180 / Math.PI;
var RAD_PER_DEG = Math.PI / 180;
var MIN_VECTOR_MAG = 0.000001;
function normalizeAngle2(angle) {
  if (!Number.isFinite(angle))
    return angle;
  let normalized = angle % TAU;
  if (normalized < 0)
    normalized += TAU;
  return normalized;
}
function geomAngleToEllipseParam(geomAngle, wR, hR) {
  if (!Number.isFinite(geomAngle) || wR === 0 || hR === 0)
    return normalizeAngle2(geomAngle);
  const angleDeg = geomAngle * DEG_PER_RAD % 360;
  const normalizedDeg = angleDeg < 0 ? angleDeg + 360 : angleDeg;
  if (normalizedDeg === 0 || normalizedDeg === 90 || normalizedDeg === 180 || normalizedDeg === 270) {
    return normalizedDeg * RAD_PER_DEG;
  }
  const phi2 = normalizedDeg * RAD_PER_DEG;
  const x2 = hR * Math.cos(phi2);
  const y2 = wR * Math.sin(phi2);
  if (Math.abs(x2) < 0.000000000001 && Math.abs(y2) < 0.000000000001)
    return phi2;
  let theta = Math.atan2(y2, x2);
  if (theta < 0)
    theta += TAU;
  return theta;
}
function drawPath(ctx, path3, env, doFill = true, doStroke = true, collectMetrics = false) {
  ctx.beginPath();
  let curX = 0;
  let curY = 0;
  let subpathStartX = 0;
  let subpathStartY = 0;
  const pathMetrics = collectMetrics ? {} : undefined;
  const numericLiteral = /^-?\d+(?:\.\d+)?$/;
  const normW = path3.w && numericLiteral.test(path3.w) ? Number(path3.w) : undefined;
  const normH = path3.h && numericLiteral.test(path3.h) ? Number(path3.h) : undefined;
  const scaleX = normW ? env.w / normW : undefined;
  const scaleY = normH ? env.h / normH : undefined;
  const hasNormX = typeof scaleX === "number" && Number.isFinite(scaleX);
  const hasNormY = typeof scaleY === "number" && Number.isFinite(scaleY);
  const resolveCoord = (expr, axis) => {
    if (!expr)
      return Number.NaN;
    const shouldScale = numericLiteral.test(expr) && (axis === "x" && hasNormX || axis === "y" && hasNormY);
    if (shouldScale) {
      const factor = axis === "x" ? scaleX ?? 1 : scaleY ?? 1;
      return Number(expr) * factor;
    }
    return resolve(expr, env);
  };
  const resolveLength = (expr, axis) => {
    if (!expr)
      return resolve(expr, env);
    if (numericLiteral.test(expr) && (axis === "x" && hasNormX || axis === "y" && hasNormY)) {
      const factor = axis === "x" ? scaleX ?? 1 : scaleY ?? 1;
      return Number(expr) * factor;
    }
    return resolve(expr, env);
  };
  const recordStart = (x2, y2, dx, dy) => {
    if (!pathMetrics || pathMetrics.start)
      return;
    if (!Number.isFinite(x2) || !Number.isFinite(y2))
      return;
    if (!Number.isFinite(dx) || !Number.isFinite(dy))
      return;
    if (Math.hypot(dx, dy) < MIN_VECTOR_MAG)
      return;
    pathMetrics.start = { x: x2, y: y2, angle: Math.atan2(dy, dx) };
  };
  const recordEnd = (x2, y2, dx, dy) => {
    if (!pathMetrics)
      return;
    if (!Number.isFinite(x2) || !Number.isFinite(y2))
      return;
    if (!Number.isFinite(dx) || !Number.isFinite(dy))
      return;
    if (Math.hypot(dx, dy) < MIN_VECTOR_MAG)
      return;
    pathMetrics.end = { x: x2, y: y2, angle: Math.atan2(dy, dx) };
  };
  const moveTo = (xExpr, yExpr) => {
    curX = resolveCoord(xExpr, "x");
    curY = resolveCoord(yExpr, "y");
    subpathStartX = curX;
    subpathStartY = curY;
    ctx.moveTo(curX, curY);
  };
  for (const c of path3.commands) {
    switch (c.cmd) {
      case "moveTo": {
        moveTo(c.x, c.y);
        break;
      }
      case "lineTo": {
        const nextX = resolveCoord(c.x, "x");
        const nextY = resolveCoord(c.y, "y");
        const prevX = curX;
        const prevY = curY;
        curX = nextX;
        curY = nextY;
        const dx = nextX - prevX;
        const dy = nextY - prevY;
        recordStart(prevX, prevY, dx, dy);
        recordEnd(nextX, nextY, dx, dy);
        ctx.lineTo(nextX, nextY);
        break;
      }
      case "quadBezTo": {
        const x1 = resolveCoord(c.x1, "x");
        const y1 = resolveCoord(c.y1, "y");
        const nextX = resolveCoord(c.x, "x");
        const nextY = resolveCoord(c.y, "y");
        const prevX = curX;
        const prevY = curY;
        curX = nextX;
        curY = nextY;
        recordStart(prevX, prevY, x1 - prevX, y1 - prevY);
        recordEnd(nextX, nextY, nextX - x1, nextY - y1);
        ctx.quadraticCurveTo(x1, y1, nextX, nextY);
        break;
      }
      case "cubicBezTo": {
        const x1 = resolveCoord(c.x1, "x");
        const y1 = resolveCoord(c.y1, "y");
        const x2 = resolveCoord(c.x2, "x");
        const y2 = resolveCoord(c.y2, "y");
        const nextX = resolveCoord(c.x, "x");
        const nextY = resolveCoord(c.y, "y");
        const prevX = curX;
        const prevY = curY;
        curX = nextX;
        curY = nextY;
        recordStart(prevX, prevY, x1 - prevX, y1 - prevY);
        recordEnd(nextX, nextY, nextX - x2, nextY - y2);
        ctx.bezierCurveTo(x1, y1, x2, y2, nextX, nextY);
        break;
      }
      case "arcTo": {
        const rawWR = resolveLength(c.wR, "x");
        const rawHR = resolveLength(c.hR, "y");
        const wR = Math.abs(rawWR);
        const hR = Math.abs(rawHR);
        const startGeom = ooxmlAngleToRad2(resolve(c.stAng, env));
        let sweepGeom = ooxmlAngleToRad2(resolve(c.swAng, env));
        if (sweepGeom > TAU)
          sweepGeom = TAU;
        if (sweepGeom < -TAU)
          sweepGeom = -TAU;
        const endGeom = startGeom + sweepGeom;
        const startParam = geomAngleToEllipseParam(startGeom, wR, hR);
        let endParam = geomAngleToEllipseParam(endGeom, wR, hR);
        const anticw = sweepGeom < 0;
        let paramDelta = endParam - startParam;
        if (sweepGeom < 0 && paramDelta >= 0) {
          endParam -= TAU;
          paramDelta = endParam - startParam;
        } else if (sweepGeom > 0 && paramDelta <= 0) {
          endParam += TAU;
          paramDelta = endParam - startParam;
        }
        if (Math.abs(sweepGeom) > 0.000000001 && Math.abs(paramDelta) < 0.000000001) {
          endParam = startParam + (sweepGeom < 0 ? -TAU : TAU);
          paramDelta = endParam - startParam;
        }
        const cx = curX - rawWR * Math.cos(startParam);
        const cy = curY - rawHR * Math.sin(startParam);
        const direction = anticw ? -1 : 1;
        const normalizedStart = normalizeAngle2(startParam);
        const normalizedEnd = normalizeAngle2(endParam);
        ctx.ellipse(cx, cy, wR, hR, 0, normalizedStart, normalizedEnd, anticw);
        recordStart(curX, curY, direction * -rawWR * Math.sin(startParam), direction * rawHR * Math.cos(startParam));
        curX = cx + rawWR * Math.cos(endParam);
        curY = cy + rawHR * Math.sin(endParam);
        recordEnd(curX, curY, direction * -rawWR * Math.sin(endParam), direction * rawHR * Math.cos(endParam));
        break;
      }
      case "close": {
        ctx.closePath();
        const prevX = curX;
        const prevY = curY;
        curX = subpathStartX;
        curY = subpathStartY;
        const dx = curX - prevX;
        const dy = curY - prevY;
        recordStart(prevX, prevY, dx, dy);
        recordEnd(curX, curY, dx, dy);
        break;
      }
    }
  }
  function ooxmlAngleToRad2(v) {
    return v / 60000 * Math.PI / 180;
  }
  const savedComp = ctx.globalCompositeOperation;
  if (path3.fill === "darken")
    ctx.globalCompositeOperation = "darken";
  if (path3.fill && path3.fill !== "none" && doFill)
    ctx.fill();
  if ((path3.stroke ?? true) && doStroke)
    ctx.stroke();
  ctx.globalCompositeOperation = savedComp;
  return pathMetrics;
}
function drawPresetShape(ctx, preset, { w, h, x: x2 = 0, y: y2 = 0, adjustments = {}, fill = true, stroke = true, collectMetrics = false }) {
  ctx.save();
  ctx.translate(x2, y2);
  const env = buildEnv(preset, w, h, adjustments);
  const renderedPaths = [];
  for (const p of preset.paths) {
    const metrics = drawPath(ctx, p, env, fill, stroke, collectMetrics);
    if (collectMetrics && metrics)
      renderedPaths.push(metrics);
  }
  ctx.restore();
  return collectMetrics ? renderedPaths : undefined;
}

// node_modules/@oai/granola/dist/shapes/render-custom-commands.js
function renderCustomCommands(ctx, commands) {
  let curX = 0;
  let curY = 0;
  ctx.beginPath();
  for (const c of commands) {
    if (c.moveTo) {
      curX = (Number(c.moveTo.x ?? curX) || 0) * EMU_TO_PX;
      curY = (Number(c.moveTo.y ?? curY) || 0) * EMU_TO_PX;
      ctx.moveTo(curX, curY);
    } else if (c.lineTo) {
      if (c.lineTo.x !== undefined)
        curX = Number(c.lineTo.x) * EMU_TO_PX;
      if (c.lineTo.y !== undefined)
        curY = Number(c.lineTo.y) * EMU_TO_PX;
      ctx.lineTo(curX, curY);
    } else if (c.quadBezTo) {
      const x1 = Number(c.quadBezTo.x1 ?? curX) * EMU_TO_PX;
      const y1 = Number(c.quadBezTo.y1 ?? curY) * EMU_TO_PX;
      curX = Number(c.quadBezTo.x ?? curX) * EMU_TO_PX;
      curY = Number(c.quadBezTo.y ?? curY) * EMU_TO_PX;
      ctx.quadraticCurveTo(x1, y1, curX, curY);
    } else if (c.cubicBezTo) {
      const x1 = Number(c.cubicBezTo.x1 ?? curX) * EMU_TO_PX;
      const y1 = Number(c.cubicBezTo.y1 ?? curY) * EMU_TO_PX;
      const x2 = Number(c.cubicBezTo.x2 ?? curX) * EMU_TO_PX;
      const y2 = Number(c.cubicBezTo.y2 ?? curY) * EMU_TO_PX;
      curX = Number(c.cubicBezTo.x ?? curX) * EMU_TO_PX;
      curY = Number(c.cubicBezTo.y ?? curY) * EMU_TO_PX;
      ctx.bezierCurveTo(x1, y1, x2, y2, curX, curY);
    } else if (c.close !== undefined) {
      ctx.closePath();
    }
  }
}

// node_modules/@oai/granola/dist/draw-utils/draw-arrow-head.js
var renderArrowheads = (el, ctx, pres, slide, strokePaint, lineWidthPx, connectorPath) => {
  if (!(el.connector && lineWidthPx > 0))
    return;
  const metrics = connectorPath ?? buildFallbackConnectorMetrics(el, pres, slide);
  const start = metrics?.start;
  const end = metrics?.end;
  if (!start || !end)
    return;
  const fallbackAngle = Math.atan2(end.y - start.y, end.x - start.x) || 0;
  const endAngle = typeof end.angle === "number" && Number.isFinite(end.angle) ? end.angle : fallbackAngle;
  const startAngle = typeof start.angle === "number" && Number.isFinite(start.angle) ? start.angle : fallbackAngle;
  const drawHead = (tipX, tipY, angleRad, which) => {
    const meta = which === "head" ? el.connector?.lineStyle?.head : el.connector?.lineStyle?.tail;
    if (!meta)
      return;
    const geometry = resolveLineEndGeometry(meta, lineWidthPx);
    if (!geometry)
      return;
    const { type, halfWidthPx: halfW, lengthPx: len } = geometry;
    ctx.save();
    ctx.translate(tipX, tipY);
    ctx.rotate(angleRad);
    ctx.fillStyle = strokePaint;
    ctx.strokeStyle = strokePaint;
    ctx.lineWidth = Math.max(1, lineWidthPx);
    if (type === 5) {
      ctx.beginPath();
      ctx.ellipse(0, 0, halfW, halfW, 0, 0, Math.PI * 2);
      ctx.fill();
    } else if (type === 4) {
      ctx.beginPath();
      ctx.moveTo(0, 0);
      ctx.lineTo(-len / 2, -halfW);
      ctx.lineTo(-len, 0);
      ctx.lineTo(-len / 2, halfW);
      ctx.closePath();
      ctx.fill();
    } else if (type === 6) {
      ctx.save();
      const prevCap = ctx.lineCap;
      const prevJoin = ctx.lineJoin;
      const prevMiter = ctx.miterLimit ?? 10;
      ctx.lineCap = "round";
      ctx.lineJoin = "round";
      ctx.miterLimit = 3.5;
      ctx.beginPath();
      ctx.moveTo(0, 0);
      ctx.lineTo(-len, -halfW);
      ctx.moveTo(0, 0);
      ctx.lineTo(-len, halfW);
      ctx.stroke();
      ctx.lineCap = prevCap;
      ctx.lineJoin = prevJoin;
      ctx.miterLimit = prevMiter;
      ctx.restore();
    } else if (type === 3) {
      const notchX = -stealthNotchDistancePx(len);
      ctx.beginPath();
      ctx.moveTo(0, 0);
      ctx.lineTo(-len, -halfW);
      ctx.lineTo(notchX, 0);
      ctx.lineTo(-len, halfW);
      ctx.closePath();
      ctx.fill();
    } else {
      ctx.beginPath();
      ctx.moveTo(0, 0);
      ctx.lineTo(-len, -halfW);
      ctx.lineTo(-len, halfW);
      ctx.closePath();
      ctx.fill();
    }
    ctx.restore();
  };
  drawHead(start.x, start.y, startAngle + Math.PI, "head");
  drawHead(end.x, end.y, endAngle, "tail");
};
var getConnectorStrokeInsets = (el, lineWidthPx) => {
  const head = resolveLineEndGeometry(el.connector?.lineStyle?.head, lineWidthPx);
  const tail = resolveLineEndGeometry(el.connector?.lineStyle?.tail, lineWidthPx);
  return {
    startPx: head?.strokeInsetPx ?? 0,
    endPx: tail?.strokeInsetPx ?? 0
  };
};
var resolveLineEndGeometry = (meta, lineWidthPx) => {
  if (!meta)
    return;
  const type = meta.type;
  if (!type || type === 1)
    return;
  const wEnum = meta.width;
  const lEnum = meta.length;
  const wK = wEnum === 3 ? 5.5 : wEnum === 2 ? 4.5 : 3.5;
  const lK = lEnum === 3 ? 6.5 : lEnum === 2 ? 5.5 : 4.5;
  const halfWidthPx = wK * lineWidthPx / 2;
  const baseLengthPx = lK * lineWidthPx;
  const lengthPx = type === 3 ? baseLengthPx * 0.72 : baseLengthPx;
  const strokeInsetPx = type === 4 ? lengthPx / 2 : type === 5 ? 0 : type === 6 ? 0 : type === 3 ? stealthNotchDistancePx(lengthPx) : lengthPx;
  return {
    type,
    halfWidthPx,
    lengthPx,
    strokeInsetPx
  };
};
var stealthNotchDistancePx = (lengthPx) => lengthPx * 0.68;
var buildFallbackConnectorMetrics = (el, pres, slide) => {
  const { width, height } = getBBox(el, pres, slide);
  if (width === 0 && height === 0)
    return;
  const horizontal = width >= height;
  if (horizontal) {
    return {
      start: { x: 0, y: height / 2, angle: 0 },
      end: { x: width, y: height / 2, angle: 0 }
    };
  }
  return {
    start: { x: width / 2, y: 0, angle: Math.PI / 2 },
    end: { x: width / 2, y: height, angle: Math.PI / 2 }
  };
};

// node_modules/@oai/granola/dist/models/auto-route/auto-route.js
var OOXML_ANGLE_UNIT = 60000;
var DEFAULT_OPTIONS = {
  clearancePx: 12,
  bendPenaltyPx: 20,
  cornerRadiusPx: 24,
  portStubPx: 24
};
var BENT_MAX_BENDS = {
  [97 /* SHAPE_GEOMETRY_BENT_CONNECTOR2 */]: 1,
  [98 /* SHAPE_GEOMETRY_BENT_CONNECTOR3 */]: 2,
  [99 /* SHAPE_GEOMETRY_BENT_CONNECTOR4 */]: 3,
  [100 /* SHAPE_GEOMETRY_BENT_CONNECTOR5 */]: 4
};
var CURVED_MAX_BENDS = {
  [101 /* SHAPE_GEOMETRY_CURVED_CONNECTOR2 */]: 1,
  [102 /* SHAPE_GEOMETRY_CURVED_CONNECTOR3 */]: 2,
  [103 /* SHAPE_GEOMETRY_CURVED_CONNECTOR4 */]: 3,
  [104 /* SHAPE_GEOMETRY_CURVED_CONNECTOR5 */]: 4
};
var BALANCED_CURVE_CONTROL_DISTANCE_RATIO = 0.38;
var BALANCED_CURVE_NORMAL_WEIGHT = 0.3;
var BALANCED_CURVE_CHORD_WEIGHT = 0.7;
var BALANCED_CURVE_OBSTACLE_SAMPLES = 18;
var MEETING_AXIS_DEVIATION_WEIGHT = 0.5;
function autoRouteConnectorPx(args) {
  const { connectorEl, elements, pres, slide } = args;
  const connMeta = connectorEl.connector;
  if (!connMeta) {
    throw new Error("Connector element is missing connector metadata.");
  }
  const kind = getConnectorKind(connectorEl);
  const options = normalizeOptions(args.options);
  const fromEl = findElementById(elements, connMeta.fromElementId);
  const toEl = findElementById(elements, connMeta.toElementId);
  if (!fromEl || !toEl) {
    throw new Error("Connected elements not found for connector.");
  }
  const fromAnchor = resolveConnectorAnchorPx({
    element: fromEl,
    siteIndex: connMeta.fromIdx,
    pres,
    slide
  });
  const toAnchor = resolveConnectorAnchorPx({
    element: toEl,
    siteIndex: connMeta.toIdx,
    pres,
    slide
  });
  const clearance = Math.max(0, options.clearancePx);
  const portStub = resolvePortStubDistancePx({
    fromAnchor,
    toAnchor,
    clearance,
    requestedPortStubPx: options.portStubPx
  });
  const startStub = offsetPoint(fromAnchor.point, fromAnchor.normal, portStub);
  const endStub = offsetPoint(toAnchor.point, toAnchor.normal, portStub);
  const fromObstacleRect = rotateElementObstacleRect({
    el: fromEl,
    pres,
    slide,
    clearance
  });
  const toObstacleRect = rotateElementObstacleRect({
    el: toEl,
    pres,
    slide,
    clearance
  });
  const meetingPoint = fromObstacleRect && toObstacleRect ? computeMeetingPointFromObstacles(fromObstacleRect, toObstacleRect) : undefined;
  const meetingGuidance = deriveMeetingAxisGuidance({
    fromNormal: fromAnchor.normal,
    toNormal: toAnchor.normal,
    meetingPoint
  });
  const excludeIds = new Set([connectorEl.id]);
  if (fromObstacleRect && (pointInsideElementObstacle(startStub, fromObstacleRect) || pointInsideElementObstacle(endStub, fromObstacleRect))) {
    excludeIds.add(fromEl.id);
  }
  if (toObstacleRect && (pointInsideElementObstacle(startStub, toObstacleRect) || pointInsideElementObstacle(endStub, toObstacleRect))) {
    excludeIds.add(toEl.id);
  }
  const obstacles = buildObstacles({
    elements,
    excludeIds,
    pres,
    slide,
    clearance
  });
  let commands;
  switch (kind) {
    case "straight": {
      commands = straightCommands(fromAnchor.point, toAnchor.point);
      break;
    }
    case "elbow": {
      const maxBends = options.maxBendsOverride ?? BENT_MAX_BENDS[connectorEl.shape?.geometry ?? -1] ?? 4;
      const skeleton = routeOrthogonal({
        start: startStub,
        end: endStub,
        obstacles,
        maxBends,
        bendPenalty: options.bendPenaltyPx,
        preferredStartDir: normalToDirection(fromAnchor.normal),
        preferredEndDir: oppositeDirection(normalToDirection(toAnchor.normal)),
        meetingGuidance
      });
      const polyline = [fromAnchor.point, ...skeleton, toAnchor.point];
      commands = polylineToCommands(polyline);
      break;
    }
    case "curved": {
      const balanced = balancedCurvedConnectorCommands({
        fromAnchor,
        toAnchor,
        obstacles
      });
      if (balanced) {
        commands = balanced;
      } else {
        const maxBends = options.maxBendsOverride ?? CURVED_MAX_BENDS[connectorEl.shape?.geometry ?? -1] ?? 4;
        const skeleton = routeOrthogonal({
          start: startStub,
          end: endStub,
          obstacles,
          maxBends,
          bendPenalty: options.bendPenaltyPx,
          preferredStartDir: normalToDirection(fromAnchor.normal),
          preferredEndDir: oppositeDirection(normalToDirection(toAnchor.normal)),
          meetingGuidance
        });
        const polyline = [fromAnchor.point, ...skeleton, toAnchor.point];
        commands = libreOfficeCurvedPolylineToCommands(polyline);
      }
      break;
    }
    default:
      commands = straightCommands(fromAnchor.point, toAnchor.point);
  }
  return {
    connectorId: connectorEl.id,
    kind,
    commands
  };
}
function normalizeOptions(overrides) {
  return {
    clearancePx: overrides?.clearancePx ?? DEFAULT_OPTIONS.clearancePx,
    bendPenaltyPx: overrides?.bendPenaltyPx ?? DEFAULT_OPTIONS.bendPenaltyPx,
    cornerRadiusPx: overrides?.cornerRadiusPx ?? DEFAULT_OPTIONS.cornerRadiusPx,
    maxBendsOverride: overrides?.maxBendsOverride,
    portStubPx: overrides?.portStubPx ?? DEFAULT_OPTIONS.portStubPx
  };
}
function resolvePortStubDistancePx(params) {
  const { fromAnchor, toAnchor, clearance, requestedPortStubPx } = params;
  const minimumStub = requestedPortStubPx > clearance ? requestedPortStubPx : clearance + 2;
  const startDirection = normalToDirection(fromAnchor.normal);
  const endDirection = normalToDirection(toAnchor.normal);
  const startAxis = directionAxis(startDirection);
  const endAxis = directionAxis(endDirection);
  if (startAxis === "none" || endAxis === "none" || startAxis !== endAxis || !isOppositeDirection(startDirection, endDirection)) {
    return minimumStub;
  }
  const delta = {
    x: toAnchor.point.x - fromAnchor.point.x,
    y: toAnchor.point.y - fromAnchor.point.y
  };
  const startForward = dot(delta, fromAnchor.normal);
  const endForward = dot({ x: -delta.x, y: -delta.y }, toAnchor.normal);
  const availableGap = Math.min(startForward, endForward);
  if (!Number.isFinite(availableGap) || availableGap <= 0) {
    return minimumStub;
  }
  return Math.min(minimumStub, Math.max(clearance, availableGap / 2));
}
function getConnectorKind(element) {
  const geometry = element.shape?.geometry;
  switch (geometry) {
    case 96 /* SHAPE_GEOMETRY_STRAIGHT_CONNECTOR1 */:
      return "straight";
    case 97 /* SHAPE_GEOMETRY_BENT_CONNECTOR2 */:
    case 98 /* SHAPE_GEOMETRY_BENT_CONNECTOR3 */:
    case 99 /* SHAPE_GEOMETRY_BENT_CONNECTOR4 */:
    case 100 /* SHAPE_GEOMETRY_BENT_CONNECTOR5 */:
      return "elbow";
    case 101 /* SHAPE_GEOMETRY_CURVED_CONNECTOR2 */:
    case 102 /* SHAPE_GEOMETRY_CURVED_CONNECTOR3 */:
    case 103 /* SHAPE_GEOMETRY_CURVED_CONNECTOR4 */:
    case 104 /* SHAPE_GEOMETRY_CURVED_CONNECTOR5 */:
      return "curved";
    default:
      return element.connector ? "elbow" : "straight";
  }
}
function findElementById(elements, id) {
  return elements.find((el) => el.id === id);
}
function resolveFallbackConnectionSite(bbox, siteIndex) {
  switch (siteIndex) {
    case 0:
      return {
        localPoint: { x: bbox.width / 2, y: 0 },
        normal: { x: 0, y: -1 }
      };
    case 1:
      return {
        localPoint: { x: 0, y: bbox.height / 2 },
        normal: { x: -1, y: 0 }
      };
    case 2:
      return {
        localPoint: { x: bbox.width / 2, y: bbox.height },
        normal: { x: 0, y: 1 }
      };
    case 3:
      return {
        localPoint: { x: bbox.width, y: bbox.height / 2 },
        normal: { x: 1, y: 0 }
      };
    default:
      return null;
  }
}
function resolveConnectorAnchorPx({ element, siteIndex, pres, slide }) {
  if (!element.shape?.geometry) {
    throw new Error("Connected element is missing a preset geometry.");
  }
  const bbox = getBBox(element, pres, slide);
  const adjustments = buildAdjustmentMap(element);
  const preset = getPresetShapeDefinition(element.shape.geometry);
  const cxn = preset?.cxnLst?.[siteIndex];
  let anchorLocal;
  let localNormal;
  if (preset && cxn) {
    const env = buildEnv(preset, bbox.width, bbox.height, adjustments);
    const localX = resolve(cxn.pos?.x, env);
    const localY = resolve(cxn.pos?.y, env);
    if (!Number.isFinite(localX) || !Number.isFinite(localY)) {
      throw new Error(`Connection site ${siteIndex} has invalid coordinates for geometry ${element.shape.geometry}`);
    }
    anchorLocal = { x: localX, y: localY };
    localNormal = resolveAnchorNormal(cxn, anchorLocal, bbox, env);
  } else {
    const fallback = resolveFallbackConnectionSite(bbox, siteIndex);
    if (!fallback) {
      if (!preset) {
        throw new Error([
          `No preset definition found for geometry ${element.shape.geometry}.`,
          `Connection site ${siteIndex} cannot be resolved without preset metadata.`,
          "Load preset shape definitions with:",
          "  const { installPresetShapeDefinitions } = await import('@oai/granola/plugins/preset-shape-definitions');",
          "  installPresetShapeDefinitions();"
        ].join(`
`));
      }
      throw new Error(`Connection site ${siteIndex} is not defined for geometry ${element.shape.geometry}`);
    }
    anchorLocal = fallback.localPoint;
    localNormal = fallback.normal;
  }
  const { point: point3, normal } = transformAnchorPoint({
    element,
    bbox,
    local: anchorLocal,
    normal: localNormal
  });
  const center = {
    x: bbox.x + bbox.width / 2,
    y: bbox.y + bbox.height / 2
  };
  return {
    siteIndex,
    point: point3,
    localPoint: anchorLocal,
    normal,
    shapeCenter: center
  };
}
function buildAdjustmentMap(element) {
  const adjustments = {};
  const entries = element.shape?.adjustmentList ?? [];
  for (const adj of entries) {
    if (adj?.name && adj.formula) {
      adjustments[adj.name] = adj.formula;
    }
  }
  return adjustments;
}
function resolveAnchorNormal(cxn, anchorLocal, bbox, env) {
  const resolvedAng = cxn.ang ? resolve(cxn.ang, env) : undefined;
  if (typeof resolvedAng === "number" && Number.isFinite(resolvedAng)) {
    const rad = ooxmlAngleToRadians(resolvedAng);
    return normalizeVector({
      x: Math.cos(rad),
      y: Math.sin(rad)
    });
  }
  const leftDist = anchorLocal.x;
  const rightDist = bbox.width - anchorLocal.x;
  const topDist = anchorLocal.y;
  const bottomDist = bbox.height - anchorLocal.y;
  const minDist = Math.min(leftDist, rightDist, topDist, bottomDist);
  if (minDist === leftDist)
    return { x: -1, y: 0 };
  if (minDist === rightDist)
    return { x: 1, y: 0 };
  if (minDist === topDist)
    return { x: 0, y: -1 };
  return { x: 0, y: 1 };
}
function transformAnchorPoint({ element, bbox, local, normal }) {
  const halfW = bbox.width / 2;
  const halfH = bbox.height / 2;
  let dx = local.x - halfW;
  let dy = local.y - halfH;
  let nx = normal.x;
  let ny = normal.y;
  const flipH = Boolean(element.bbox?.horizontalFlip);
  const flipV = Boolean(element.bbox?.verticalFlip);
  if (flipH) {
    dx = -dx;
    nx = -nx;
  }
  if (flipV) {
    dy = -dy;
    ny = -ny;
  }
  const theta = emuRotationToRadians(element.bbox?.rotation ?? 0);
  if (theta !== 0) {
    ({ x: dx, y: dy } = rotate(dx, dy, theta));
    ({ x: nx, y: ny } = rotate(nx, ny, theta));
  }
  const point3 = {
    x: bbox.x + halfW + dx,
    y: bbox.y + halfH + dy
  };
  const normalWorld = normalizeVector({ x: nx, y: ny });
  return { point: point3, normal: normalWorld };
}
function rotate(x2, y2, theta) {
  const cos2 = Math.cos(theta);
  const sin2 = Math.sin(theta);
  return {
    x: x2 * cos2 - y2 * sin2,
    y: x2 * sin2 + y2 * cos2
  };
}
function normalizeVector(vec) {
  const mag = Math.hypot(vec.x, vec.y);
  if (!mag)
    return { x: 0, y: 0 };
  return { x: vec.x / mag, y: vec.y / mag };
}
function offsetPoint(point3, normal, distance) {
  return {
    x: point3.x + normal.x * distance,
    y: point3.y + normal.y * distance
  };
}
function ooxmlAngleToRadians(value) {
  return value / OOXML_ANGLE_UNIT * Math.PI / 180;
}
function buildObstacles(params) {
  const { elements, excludeIds, pres, slide, clearance } = params;
  const obstacles = [];
  for (const el of elements) {
    if (!el || excludeIds.has(el.id)) {
      continue;
    }
    const rect = elementObstacleRect({
      el,
      pres,
      slide,
      clearance
    });
    if (rect) {
      obstacles.push({ ...rect, id: el.id });
    }
  }
  return obstacles;
}
function elementObstacleRect({ el, pres, slide, clearance }) {
  if (el.type !== 5 /* ELEMENT_TYPE_SHAPE */ || el.connector || isBackgroundShape(el, pres, slide)) {
    return null;
  }
  return rotateElementObstacleRect({
    el,
    pres,
    slide,
    clearance
  });
}
function rotateElementObstacleRect({ el, pres, slide, clearance }) {
  const bbox = getBBox(el, pres, slide);
  if (!bbox.width || !bbox.height) {
    return null;
  }
  const rect = rotateRect({
    x: bbox.x,
    y: bbox.y,
    width: bbox.width,
    height: bbox.height,
    rotation: emuRotationToRadians(el.bbox?.rotation ?? 0)
  });
  return inflateRect(rect, clearance);
}
function isBackgroundShape(element, pres, slide) {
  if (/^bg[._-]/i.test(element.id)) {
    return true;
  }
  const frame = slide.frame;
  if (!frame) {
    return false;
  }
  const bbox = getBBox(element, pres, slide);
  const tolerance = 1;
  return Math.abs(bbox.x - frame.left) <= tolerance && Math.abs(bbox.y - frame.top) <= tolerance && Math.abs(bbox.width - frame.width) <= tolerance && Math.abs(bbox.height - frame.height) <= tolerance;
}
function pointInsideElementObstacle(point3, rect) {
  return point3.x > rect.minX && point3.x < rect.maxX && point3.y > rect.minY && point3.y < rect.maxY;
}
function computeMeetingPointFromObstacles(a, b) {
  return {
    x: computeMeetingAxisValue(a.minX, a.maxX, b.minX, b.maxX),
    y: computeMeetingAxisValue(a.minY, a.maxY, b.minY, b.maxY)
  };
}
function computeMeetingAxisValue(aMin, aMax, bMin, bMax) {
  const overlapMin = Math.max(aMin, bMin);
  const overlapMax = Math.min(aMax, bMax);
  if (overlapMin <= overlapMax) {
    return (overlapMin + overlapMax) / 2;
  }
  const aCenter = (aMin + aMax) / 2;
  const bCenter = (bMin + bMax) / 2;
  if (aCenter <= bCenter) {
    return (aMax + bMin) / 2;
  }
  return (bMax + aMin) / 2;
}
function deriveMeetingAxisGuidance(params) {
  const { fromNormal, toNormal, meetingPoint } = params;
  if (!meetingPoint) {
    return;
  }
  const fromDirection = normalToDirection(fromNormal);
  const toDirection = normalToDirection(toNormal);
  const fromVertical = fromDirection === "up" || fromDirection === "down";
  const toVertical = toDirection === "up" || toDirection === "down";
  if (fromVertical && toVertical) {
    return { preferredMeetingY: meetingPoint.y };
  }
  const fromHorizontal = fromDirection === "left" || fromDirection === "right";
  const toHorizontal = toDirection === "left" || toDirection === "right";
  if (fromHorizontal && toHorizontal) {
    return { preferredMeetingX: meetingPoint.x };
  }
  return;
}
function rotateRect({ x: x2, y: y2, width, height, rotation }) {
  if (rotation === 0) {
    return { minX: x2, minY: y2, maxX: x2 + width, maxY: y2 + height };
  }
  const cx = x2 + width / 2;
  const cy = y2 + height / 2;
  const corners = [
    { x: x2 - cx, y: y2 - cy },
    { x: x2 + width - cx, y: y2 - cy },
    { x: x2 + width - cx, y: y2 + height - cy },
    { x: x2 - cx, y: y2 + height - cy }
  ];
  const rotated = corners.map((corner) => rotate(corner.x, corner.y, rotation));
  let minX = Number.POSITIVE_INFINITY;
  let maxX = Number.NEGATIVE_INFINITY;
  let minY = Number.POSITIVE_INFINITY;
  let maxY = Number.NEGATIVE_INFINITY;
  for (const c of rotated) {
    const absX = c.x + cx;
    const absY = c.y + cy;
    minX = Math.min(minX, absX);
    maxX = Math.max(maxX, absX);
    minY = Math.min(minY, absY);
    maxY = Math.max(maxY, absY);
  }
  return { minX, minY, maxX, maxY };
}
function inflateRect(rect, amount) {
  if (!amount)
    return rect;
  return {
    minX: rect.minX - amount,
    minY: rect.minY - amount,
    maxX: rect.maxX + amount,
    maxY: rect.maxY + amount
  };
}
function straightCommands(start, end) {
  return [
    { cmd: "moveTo", x: start.x, y: start.y },
    { cmd: "lineTo", x: end.x, y: end.y }
  ];
}
function polylineToCommands(points) {
  const deduped = dedupePoints(points);
  if (deduped.length < 2) {
    return [];
  }
  const first = deduped[0];
  if (!first)
    return [];
  const commands = [{ cmd: "moveTo", x: first.x, y: first.y }];
  for (let i = 1;i < deduped.length; i += 1) {
    const point3 = deduped[i];
    if (!point3)
      continue;
    commands.push({ cmd: "lineTo", x: point3.x, y: point3.y });
  }
  return commands;
}
function balancedCurvedConnectorCommands(params) {
  const { fromAnchor, toAnchor, obstacles } = params;
  const start = fromAnchor.point;
  const end = toAnchor.point;
  const delta = {
    x: end.x - start.x,
    y: end.y - start.y
  };
  const distance = Math.hypot(delta.x, delta.y);
  if (distance <= 0.001) {
    return;
  }
  const chordDirection = {
    x: delta.x / distance,
    y: delta.y / distance
  };
  const startDirection = balancedCurveTangentDirection(fromAnchor.normal, chordDirection);
  const endDirection = balancedCurveTangentDirection({ x: -toAnchor.normal.x, y: -toAnchor.normal.y }, chordDirection);
  const controlDistance = balancedCurveControlDistance({
    delta,
    distance,
    startDirection,
    endDirection
  });
  const cubic = {
    cmd: "cubicBezTo",
    x1: start.x + startDirection.x * controlDistance,
    y1: start.y + startDirection.y * controlDistance,
    x2: end.x - endDirection.x * controlDistance,
    y2: end.y - endDirection.y * controlDistance,
    x: end.x,
    y: end.y
  };
  if (!cubicAvoidsObstacles(start, cubic, obstacles)) {
    return;
  }
  return [{ cmd: "moveTo", x: start.x, y: start.y }, cubic];
}
function balancedCurveTangentDirection(normal, chordDirection) {
  const weighted = {
    x: normal.x * BALANCED_CURVE_NORMAL_WEIGHT + chordDirection.x * BALANCED_CURVE_CHORD_WEIGHT,
    y: normal.y * BALANCED_CURVE_NORMAL_WEIGHT + chordDirection.y * BALANCED_CURVE_CHORD_WEIGHT
  };
  const resolved = normalizeVector(weighted);
  if (Math.hypot(resolved.x, resolved.y) > 0) {
    return resolved;
  }
  return chordDirection;
}
function balancedCurveControlDistance(params) {
  const { delta, distance, startDirection, endDirection } = params;
  let controlDistance = distance * BALANCED_CURVE_CONTROL_DISTANCE_RATIO;
  const xLimit = balancedCurveAxisControlLimit(delta.x, startDirection.x, endDirection.x);
  if (xLimit !== undefined) {
    controlDistance = Math.min(controlDistance, xLimit);
  }
  const yLimit = balancedCurveAxisControlLimit(delta.y, startDirection.y, endDirection.y);
  if (yLimit !== undefined) {
    controlDistance = Math.min(controlDistance, yLimit);
  }
  return controlDistance;
}
function balancedCurveAxisControlLimit(axisDelta, startAxisDirection, endAxisDirection) {
  if (Math.abs(axisDelta) <= 0.001) {
    return;
  }
  if (axisDelta * startAxisDirection <= 0 || axisDelta * endAxisDirection <= 0) {
    return;
  }
  const combinedDirection = Math.abs(startAxisDirection) + Math.abs(endAxisDirection);
  if (combinedDirection <= 0.001) {
    return;
  }
  return Math.abs(axisDelta) / combinedDirection * 0.9;
}
function cubicAvoidsObstacles(start, command, obstacles) {
  if (obstacles.length === 0) {
    return true;
  }
  for (let i = 1;i < BALANCED_CURVE_OBSTACLE_SAMPLES; i += 1) {
    const point3 = cubicRoutePoint(start, command, i / BALANCED_CURVE_OBSTACLE_SAMPLES);
    if (pointInsideAnyObstacle(point3.x, point3.y, obstacles)) {
      return false;
    }
  }
  return true;
}
function cubicRoutePoint(start, command, t) {
  const mt = 1 - t;
  const mt2 = mt * mt;
  const t2 = t * t;
  return {
    x: start.x * mt2 * mt + 3 * command.x1 * mt2 * t + 3 * command.x2 * mt * t2 + command.x * t * t2,
    y: start.y * mt2 * mt + 3 * command.y1 * mt2 * t + 3 * command.y2 * mt * t2 + command.y * t * t2
  };
}
function libreOfficeCurvedPolylineToCommands(points) {
  const deduped = dedupePoints(points);
  if (deduped.length <= 2) {
    return polylineToCommands(deduped);
  }
  const first = deduped[0];
  if (!first)
    return [];
  if (deduped.length === 3) {
    const bend = deduped[1];
    const end = deduped[2];
    if (!bend || !end)
      return [];
    return [
      { cmd: "moveTo", x: first.x, y: first.y },
      {
        cmd: "cubicBezTo",
        x1: bend.x - (bend.x - first.x) / 3,
        y1: bend.y - (bend.y - first.y) / 3,
        x2: bend.x - (bend.x - end.x) / 3,
        y2: bend.y - (bend.y - end.y) / 3,
        x: end.x,
        y: end.y
      }
    ];
  }
  const last = deduped[deduped.length - 1];
  const firstBend = deduped[1];
  const lastBend = deduped[deduped.length - 2];
  if (!last || !firstBend || !lastBend)
    return [];
  const firstControl = extendPoint(firstBend, first, 0.5);
  const lastControl = extendPoint(lastBend, last, 0.5);
  const commands = [{ cmd: "moveTo", x: first.x, y: first.y }];
  if (deduped.length === 4) {
    commands.push({
      cmd: "cubicBezTo",
      x1: firstControl.x,
      y1: firstControl.y,
      x2: lastControl.x,
      y2: lastControl.y,
      x: last.x,
      y: last.y
    });
    return commands;
  }
  if (deduped.length === 5) {
    const center = deduped[2];
    if (!center)
      return commands;
    const controlBeforeCenter = midpoint(firstControl, center);
    const centerPoint = {
      x: center.x - (center.x - firstControl.x + (center.x - lastControl.x)) / 4,
      y: center.y - (center.y - firstControl.y + (center.y - lastControl.y)) / 4
    };
    const controlAfterCenter = midpoint(lastControl, center);
    commands.push({
      cmd: "cubicBezTo",
      x1: firstControl.x,
      y1: firstControl.y,
      x2: controlBeforeCenter.x,
      y2: controlBeforeCenter.y,
      x: centerPoint.x,
      y: centerPoint.y
    });
    commands.push({
      cmd: "cubicBezTo",
      x1: controlAfterCenter.x,
      y1: controlAfterCenter.y,
      x2: lastControl.x,
      y2: lastControl.y,
      x: last.x,
      y: last.y
    });
    return commands;
  }
  if (deduped.length === 6) {
    const centerStart = deduped[2];
    const centerEnd = deduped[3];
    if (!centerStart || !centerEnd)
      return commands;
    const center = midpoint(centerStart, centerEnd);
    commands.push({
      cmd: "cubicBezTo",
      x1: firstControl.x,
      y1: firstControl.y,
      x2: centerStart.x,
      y2: centerStart.y,
      x: center.x,
      y: center.y
    });
    commands.push({
      cmd: "cubicBezTo",
      x1: centerEnd.x,
      y1: centerEnd.y,
      x2: lastControl.x,
      y2: lastControl.y,
      x: last.x,
      y: last.y
    });
    return commands;
  }
  return ooxmlCurvedPolylineToCommands(deduped);
}
function ooxmlCurvedPolylineToCommands(points) {
  const deduped = dedupePoints(points);
  if (deduped.length <= 2) {
    return polylineToCommands(deduped);
  }
  const first = deduped[0];
  if (!first)
    return [];
  const commands = [{ cmd: "moveTo", x: first.x, y: first.y }];
  const lastIndex = deduped.length - 1;
  if (deduped.length === 3) {
    const end = deduped[2];
    if (!end)
      return commands;
    const control1 = pointOnSegment(deduped, 1, 0.5);
    const control2 = pointOnSegment(deduped, 2, 0.5);
    commands.push({
      cmd: "cubicBezTo",
      x1: control1.x,
      y1: control1.y,
      x2: control2.x,
      y2: control2.y,
      x: end.x,
      y: end.y
    });
    return commands;
  }
  const firstControl1 = pointOnSegment(deduped, 1, 0.5);
  const firstControl2 = pointOnSegment(deduped, 2, 0.25);
  const firstCurveEnd = pointOnSegment(deduped, 2, 0.5);
  commands.push({
    cmd: "cubicBezTo",
    x1: firstControl1.x,
    y1: firstControl1.y,
    x2: firstControl2.x,
    y2: firstControl2.y,
    x: firstCurveEnd.x,
    y: firstCurveEnd.y
  });
  for (let segmentEnd = 3;segmentEnd <= lastIndex - 1; segmentEnd += 1) {
    const control1 = pointOnSegment(deduped, segmentEnd - 1, 0.75);
    const control2 = pointOnSegment(deduped, segmentEnd, 0.25);
    const end = pointOnSegment(deduped, segmentEnd, 0.5);
    commands.push({
      cmd: "cubicBezTo",
      x1: control1.x,
      y1: control1.y,
      x2: control2.x,
      y2: control2.y,
      x: end.x,
      y: end.y
    });
  }
  const finalPoint = deduped[lastIndex];
  if (!finalPoint)
    return commands;
  const finalControl1 = pointOnSegment(deduped, lastIndex - 1, 0.75);
  const finalControl2 = pointOnSegment(deduped, lastIndex, 0.5);
  commands.push({
    cmd: "cubicBezTo",
    x1: finalControl1.x,
    y1: finalControl1.y,
    x2: finalControl2.x,
    y2: finalControl2.y,
    x: finalPoint.x,
    y: finalPoint.y
  });
  return commands;
}
function extendPoint(point3, anchor, factor) {
  return {
    x: point3.x + (point3.x - anchor.x) * factor,
    y: point3.y + (point3.y - anchor.y) * factor
  };
}
function midpoint(a, b) {
  return {
    x: (a.x + b.x) / 2,
    y: (a.y + b.y) / 2
  };
}
function pointOnSegment(points, endIndex, factor) {
  const start = points[endIndex - 1];
  const end = points[endIndex];
  if (!start || !end) {
    throw new Error(`Curved connector segment ${endIndex} is missing a point.`);
  }
  return {
    x: start.x + factor * (end.x - start.x),
    y: start.y + factor * (end.y - start.y)
  };
}
function dedupePoints(points) {
  const deduped = [];
  for (const point3 of points) {
    const last = deduped[deduped.length - 1];
    if (last && almostEqualPoints(last, point3)) {
      continue;
    }
    deduped.push(point3);
  }
  return deduped;
}
function almostEqualPoints(a, b) {
  return Math.abs(a.x - b.x) < 0.0001 && Math.abs(a.y - b.y) < 0.0001;
}
function routeOrthogonal(params) {
  const { start, end, obstacles, maxBends, bendPenalty, preferredStartDir, preferredEndDir, meetingGuidance } = params;
  const simpleRoute = trySimpleOrthogonalRoute({
    start,
    end,
    obstacles,
    preferredStartDir,
    preferredEndDir,
    meetingGuidance
  });
  if (simpleRoute) {
    return simpleRoute;
  }
  const nodes = buildGridNodes(start, end, obstacles, meetingGuidance);
  const adjacency = buildAdjacency(nodes, obstacles);
  const startKey = pointKey(start);
  const endKey = pointKey(end);
  const startIndex = nodes.findIndex((node) => node.key === startKey);
  const endIndex = nodes.findIndex((node) => node.key === endKey);
  if (startIndex < 0 || endIndex < 0) {
    throw new Error("Failed to seed orthogonal routing nodes.");
  }
  const startNode = nodes[startIndex];
  const endNode = nodes[endIndex];
  if (!startNode || !endNode) {
    throw new Error("Failed to seed routing endpoints.");
  }
  const open = [];
  const cameFrom = new Map;
  const gScores = new Map;
  const startState = {
    node: startIndex,
    dir: "none",
    bends: 0,
    g: 0,
    f: manhattan(startNode, endNode),
    pathLen: 0
  };
  open.push(startState);
  gScores.set(stateKey(startState), 0);
  while (open.length > 0) {
    open.sort((a, b) => a.f - b.f || a.bends - b.bends || a.g - b.g || a.pathLen - b.pathLen);
    const current = open.shift();
    if (current.node === endIndex) {
      return reconstructPath({
        nodes,
        cameFrom,
        state: current
      });
    }
    const currentKey = stateKey(current);
    const currentNode = nodes[current.node];
    if (!currentNode) {
      continue;
    }
    const neighbors = adjacency.get(currentNode.key) ?? [];
    for (const neighbor of neighbors) {
      const neighborNode = nodes[neighbor.index];
      if (!neighborNode)
        continue;
      const nextDir = directionBetween(currentNode, neighborNode);
      if (nextDir === "none")
        continue;
      const bends = current.dir === "none" || current.dir === nextDir ? current.bends : current.bends + 1;
      if (bends > maxBends)
        continue;
      const distance = Math.hypot(neighborNode.x - currentNode.x, neighborNode.y - currentNode.y);
      const bendPenaltyCost = bends > current.bends ? bendPenalty : 0;
      const startAlignmentPenalty = current.dir === "none" && preferredStartDir !== "none" && isOppositeDirection(nextDir, preferredStartDir) ? bendPenalty * 2 : 0;
      const endAlignmentPenalty = neighbor.index === endIndex && preferredEndDir !== "none" && isOppositeDirection(nextDir, preferredEndDir) ? bendPenalty * 2 : 0;
      const centerlineDeviationPenalty = meetingAxisPenalty({
        currentNode,
        nextNode: neighborNode,
        nextDir,
        currentIndex: current.node,
        nextIndex: neighbor.index,
        startIndex,
        endIndex,
        meetingGuidance
      });
      const tentativeG = current.g + distance + bendPenaltyCost + startAlignmentPenalty + endAlignmentPenalty + centerlineDeviationPenalty;
      const neighborState = {
        node: neighbor.index,
        dir: nextDir,
        bends,
        g: tentativeG,
        f: tentativeG + manhattan(neighborNode, endNode),
        pathLen: current.pathLen + 1
      };
      const neighborKey = stateKey(neighborState);
      if (tentativeG < (gScores.get(neighborKey) ?? Number.POSITIVE_INFINITY)) {
        cameFrom.set(neighborKey, {
          prevKey: currentKey,
          node: current.node,
          dir: current.dir
        });
        gScores.set(neighborKey, tentativeG);
        open.push(neighborState);
      }
    }
  }
  throw new Error("Failed to compute orthogonal route.");
}
function trySimpleOrthogonalRoute(params) {
  const { start, end, obstacles, preferredStartDir, preferredEndDir, meetingGuidance } = params;
  const centeredRoute = buildCenteredMeetingRoute({
    start,
    end,
    preferredStartDir,
    preferredEndDir,
    meetingGuidance
  });
  if (centeredRoute) {
    const simplified = dedupePoints(centeredRoute);
    if (simplified.length >= 2 && isOrthogonalPolyline(simplified) && isOrthogonalPolylineClear(simplified, obstacles)) {
      return simplified;
    }
  }
  const candidates = [
    [start, end],
    [start, { x: end.x, y: start.y }, end],
    [start, { x: start.x, y: end.y }, end]
  ];
  let best;
  for (const candidate of candidates) {
    const simplified = dedupePoints(candidate);
    if (simplified.length < 2 || !isOrthogonalPolyline(simplified)) {
      continue;
    }
    if (!isOrthogonalPolylineClear(simplified, obstacles)) {
      continue;
    }
    const score = scoreSimpleOrthogonalRoute({
      points: simplified,
      preferredStartDir,
      preferredEndDir
    });
    if (!best || score < best.score) {
      best = {
        points: simplified,
        score
      };
    }
  }
  return best?.points;
}
function buildCenteredMeetingRoute(params) {
  const { start, end, preferredStartDir, preferredEndDir, meetingGuidance } = params;
  if (!meetingGuidance || preferredStartDir !== preferredEndDir) {
    return;
  }
  if (directionAxis(preferredStartDir) === "horizontal" && meetingGuidance.preferredMeetingX !== undefined) {
    const x2 = meetingGuidance.preferredMeetingX;
    return [start, { x: x2, y: start.y }, { x: x2, y: end.y }, end];
  }
  if (directionAxis(preferredStartDir) === "vertical" && meetingGuidance.preferredMeetingY !== undefined) {
    const y2 = meetingGuidance.preferredMeetingY;
    return [start, { x: start.x, y: y2 }, { x: end.x, y: y2 }, end];
  }
  return;
}
function isOrthogonalPolyline(points) {
  for (let i = 1;i < points.length; i += 1) {
    if (directionBetween(points[i - 1], points[i]) === "none") {
      return false;
    }
  }
  return true;
}
function isOrthogonalPolylineClear(points, obstacles) {
  for (let i = 1;i < points.length; i += 1) {
    if (!isOrthogonalSegmentClear(points[i - 1], points[i], obstacles)) {
      return false;
    }
  }
  return true;
}
function isOrthogonalSegmentClear(from, to, obstacles) {
  const start = { x: from.x, y: from.y, key: pointKey(from) };
  const end = { x: to.x, y: to.y, key: pointKey(to) };
  if (from.x === to.x) {
    return !verticalSegmentBlocked(start, end, obstacles);
  }
  if (from.y === to.y) {
    return !horizontalSegmentBlocked(start, end, obstacles);
  }
  return false;
}
function scoreSimpleOrthogonalRoute(params) {
  const { points, preferredStartDir, preferredEndDir } = params;
  let length = 0;
  let bends = 0;
  let previousDirection = "none";
  for (let i = 1;i < points.length; i += 1) {
    const from = points[i - 1];
    const to = points[i];
    const direction = directionBetween(from, to);
    if (direction === "none") {
      continue;
    }
    length += manhattan(from, to);
    if (previousDirection !== "none" && direction !== previousDirection) {
      bends += 1;
    }
    previousDirection = direction;
  }
  const firstDirection = directionBetween(points[0], points[1]);
  const lastDirection = directionBetween(points[points.length - 2], points[points.length - 1]);
  const startPenalty = preferredStartDir !== "none" && isOppositeDirection(firstDirection, preferredStartDir) ? 500 : 0;
  const endPenalty = preferredEndDir !== "none" && isOppositeDirection(lastDirection, preferredEndDir) ? 500 : 0;
  return bends * 1000 + length + startPenalty + endPenalty;
}
function meetingAxisPenalty(params) {
  const { currentNode, nextNode, nextDir, currentIndex, nextIndex, startIndex, endIndex, meetingGuidance } = params;
  if (!meetingGuidance) {
    return 0;
  }
  if (currentIndex === startIndex || currentIndex === endIndex || nextIndex === startIndex || nextIndex === endIndex) {
    return 0;
  }
  if ((nextDir === "up" || nextDir === "down") && meetingGuidance.preferredMeetingX !== undefined) {
    const deviation = Math.abs(currentNode.x - meetingGuidance.preferredMeetingX) + Math.abs(nextNode.x - meetingGuidance.preferredMeetingX);
    return deviation * 0.5 * MEETING_AXIS_DEVIATION_WEIGHT;
  }
  if ((nextDir === "left" || nextDir === "right") && meetingGuidance.preferredMeetingY !== undefined) {
    const deviation = Math.abs(currentNode.y - meetingGuidance.preferredMeetingY) + Math.abs(nextNode.y - meetingGuidance.preferredMeetingY);
    return deviation * 0.5 * MEETING_AXIS_DEVIATION_WEIGHT;
  }
  return 0;
}
function buildGridNodes(start, end, obstacles, meetingGuidance) {
  const xs = new Set([start.x, end.x]);
  const ys = new Set([start.y, end.y]);
  if (meetingGuidance?.preferredMeetingX !== undefined) {
    xs.add(meetingGuidance.preferredMeetingX);
  }
  if (meetingGuidance?.preferredMeetingY !== undefined) {
    ys.add(meetingGuidance.preferredMeetingY);
  }
  for (const obs of obstacles) {
    xs.add(obs.minX);
    xs.add(obs.maxX);
    ys.add(obs.minY);
    ys.add(obs.maxY);
  }
  const sortedX = [...xs].sort((a, b) => a - b);
  const sortedY = [...ys].sort((a, b) => a - b);
  const nodes = [];
  for (const x2 of sortedX) {
    for (const y2 of sortedY) {
      const isEndpoint = isSamePoint({ x: x2, y: y2 }, start) || isSamePoint({ x: x2, y: y2 }, end);
      if (!isEndpoint && pointInsideAnyObstacle(x2, y2, obstacles)) {
        continue;
      }
      nodes.push({ x: x2, y: y2, key: pointKey({ x: x2, y: y2 }) });
    }
  }
  return nodes;
}
function buildAdjacency(nodes, obstacles) {
  const adjacency = new Map;
  const indexByKey = new Map;
  nodes.forEach((node, idx) => {
    adjacency.set(node.key, []);
    indexByKey.set(node.key, idx);
  });
  const nodesByX = new Map;
  const nodesByY = new Map;
  nodes.forEach((node) => {
    if (!nodesByX.has(node.x))
      nodesByX.set(node.x, []);
    nodesByX.get(node.x).push(node);
    if (!nodesByY.has(node.y))
      nodesByY.set(node.y, []);
    nodesByY.get(node.y).push(node);
  });
  nodesByX.forEach((column) => {
    column.sort((a, b) => a.y - b.y);
    for (let i = 0;i < column.length - 1; i += 1) {
      const current = column[i];
      const next = column[i + 1];
      if (!current || !next)
        continue;
      if (verticalSegmentBlocked(current, next, obstacles))
        continue;
      link(adjacency, indexByKey, current, next);
      link(adjacency, indexByKey, next, current);
    }
  });
  nodesByY.forEach((row) => {
    row.sort((a, b) => a.x - b.x);
    for (let i = 0;i < row.length - 1; i += 1) {
      const current = row[i];
      const next = row[i + 1];
      if (!current || !next)
        continue;
      if (horizontalSegmentBlocked(current, next, obstacles))
        continue;
      link(adjacency, indexByKey, current, next);
      link(adjacency, indexByKey, next, current);
    }
  });
  return adjacency;
}
function link(adjacency, indexByKey, from, to) {
  const targetIndex = indexByKey.get(to.key);
  if (targetIndex === undefined)
    return;
  const list = adjacency.get(from.key);
  if (!list)
    return;
  if (!list.some((entry) => entry.index === targetIndex)) {
    list.push({ index: targetIndex });
  }
}
function verticalSegmentBlocked(a, b, obstacles) {
  if (a.x !== b.x) {
    return true;
  }
  const minY = Math.min(a.y, b.y);
  const maxY = Math.max(a.y, b.y);
  for (const rect of obstacles) {
    if (a.x <= rect.minX || a.x >= rect.maxX)
      continue;
    if (maxY <= rect.minY || minY >= rect.maxY)
      continue;
    return true;
  }
  return false;
}
function horizontalSegmentBlocked(a, b, obstacles) {
  if (a.y !== b.y) {
    return true;
  }
  const minX = Math.min(a.x, b.x);
  const maxX = Math.max(a.x, b.x);
  for (const rect of obstacles) {
    if (a.y <= rect.minY || a.y >= rect.maxY)
      continue;
    if (maxX <= rect.minX || minX >= rect.maxX)
      continue;
    return true;
  }
  return false;
}
function pointInsideAnyObstacle(x2, y2, obstacles) {
  return obstacles.some((rect) => x2 > rect.minX && x2 < rect.maxX && y2 > rect.minY && y2 < rect.maxY);
}
function directionBetween(a, b) {
  if (a.x === b.x) {
    return b.y > a.y ? "down" : "up";
  }
  if (a.y === b.y) {
    return b.x > a.x ? "right" : "left";
  }
  return "none";
}
function manhattan(a, b) {
  return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
}
function stateKey(state) {
  return `${state.node}:${state.dir}:${state.bends}`;
}
function pointKey(point3) {
  return `${point3.x}|${point3.y}`;
}
function normalToDirection(normal) {
  const absX = Math.abs(normal.x);
  const absY = Math.abs(normal.y);
  if (absX < 0.000001 && absY < 0.000001) {
    return "none";
  }
  if (absX >= absY) {
    return normal.x >= 0 ? "right" : "left";
  }
  return normal.y >= 0 ? "down" : "up";
}
function oppositeDirection(direction) {
  switch (direction) {
    case "up":
      return "down";
    case "down":
      return "up";
    case "left":
      return "right";
    case "right":
      return "left";
    default:
      return "none";
  }
}
function isOppositeDirection(a, b) {
  return a !== "none" && b !== "none" && oppositeDirection(a) === b;
}
function isSamePoint(a, b) {
  return Math.abs(a.x - b.x) < 0.0001 && Math.abs(a.y - b.y) < 0.0001;
}
function directionAxis(direction) {
  if (direction === "left" || direction === "right") {
    return "horizontal";
  }
  if (direction === "up" || direction === "down") {
    return "vertical";
  }
  return "none";
}
function dot(a, b) {
  return a.x * b.x + a.y * b.y;
}
function reconstructPath({ nodes, cameFrom, state }) {
  const indices = [state.node];
  let cursorKey = stateKey(state);
  while (cameFrom.has(cursorKey)) {
    const prev = cameFrom.get(cursorKey);
    indices.push(prev.node);
    if (!prev.prevKey)
      break;
    cursorKey = prev.prevKey;
  }
  return indices.reverse().map((index) => {
    const node = nodes[index];
    if (!node) {
      throw new Error("Route reconstruction failed.");
    }
    return { x: node.x, y: node.y };
  });
}

// node_modules/@oai/granola/dist/draw-utils/shadow-utils.js
var OOXML_ANGLE_PER_DEG = 60000;
function shadowDirectionToOffsetPx(direction, distancePx) {
  const safeDistance = Number.isFinite(distancePx) ? distancePx : 0;
  if (safeDistance === 0) {
    return { x: 0, y: 0 };
  }
  const raw = typeof direction === "number" && Number.isFinite(direction) ? direction : 0;
  const degrees = raw / OOXML_ANGLE_PER_DEG;
  const radians = degrees * Math.PI / 180;
  return {
    x: safeDistance * Math.cos(radians),
    y: safeDistance * Math.sin(radians)
  };
}

// node_modules/@oai/granola/dist/draw-utils/draw-shape.util.js
function buildCustomPathMetrics(commands, scaleX, scaleY) {
  let startPoint;
  let startAngle;
  let endPoint;
  let endAngle;
  let cursor;
  for (const command of commands) {
    if (command.moveTo) {
      const x2 = Number(command.moveTo.x ?? 0) * EMU_TO_PX * scaleX;
      const y2 = Number(command.moveTo.y ?? 0) * EMU_TO_PX * scaleY;
      cursor = { x: x2, y: y2 };
      if (!startPoint) {
        startPoint = { ...cursor };
      }
      continue;
    }
    if (command.lineTo && cursor) {
      const x2 = Number(command.lineTo.x ?? cursor.x) * EMU_TO_PX * scaleX;
      const y2 = Number(command.lineTo.y ?? cursor.y) * EMU_TO_PX * scaleY;
      const angle = Math.atan2(y2 - cursor.y, x2 - cursor.x);
      if (startPoint && startAngle === undefined) {
        startAngle = angle;
      }
      cursor = { x: x2, y: y2 };
      endPoint = { ...cursor };
      endAngle = angle;
      continue;
    }
    if (command.quadBezTo && cursor) {
      const x1 = Number(command.quadBezTo.x1 ?? cursor.x) * EMU_TO_PX * scaleX;
      const y1 = Number(command.quadBezTo.y1 ?? cursor.y) * EMU_TO_PX * scaleY;
      const x2 = Number(command.quadBezTo.x ?? cursor.x) * EMU_TO_PX * scaleX;
      const y2 = Number(command.quadBezTo.y ?? cursor.y) * EMU_TO_PX * scaleY;
      const angle = Math.atan2(y1 - cursor.y, x1 - cursor.x);
      if (startPoint && startAngle === undefined) {
        startAngle = angle;
      }
      cursor = { x: x2, y: y2 };
      endPoint = { ...cursor };
      endAngle = Math.atan2(y2 - y1, x2 - x1);
      continue;
    }
    if (command.cubicBezTo && cursor) {
      const x1 = Number(command.cubicBezTo.x1 ?? cursor.x) * EMU_TO_PX * scaleX;
      const y1 = Number(command.cubicBezTo.y1 ?? cursor.y) * EMU_TO_PX * scaleY;
      const x2 = Number(command.cubicBezTo.x2 ?? cursor.x) * EMU_TO_PX * scaleX;
      const y2 = Number(command.cubicBezTo.y2 ?? cursor.y) * EMU_TO_PX * scaleY;
      const x3 = Number(command.cubicBezTo.x ?? cursor.x) * EMU_TO_PX * scaleX;
      const y3 = Number(command.cubicBezTo.y ?? cursor.y) * EMU_TO_PX * scaleY;
      const angle = Math.atan2(y1 - cursor.y, x1 - cursor.x);
      if (startPoint && startAngle === undefined) {
        startAngle = angle;
      }
      cursor = { x: x3, y: y3 };
      endPoint = { ...cursor };
      endAngle = Math.atan2(y3 - y2, x3 - x2);
    }
  }
  if (!startPoint || !endPoint) {
    return;
  }
  if (startAngle === undefined && endAngle !== undefined) {
    startAngle = endAngle;
  }
  if (endAngle === undefined && startAngle !== undefined) {
    endAngle = startAngle;
  }
  return {
    start: { x: startPoint.x, y: startPoint.y, angle: startAngle ?? 0 },
    end: { x: endPoint.x, y: endPoint.y, angle: endAngle ?? 0 }
  };
}

// node_modules/@oai/granola/dist/draw-utils/draw-shape.js
function resolveOuterShadowStyle(el, themeMap) {
  if (!el.effectReference) {
    return;
  }
  const effectStyle = themeMap.effectMap[el.effectReference.index];
  const outerShadow = effectStyle?.effects.find((effect) => effect.type === 1 /* EFFECT_TYPE_OUTER_SHADOW */);
  if (!outerShadow?.shadow) {
    return;
  }
  const shadowColor = outerShadow.shadow.color ? resolveColor(outerShadow.shadow.color, themeMap) : "transparent";
  const blur = outerShadow.shadow.blurRadius ? outerShadow.shadow.blurRadius * EMU_TO_PX : 0;
  const distancePx = outerShadow.shadow.distance ? outerShadow.shadow.distance * EMU_TO_PX : 0;
  const offset = shadowDirectionToOffsetPx(outerShadow.shadow.direction, distancePx);
  return {
    color: shadowColor ?? "transparent",
    blur,
    offsetX: offset.x,
    offsetY: offset.y
  };
}
function applyCanvasShadowStyle(ctx, shadowStyle) {
  ctx.shadowColor = shadowStyle.color;
  ctx.shadowBlur = shadowStyle.blur;
  ctx.shadowOffsetX = shadowStyle.offsetX;
  ctx.shadowOffsetY = shadowStyle.offsetY;
}
function clearCanvasShadowStyle(ctx) {
  ctx.shadowColor = "transparent";
  ctx.shadowBlur = 0;
  ctx.shadowOffsetX = 0;
  ctx.shadowOffsetY = 0;
}
function drawShape(el, ctx, pres, slide, themeMap) {
  if (!el.shape)
    return;
  const { fill, line, geometry, adjustmentList } = el.shape;
  const bbox = getBBox(el, pres, slide);
  const { width, height } = bbox;
  const hasExplicitLine = Boolean(line);
  const hasExplicitNoLine = hasExplicitLine && isExplicitEmptyFill(line?.fill);
  const themeLine = el.lineReference ? themeMap.lineStyleMap[el.lineReference.index] : undefined;
  const explicitLineWidthEmu = readLineWidthEmu(line);
  const fallbackLineWidthEmu = hasExplicitNoLine ? undefined : readLineWidthEmu(themeLine);
  const lineWidthPx = (explicitLineWidthEmu ?? fallbackLineWidthEmu ?? 0) * EMU_TO_PX;
  const strokeColor = resolveColor(line?.fill?.color ?? el.lineReference?.color ?? themeLine?.fill?.color, themeMap);
  const lineFill = hasExplicitLine ? line?.fill : themeLine?.fill;
  const resolvedLineStyle = resolveLineStyle(line) ?? (!hasExplicitNoLine ? resolveLineStyle(themeLine) : undefined) ?? 1 /* LINE_STYLE_SOLID */;
  const shadowStyle = resolveOuterShadowStyle(el, themeMap);
  const isConnector = Boolean(el.connector) && isConnectorGeometry(geometry ?? undefined);
  if (isConnector) {
    const strokePaint = resolveFillPaint(ctx, bbox, lineFill, themeMap, strokeColor ?? "transparent");
    drawConnectorElement({
      el,
      ctx,
      pres,
      slide,
      strokePaint,
      lineWidthPx,
      lineStyle: resolvedLineStyle
    });
    return;
  }
  ctx.save();
  ctx.lineWidth = lineWidthPx > 0 ? lineWidthPx : 0.001;
  if (el.connector) {
    const cap = el.connector.lineStyle?.cap;
    if (cap === 1 /* LINE_CAP_FLAT */)
      ctx.lineCap = "butt";
    else if (cap === 2 /* LINE_CAP_ROUND */)
      ctx.lineCap = "round";
    else if (cap === 3 /* LINE_CAP_SQUARE */)
      ctx.lineCap = "square";
    const join = el.connector.lineStyle?.join;
    if (join === 1 /* LINE_JOIN_ROUND */)
      ctx.lineJoin = "round";
    else if (join === 2 /* LINE_JOIN_BEVEL */)
      ctx.lineJoin = "bevel";
    else if (join === 3 /* LINE_JOIN_MITER */)
      ctx.lineJoin = "miter";
  }
  applyLineStyle2(ctx, resolvedLineStyle, ctx.lineWidth);
  pushElementTransform(ctx, el, pres, slide);
  const localBBox = { x: 0, y: 0, width, height };
  const createFillPaint = (bbox2 = localBBox) => resolveFillPaint(ctx, bbox2, fill, themeMap);
  const createStrokePaint = (bbox2 = localBBox) => resolveFillPaint(ctx, bbox2, lineFill, themeMap, strokeColor);
  const baseFillPaint = createFillPaint();
  const baseStrokePaint = createStrokePaint();
  ctx.fillStyle = baseFillPaint;
  ctx.strokeStyle = baseStrokePaint;
  ctx.beginPath();
  switch (geometry) {
    case 0 /* SHAPE_GEOMETRY_UNSPECIFIED */:
    case -1 /* UNRECOGNIZED */: {
      ctx.restore();
      break;
    }
    case 188 /* SHAPE_GEOMETRY_CUSTOM */: {
      let customConnectorPath;
      el.shape.customPaths.forEach((p) => {
        const pWidth = Number(p.widthEmu) * EMU_TO_PX;
        const pHeight = Number(p.heightEmu) * EMU_TO_PX;
        const scaleX = width / pWidth;
        const scaleY = height / pHeight;
        const drawCustomPathPass = (options) => {
          ctx.save();
          ctx.scale(scaleX, scaleY);
          if (options.shadow) {
            applyCanvasShadowStyle(ctx, options.shadow);
          } else {
            clearCanvasShadowStyle(ctx);
          }
          const pathBBox = { x: 0, y: 0, width: pWidth, height: pHeight };
          ctx.fillStyle = createFillPaint(pathBBox);
          ctx.strokeStyle = options.stroke ? createStrokePaint(pathBBox) : "rgba(0, 0, 0, 0)";
          renderCustomCommands(ctx, p.commands);
          ctx.fill();
          if (options.stroke) {
            if (el.connector) {
              const commands = customPathCommandsToRouteCommands(p.commands, scaleX, scaleY);
              strokeConnectorRouteCommands(ctx, commands, el, lineWidthPx);
            } else {
              ctx.stroke();
            }
          }
          if (!customConnectorPath && el.connector) {
            customConnectorPath = buildCustomPathMetrics(p.commands, scaleX, scaleY);
          }
          ctx.restore();
        };
        if (shadowStyle) {
          drawCustomPathPass({ shadow: shadowStyle, stroke: false });
        }
        drawCustomPathPass({
          stroke: lineWidthPx > 0 && !hasExplicitNoLine
        });
      });
      renderArrowheads(el, ctx, pres, slide, baseStrokePaint, lineWidthPx, customConnectorPath);
      ctx.restore();
      ctx.restore();
      return;
    }
    default: {
      const preset = getPresetShapeDefinition(geometry);
      let connectorPath;
      if (preset) {
        const adjustments = adjustmentList?.reduce((acc, adj) => {
          acc[adj.name] = adj.formula;
          return acc;
        }, {});
        if (shadowStyle) {
          ctx.save();
          applyCanvasShadowStyle(ctx, shadowStyle);
          drawPresetShape(ctx, preset, {
            w: width,
            h: height,
            x: 0,
            y: 0,
            adjustments,
            fill: true,
            stroke: false,
            collectMetrics: false
          });
          ctx.restore();
        }
        clearCanvasShadowStyle(ctx);
        const shouldTrimStraightConnector = Boolean(el.connector) && geometry === 96 /* SHAPE_GEOMETRY_STRAIGHT_CONNECTOR1 */;
        const renderedPaths = drawPresetShape(ctx, preset, {
          w: width,
          h: height,
          x: 0,
          y: 0,
          adjustments,
          fill: true,
          stroke: lineWidthPx > 0 && !hasExplicitNoLine && !shouldTrimStraightConnector,
          collectMetrics: Boolean(el.connector)
        });
        if (el.connector && renderedPaths?.length) {
          connectorPath = renderedPaths.find((metrics) => metrics.start && metrics.end);
        }
        if (shouldTrimStraightConnector && connectorPath && connectorPath.start && connectorPath.end && lineWidthPx > 0 && !hasExplicitNoLine) {
          const { start, end } = connectorPath;
          strokeConnectorRouteCommands(ctx, [
            {
              cmd: "moveTo",
              x: start.x,
              y: start.y
            },
            {
              cmd: "lineTo",
              x: end.x,
              y: end.y
            }
          ], el, lineWidthPx);
        }
      }
      renderArrowheads(el, ctx, pres, slide, baseStrokePaint, lineWidthPx, connectorPath);
      ctx.restore();
      ctx.restore();
      return;
    }
  }
  ctx.fill();
  if (lineWidthPx > 0 && !hasExplicitNoLine)
    ctx.stroke();
  ctx.restore();
}
function drawConnectorElement({ el, ctx, pres, slide, strokePaint, lineWidthPx, lineStyle }) {
  if (!el.connector)
    return;
  ctx.save();
  ctx.lineWidth = lineWidthPx > 0 ? lineWidthPx : 0.001;
  ctx.strokeStyle = strokePaint;
  applyLineStyle2(ctx, lineStyle, ctx.lineWidth);
  const elements = slide.elements.items.map((item) => item.toProto());
  if (el.id && !elements.some((entry) => entry.id === el.id)) {
    elements.push(el);
  }
  let commands;
  try {
    commands = autoRouteConnectorPx({
      connectorEl: el,
      elements,
      pres,
      slide
    }).commands;
  } catch (error) {
    console.warn("autoRouteConnectorPx failed, using fallback path", error);
    commands = buildConnectorFallbackCommands(el, elements, pres, slide);
  }
  if (!commands || commands.length === 0) {
    ctx.restore();
    return;
  }
  strokeConnectorRouteCommands(ctx, commands, el, ctx.lineWidth);
  const metrics = buildConnectorPathMetrics(commands);
  renderArrowheads(el, ctx, pres, slide, strokePaint, ctx.lineWidth, metrics);
  ctx.restore();
}
function renderConnectorCommands(ctx, commands) {
  for (const command of commands) {
    if (command.cmd === "moveTo") {
      ctx.moveTo(command.x, command.y);
    } else if (command.cmd === "lineTo") {
      ctx.lineTo(command.x, command.y);
    } else if (command.cmd === "cubicBezTo") {
      ctx.bezierCurveTo(command.x1, command.y1, command.x2, command.y2, command.x, command.y);
    }
  }
}
function strokeConnectorRouteCommands(ctx, commands, el, lineWidthPx) {
  const insets = getConnectorStrokeInsets(el, lineWidthPx);
  const trimmedCommands = trimConnectorRouteCommands(commands, insets);
  const previousLineCap = ctx.lineCap;
  if (insets.startPx > 0 || insets.endPx > 0) {
    ctx.lineCap = "butt";
  }
  ctx.beginPath();
  renderConnectorCommands(ctx, trimmedCommands);
  ctx.stroke();
  ctx.lineCap = previousLineCap;
}
function customPathCommandsToRouteCommands(commands, scaleX, scaleY) {
  const routeCommands = [];
  let cursor = { x: 0, y: 0 };
  for (const command of commands) {
    if (command.moveTo) {
      cursor = {
        x: Number(command.moveTo.x ?? 0) * EMU_TO_PX * scaleX,
        y: Number(command.moveTo.y ?? 0) * EMU_TO_PX * scaleY
      };
      routeCommands.push({ cmd: "moveTo", x: cursor.x, y: cursor.y });
    } else if (command.lineTo) {
      cursor = {
        x: Number(command.lineTo.x ?? cursor.x) * EMU_TO_PX * scaleX,
        y: Number(command.lineTo.y ?? cursor.y) * EMU_TO_PX * scaleY
      };
      routeCommands.push({ cmd: "lineTo", x: cursor.x, y: cursor.y });
    } else if (command.cubicBezTo) {
      const x1 = Number(command.cubicBezTo.x1 ?? cursor.x) * EMU_TO_PX * scaleX;
      const y1 = Number(command.cubicBezTo.y1 ?? cursor.y) * EMU_TO_PX * scaleY;
      const x2 = Number(command.cubicBezTo.x2 ?? cursor.x) * EMU_TO_PX * scaleX;
      const y2 = Number(command.cubicBezTo.y2 ?? cursor.y) * EMU_TO_PX * scaleY;
      cursor = {
        x: Number(command.cubicBezTo.x ?? cursor.x) * EMU_TO_PX * scaleX,
        y: Number(command.cubicBezTo.y ?? cursor.y) * EMU_TO_PX * scaleY
      };
      routeCommands.push({
        cmd: "cubicBezTo",
        x1,
        y1,
        x2,
        y2,
        x: cursor.x,
        y: cursor.y
      });
    }
  }
  return routeCommands;
}
function trimConnectorRouteCommands(commands, insets) {
  let trimmed = trimRouteStart(commands, insets.startPx);
  trimmed = trimRouteEnd(trimmed, insets.endPx);
  return trimmed;
}
function trimRouteStart(commands, insetPx) {
  if (insetPx <= 0 || commands.length < 2) {
    return commands;
  }
  const nextCommands = commands.map((command) => ({ ...command }));
  const move = nextCommands[0];
  const first = nextCommands[1];
  if (!move || move.cmd !== "moveTo" || !first) {
    return nextCommands;
  }
  if (first.cmd === "lineTo") {
    const len = Math.hypot(first.x - move.x, first.y - move.y);
    if (len <= 0) {
      return nextCommands;
    }
    const trim = Math.min(insetPx, len - 0.001);
    move.x += (first.x - move.x) / len * trim;
    move.y += (first.y - move.y) / len * trim;
  } else if (first.cmd === "cubicBezTo") {
    const curve = {
      p0: { x: move.x, y: move.y },
      p1: { x: first.x1, y: first.y1 },
      p2: { x: first.x2, y: first.y2 },
      p3: { x: first.x, y: first.y }
    };
    const length = cubicLength(curve);
    const trim = Math.min(insetPx, length - 0.001);
    if (trim > 0) {
      const [, right] = splitCubic(curve, cubicTAtLength(curve, trim));
      const tangent = normalizeCubicTangent({
        x: first.x1 - move.x,
        y: first.y1 - move.y
      });
      const base = {
        x: move.x + tangent.x * trim,
        y: move.y + tangent.y * trim
      };
      const handleLength = Math.hypot(right.p1.x - right.p0.x, right.p1.y - right.p0.y);
      move.x = base.x;
      move.y = base.y;
      first.x1 = base.x + tangent.x * handleLength;
      first.y1 = base.y + tangent.y * handleLength;
      first.x2 = right.p2.x;
      first.y2 = right.p2.y;
      first.x = right.p3.x;
      first.y = right.p3.y;
    }
  }
  return nextCommands;
}
function trimRouteEnd(commands, insetPx) {
  if (insetPx <= 0 || commands.length < 2) {
    return commands;
  }
  const nextCommands = commands.map((command) => ({ ...command }));
  let cursor;
  let previous;
  let lastIndex = -1;
  for (let i = 0;i < nextCommands.length; i += 1) {
    const command = nextCommands[i];
    if (!command)
      continue;
    if (command.cmd === "moveTo") {
      cursor = { x: command.x, y: command.y };
    } else if (command.cmd === "lineTo" || command.cmd === "cubicBezTo") {
      previous = cursor;
      cursor = { x: command.x, y: command.y };
      lastIndex = i;
    }
  }
  const last = nextCommands[lastIndex];
  if (!last || !previous) {
    return nextCommands;
  }
  if (last.cmd === "lineTo") {
    const len = Math.hypot(last.x - previous.x, last.y - previous.y);
    if (len <= 0) {
      return nextCommands;
    }
    const trim = Math.min(insetPx, len - 0.001);
    last.x -= (last.x - previous.x) / len * trim;
    last.y -= (last.y - previous.y) / len * trim;
  } else if (last.cmd === "cubicBezTo") {
    const curve = {
      p0: previous,
      p1: { x: last.x1, y: last.y1 },
      p2: { x: last.x2, y: last.y2 },
      p3: { x: last.x, y: last.y }
    };
    const length = cubicLength(curve);
    const trim = Math.min(insetPx, length - 0.001);
    if (trim > 0) {
      const [left] = splitCubic(curve, cubicTAtLength(curve, length - trim));
      last.x1 = left.p1.x;
      last.y1 = left.p1.y;
      const tangent = normalizeCubicTangent({
        x: last.x - last.x2,
        y: last.y - last.y2
      });
      const base = {
        x: last.x - tangent.x * trim,
        y: last.y - tangent.y * trim
      };
      const handleLength = Math.hypot(left.p3.x - left.p2.x, left.p3.y - left.p2.y);
      last.x2 = base.x - tangent.x * handleLength;
      last.y2 = base.y - tangent.y * handleLength;
      last.x = base.x;
      last.y = base.y;
    }
  }
  return nextCommands;
}
function cubicPoint(curve, t) {
  const mt = 1 - t;
  const mt2 = mt * mt;
  const t2 = t * t;
  return {
    x: curve.p0.x * mt2 * mt + 3 * curve.p1.x * mt2 * t + 3 * curve.p2.x * mt * t2 + curve.p3.x * t * t2,
    y: curve.p0.y * mt2 * mt + 3 * curve.p1.y * mt2 * t + 3 * curve.p2.y * mt * t2 + curve.p3.y * t * t2
  };
}
function cubicLength(curve) {
  let length = 0;
  let prev = curve.p0;
  for (let i = 1;i <= 24; i += 1) {
    const point3 = cubicPoint(curve, i / 24);
    length += Math.hypot(point3.x - prev.x, point3.y - prev.y);
    prev = point3;
  }
  return length;
}
function cubicTAtLength(curve, targetLength) {
  const total = cubicLength(curve);
  if (targetLength <= 0)
    return 0;
  if (targetLength >= total)
    return 1;
  let lo = 0;
  let hi = 1;
  for (let i = 0;i < 16; i += 1) {
    const mid = (lo + hi) / 2;
    const [left] = splitCubic(curve, mid);
    if (cubicLength(left) < targetLength) {
      lo = mid;
    } else {
      hi = mid;
    }
  }
  return (lo + hi) / 2;
}
function splitCubic(curve, t) {
  const p01 = lerpPoint(curve.p0, curve.p1, t);
  const p12 = lerpPoint(curve.p1, curve.p2, t);
  const p23 = lerpPoint(curve.p2, curve.p3, t);
  const p012 = lerpPoint(p01, p12, t);
  const p123 = lerpPoint(p12, p23, t);
  const p0123 = lerpPoint(p012, p123, t);
  return [
    { p0: curve.p0, p1: p01, p2: p012, p3: p0123 },
    { p0: p0123, p1: p123, p2: p23, p3: curve.p3 }
  ];
}
function lerpPoint(a, b, t) {
  return {
    x: a.x + (b.x - a.x) * t,
    y: a.y + (b.y - a.y) * t
  };
}
function normalizeCubicTangent(vec) {
  const length = Math.hypot(vec.x, vec.y);
  if (!length) {
    return { x: 0, y: 0 };
  }
  return {
    x: vec.x / length,
    y: vec.y / length
  };
}
function buildConnectorFallbackCommands(el, elements, pres, slide) {
  const conn = el.connector;
  if (!conn)
    return [];
  const from = elements.find((candidate) => candidate.id === conn.fromElementId);
  const to = elements.find((candidate) => candidate.id === conn.toElementId);
  if (!from || !to) {
    return [];
  }
  const fromCenter = bboxCenter(getBBox(from, pres, slide));
  const toCenter = bboxCenter(getBBox(to, pres, slide));
  return [
    { cmd: "moveTo", x: fromCenter.x, y: fromCenter.y },
    { cmd: "lineTo", x: toCenter.x, y: toCenter.y }
  ];
}
function bboxCenter(rect) {
  return {
    x: rect.x + rect.width / 2,
    y: rect.y + rect.height / 2
  };
}
function buildConnectorPathMetrics(commands) {
  let startPoint;
  let startAngle;
  let endPoint;
  let endAngle;
  let cursor;
  for (const command of commands) {
    if (command.cmd === "moveTo") {
      cursor = { x: command.x, y: command.y };
      if (!startPoint) {
        startPoint = { ...cursor };
      }
    } else if (command.cmd === "lineTo" && cursor) {
      const angle = Math.atan2(command.y - cursor.y, command.x - cursor.x);
      if (startPoint && startAngle === undefined) {
        startAngle = angle;
      }
      cursor = { x: command.x, y: command.y };
      endPoint = { ...cursor };
      endAngle = angle;
    } else if (command.cmd === "cubicBezTo" && cursor) {
      const startVecAngle = Math.atan2(command.y1 - cursor.y, command.x1 - cursor.x);
      if (startPoint && startAngle === undefined) {
        startAngle = startVecAngle;
      }
      cursor = { x: command.x, y: command.y };
      endPoint = { ...cursor };
      endAngle = Math.atan2(command.y - command.y2, command.x - command.x2);
    }
  }
  if (!startPoint || !endPoint) {
    return;
  }
  if (startAngle === undefined && endAngle !== undefined) {
    startAngle = endAngle;
  }
  if (endAngle === undefined && startAngle !== undefined) {
    endAngle = startAngle;
  }
  return {
    start: { x: startPoint.x, y: startPoint.y, angle: startAngle ?? 0 },
    end: { x: endPoint.x, y: endPoint.y, angle: endAngle ?? 0 }
  };
}
var CONNECTOR_GEOMETRIES = new Set([
  96 /* SHAPE_GEOMETRY_STRAIGHT_CONNECTOR1 */,
  97 /* SHAPE_GEOMETRY_BENT_CONNECTOR2 */,
  98 /* SHAPE_GEOMETRY_BENT_CONNECTOR3 */,
  99 /* SHAPE_GEOMETRY_BENT_CONNECTOR4 */,
  100 /* SHAPE_GEOMETRY_BENT_CONNECTOR5 */,
  101 /* SHAPE_GEOMETRY_CURVED_CONNECTOR2 */,
  102 /* SHAPE_GEOMETRY_CURVED_CONNECTOR3 */,
  103 /* SHAPE_GEOMETRY_CURVED_CONNECTOR4 */,
  104 /* SHAPE_GEOMETRY_CURVED_CONNECTOR5 */
]);
function isConnectorGeometry(geometry) {
  if (geometry === undefined || geometry === null) {
    return false;
  }
  return CONNECTOR_GEOMETRIES.has(geometry);
}
function readLineWidthEmu(line) {
  if (!line)
    return;
  const { widthEmu } = line;
  if (widthEmu === undefined || widthEmu === null)
    return;
  const width = Number(widthEmu);
  return Number.isFinite(width) ? width : undefined;
}
function resolveLineStyle(line) {
  if (!line)
    return;
  const { style } = line;
  if (style === 0 /* LINE_STYLE_UNSPECIFIED */) {
    return;
  }
  return style;
}
function isExplicitEmptyFill(fill) {
  if (!fill)
    return false;
  if (Object.keys(fill).length === 0)
    return true;
  if (fill.type !== 0 /* FILL_TYPE_UNSPECIFIED */)
    return false;
  const hasGradientStops = (fill.gradientStops?.length ?? 0) > 0;
  const hasColor = fill.color !== undefined;
  const hasPattern = fill.pattern !== undefined;
  const hasImage = fill.imageReference !== undefined;
  const hasRelId = fill.relId !== undefined;
  const hasGeometry = fill.gradientKind !== undefined || fill.angleDeg !== undefined || fill.pathType !== undefined;
  const hasRects = fill.fillRect !== undefined || fill.stretchFillRect !== undefined || fill.srcRect !== undefined;
  const hasAlpha = fill.alphaModFix !== undefined;
  return !hasGradientStops && !hasColor && !hasPattern && !hasImage && !hasRelId && !hasGeometry && !hasRects && !hasAlpha;
}

// node_modules/@oai/granola/dist/draw-utils/draw-table.js
var PX_TO_EMU = 1 / EMU_TO_PX;
var DEFAULT_ROW_HEIGHT_PX = 24;
var DEFAULT_ROW_HEIGHT = 24;
var DEFAULT_STROKE_COLOR = "#000000";
var MIN_ROW_HEIGHT_PX = 1;
var DEFAULT_TABLE_WIDTH_EMU = 600;
var DOCX_DEFAULT_TABLE_CELL_HORIZONTAL_MARGIN_TWIPS = 108;
var DEFAULT_TABLE_CELL_PADDING_PX = {
  left: twipsToPx(DOCX_DEFAULT_TABLE_CELL_HORIZONTAL_MARGIN_TWIPS),
  right: twipsToPx(DOCX_DEFAULT_TABLE_CELL_HORIZONTAL_MARGIN_TWIPS),
  top: 0,
  bottom: 0
};
function collapseTableCellParagraphBoundarySpacing(paragraphs) {
  if (!paragraphs || paragraphs.length === 0) {
    return paragraphs;
  }
  return paragraphs.map((paragraph, index) => {
    if (index !== 0 && index !== paragraphs.length - 1) {
      return paragraph;
    }
    return {
      ...paragraph,
      ...index === 0 ? { spaceBefore: 0 } : {},
      ...index === paragraphs.length - 1 ? { spaceAfter: 0 } : {}
    };
  });
}
function createTableCellTextElement(cell, bbox) {
  const anchor = resolveTableCellAnchor(cell.anchor);
  return {
    bbox,
    paragraphs: collapseTableCellParagraphBoundarySpacing(cell.paragraphs) ?? [],
    textStyle: anchor !== undefined ? {
      ...cell.textStyle ?? {},
      anchor
    } : cell.textStyle,
    levelsStyles: cell.levelsStyles ?? [],
    type: 1 /* ELEMENT_TYPE_TEXT */,
    effects: [],
    children: [],
    id: "",
    citations: []
  };
}
function resolveTableCellAnchor(anchor) {
  switch (anchor) {
    case "b":
      return 3 /* ANCHOR_TYPE_BOTTOM */;
    case "ctr":
      return 2 /* ANCHOR_TYPE_MIDDLE */;
    case "t":
      return 1 /* ANCHOR_TYPE_TOP */;
    default:
      return;
  }
}
function drawCellBorders(ctx, theme, xPx, yPx, wPx, hPx, lines) {
  const widthToPx = (emu) => Math.max(1, (emu ?? 0) * EMU_TO_PX);
  if (lines?.top && lines.top.fill?.color) {
    ctx.beginPath();
    ctx.strokeStyle = resolveColor(lines.top.fill.color, theme, DEFAULT_STROKE_COLOR);
    ctx.lineWidth = widthToPx(lines.top.widthEmu);
    ctx.moveTo(xPx, yPx);
    ctx.lineTo(xPx + wPx, yPx);
    ctx.stroke();
  }
  if (lines?.right && lines.right.fill?.color) {
    ctx.beginPath();
    ctx.strokeStyle = resolveColor(lines.right.fill.color, theme, DEFAULT_STROKE_COLOR);
    ctx.lineWidth = widthToPx(lines.right.widthEmu);
    ctx.moveTo(xPx + wPx, yPx);
    ctx.lineTo(xPx + wPx, yPx + hPx);
    ctx.stroke();
  }
  if (lines?.bottom && lines.bottom.fill?.color) {
    ctx.beginPath();
    ctx.strokeStyle = resolveColor(lines.bottom.fill.color, theme, DEFAULT_STROKE_COLOR);
    ctx.lineWidth = widthToPx(lines.bottom.widthEmu);
    ctx.moveTo(xPx, yPx + hPx);
    ctx.lineTo(xPx + wPx, yPx + hPx);
    ctx.stroke();
  }
  if (lines?.left && lines.left.fill?.color) {
    ctx.beginPath();
    ctx.strokeStyle = resolveColor(lines.left.fill.color, theme, DEFAULT_STROKE_COLOR);
    ctx.lineWidth = widthToPx(lines.left.widthEmu);
    ctx.moveTo(xPx, yPx);
    ctx.lineTo(xPx, yPx + hPx);
    ctx.stroke();
  }
}
function drawDefaultCellBorders(ctx, xPx, yPx, wPx, hPx, drawRight, drawBottom) {
  const left = Math.round(xPx) + 0.5;
  const top = Math.round(yPx) + 0.5;
  const right = Math.round(xPx + wPx) + 0.5;
  const bottom = Math.round(yPx + hPx) + 0.5;
  ctx.strokeStyle = DEFAULT_STROKE_COLOR;
  ctx.lineWidth = 1;
  ctx.beginPath();
  ctx.moveTo(left, top);
  ctx.lineTo(right, top);
  ctx.moveTo(left, top);
  ctx.lineTo(left, bottom);
  if (drawRight) {
    ctx.moveTo(right, top);
    ctx.lineTo(right, bottom);
  }
  if (drawBottom) {
    ctx.moveTo(left, bottom);
    ctx.lineTo(right, bottom);
  }
  ctx.stroke();
}
function hasLineColor(line) {
  return Boolean(line?.fill?.color);
}
function cellHasBorders(lines) {
  return hasLineColor(lines?.top) || hasLineColor(lines?.right) || hasLineColor(lines?.bottom) || hasLineColor(lines?.left);
}
function tableHasBorders(el) {
  const rows = el.table?.rows ?? [];
  for (const row of rows) {
    for (const cell of row.cells ?? []) {
      if (cellHasBorders(cell.lines)) {
        return true;
      }
    }
  }
  return false;
}
function resolveTableCellPaddingPx(cell) {
  return {
    left: cell.marginLeft !== undefined ? cell.marginLeft * EMU_TO_PX : DEFAULT_TABLE_CELL_PADDING_PX.left,
    right: cell.marginRight !== undefined ? cell.marginRight * EMU_TO_PX : DEFAULT_TABLE_CELL_PADDING_PX.right,
    top: cell.marginTop !== undefined ? cell.marginTop * EMU_TO_PX : DEFAULT_TABLE_CELL_PADDING_PX.top,
    bottom: cell.marginBottom !== undefined ? cell.marginBottom * EMU_TO_PX : DEFAULT_TABLE_CELL_PADDING_PX.bottom
  };
}
function drawTable(el, ctx, theme, opts = {}) {
  if (!el.table) {
    return;
  }
  const numRows = el.table.rows.length;
  const numCols = el.table.rows.reduce((max3, r) => Math.max(max3, r.cells.length), 0);
  const hasExplicitBorders = tableHasBorders(el);
  const bboxWithDefaults = {
    ...el.bbox,
    heightEmu: el.bbox?.heightEmu ?? DEFAULT_ROW_HEIGHT * numRows,
    widthEmu: el.bbox?.widthEmu ?? DEFAULT_TABLE_WIDTH_EMU,
    xEmu: el.bbox?.xEmu ?? 0,
    yEmu: el.bbox?.yEmu ?? 0
  };
  if (numCols <= 0) {
    return;
  }
  let columnWidths = el.table.columnWidths?.map((width) => width && width > 0 ? width : undefined).filter((width) => width !== undefined) ?? [];
  if (columnWidths.length === 0) {
    const fallbackWidthEmu = bboxWithDefaults.widthEmu / numCols;
    columnWidths = new Array(numCols).fill(fallbackWidthEmu);
  } else if (columnWidths.length < numCols) {
    const fallbackWidthEmu = columnWidths[columnWidths.length - 1] ?? bboxWithDefaults.widthEmu / numCols;
    columnWidths = columnWidths.concat(new Array(numCols - columnWidths.length).fill(fallbackWidthEmu));
  } else if (columnWidths.length > numCols) {
    columnWidths = columnWidths.slice(0, numCols);
  }
  const explicitRowHeightBehavior = opts.explicitRowHeightBehavior ?? "exact";
  const autoRowMinimumHeightPx = opts.autoRowMinimumHeightPx ?? DEFAULT_ROW_HEIGHT_PX;
  const baseRowHeightsEmu = new Array(el.table.rows.length).fill(0);
  const baseRowHeightsPx = new Array(el.table.rows.length).fill(0);
  for (let ri = 0;ri < el.table.rows.length; ri++) {
    const row = el.table.rows[ri];
    if (!row)
      continue;
    let measuredContentHeightPx = 0;
    let xMeasure = 0;
    for (let ci = 0;ci < row.cells.length; ci++) {
      const colWEmu = columnWidths[ci] ?? 0;
      const cell = row.cells[ci];
      if (!cell)
        continue;
      const paddingPx = resolveTableCellPaddingPx(cell);
      const cellEl = createTableCellTextElement(cell, {
        xEmu: xMeasure,
        yEmu: 0,
        widthEmu: colWEmu,
        heightEmu: 1
      });
      const resolvedCellStyle = mergeStylesLodash(cellEl.textStyle ?? {}, opts?.resolvedStyle);
      const block = drawText(cellEl, ctx, theme, undefined, {
        mode: "layout",
        resolvedStyle: resolvedCellStyle,
        paddingPx,
        paragraphSpacingUnit: opts?.paragraphSpacingUnit,
        masterDefaults: opts?.masterDefaults
      });
      const requiredCellHeightPx = (block?.height ?? 0) + paddingPx.top + paddingPx.bottom;
      measuredContentHeightPx = Math.max(measuredContentHeightPx, requiredCellHeightPx);
      xMeasure += colWEmu;
    }
    const explicitHeightPx = row.heightEmu && row.heightEmu > 0 ? row.heightEmu * EMU_TO_PX : 0;
    const hasExplicitHeight = explicitHeightPx > 0;
    let resolvedRowHeightPx;
    if (!hasExplicitHeight) {
      resolvedRowHeightPx = Math.max(autoRowMinimumHeightPx, measuredContentHeightPx);
    } else if (explicitRowHeightBehavior === "atLeast") {
      resolvedRowHeightPx = Math.max(explicitHeightPx, measuredContentHeightPx);
    } else {
      resolvedRowHeightPx = explicitHeightPx;
    }
    const safeRowHeightPx = Math.max(MIN_ROW_HEIGHT_PX, resolvedRowHeightPx);
    baseRowHeightsPx[ri] = safeRowHeightPx;
    baseRowHeightsEmu[ri] = Math.max(1, safeRowHeightPx * PX_TO_EMU);
  }
  for (let ri = 0;ri < el.table.rows.length; ri++) {
    const baseRowHeight = baseRowHeightsEmu[ri];
    if (!baseRowHeight || baseRowHeight <= 0) {
      baseRowHeightsPx[ri] = Math.max(MIN_ROW_HEIGHT_PX, autoRowMinimumHeightPx);
      baseRowHeightsEmu[ri] = Math.max(1, baseRowHeightsPx[ri] * PX_TO_EMU);
    }
  }
  ctx.save();
  const rowHeightsPx = [];
  let y2 = bboxWithDefaults.yEmu;
  const cellRects = [];
  const cellLayouts = [];
  for (let ri = 0;ri < el.table.rows.length; ri++) {
    const row = el.table.rows[ri];
    if (!row)
      continue;
    const baseRowH = baseRowHeightsEmu[ri] || 0;
    const rowH = baseRowH;
    rowHeightsPx.push(rowH * EMU_TO_PX);
    let x2 = bboxWithDefaults.xEmu;
    for (let ci = 0;ci < row.cells.length; ci++) {
      const cell = row.cells[ci];
      if (!cell)
        continue;
      const colW = columnWidths[ci] ?? 0;
      const paddingPx = resolveTableCellPaddingPx(cell);
      const cellEl = createTableCellTextElement(cell, {
        xEmu: x2,
        yEmu: y2,
        widthEmu: colW,
        heightEmu: rowH
      });
      const resolvedCellStyle = mergeStylesLodash(cellEl.textStyle ?? {}, opts?.resolvedStyle);
      const fill = cell.fill;
      const fillString = resolveColor(fill?.color, theme, "transparent");
      const xPx = x2 * EMU_TO_PX;
      const yPx = y2 * EMU_TO_PX;
      const wPx = colW * EMU_TO_PX;
      const hPx = rowH * EMU_TO_PX;
      ctx.fillStyle = fillString;
      ctx.fillRect(xPx, yPx, wPx, hPx);
      const block = drawText(cellEl, ctx, theme, undefined, {
        resolvedStyle: resolvedCellStyle,
        paddingPx,
        paragraphSpacingUnit: opts?.paragraphSpacingUnit,
        masterDefaults: opts?.masterDefaults
      });
      if (block) {
        cellLayouts.push({ row: ri, col: ci, block });
      }
      if (hasExplicitBorders) {
        drawCellBorders(ctx, theme, xPx, yPx, wPx, hPx, cell.lines);
      } else {
        drawDefaultCellBorders(ctx, xPx, yPx, wPx, hPx, ci === row.cells.length - 1, ri === el.table.rows.length - 1);
      }
      cellRects.push({
        row: ri,
        col: ci,
        xPx,
        yPx,
        widthPx: wPx,
        heightPx: hPx
      });
      x2 += colW;
    }
    y2 += rowH;
  }
  ctx.restore();
  return {
    cellRects,
    cellLayouts,
    rowHeightsPx,
    heightPx: (y2 - bboxWithDefaults.yEmu) * EMU_TO_PX
  };
}

// node_modules/@oai/granola/dist/draw-utils/resolve-background.js
function pickBackground(slide, pres) {
  if (slide.background.isSet) {
    return slide.background;
  }
  const layout = pres.layouts.getById(slide.useLayoutId);
  if (layout?.background?.isSet) {
    return layout.background;
  }
  const master = layout?.parentLayoutId ? pres.layouts.getById(layout.parentLayoutId) : pres.layouts.items.find((candidate) => candidate.type === "master");
  if (master?.background?.isSet) {
    return master.background;
  }
  return;
}
function resolveBackground(slide, pres, themeMap) {
  const bg = pickBackground(slide, pres);
  const fillColor = bg?.fill?.color?.toProto();
  if (fillColor) {
    return resolveColor(fillColor, themeMap);
  }
  if (bg?.ref && bg.ref.index != null) {
    const idx = bg.ref.index - 1001;
    const tpl = pres.theme?.backgroundFillStyleList?.[idx];
    const base = tpl?.color;
    if (!base)
      return themeMap.colorMap["bg1"] ?? "#ffffff";
    const shouldReplace = base.type === 2 /* COLOR_TYPE_SCHEME */ && base.value === "phClr";
    const colorToResolve = shouldReplace && bg.ref.schemeColor ? { ...base, value: bg.ref.schemeColor } : base;
    return resolveColor(colorToResolve, themeMap);
  }
  return themeMap.colorMap["bg1"] ?? "#ffffff";
}
function resolveBackgroundImage(slide, pres) {
  const tryResolve = (bg) => {
    const imgRefId = bg?.fill?.imageReference?.id;
    if (!imgRefId)
      return;
    const image = pres.images.items.find((i) => i.id === imgRefId);
    if (!image)
      return;
    return { image, bg };
  };
  const fromSlide = tryResolve(slide.background);
  if (fromSlide)
    return fromSlide;
  const layout = pres.layouts.getById(slide.useLayoutId);
  const fromLayout = tryResolve(layout?.background);
  if (fromLayout)
    return fromLayout;
  const master = layout?.parentLayoutId ? pres.layouts.getById(layout.parentLayoutId) : pres.layouts.items.find((candidate) => candidate.type === "master");
  const fromMaster = tryResolve(master?.background);
  if (fromMaster)
    return fromMaster;
  return;
}

// node_modules/@oai/granola/dist/draw-utils/draw-background.js
function drawRoundedRectPath2(ctx, width, height, radius) {
  const safeRadius = Math.max(0, Math.min(radius, width / 2, height / 2));
  ctx.beginPath();
  ctx.moveTo(safeRadius, 0);
  ctx.lineTo(width - safeRadius, 0);
  ctx.quadraticCurveTo(width, 0, width, safeRadius);
  ctx.lineTo(width, height - safeRadius);
  ctx.quadraticCurveTo(width, height, width - safeRadius, height);
  ctx.lineTo(safeRadius, height);
  ctx.quadraticCurveTo(0, height, 0, height - safeRadius);
  ctx.lineTo(0, safeRadius);
  ctx.quadraticCurveTo(0, 0, safeRadius, 0);
  ctx.closePath();
}
async function drawBackground(slide, pres, ctx, themeMap, width, height, options) {
  const baseColor = resolveBackground(slide, pres, themeMap) || themeMap.colorMap["bg1"] || "#ffffff";
  const effectiveBackground = pickBackground(slide, pres);
  const fillProto = effectiveBackground?.fill?.toProto();
  const paint = fillProto ? resolveFillPaint(ctx, { x: 0, y: 0, width, height }, fillProto, themeMap, baseColor) : baseColor;
  ctx.save();
  ctx.globalAlpha = 1;
  ctx.globalCompositeOperation = "source-over";
  if ((options?.clipRadiusPx ?? 0) > 0) {
    drawRoundedRectPath2(ctx, width, height, options?.clipRadiusPx ?? 0);
    ctx.clip();
  }
  ctx.fillStyle = paint;
  ctx.fillRect(0, 0, width, height);
  ctx.restore();
  const bgResolved = resolveBackgroundImage(slide, pres);
  if (bgResolved) {
    const { image, bg } = bgResolved;
    const bmp = await image.getBitmap(slide.frame.width, slide.frame.height);
    if (!bmp)
      return;
    ctx.save();
    if ((options?.clipRadiusPx ?? 0) > 0) {
      drawRoundedRectPath2(ctx, width, height, options?.clipRadiusPx ?? 0);
      ctx.clip();
    }
    const alpha = bg?.fill?.alphaModFix;
    if (alpha != null) {
      ctx.globalAlpha = Math.max(0, Math.min(1, alpha / 1e5));
    }
    const frac = (v) => (v ?? 0) / 1e5;
    let sx = 0, sy = 0, sw = bmp.width, sh = bmp.height;
    const src = bg?.fill?.srcRect;
    if (src) {
      const pl = frac(src.l);
      const pt = frac(src.t);
      const pr = frac(src.r);
      const pb = frac(src.b);
      sx += pl * bmp.width;
      sy += pt * bmp.height;
      sw -= (pl + pr) * bmp.width;
      sh -= (pt + pb) * bmp.height;
    }
    let dx = 0, dy = 0, dw = width, dh = height;
    const stretch = bg?.fill?.stretchFillRect;
    if (stretch) {
      const pl = frac(stretch.l);
      const pt = frac(stretch.t);
      const pr = frac(stretch.r);
      const pb = frac(stretch.b);
      dx = pl * width;
      dy = pt * height;
      dw = width * (1 - pl - pr);
      dh = height * (1 - pt - pb);
    }
    ctx.drawImage(bmp, sx, sy, sw, sh, dx, dy, dw, dh);
    ctx.restore();
  }
}

// node_modules/@oai/granola/dist/models/presentation/types.js
var MAP_AREA_TO_PROTO = {
  world: 2 /* MAP_AREA_WORLD */,
  auto: 1 /* MAP_AREA_AUTO */,
  dataOnly: 3 /* MAP_AREA_DATA_ONLY */,
  region: 4 /* MAP_AREA_REGION */
};
var MAP_AREA_FROM_PROTO = {
  [2 /* MAP_AREA_WORLD */]: "world",
  [1 /* MAP_AREA_AUTO */]: "auto",
  [3 /* MAP_AREA_DATA_ONLY */]: "dataOnly",
  [4 /* MAP_AREA_REGION */]: "region",
  [0 /* MAP_AREA_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var MAP_DATA_LEVEL_TO_PROTO = {
  countryOrRegion: 2 /* MAP_DATA_LEVEL_COUNTRY_OR_REGION */,
  stateOrProvince: 3 /* MAP_DATA_LEVEL_STATE_OR_PROVINCE */,
  county: 4 /* MAP_DATA_LEVEL_COUNTY */,
  postalCode: 5 /* MAP_DATA_LEVEL_POSTAL_CODE */,
  countryOrRegionCode: 6 /* MAP_DATA_LEVEL_COUNTRY_OR_REGION_CODE */,
  stateCode: 7 /* MAP_DATA_LEVEL_STATE_CODE */,
  countyCode: 8 /* MAP_DATA_LEVEL_COUNTY_CODE */,
  auto: 1 /* MAP_DATA_LEVEL_AUTO */
};
var MAP_DATA_LEVEL_FROM_PROTO = {
  [2 /* MAP_DATA_LEVEL_COUNTRY_OR_REGION */]: "countryOrRegion",
  [3 /* MAP_DATA_LEVEL_STATE_OR_PROVINCE */]: "stateOrProvince",
  [4 /* MAP_DATA_LEVEL_COUNTY */]: "county",
  [5 /* MAP_DATA_LEVEL_POSTAL_CODE */]: "postalCode",
  [6 /* MAP_DATA_LEVEL_COUNTRY_OR_REGION_CODE */]: "countryOrRegionCode",
  [7 /* MAP_DATA_LEVEL_STATE_CODE */]: "stateCode",
  [8 /* MAP_DATA_LEVEL_COUNTY_CODE */]: "countyCode",
  [1 /* MAP_DATA_LEVEL_AUTO */]: "auto",
  [0 /* MAP_DATA_LEVEL_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var MAP_LABEL_LAYOUT_TO_PROTO = {
  none: 1 /* MAP_LABEL_LAYOUT_NONE */,
  bestFit: 2 /* MAP_LABEL_LAYOUT_BEST_FIT */,
  showAll: 3 /* MAP_LABEL_LAYOUT_SHOW_ALL */
};
var MAP_LABEL_LAYOUT_FROM_PROTO = {
  [1 /* MAP_LABEL_LAYOUT_NONE */]: "none",
  [2 /* MAP_LABEL_LAYOUT_BEST_FIT */]: "bestFit",
  [3 /* MAP_LABEL_LAYOUT_SHOW_ALL */]: "showAll",
  [0 /* MAP_LABEL_LAYOUT_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var MAP_PROJECTION_TO_PROTO = {
  mercator: 2 /* MAP_PROJECTION_MERCATOR */,
  auto: 1 /* MAP_PROJECTION_AUTO */,
  miller: 3 /* MAP_PROJECTION_MILLER */,
  albers: 4 /* MAP_PROJECTION_ALBERS */
};
var MAP_PROJECTION_FROM_PROTO = {
  [2 /* MAP_PROJECTION_MERCATOR */]: "mercator",
  [1 /* MAP_PROJECTION_AUTO */]: "auto",
  [3 /* MAP_PROJECTION_MILLER */]: "miller",
  [4 /* MAP_PROJECTION_ALBERS */]: "albers",
  [0 /* MAP_PROJECTION_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var TREEMAP_PARENT_LABEL_LAYOUT_TO_PROTO = {
  overlapping: 3 /* PARENT_LABEL_LAYOUT_OVERLAPPING */,
  banner: 2 /* PARENT_LABEL_LAYOUT_BANNER */,
  none: 1 /* PARENT_LABEL_LAYOUT_NONE */
};
var TREEMAP_PARENT_LABEL_LAYOUT_FROM_PROTO = {
  [1 /* PARENT_LABEL_LAYOUT_NONE */]: "none",
  [3 /* PARENT_LABEL_LAYOUT_OVERLAPPING */]: "overlapping",
  [2 /* PARENT_LABEL_LAYOUT_BANNER */]: "banner",
  [0 /* PARENT_LABEL_LAYOUT_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var BOX_WHISKER_QUARTILE_METHOD_TO_PROTO = {
  inclusive: 1 /* QUARTILE_METHOD_INCLUSIVE */,
  exclusive: 2 /* QUARTILE_METHOD_EXCLUSIVE */
};
var BOX_WHISKER_QUARTILE_METHOD_FROM_PROTO = {
  [1 /* QUARTILE_METHOD_INCLUSIVE */]: "inclusive",
  [2 /* QUARTILE_METHOD_EXCLUSIVE */]: "exclusive",
  [0 /* QUARTILE_METHOD_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var ShapePositionUnit;
(function(ShapePositionUnit2) {
  ShapePositionUnit2["pixels"] = "px";
  ShapePositionUnit2["emu"] = "emu";
})(ShapePositionUnit || (ShapePositionUnit = {}));
var CHART_TYPE_TO_PROTO = {
  line: 13 /* CHART_TYPE_LINE */,
  pie: 16 /* CHART_TYPE_PIE */,
  bar: 4 /* CHART_TYPE_BAR */,
  doughnut: 8 /* CHART_TYPE_DOUGHNUT */,
  scatter: 18 /* CHART_TYPE_SCATTER */,
  bubble: 5 /* CHART_TYPE_BUBBLE */,
  radar: 17 /* CHART_TYPE_RADAR */,
  treemap: 29 /* CHART_TYPE_TREEMAP */,
  sunburst: 30 /* CHART_TYPE_SUNBURST */,
  map: 23 /* CHART_TYPE_MAP */,
  waterfall: 27 /* CHART_TYPE_WATERFALL */,
  line3D: 12 /* CHART_TYPE_LINE_3D */,
  pie3D: 15 /* CHART_TYPE_PIE_3D */,
  area3D: 1 /* CHART_TYPE_AREA_3D */,
  bar3D: 3 /* CHART_TYPE_BAR_3D */,
  funnel: 28 /* CHART_TYPE_FUNNEL */,
  histogram: 24 /* CHART_TYPE_HISTOGRAM */,
  boxWhisker: 26 /* CHART_TYPE_BOX_WHISKER */,
  stock: 20 /* CHART_TYPE_STOCK */,
  surface3D: 21 /* CHART_TYPE_SURFACE_3D */,
  ofPie: 14 /* CHART_TYPE_OF_PIE */,
  surface: 22 /* CHART_TYPE_SURFACE */,
  pareto: 25 /* CHART_TYPE_PARETO */,
  combo: 31 /* CHART_TYPE_COMBO */,
  area: 2 /* CHART_TYPE_AREA */
};
var AREA_GROUPING_TO_PROTO = {
  standard: 1 /* AREA_GROUPING_STANDARD */,
  stacked: 2 /* AREA_GROUPING_STACKED */,
  percentStacked: 3 /* AREA_GROUPING_PERCENT_STACKED */
};
var AREA_GROUPING_FROM_PROTO = {
  [1 /* AREA_GROUPING_STANDARD */]: "standard",
  [2 /* AREA_GROUPING_STACKED */]: "stacked",
  [3 /* AREA_GROUPING_PERCENT_STACKED */]: "percentStacked",
  [0 /* AREA_GROUPING_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var LINE_GROUPING_TO_PROTO = {
  standard: 1 /* LINE_GROUPING_STANDARD */,
  stacked: 2 /* LINE_GROUPING_STACKED */,
  percentStacked: 3 /* LINE_GROUPING_PERCENT_STACKED */
};
var LINE_GROUPING_FROM_PROTO = {
  [1 /* LINE_GROUPING_STANDARD */]: "standard",
  [2 /* LINE_GROUPING_STACKED */]: "stacked",
  [3 /* LINE_GROUPING_PERCENT_STACKED */]: "percentStacked",
  [0 /* LINE_GROUPING_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var CHART_TYPE_FROM_PROTO = {
  [13 /* CHART_TYPE_LINE */]: "line",
  [16 /* CHART_TYPE_PIE */]: "pie",
  [4 /* CHART_TYPE_BAR */]: "bar",
  [2 /* CHART_TYPE_AREA */]: "area",
  [8 /* CHART_TYPE_DOUGHNUT */]: "doughnut",
  [18 /* CHART_TYPE_SCATTER */]: "scatter",
  [5 /* CHART_TYPE_BUBBLE */]: "bubble",
  [17 /* CHART_TYPE_RADAR */]: "radar",
  [29 /* CHART_TYPE_TREEMAP */]: "treemap",
  [30 /* CHART_TYPE_SUNBURST */]: "sunburst",
  [23 /* CHART_TYPE_MAP */]: "map",
  [27 /* CHART_TYPE_WATERFALL */]: "waterfall",
  [12 /* CHART_TYPE_LINE_3D */]: "line3D",
  [15 /* CHART_TYPE_PIE_3D */]: "pie3D",
  [1 /* CHART_TYPE_AREA_3D */]: "area3D",
  [3 /* CHART_TYPE_BAR_3D */]: "bar3D",
  [28 /* CHART_TYPE_FUNNEL */]: "funnel",
  [24 /* CHART_TYPE_HISTOGRAM */]: "histogram",
  [26 /* CHART_TYPE_BOX_WHISKER */]: "boxWhisker",
  [20 /* CHART_TYPE_STOCK */]: "stock",
  [21 /* CHART_TYPE_SURFACE_3D */]: "surface3D",
  [14 /* CHART_TYPE_OF_PIE */]: "ofPie",
  [0 /* CHART_TYPE_UNSPECIFIED */]: undefined,
  [22 /* CHART_TYPE_SURFACE */]: "surface",
  [25 /* CHART_TYPE_PARETO */]: "pareto",
  [31 /* CHART_TYPE_COMBO */]: "combo",
  [-1 /* UNRECOGNIZED */]: undefined
};
var TEXT_WRAP_TO_PROTO = {
  square: 2 /* TEXT_WRAPPING_TYPE_SQUARE */,
  none: 1 /* TEXT_WRAPPING_TYPE_NONE */
};
var TEXT_WRAP_FROM_PROTO = {
  [2 /* TEXT_WRAPPING_TYPE_SQUARE */]: "square",
  [1 /* TEXT_WRAPPING_TYPE_NONE */]: "none",
  [0 /* TEXT_WRAPPING_TYPE_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var SHAPE_GEOMETRY_NAME_TO_PROTO = {
  line: 1 /* SHAPE_GEOMETRY_LINE */,
  lineInv: 2 /* SHAPE_GEOMETRY_LINE_INV */,
  triangle: 3 /* SHAPE_GEOMETRY_TRIANGLE */,
  rtTriangle: 4 /* SHAPE_GEOMETRY_RT_TRIANGLE */,
  rect: 5 /* SHAPE_GEOMETRY_RECT */,
  diamond: 6 /* SHAPE_GEOMETRY_DIAMOND */,
  parallelogram: 7 /* SHAPE_GEOMETRY_PARALLELOGRAM */,
  trapezoid: 8 /* SHAPE_GEOMETRY_TRAPEZOID */,
  nonIsoscelesTrapezoid: 9 /* SHAPE_GEOMETRY_NON_ISOSCELES_TRAPEZOID */,
  pentagon: 10 /* SHAPE_GEOMETRY_PENTAGON */,
  hexagon: 11 /* SHAPE_GEOMETRY_HEXAGON */,
  heptagon: 12 /* SHAPE_GEOMETRY_HEPTAGON */,
  octagon: 13 /* SHAPE_GEOMETRY_OCTAGON */,
  decagon: 14 /* SHAPE_GEOMETRY_DECAGON */,
  dodecagon: 15 /* SHAPE_GEOMETRY_DODECAGON */,
  star4: 16 /* SHAPE_GEOMETRY_STAR4 */,
  star5: 17 /* SHAPE_GEOMETRY_STAR5 */,
  star6: 18 /* SHAPE_GEOMETRY_STAR6 */,
  star7: 19 /* SHAPE_GEOMETRY_STAR7 */,
  star8: 20 /* SHAPE_GEOMETRY_STAR8 */,
  star10: 21 /* SHAPE_GEOMETRY_STAR10 */,
  star12: 22 /* SHAPE_GEOMETRY_STAR12 */,
  star16: 23 /* SHAPE_GEOMETRY_STAR16 */,
  star24: 24 /* SHAPE_GEOMETRY_STAR24 */,
  star32: 25 /* SHAPE_GEOMETRY_STAR32 */,
  roundRect: 26 /* SHAPE_GEOMETRY_ROUND_RECT */,
  round1Rect: 27 /* SHAPE_GEOMETRY_ROUND1_RECT */,
  round2SameRect: 28 /* SHAPE_GEOMETRY_ROUND2_SAME_RECT */,
  round2DiagRect: 29 /* SHAPE_GEOMETRY_ROUND2_DIAG_RECT */,
  snipRoundRect: 30 /* SHAPE_GEOMETRY_SNIP_ROUND_RECT */,
  snip1Rect: 31 /* SHAPE_GEOMETRY_SNIP1_RECT */,
  snip2SameRect: 32 /* SHAPE_GEOMETRY_SNIP2_SAME_RECT */,
  snip2DiagRect: 33 /* SHAPE_GEOMETRY_SNIP2_DIAG_RECT */,
  plaque: 34 /* SHAPE_GEOMETRY_PLAQUE */,
  ellipse: 35 /* SHAPE_GEOMETRY_ELLIPSE */,
  teardrop: 36 /* SHAPE_GEOMETRY_TEARDROP */,
  homePlate: 37 /* SHAPE_GEOMETRY_HOME_PLATE */,
  chevron: 38 /* SHAPE_GEOMETRY_CHEVRON */,
  pieWedge: 39 /* SHAPE_GEOMETRY_PIE_WEDGE */,
  pie: 40 /* SHAPE_GEOMETRY_PIE */,
  blockArc: 41 /* SHAPE_GEOMETRY_BLOCK_ARC */,
  donut: 42 /* SHAPE_GEOMETRY_DONUT */,
  noSmoking: 43 /* SHAPE_GEOMETRY_NO_SMOKING */,
  rightArrow: 44 /* SHAPE_GEOMETRY_RIGHT_ARROW */,
  leftArrow: 45 /* SHAPE_GEOMETRY_LEFT_ARROW */,
  upArrow: 46 /* SHAPE_GEOMETRY_UP_ARROW */,
  downArrow: 47 /* SHAPE_GEOMETRY_DOWN_ARROW */,
  stripedRightArrow: 48 /* SHAPE_GEOMETRY_STRIPED_RIGHT_ARROW */,
  notchedRightArrow: 49 /* SHAPE_GEOMETRY_NOTCHED_RIGHT_ARROW */,
  bentUpArrow: 50 /* SHAPE_GEOMETRY_BENT_UP_ARROW */,
  leftRightArrow: 51 /* SHAPE_GEOMETRY_LEFT_RIGHT_ARROW */,
  upDownArrow: 52 /* SHAPE_GEOMETRY_UP_DOWN_ARROW */,
  leftUpArrow: 53 /* SHAPE_GEOMETRY_LEFT_UP_ARROW */,
  leftRightUpArrow: 54 /* SHAPE_GEOMETRY_LEFT_RIGHT_UP_ARROW */,
  quadArrow: 55 /* SHAPE_GEOMETRY_QUAD_ARROW */,
  leftArrowCallout: 56 /* SHAPE_GEOMETRY_LEFT_ARROW_CALLOUT */,
  rightArrowCallout: 57 /* SHAPE_GEOMETRY_RIGHT_ARROW_CALLOUT */,
  upArrowCallout: 58 /* SHAPE_GEOMETRY_UP_ARROW_CALLOUT */,
  downArrowCallout: 59 /* SHAPE_GEOMETRY_DOWN_ARROW_CALLOUT */,
  leftRightArrowCallout: 60 /* SHAPE_GEOMETRY_LEFT_RIGHT_ARROW_CALLOUT */,
  upDownArrowCallout: 61 /* SHAPE_GEOMETRY_UP_DOWN_ARROW_CALLOUT */,
  quadArrowCallout: 62 /* SHAPE_GEOMETRY_QUAD_ARROW_CALLOUT */,
  bentArrow: 63 /* SHAPE_GEOMETRY_BENT_ARROW */,
  uturnArrow: 64 /* SHAPE_GEOMETRY_UTURN_ARROW */,
  circularArrow: 65 /* SHAPE_GEOMETRY_CIRCULAR_ARROW */,
  leftCircularArrow: 66 /* SHAPE_GEOMETRY_LEFT_CIRCULAR_ARROW */,
  leftRightCircularArrow: 67 /* SHAPE_GEOMETRY_LEFT_RIGHT_CIRCULAR_ARROW */,
  curvedRightArrow: 68 /* SHAPE_GEOMETRY_CURVED_RIGHT_ARROW */,
  curvedLeftArrow: 69 /* SHAPE_GEOMETRY_CURVED_LEFT_ARROW */,
  curvedUpArrow: 70 /* SHAPE_GEOMETRY_CURVED_UP_ARROW */,
  curvedDownArrow: 71 /* SHAPE_GEOMETRY_CURVED_DOWN_ARROW */,
  swooshArrow: 72 /* SHAPE_GEOMETRY_SWOOSH_ARROW */,
  cube: 73 /* SHAPE_GEOMETRY_CUBE */,
  can: 74 /* SHAPE_GEOMETRY_CAN */,
  lightningBolt: 75 /* SHAPE_GEOMETRY_LIGHTNING_BOLT */,
  heart: 76 /* SHAPE_GEOMETRY_HEART */,
  sun: 77 /* SHAPE_GEOMETRY_SUN */,
  moon: 78 /* SHAPE_GEOMETRY_MOON */,
  smileyFace: 79 /* SHAPE_GEOMETRY_SMILEY_FACE */,
  irregularSeal1: 80 /* SHAPE_GEOMETRY_IRREGULAR_SEAL1 */,
  irregularSeal2: 81 /* SHAPE_GEOMETRY_IRREGULAR_SEAL2 */,
  foldedCorner: 82 /* SHAPE_GEOMETRY_FOLDED_CORNER */,
  bevel: 83 /* SHAPE_GEOMETRY_BEVEL */,
  frame: 84 /* SHAPE_GEOMETRY_FRAME */,
  halfFrame: 85 /* SHAPE_GEOMETRY_HALF_FRAME */,
  corner: 86 /* SHAPE_GEOMETRY_CORNER */,
  diagStripe: 87 /* SHAPE_GEOMETRY_DIAG_STRIPE */,
  chord: 88 /* SHAPE_GEOMETRY_CHORD */,
  arc: 89 /* SHAPE_GEOMETRY_ARC */,
  leftBracket: 90 /* SHAPE_GEOMETRY_LEFT_BRACKET */,
  rightBracket: 91 /* SHAPE_GEOMETRY_RIGHT_BRACKET */,
  leftBrace: 92 /* SHAPE_GEOMETRY_LEFT_BRACE */,
  rightBrace: 93 /* SHAPE_GEOMETRY_RIGHT_BRACE */,
  bracketPair: 94 /* SHAPE_GEOMETRY_BRACKET_PAIR */,
  bracePair: 95 /* SHAPE_GEOMETRY_BRACE_PAIR */,
  straightConnector1: 96 /* SHAPE_GEOMETRY_STRAIGHT_CONNECTOR1 */,
  bentConnector2: 97 /* SHAPE_GEOMETRY_BENT_CONNECTOR2 */,
  bentConnector3: 98 /* SHAPE_GEOMETRY_BENT_CONNECTOR3 */,
  bentConnector4: 99 /* SHAPE_GEOMETRY_BENT_CONNECTOR4 */,
  bentConnector5: 100 /* SHAPE_GEOMETRY_BENT_CONNECTOR5 */,
  curvedConnector2: 101 /* SHAPE_GEOMETRY_CURVED_CONNECTOR2 */,
  curvedConnector3: 102 /* SHAPE_GEOMETRY_CURVED_CONNECTOR3 */,
  curvedConnector4: 103 /* SHAPE_GEOMETRY_CURVED_CONNECTOR4 */,
  curvedConnector5: 104 /* SHAPE_GEOMETRY_CURVED_CONNECTOR5 */,
  callout1: 105 /* SHAPE_GEOMETRY_CALLOUT1 */,
  callout2: 106 /* SHAPE_GEOMETRY_CALLOUT2 */,
  callout3: 107 /* SHAPE_GEOMETRY_CALLOUT3 */,
  accentCallout1: 108 /* SHAPE_GEOMETRY_ACCENT_CALLOUT1 */,
  accentCallout2: 109 /* SHAPE_GEOMETRY_ACCENT_CALLOUT2 */,
  accentCallout3: 110 /* SHAPE_GEOMETRY_ACCENT_CALLOUT3 */,
  borderCallout1: 111 /* SHAPE_GEOMETRY_BORDER_CALLOUT1 */,
  borderCallout2: 112 /* SHAPE_GEOMETRY_BORDER_CALLOUT2 */,
  borderCallout3: 113 /* SHAPE_GEOMETRY_BORDER_CALLOUT3 */,
  accentBorderCallout1: 114 /* SHAPE_GEOMETRY_ACCENT_BORDER_CALLOUT1 */,
  accentBorderCallout2: 115 /* SHAPE_GEOMETRY_ACCENT_BORDER_CALLOUT2 */,
  accentBorderCallout3: 116 /* SHAPE_GEOMETRY_ACCENT_BORDER_CALLOUT3 */,
  wedgeRectCallout: 117 /* SHAPE_GEOMETRY_WEDGE_RECT_CALLOUT */,
  wedgeRoundRectCallout: 118 /* SHAPE_GEOMETRY_WEDGE_ROUND_RECT_CALLOUT */,
  wedgeEllipseCallout: 119 /* SHAPE_GEOMETRY_WEDGE_ELLIPSE_CALLOUT */,
  cloudCallout: 120 /* SHAPE_GEOMETRY_CLOUD_CALLOUT */,
  cloud: 121 /* SHAPE_GEOMETRY_CLOUD */,
  ribbon: 122 /* SHAPE_GEOMETRY_RIBBON */,
  ribbon2: 123 /* SHAPE_GEOMETRY_RIBBON2 */,
  ellipseRibbon: 124 /* SHAPE_GEOMETRY_ELLIPSE_RIBBON */,
  ellipseRibbon2: 125 /* SHAPE_GEOMETRY_ELLIPSE_RIBBON2 */,
  leftRightRibbon: 126 /* SHAPE_GEOMETRY_LEFT_RIGHT_RIBBON */,
  verticalScroll: 127 /* SHAPE_GEOMETRY_VERTICAL_SCROLL */,
  horizontalScroll: 128 /* SHAPE_GEOMETRY_HORIZONTAL_SCROLL */,
  wave: 129 /* SHAPE_GEOMETRY_WAVE */,
  doubleWave: 130 /* SHAPE_GEOMETRY_DOUBLE_WAVE */,
  plus: 131 /* SHAPE_GEOMETRY_PLUS */,
  flowChartProcess: 132 /* SHAPE_GEOMETRY_FLOW_CHART_PROCESS */,
  flowChartDecision: 133 /* SHAPE_GEOMETRY_FLOW_CHART_DECISION */,
  flowChartInputOutput: 134 /* SHAPE_GEOMETRY_FLOW_CHART_INPUT_OUTPUT */,
  flowChartPredefinedProcess: 135 /* SHAPE_GEOMETRY_FLOW_CHART_PREDEFINED_PROCESS */,
  flowChartInternalStorage: 136 /* SHAPE_GEOMETRY_FLOW_CHART_INTERNAL_STORAGE */,
  flowChartDocument: 137 /* SHAPE_GEOMETRY_FLOW_CHART_DOCUMENT */,
  flowChartMultidocument: 138 /* SHAPE_GEOMETRY_FLOW_CHART_MULTIDOCUMENT */,
  flowChartTerminator: 139 /* SHAPE_GEOMETRY_FLOW_CHART_TERMINATOR */,
  flowChartPreparation: 140 /* SHAPE_GEOMETRY_FLOW_CHART_PREPARATION */,
  flowChartManualInput: 141 /* SHAPE_GEOMETRY_FLOW_CHART_MANUAL_INPUT */,
  flowChartManualOperation: 142 /* SHAPE_GEOMETRY_FLOW_CHART_MANUAL_OPERATION */,
  flowChartConnector: 143 /* SHAPE_GEOMETRY_FLOW_CHART_CONNECTOR */,
  flowChartPunchedCard: 144 /* SHAPE_GEOMETRY_FLOW_CHART_PUNCHED_CARD */,
  flowChartPunchedTape: 145 /* SHAPE_GEOMETRY_FLOW_CHART_PUNCHED_TAPE */,
  flowChartSummingJunction: 146 /* SHAPE_GEOMETRY_FLOW_CHART_SUMMING_JUNCTION */,
  flowChartOr: 147 /* SHAPE_GEOMETRY_FLOW_CHART_OR */,
  flowChartCollate: 148 /* SHAPE_GEOMETRY_FLOW_CHART_COLLATE */,
  flowChartSort: 149 /* SHAPE_GEOMETRY_FLOW_CHART_SORT */,
  flowChartExtract: 150 /* SHAPE_GEOMETRY_FLOW_CHART_EXTRACT */,
  flowChartMerge: 151 /* SHAPE_GEOMETRY_FLOW_CHART_MERGE */,
  flowChartOfflineStorage: 152 /* SHAPE_GEOMETRY_FLOW_CHART_OFFLINE_STORAGE */,
  flowChartOnlineStorage: 153 /* SHAPE_GEOMETRY_FLOW_CHART_ONLINE_STORAGE */,
  flowChartMagneticTape: 154 /* SHAPE_GEOMETRY_FLOW_CHART_MAGNETIC_TAPE */,
  flowChartMagneticDisk: 155 /* SHAPE_GEOMETRY_FLOW_CHART_MAGNETIC_DISK */,
  flowChartDatabase: 155 /* SHAPE_GEOMETRY_FLOW_CHART_MAGNETIC_DISK */,
  flowChartMagneticDrum: 156 /* SHAPE_GEOMETRY_FLOW_CHART_MAGNETIC_DRUM */,
  flowChartDisplay: 157 /* SHAPE_GEOMETRY_FLOW_CHART_DISPLAY */,
  flowChartDelay: 158 /* SHAPE_GEOMETRY_FLOW_CHART_DELAY */,
  flowChartAlternateProcess: 159 /* SHAPE_GEOMETRY_FLOW_CHART_ALTERNATE_PROCESS */,
  flowChartOffpageConnector: 160 /* SHAPE_GEOMETRY_FLOW_CHART_OFFPAGE_CONNECTOR */,
  actionButtonBlank: 161 /* SHAPE_GEOMETRY_ACTION_BUTTON_BLANK */,
  actionButtonHome: 162 /* SHAPE_GEOMETRY_ACTION_BUTTON_HOME */,
  actionButtonHelp: 163 /* SHAPE_GEOMETRY_ACTION_BUTTON_HELP */,
  actionButtonInformation: 164 /* SHAPE_GEOMETRY_ACTION_BUTTON_INFORMATION */,
  actionButtonForwardNext: 165 /* SHAPE_GEOMETRY_ACTION_BUTTON_FORWARD_NEXT */,
  actionButtonBackPrevious: 166 /* SHAPE_GEOMETRY_ACTION_BUTTON_BACK_PREVIOUS */,
  actionButtonEnd: 167 /* SHAPE_GEOMETRY_ACTION_BUTTON_END */,
  actionButtonBeginning: 168 /* SHAPE_GEOMETRY_ACTION_BUTTON_BEGINNING */,
  actionButtonReturn: 169 /* SHAPE_GEOMETRY_ACTION_BUTTON_RETURN */,
  actionButtonDocument: 170 /* SHAPE_GEOMETRY_ACTION_BUTTON_DOCUMENT */,
  actionButtonSound: 171 /* SHAPE_GEOMETRY_ACTION_BUTTON_SOUND */,
  actionButtonMovie: 172 /* SHAPE_GEOMETRY_ACTION_BUTTON_MOVIE */,
  gear6: 173 /* SHAPE_GEOMETRY_GEAR6 */,
  gear9: 174 /* SHAPE_GEOMETRY_GEAR9 */,
  funnel: 175 /* SHAPE_GEOMETRY_FUNNEL */,
  mathPlus: 176 /* SHAPE_GEOMETRY_MATH_PLUS */,
  mathMinus: 177 /* SHAPE_GEOMETRY_MATH_MINUS */,
  mathMultiply: 178 /* SHAPE_GEOMETRY_MATH_MULTIPLY */,
  mathDivide: 179 /* SHAPE_GEOMETRY_MATH_DIVIDE */,
  mathEqual: 180 /* SHAPE_GEOMETRY_MATH_EQUAL */,
  mathNotEqual: 181 /* SHAPE_GEOMETRY_MATH_NOT_EQUAL */,
  cornerTabs: 182 /* SHAPE_GEOMETRY_CORNER_TABS */,
  squareTabs: 183 /* SHAPE_GEOMETRY_SQUARE_TABS */,
  plaqueTabs: 184 /* SHAPE_GEOMETRY_PLAQUE_TABS */,
  chartX: 185 /* SHAPE_GEOMETRY_CHART_X */,
  chartStar: 186 /* SHAPE_GEOMETRY_CHART_STAR */,
  chartPlus: 187 /* SHAPE_GEOMETRY_CHART_PLUS */,
  custom: 188 /* SHAPE_GEOMETRY_CUSTOM */,
  textbox: 5 /* SHAPE_GEOMETRY_RECT */
};
var PLACEHOLDER_TYPE_FROM_PROTO = {
  title: "title",
  subTitle: "subtitle",
  body: "body",
  picture: "picture",
  chart: "chart",
  tbl: "table",
  content: "content"
};
var LEGEND_POSITION_TO_PROTO = {
  left: 2 /* LEGEND_POSITION_LEFT */,
  top: 3 /* LEGEND_POSITION_TOP */,
  topRight: 5 /* LEGEND_POSITION_TOP_RIGHT */,
  right: 1 /* LEGEND_POSITION_RIGHT */,
  bottom: 4 /* LEGEND_POSITION_BOTTOM */
};
var LEGEND_POSITION_FROM_PROTO = {
  [2 /* LEGEND_POSITION_LEFT */]: "left",
  [3 /* LEGEND_POSITION_TOP */]: "top",
  [5 /* LEGEND_POSITION_TOP_RIGHT */]: "topRight",
  [1 /* LEGEND_POSITION_RIGHT */]: "right",
  [4 /* LEGEND_POSITION_BOTTOM */]: "bottom",
  [0 /* LEGEND_POSITION_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var DATA_LABEL_POSITION_TO_PROTO = {
  center: 3 /* DATA_LABEL_POSITION_CENTER */,
  inEnd: 2 /* DATA_LABEL_POSITION_IN_END */,
  outEnd: 1 /* DATA_LABEL_POSITION_OUT_END */
};
var DATA_LABEL_POSITION_FROM_PROTO = {
  [3 /* DATA_LABEL_POSITION_CENTER */]: "center",
  [2 /* DATA_LABEL_POSITION_IN_END */]: "inEnd",
  [1 /* DATA_LABEL_POSITION_OUT_END */]: "outEnd",
  [0 /* DATA_LABEL_POSITION_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var AXIS_POSITION_TO_PROTO = {
  left: 1 /* AXIS_POSITION_LEFT */,
  right: 2 /* AXIS_POSITION_RIGHT */,
  top: 3 /* AXIS_POSITION_TOP */,
  bottom: 4 /* AXIS_POSITION_BOTTOM */
};
var AXIS_POSITION_FROM_PROTO = {
  [1 /* AXIS_POSITION_LEFT */]: "left",
  [2 /* AXIS_POSITION_RIGHT */]: "right",
  [3 /* AXIS_POSITION_TOP */]: "top",
  [4 /* AXIS_POSITION_BOTTOM */]: "bottom",
  [0 /* AXIS_POSITION_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var AXIS_ORIENTATION_TO_PROTO = {
  minMax: 1 /* AXIS_ORIENTATION_MIN_MAX */,
  maxMin: 2 /* AXIS_ORIENTATION_MAX_MIN */
};
var AXIS_ORIENTATION_FROM_PROTO = {
  [1 /* AXIS_ORIENTATION_MIN_MAX */]: "minMax",
  [2 /* AXIS_ORIENTATION_MAX_MIN */]: "maxMin",
  [0 /* AXIS_ORIENTATION_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var TICK_MARK_TO_PROTO = {
  none: 1 /* TICK_MARK_NONE */,
  inside: 2 /* TICK_MARK_INSIDE */,
  outside: 3 /* TICK_MARK_OUTSIDE */,
  cross: 4 /* TICK_MARK_CROSS */
};
var TICK_MARK_FROM_PROTO = {
  [1 /* TICK_MARK_NONE */]: "none",
  [2 /* TICK_MARK_INSIDE */]: "inside",
  [3 /* TICK_MARK_OUTSIDE */]: "outside",
  [4 /* TICK_MARK_CROSS */]: "cross",
  [0 /* TICK_MARK_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var TICK_LABEL_POSITION_TO_PROTO = {
  high: 1 /* TICK_LABEL_POSITION_HIGH */,
  low: 2 /* TICK_LABEL_POSITION_LOW */,
  nextTo: 3 /* TICK_LABEL_POSITION_NEXT_TO */
};
var TICK_LABEL_POSITION_FROM_PROTO = {
  [1 /* TICK_LABEL_POSITION_HIGH */]: "high",
  [2 /* TICK_LABEL_POSITION_LOW */]: "low",
  [3 /* TICK_LABEL_POSITION_NEXT_TO */]: "nextTo",
  [0 /* TICK_LABEL_POSITION_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var CROSS_BETWEEN_TO_PROTO = {
  between: 1 /* CROSS_BETWEEN_BETWEEN */,
  midpointCategory: 2 /* CROSS_BETWEEN_MIDPOINT_CATEGORY */
};
var CROSS_BETWEEN_FROM_PROTO = {
  [1 /* CROSS_BETWEEN_BETWEEN */]: "between",
  [2 /* CROSS_BETWEEN_MIDPOINT_CATEGORY */]: "midpointCategory",
  [0 /* CROSS_BETWEEN_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var CROSSES_TO_PROTO = {
  autoZero: 1 /* CROSSES_AUTO_ZERO */,
  min: 2 /* CROSSES_MIN */,
  max: 3 /* CROSSES_MAX */,
  at: 4 /* CROSSES_AT */
};
var CROSSES_FROM_PROTO = {
  [1 /* CROSSES_AUTO_ZERO */]: "autoZero",
  [2 /* CROSSES_MIN */]: "min",
  [3 /* CROSSES_MAX */]: "max",
  [4 /* CROSSES_AT */]: "at",
  [0 /* CROSSES_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var TRENDLINE_TYPE_TO_PROTO = {
  linear: 1 /* TRENDLINE_TYPE_LINEAR */,
  exponential: 2 /* TRENDLINE_TYPE_EXPONENTIAL */,
  logarithmic: 3 /* TRENDLINE_TYPE_LOGARITHMIC */,
  polynomial: 4 /* TRENDLINE_TYPE_POLYNOMIAL */,
  power: 5 /* TRENDLINE_TYPE_POWER */,
  movingAverage: 6 /* TRENDLINE_TYPE_MOVING_AVERAGE */
};
var TRENDLINE_TYPE_FROM_PROTO = {
  [1 /* TRENDLINE_TYPE_LINEAR */]: "linear",
  [2 /* TRENDLINE_TYPE_EXPONENTIAL */]: "exponential",
  [3 /* TRENDLINE_TYPE_LOGARITHMIC */]: "logarithmic",
  [4 /* TRENDLINE_TYPE_POLYNOMIAL */]: "polynomial",
  [5 /* TRENDLINE_TYPE_POWER */]: "power",
  [6 /* TRENDLINE_TYPE_MOVING_AVERAGE */]: "movingAverage",
  [0 /* TRENDLINE_TYPE_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var MARKER_SYMBOL_TO_PROTO = {
  none: 1 /* MARKER_SYMBOL_NONE */,
  circle: 3 /* MARKER_SYMBOL_CIRCLE */,
  square: 4 /* MARKER_SYMBOL_SQUARE */,
  diamond: 5 /* MARKER_SYMBOL_DIAMOND */,
  triangle: 6 /* MARKER_SYMBOL_TRIANGLE */,
  x: 7 /* MARKER_SYMBOL_X */,
  star: 8 /* MARKER_SYMBOL_STAR */,
  plus: 9 /* MARKER_SYMBOL_PLUS */,
  dot: 2 /* MARKER_SYMBOL_DOT */
};
var MARKER_SYMBOL_FROM_PROTO = {
  [1 /* MARKER_SYMBOL_NONE */]: "none",
  [3 /* MARKER_SYMBOL_CIRCLE */]: "circle",
  [4 /* MARKER_SYMBOL_SQUARE */]: "square",
  [5 /* MARKER_SYMBOL_DIAMOND */]: "diamond",
  [6 /* MARKER_SYMBOL_TRIANGLE */]: "triangle",
  [7 /* MARKER_SYMBOL_X */]: "x",
  [8 /* MARKER_SYMBOL_STAR */]: "star",
  [9 /* MARKER_SYMBOL_PLUS */]: "plus",
  [2 /* MARKER_SYMBOL_DOT */]: "dot",
  [-1 /* UNRECOGNIZED */]: undefined,
  [0 /* MARKER_SYMBOL_UNSPECIFIED */]: undefined
};
var BAR_DIRECTION_TO_PROTO = {
  column: 1 /* BAR_DIRECTION_COLUMN */,
  bar: 2 /* BAR_DIRECTION_BAR */
};
var BAR_DIRECTION_FROM_PROTO = {
  [1 /* BAR_DIRECTION_COLUMN */]: "column",
  [2 /* BAR_DIRECTION_BAR */]: "bar",
  [0 /* BAR_DIRECTION_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var BAR_GROUPING_TO_PROTO = {
  clustered: 1 /* BAR_GROUPING_CLUSTERED */,
  stacked: 2 /* BAR_GROUPING_STACKED */,
  percentStacked: 3 /* BAR_GROUPING_PERCENT_STACKED */
};
var BAR_GROUPING_FROM_PROTO = {
  [1 /* BAR_GROUPING_CLUSTERED */]: "clustered",
  [2 /* BAR_GROUPING_STACKED */]: "stacked",
  [3 /* BAR_GROUPING_PERCENT_STACKED */]: "percentStacked",
  [0 /* BAR_GROUPING_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var SCATTER_STYLE_TO_PROTO = {
  line: 2 /* SCATTER_STYLE_LINE */,
  lineWithMarkers: 1 /* SCATTER_STYLE_LINE_MARKER */,
  smooth: 4 /* SCATTER_STYLE_SMOOTH */,
  smoothWithMarkers: 5 /* SCATTER_STYLE_SMOOTH_MARKER */,
  marker: 3 /* SCATTER_STYLE_MARKER */
};
var SCATTER_STYLE_FROM_PROTO = {
  [2 /* SCATTER_STYLE_LINE */]: "line",
  [1 /* SCATTER_STYLE_LINE_MARKER */]: "lineWithMarkers",
  [4 /* SCATTER_STYLE_SMOOTH */]: "smooth",
  [5 /* SCATTER_STYLE_SMOOTH_MARKER */]: "smoothWithMarkers",
  [3 /* SCATTER_STYLE_MARKER */]: "marker",
  [0 /* SCATTER_STYLE_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var TEXT_VERTICAL_ALIGNMENT_TO_PROTO = {
  top: 1 /* ANCHOR_TYPE_TOP */,
  middle: 2 /* ANCHOR_TYPE_MIDDLE */,
  bottom: 3 /* ANCHOR_TYPE_BOTTOM */
};
var TEXT_VERTICAL_ALIGNMENT_FROM_PROTO = {
  [1 /* ANCHOR_TYPE_TOP */]: "top",
  [2 /* ANCHOR_TYPE_MIDDLE */]: "middle",
  [3 /* ANCHOR_TYPE_BOTTOM */]: "bottom",
  [0 /* ANCHOR_TYPE_UNSPECIFIED */]: undefined,
  [-1 /* UNRECOGNIZED */]: undefined
};
var TextDirection;
(function(TextDirection2) {
  TextDirection2["horizontal"] = "horizontal";
  TextDirection2["vertical"] = "vertical";
})(TextDirection || (TextDirection = {}));
var PATTERN_NAME_TO_TYPE_MAP = {
  none: 1 /* PATTERN_TYPE_NONE */,
  solid: 2 /* PATTERN_TYPE_SOLID */,
  mediumGray: 3 /* PATTERN_TYPE_MEDIUM_GRAY */,
  darkGray: 4 /* PATTERN_TYPE_DARK_GRAY */,
  lightGray: 5 /* PATTERN_TYPE_LIGHT_GRAY */,
  darkHorizontal: 6 /* PATTERN_TYPE_DARK_HORIZONTAL */,
  darkVertical: 7 /* PATTERN_TYPE_DARK_VERTICAL */,
  darkDown: 8 /* PATTERN_TYPE_DARK_DOWN */,
  darkUp: 9 /* PATTERN_TYPE_DARK_UP */,
  darkGrid: 10 /* PATTERN_TYPE_DARK_GRID */,
  darkTrellis: 11 /* PATTERN_TYPE_DARK_TRELLIS */,
  lightHorizontal: 12 /* PATTERN_TYPE_LIGHT_HORIZONTAL */,
  lightVertical: 13 /* PATTERN_TYPE_LIGHT_VERTICAL */,
  lightDown: 14 /* PATTERN_TYPE_LIGHT_DOWN */,
  lightUp: 15 /* PATTERN_TYPE_LIGHT_UP */,
  lightGrid: 16 /* PATTERN_TYPE_LIGHT_GRID */,
  lightTrellis: 17 /* PATTERN_TYPE_LIGHT_TRELLIS */,
  gray125: 18 /* PATTERN_TYPE_GRAY125 */,
  gray0625: 19 /* PATTERN_TYPE_GRAY0625 */,
  percent5: 20 /* PATTERN_TYPE_PERCENT_5 */,
  percent10: 21 /* PATTERN_TYPE_PERCENT_10 */,
  percent20: 22 /* PATTERN_TYPE_PERCENT_20 */,
  percent25: 23 /* PATTERN_TYPE_PERCENT_25 */,
  percent30: 24 /* PATTERN_TYPE_PERCENT_30 */,
  percent40: 25 /* PATTERN_TYPE_PERCENT_40 */,
  percent50: 26 /* PATTERN_TYPE_PERCENT_50 */,
  percent60: 27 /* PATTERN_TYPE_PERCENT_60 */,
  percent70: 28 /* PATTERN_TYPE_PERCENT_70 */,
  percent75: 29 /* PATTERN_TYPE_PERCENT_75 */,
  percent80: 30 /* PATTERN_TYPE_PERCENT_80 */,
  percent90: 31 /* PATTERN_TYPE_PERCENT_90 */,
  horizontal: 32 /* PATTERN_TYPE_HORIZONTAL */,
  vertical: 33 /* PATTERN_TYPE_VERTICAL */,
  narrowHorizontal: 34 /* PATTERN_TYPE_NARROW_HORIZONTAL */,
  narrowVertical: 35 /* PATTERN_TYPE_NARROW_VERTICAL */,
  dashedHorizontal: 36 /* PATTERN_TYPE_DASHED_HORIZONTAL */,
  dashedVertical: 37 /* PATTERN_TYPE_DASHED_VERTICAL */,
  cross: 38 /* PATTERN_TYPE_CROSS */,
  largeGrid: 39 /* PATTERN_TYPE_LARGE_GRID */,
  smallGrid: 40 /* PATTERN_TYPE_SMALL_GRID */,
  dotGrid: 41 /* PATTERN_TYPE_DOT_GRID */,
  downwardDiagonal: 42 /* PATTERN_TYPE_DOWNWARD_DIAGONAL */,
  upwardDiagonal: 43 /* PATTERN_TYPE_UPWARD_DIAGONAL */,
  wideDownwardDiagonal: 44 /* PATTERN_TYPE_WIDE_DOWNWARD_DIAGONAL */,
  wideUpwardDiagonal: 45 /* PATTERN_TYPE_WIDE_UPWARD_DIAGONAL */,
  dashedDownwardDiagonal: 46 /* PATTERN_TYPE_DASHED_DOWNWARD_DIAGONAL */,
  dashedUpwardDiagonal: 47 /* PATTERN_TYPE_DASHED_UPWARD_DIAGONAL */,
  diagonalCross: 48 /* PATTERN_TYPE_DIAGONAL_CROSS */,
  smallCheck: 49 /* PATTERN_TYPE_SMALL_CHECK */,
  largeCheck: 50 /* PATTERN_TYPE_LARGE_CHECK */,
  smallConfetti: 51 /* PATTERN_TYPE_SMALL_CONFETTI */,
  largeConfetti: 52 /* PATTERN_TYPE_LARGE_CONFETTI */,
  horizontalBrick: 53 /* PATTERN_TYPE_HORIZONTAL_BRICK */,
  diagonalBrick: 54 /* PATTERN_TYPE_DIAGONAL_BRICK */,
  solidDiamond: 55 /* PATTERN_TYPE_SOLID_DIAMOND */,
  openDiamond: 56 /* PATTERN_TYPE_OPEN_DIAMOND */,
  dottedDiamond: 57 /* PATTERN_TYPE_DOTTED_DIAMOND */,
  plaid: 58 /* PATTERN_TYPE_PLAID */,
  sphere: 59 /* PATTERN_TYPE_SPHERE */,
  weave: 60 /* PATTERN_TYPE_WEAVE */,
  divot: 61 /* PATTERN_TYPE_DIVOT */,
  shingle: 62 /* PATTERN_TYPE_SHINGLE */,
  wave: 63 /* PATTERN_TYPE_WAVE */,
  trellis: 64 /* PATTERN_TYPE_TRELLIS */,
  zigZag: 65 /* PATTERN_TYPE_ZIG_ZAG */
};

// node_modules/@oai/granola/dist/draw-utils/draw-image-placeholder.js
var PLACEHOLDER_BACKGROUND = "#F7F7F7";
var PLACEHOLDER_TEXT = "Creating image";
var PLACEHOLDER_TEXT_COLOR = "#6B7280";
var PLACEHOLDER_FONT_PX = 16;
function drawImagePlaceholder(args) {
  const { width, height, ctx, themeMap } = args;
  if (width <= 0 || height <= 0) {
    return;
  }
  ctx.save();
  ctx.fillStyle = PLACEHOLDER_BACKGROUND;
  ctx.fillRect(0, 0, width, height);
  const horizontalInset = Math.min(width * 0.12, 48);
  const lineHeightPx = PLACEHOLDER_FONT_PX * 1.25;
  const boxHeightPx = Math.min(height, lineHeightPx * 1.2);
  const box = {
    x: horizontalInset,
    y: Math.max(0, (height - boxHeightPx) / 2),
    width: Math.max(0, width - horizontalInset * 2),
    height: boxHeightPx
  };
  if (box.width > 0 && box.height > 0) {
    drawPlaceholderLabel({
      ctx,
      themeMap,
      box,
      fontPx: PLACEHOLDER_FONT_PX
    });
  }
  ctx.restore();
}
function drawPlaceholderLabel(args) {
  const element = createPlaceholderTextElement({
    text: PLACEHOLDER_TEXT,
    fontPx: args.fontPx
  });
  const themedTextMap = {
    ...args.themeMap,
    colorMap: {
      ...args.themeMap.colorMap ?? {},
      tx1: PLACEHOLDER_TEXT_COLOR
    }
  };
  const layout = layoutTextBlock(element, themedTextMap, {
    bboxPx: args.box,
    paddingPx: { left: 0, right: 0, top: 0, bottom: 0 },
    resolvedStyle: element.textStyle,
    wrap: true
  });
  if (!layout) {
    return;
  }
  renderTextBlock(element, layout, args.ctx, undefined, {
    bboxPx: args.box,
    paddingPx: { left: 0, right: 0, top: 0, bottom: 0 },
    resolvedStyle: element.textStyle
  });
}
function createPlaceholderTextElement(args) {
  const run = {
    text: args.text,
    citations: [],
    reviewMarkIds: [],
    textStyle: {
      fontSize: pxToPtHundred(args.fontPx)
    }
  };
  const paragraph = {
    runs: [run]
  };
  return {
    paragraphs: [paragraph],
    textStyle: {
      anchor: 1 /* ANCHOR_TYPE_TOP */,
      alignment: 2 /* ALIGNMENT_TYPE_CENTER */
    }
  };
}
function pxToPtHundred(px) {
  return Math.round(px * 72 * 100 / 96);
}

// node_modules/@oai/granola/dist/draw-utils/draw-image-cached.js
async function drawImageCached(el, slideElement, ctx, pres, slide, themeMap) {
  if (!el.imageReference)
    return;
  const { width: dw, height: dh } = getBBox(el, pres, slide);
  const bmp = await slideElement.getBitmap();
  let sx = 0, sy = 0, sw = bmp?.width ?? 0, sh = bmp?.height ?? 0;
  const f = (v) => (v ?? 0) / 1e5;
  const src = el.fill?.srcRect;
  if (bmp) {
    if (src) {
      const pl = f(src.l);
      const pt = f(src.t);
      const pr = f(src.r);
      const pb = f(src.b);
      sx += pl * bmp.width;
      sy += pt * bmp.height;
      sw -= (pl + pr) * bmp.width;
      sh -= (pt + pb) * bmp.height;
    } else if (el.image?.mask) {
      const m = el.image.mask;
      const cw = bmp.width;
      const ch = bmp.height;
      sx += f(m.cropLeft) * cw;
      sy += f(m.cropTop) * ch;
      sw -= (f(m.cropLeft) + f(m.cropRight)) * cw;
      sh -= (f(m.cropTop) + f(m.cropBottom)) * ch;
    }
  }
  let dx = 0;
  let dy = 0;
  let dwOut = dw;
  let dhOut = dh;
  const stretch = el.fill?.stretchFillRect;
  if (stretch) {
    const pl = f(stretch.l);
    const pt = f(stretch.t);
    const pr = f(stretch.r);
    const pb = f(stretch.b);
    dx = pl * dw;
    dy = pt * dh;
    dwOut = dw * (1 - pl - pr);
    dhOut = dh * (1 - pt - pb);
  }
  const duotone = el.fill?.duotone;
  if (duotone) {}
  pushElementTransform(ctx, el, pres, slide);
  const imageMask = el.imageMask;
  let maskGeometry;
  const rawMaskGeometry = imageMask?.geometry;
  if (rawMaskGeometry !== undefined) {
    if (rawMaskGeometry in SHAPE_GEOMETRY_NAME_TO_PROTO) {
      maskGeometry = SHAPE_GEOMETRY_NAME_TO_PROTO[rawMaskGeometry];
    }
  }
  if (maskGeometry !== undefined && maskGeometry !== 0 /* SHAPE_GEOMETRY_UNSPECIFIED */ && maskGeometry !== -1 /* UNRECOGNIZED */ && maskGeometry !== 5 /* SHAPE_GEOMETRY_RECT */) {
    const preset = getPresetShapeDefinition(maskGeometry);
    if (preset) {
      const adjustments = imageMask?.adjustmentList?.reduce((acc, adj) => {
        acc[adj.name] = adj.formula;
        return acc;
      }, {});
      const originalBeginPath = ctx.beginPath.bind(ctx);
      ctx.beginPath();
      ctx.beginPath = () => {};
      try {
        drawPresetShape(ctx, preset, {
          w: dw,
          h: dh,
          x: 0,
          y: 0,
          adjustments,
          fill: false,
          stroke: false
        });
      } finally {
        ctx.beginPath = originalBeginPath;
      }
      ctx.clip();
    }
  }
  if (bmp) {
    ctx.drawImage(bmp, sx, sy, sw, sh, dx, dy, dwOut, dhOut);
  } else {
    drawImagePlaceholder({
      width: dw,
      height: dh,
      ctx,
      themeMap
    });
  }
  ctx.restore();
}

// node_modules/@oai/granola/dist/draw-slide-to-ctx.js
async function drawSlideToCtx(slide, pres, ctx, linkRects, threeCtx, on3DLayout, mapCtx, onMapLayout, chartHoverTargets, textLayoutCollector, options) {
  const masterSchemeRemap = getMasterSchemeRemap(pres, slide);
  const themeMap = buildThemeMap(pres.theme, masterSchemeRemap);
  const width = slide.frame.width;
  const height = slide.frame.height;
  ctx.save();
  ctx.globalAlpha = 1;
  ctx.globalCompositeOperation = "source-over";
  if (options?.clearBeforeDraw !== false) {
    ctx.clearRect(0, 0, width, height);
  }
  await drawBackground(slide, pres, ctx, themeMap, width, height, {
    clipRadiusPx: options?.backgroundClipRadiusPx
  });
  const layout = pres.layouts.items.find((l) => l.id === slide.useLayoutId);
  const layoutElementsProto = layout?.elements ?? [];
  let masterOrdered = [];
  if (layout?.parentLayoutId) {
    const masterLayout = pres.layouts.items.find((l) => l.id === layout.parentLayoutId);
    const masterElementsProto = masterLayout?.elements ?? [];
    const nonPlaceholderElements = masterElementsProto.filter((e) => e.placeholderIndex === undefined && e.placeholderType === undefined);
    masterOrdered = nonPlaceholderElements.map((e) => e);
  }
  const layoutOrdered = layoutElementsProto.filter((e) => e.placeholderIndex === undefined && e.placeholderType === undefined).map((e) => e);
  const ordered = slide.elements.items.map((element, index) => ({
    element,
    index,
    zIndex: element.zIndex ?? 0
  })).sort((a, b) => {
    if (a.zIndex !== b.zIndex) {
      return a.zIndex - b.zIndex;
    }
    return a.index - b.index;
  }).map(({ element }) => element);
  const drawOrdered = [...masterOrdered, ...layoutOrdered, ...ordered];
  const imagesToWarm = drawOrdered.filter((element) => element.type === "image");
  await Promise.all(imagesToWarm.map((element) => element.getBitmap())).catch((error) => {
    console.error("Error warming images", error);
  });
  for (const slideElement of drawOrdered) {
    const el = slideElement.toProto();
    if (slideElement.type === "image") {
      await drawImageCached(el, slideElement, ctx, pres, slide, themeMap);
    }
    if (slideElement.type === "chart") {
      drawChartReference(el, ctx, pres, slide, themeMap, chartHoverTargets, undefined, mapCtx ?? null, threeCtx ?? null, on3DLayout, onMapLayout, textLayoutCollector, slideElement.chart);
    }
    if (slideElement.type === "table") {
      const resolvedStyle = resolveStyles(el, pres, slide);
      const masterDefaults = getMasterLevelDefaults(el, pres, slide);
      drawTable(el, ctx, themeMap, { resolvedStyle, masterDefaults });
    }
    if (slideElement.type === "shape") {
      drawShape(el, ctx, pres, slide, themeMap);
    }
    if (el.paragraphs && el.paragraphs.length > 0) {
      const bbox = getBBox(el, pres, slide);
      const resolvedStyle = resolveStyles(el, pres, slide);
      const wrap = resolvedStyle?.wrap === 1 /* TEXT_WRAPPING_TYPE_NONE */ ? false : true;
      const textScaleRaw = resolvedStyle?.autoFit?.normalAutoFit?.fontScale;
      const textScale = typeof textScaleRaw === "number" ? textScaleRaw / 1e5 : 1;
      const layout2 = drawText(el, ctx, themeMap, linkRects, {
        resolvedStyle,
        masterDefaults: getMasterLevelDefaults(el, pres, slide),
        bboxPx: bbox,
        wrap,
        textScale
      });
      if (layout2 && textLayoutCollector) {
        const blockId = el.id && el.id.length ? el.id : `text:${Math.round(bbox.x)}:${Math.round(bbox.y)}:${Math.round(bbox.width)}:${Math.round(bbox.height)}`;
        textLayoutCollector.add({
          id: blockId,
          layout: layout2,
          rotationDeg: resolvedStyle?.rotation ?? 0,
          zIndex: el.zIndex ?? 0,
          hitBox: {
            x: bbox.x,
            y: bbox.y,
            width: bbox.width,
            height: bbox.height
          },
          getRunText: (paraIndex, runIndex) => el.paragraphs?.[paraIndex]?.runs?.[runIndex]?.text ?? ""
        });
      }
    }
    if (linkRects && el.hyperlink) {
      const { x: x2, y: y2, width: width2, height: height2 } = getBBox(el, pres, slide);
      linkRects.push({
        x: x2,
        y: y2,
        width: width2,
        height: height2,
        url: el.hyperlink.uri,
        action: el.hyperlink.action
      });
    }
  }
  ctx.restore();
}

// node_modules/@oai/granola/dist/models/presentation/citations-collection.js
class CitationsCollection {
  #items;
  constructor(_context, proto) {
    this.#items = (proto ?? []).map((citation) => new Citation(this.#citationContext(), citation));
  }
  get items() {
    return [...this.#items];
  }
  add() {
    const citationProto = {
      id: "",
      type: 0 /* CONTENT_REFERENCE_TYPE_UNSPECIFIED */,
      tetherId: "",
      targetId: ""
    };
    const citation = new Citation(this.#citationContext(), citationProto);
    this.#items.push(citation);
    return citation;
  }
  replace(proto) {
    this.#items = (proto ?? []).map((citation) => new Citation(this.#citationContext(), citation));
  }
  toProto() {
    return this.#items.map((citation) => citation.toProto());
  }
  #citationContext() {
    return {
      stub: () => {}
    };
  }
}

class Citation {
  #data;
  constructor(_context, proto) {
    this.#data = {
      id: proto.id ?? "",
      uri: proto.uri ?? "",
      title: proto.title ?? "",
      type: proto.type ?? undefined
    };
  }
  get id() {
    return this.#data.id;
  }
  toProto() {
    return {
      id: this.#data.id,
      uri: this.#data.uri ?? "",
      title: this.#data.title ?? "",
      type: this.#data.type
    };
  }
}

// node_modules/@oai/granola/dist/models/presentation/utils/tailwind/tailwind-colors.generated.js
var TAILWIND_COLOR_HEX_BY_TOKEN = {
  "amber-100": "#FEF3C6",
  "amber-200": "#FEE685",
  "amber-300": "#FFD230",
  "amber-400": "#FFB900",
  "amber-50": "#FFFBEB",
  "amber-500": "#FE9A00",
  "amber-600": "#E17100",
  "amber-700": "#BB4D00",
  "amber-800": "#973C00",
  "amber-900": "#7B3306",
  "amber-950": "#461901",
  black: "#000000",
  "blue-100": "#DBEAFE",
  "blue-200": "#BEDBFF",
  "blue-300": "#8EC5FF",
  "blue-400": "#51A2FF",
  "blue-50": "#EFF6FF",
  "blue-500": "#2B7FFF",
  "blue-600": "#155DFC",
  "blue-700": "#1447E6",
  "blue-800": "#193CB8",
  "blue-900": "#1C398E",
  "blue-950": "#162456",
  "cyan-100": "#CEFAFE",
  "cyan-200": "#A2F4FD",
  "cyan-300": "#53EAFD",
  "cyan-400": "#00D3F2",
  "cyan-50": "#ECFEFF",
  "cyan-500": "#00B8DB",
  "cyan-600": "#0092B8",
  "cyan-700": "#007595",
  "cyan-800": "#005F78",
  "cyan-900": "#104E64",
  "cyan-950": "#053345",
  "emerald-100": "#D0FAE5",
  "emerald-200": "#A4F4CF",
  "emerald-300": "#5EE9B5",
  "emerald-400": "#00D492",
  "emerald-50": "#ECFDF5",
  "emerald-500": "#00BC7D",
  "emerald-600": "#009966",
  "emerald-700": "#007A55",
  "emerald-800": "#006045",
  "emerald-900": "#004F3B",
  "emerald-950": "#002C22",
  "fuchsia-100": "#FAE8FF",
  "fuchsia-200": "#F6CFFF",
  "fuchsia-300": "#F4A8FF",
  "fuchsia-400": "#ED6AFF",
  "fuchsia-50": "#FDF4FF",
  "fuchsia-500": "#E12AFB",
  "fuchsia-600": "#C800DE",
  "fuchsia-700": "#A800B7",
  "fuchsia-800": "#8A0194",
  "fuchsia-900": "#721378",
  "fuchsia-950": "#4B004F",
  "gray-100": "#F3F4F6",
  "gray-200": "#E5E7EB",
  "gray-300": "#D1D5DC",
  "gray-400": "#99A1AF",
  "gray-50": "#F9FAFB",
  "gray-500": "#6A7282",
  "gray-600": "#4A5565",
  "gray-700": "#364153",
  "gray-800": "#1E2939",
  "gray-900": "#101828",
  "gray-950": "#030712",
  "green-100": "#DCFCE7",
  "green-200": "#B9F8CF",
  "green-300": "#7BF1A8",
  "green-400": "#05DF72",
  "green-50": "#F0FDF4",
  "green-500": "#00C950",
  "green-600": "#00A63E",
  "green-700": "#008236",
  "green-800": "#016630",
  "green-900": "#0D542B",
  "green-950": "#032E15",
  "indigo-100": "#E0E7FF",
  "indigo-200": "#C6D2FF",
  "indigo-300": "#A3B3FF",
  "indigo-400": "#7C86FF",
  "indigo-50": "#EEF2FF",
  "indigo-500": "#615FFF",
  "indigo-600": "#4F39F6",
  "indigo-700": "#432DD7",
  "indigo-800": "#372AAC",
  "indigo-900": "#312C85",
  "indigo-950": "#1E1A4D",
  "lime-100": "#ECFCCA",
  "lime-200": "#D8F999",
  "lime-300": "#BBF451",
  "lime-400": "#9AE600",
  "lime-50": "#F7FEE7",
  "lime-500": "#7CCF00",
  "lime-600": "#5EA500",
  "lime-700": "#497D00",
  "lime-800": "#3C6300",
  "lime-900": "#35530E",
  "lime-950": "#192E03",
  "mauve-100": "#F3F1F3",
  "mauve-200": "#E7E4E7",
  "mauve-300": "#D7D0D7",
  "mauve-400": "#A89EA9",
  "mauve-50": "#FAFAFA",
  "mauve-500": "#79697B",
  "mauve-600": "#594C5B",
  "mauve-700": "#463947",
  "mauve-800": "#2A212C",
  "mauve-900": "#1D161E",
  "mauve-950": "#0C090C",
  "mist-100": "#F1F3F3",
  "mist-200": "#E3E7E8",
  "mist-300": "#D0D6D8",
  "mist-400": "#9CA8AB",
  "mist-50": "#F9FBFB",
  "mist-500": "#67787C",
  "mist-600": "#4B585B",
  "mist-700": "#394447",
  "mist-800": "#22292B",
  "mist-900": "#161B1D",
  "mist-950": "#090B0C",
  "neutral-100": "#F5F5F5",
  "neutral-200": "#E5E5E5",
  "neutral-300": "#D4D4D4",
  "neutral-400": "#A1A1A1",
  "neutral-50": "#FAFAFA",
  "neutral-500": "#737373",
  "neutral-600": "#525252",
  "neutral-700": "#404040",
  "neutral-800": "#262626",
  "neutral-900": "#171717",
  "neutral-950": "#0A0A0A",
  "olive-100": "#F4F4F0",
  "olive-200": "#E8E8E3",
  "olive-300": "#D8D8D0",
  "olive-400": "#ABAB9C",
  "olive-50": "#FBFBF9",
  "olive-500": "#7C7C67",
  "olive-600": "#5B5B4B",
  "olive-700": "#474739",
  "olive-800": "#2B2B22",
  "olive-900": "#1D1D16",
  "olive-950": "#0C0C09",
  "orange-100": "#FFEDD4",
  "orange-200": "#FFD6A7",
  "orange-300": "#FFB86A",
  "orange-400": "#FF8904",
  "orange-50": "#FFF7ED",
  "orange-500": "#FF6900",
  "orange-600": "#F54900",
  "orange-700": "#CA3500",
  "orange-800": "#9F2D00",
  "orange-900": "#7E2A0C",
  "orange-950": "#441306",
  "pink-100": "#FCE7F3",
  "pink-200": "#FCCEE8",
  "pink-300": "#FDA5D5",
  "pink-400": "#FB64B6",
  "pink-50": "#FDF2F8",
  "pink-500": "#F6339A",
  "pink-600": "#E60076",
  "pink-700": "#C6005C",
  "pink-800": "#A3004C",
  "pink-900": "#861043",
  "pink-950": "#510424",
  "purple-100": "#F3E8FF",
  "purple-200": "#E9D4FF",
  "purple-300": "#DAB2FF",
  "purple-400": "#C27AFF",
  "purple-50": "#FAF5FF",
  "purple-500": "#AD46FF",
  "purple-600": "#9810FA",
  "purple-700": "#8200DB",
  "purple-800": "#6E11B0",
  "purple-900": "#59168B",
  "purple-950": "#3C0366",
  "red-100": "#FFE2E2",
  "red-200": "#FFC9C9",
  "red-300": "#FFA2A2",
  "red-400": "#FF6467",
  "red-50": "#FEF2F2",
  "red-500": "#FB2C36",
  "red-600": "#E7000B",
  "red-700": "#C10007",
  "red-800": "#9F0712",
  "red-900": "#82181A",
  "red-950": "#460809",
  "rose-100": "#FFE4E6",
  "rose-200": "#FFCCD3",
  "rose-300": "#FFA1AD",
  "rose-400": "#FF637E",
  "rose-50": "#FFF1F2",
  "rose-500": "#FF2056",
  "rose-600": "#EC003F",
  "rose-700": "#C70036",
  "rose-800": "#A50036",
  "rose-900": "#8B0836",
  "rose-950": "#4D0218",
  "sky-100": "#DFF2FE",
  "sky-200": "#B8E6FE",
  "sky-300": "#74D4FF",
  "sky-400": "#00BCFF",
  "sky-50": "#F0F9FF",
  "sky-500": "#00A6F4",
  "sky-600": "#0084D1",
  "sky-700": "#0069A8",
  "sky-800": "#00598A",
  "sky-900": "#024A70",
  "sky-950": "#052F4A",
  "slate-100": "#F1F5F9",
  "slate-200": "#E2E8F0",
  "slate-300": "#CAD5E2",
  "slate-400": "#90A1B9",
  "slate-50": "#F8FAFC",
  "slate-500": "#62748E",
  "slate-600": "#45556C",
  "slate-700": "#314158",
  "slate-800": "#1D293D",
  "slate-900": "#0F172B",
  "slate-950": "#020618",
  "stone-100": "#F5F5F4",
  "stone-200": "#E7E5E4",
  "stone-300": "#D6D3D1",
  "stone-400": "#A6A09B",
  "stone-50": "#FAFAF9",
  "stone-500": "#79716B",
  "stone-600": "#57534D",
  "stone-700": "#44403B",
  "stone-800": "#292524",
  "stone-900": "#1C1917",
  "stone-950": "#0C0A09",
  "taupe-100": "#F3F1F1",
  "taupe-200": "#E8E4E3",
  "taupe-300": "#D8D2D0",
  "taupe-400": "#ABA09C",
  "taupe-50": "#FBFAF9",
  "taupe-500": "#7C6D67",
  "taupe-600": "#5B4F4B",
  "taupe-700": "#473C39",
  "taupe-800": "#2B2422",
  "taupe-900": "#1D1816",
  "taupe-950": "#0C0A09",
  "teal-100": "#CBFBF1",
  "teal-200": "#96F7E4",
  "teal-300": "#46ECD5",
  "teal-400": "#00D5BE",
  "teal-50": "#F0FDFA",
  "teal-500": "#00BBA7",
  "teal-600": "#009689",
  "teal-700": "#00786F",
  "teal-800": "#005F5A",
  "teal-900": "#0B4F4A",
  "teal-950": "#022F2E",
  "violet-100": "#EDE9FE",
  "violet-200": "#DDD6FF",
  "violet-300": "#C4B4FF",
  "violet-400": "#A684FF",
  "violet-50": "#F5F3FF",
  "violet-500": "#8E51FF",
  "violet-600": "#7F22FE",
  "violet-700": "#7008E7",
  "violet-800": "#5D0EC0",
  "violet-900": "#4D179A",
  "violet-950": "#2F0D68",
  white: "#FFFFFF",
  "yellow-100": "#FEF9C2",
  "yellow-200": "#FFF085",
  "yellow-300": "#FFDF20",
  "yellow-400": "#FDC700",
  "yellow-50": "#FEFCE8",
  "yellow-500": "#F0B100",
  "yellow-600": "#D08700",
  "yellow-700": "#A65F00",
  "yellow-800": "#894B00",
  "yellow-900": "#733E0A",
  "yellow-950": "#432004",
  "zinc-100": "#F4F4F5",
  "zinc-200": "#E4E4E7",
  "zinc-300": "#D4D4D8",
  "zinc-400": "#9F9FA9",
  "zinc-50": "#FAFAFA",
  "zinc-500": "#71717B",
  "zinc-600": "#52525C",
  "zinc-700": "#3F3F46",
  "zinc-800": "#27272A",
  "zinc-900": "#18181B",
  "zinc-950": "#09090B"
};

// node_modules/@oai/granola/dist/models/presentation/utils/tailwind/parse-tailwind-color-token.js
var clampUnit = (value) => {
  if (!Number.isFinite(value))
    return 0;
  if (value < 0)
    return 0;
  if (value > 1)
    return 1;
  return value;
};
var parseAlpha = (raw) => {
  if (!raw)
    return;
  const trimmed = raw.trim();
  if (!trimmed)
    return;
  if (trimmed.endsWith("%")) {
    const numeric2 = Number(trimmed.slice(0, -1));
    if (Number.isNaN(numeric2))
      return;
    return clampUnit(numeric2 / 100);
  }
  const numeric = Number(trimmed);
  if (Number.isNaN(numeric))
    return;
  if (numeric > 1) {
    return clampUnit(numeric / 100);
  }
  return clampUnit(numeric);
};
function parseTailwindColorToken(input) {
  const trimmed = input.trim();
  if (!trimmed)
    return null;
  const normalized = trimmed.toLowerCase();
  const slashIndex = normalized.indexOf("/");
  const base = (slashIndex >= 0 ? normalized.slice(0, slashIndex) : normalized).trim();
  const alphaRaw = slashIndex >= 0 ? normalized.slice(slashIndex + 1) : undefined;
  if (!base)
    return null;
  const hex2 = TAILWIND_COLOR_HEX_BY_TOKEN[base];
  if (typeof hex2 !== "string") {
    return null;
  }
  const alpha = parseAlpha(alphaRaw);
  return alpha === undefined ? { hex: hex2 } : { hex: hex2, alpha };
}

// node_modules/@oai/granola/dist/models/presentation/color.js
var THEME_COLOR_NAMES = [
  "accent1",
  "accent2",
  "accent3",
  "accent4",
  "accent5",
  "accent6",
  "bg1",
  "bg2",
  "tx1",
  "tx2",
  "dk1",
  "lt1",
  "dk2",
  "lt2",
  "hlink",
  "folHlink"
];
var THEME_COLOR_SET = new Set(THEME_COLOR_NAMES);
var THEME_COLOR_ALIASES = {
  background1: "bg1",
  background2: "bg2",
  text1: "tx1",
  text2: "tx2",
  dark1: "dk1",
  dark2: "dk2",
  light1: "lt1",
  light2: "lt2"
};
var PB_COLOR_TYPE_TO_COLOR_TYPE = {
  [0 /* COLOR_TYPE_UNSPECIFIED */]: "unspecified",
  [1 /* COLOR_TYPE_RGB */]: "rgb",
  [2 /* COLOR_TYPE_SCHEME */]: "theme",
  [3 /* COLOR_TYPE_SYSTEM */]: "system",
  [-1 /* UNRECOGNIZED */]: "unspecified"
};
var HEX_PATTERN = /^[0-9a-f]+$/i;
var RGB_INPUT_PATTERN = /^rgba?\(\s*(\d{1,3})\s*(?:,\s*|\s+)(\d{1,3})\s*(?:,\s*|\s+)(\d{1,3})(?:\s*(?:\/|,)\s*([\d.]+%?))?\s*\)$/i;
var DEFAULT_HEX = "#000000";
var DEBUG = false;
function warn(message) {
  if (DEBUG) {
    console.warn(`[Color] ${message}`);
  }
}
function isThemeColorName(candidate) {
  return THEME_COLOR_SET.has(candidate);
}
function clampChannel(value) {
  if (Number.isNaN(value)) {
    return 0;
  }
  return Math.min(Math.max(Math.round(value), 0), 255);
}
function toChannelHex(value) {
  return clampChannel(value).toString(16).padStart(2, "0");
}
function clampUnit2(value) {
  if (Number.isNaN(value)) {
    return 0;
  }
  return Math.min(Math.max(value, 0), 1);
}
function normalizePercentLikeUnit(value) {
  if (Number.isNaN(value)) {
    return 0;
  }
  if (value > 1) {
    return clampUnit2(value / 100);
  }
  return clampUnit2(value);
}
function friendlyTransformToProto(transform) {
  if (!transform) {
    return;
  }
  const hasAny = Object.values(transform).some((v) => v !== undefined);
  if (!hasAny) {
    return;
  }
  const { opacity, lighten, darken } = transform;
  const hasLighten = typeof lighten === "number" && lighten !== 0;
  const hasDarken = typeof darken === "number" && darken !== 0;
  if (hasLighten && hasDarken) {
    throw new Error("Color transform cannot set both lighten and darken; pick one.");
  }
  const next = {};
  if (typeof opacity === "number") {
    next.alpha = Math.round(normalizePercentLikeUnit(opacity) * 1e5);
  }
  if (typeof lighten === "number" && lighten !== 0) {
    next.tint = Math.round(normalizePercentLikeUnit(lighten) * 1e5);
  }
  if (typeof darken === "number" && darken !== 0) {
    next.tint = -Math.round(normalizePercentLikeUnit(darken) * 1e5);
  }
  const hasAlpha = next.alpha !== undefined;
  const hasTint = next.tint !== undefined && next.tint !== 0;
  return hasAlpha || hasTint ? next : undefined;
}
function protoTransformToFriendly(transform) {
  if (!transform) {
    return;
  }
  const alpha = transform.alpha;
  const tint = transform.tint;
  const friendly = {};
  if (typeof alpha === "number") {
    friendly.opacity = clampUnit2(alpha / 1e5);
  }
  if (typeof tint === "number" && tint !== 0) {
    const unit2 = Math.min(Math.max(tint / 1e5, -1), 1);
    if (unit2 > 0) {
      friendly.lighten = unit2;
    } else if (unit2 < 0) {
      friendly.darken = Math.abs(unit2);
    }
  }
  return Object.keys(friendly).length > 0 ? friendly : undefined;
}
function parseAlphaComponent(token) {
  if (!token) {
    return;
  }
  const trimmed = token.trim();
  if (!trimmed) {
    return;
  }
  if (trimmed.endsWith("%")) {
    const numeric2 = Number(trimmed.slice(0, -1));
    if (Number.isNaN(numeric2)) {
      return;
    }
    return clampUnit2(numeric2 / 100);
  }
  const numeric = Number(trimmed);
  if (Number.isNaN(numeric)) {
    return;
  }
  if (numeric > 1 && numeric <= 100) {
    return clampUnit2(numeric / 100);
  }
  return clampUnit2(numeric);
}
function parseHexColor(input) {
  if (!input.startsWith("#")) {
    return null;
  }
  const raw = input.slice(1);
  if (!HEX_PATTERN.test(raw)) {
    return null;
  }
  if (raw.length === 3 || raw.length === 4) {
    const [r, g, b] = raw.slice(0, 3);
    const hex2 = `#${r}${r}${g}${g}${b}${b}`.toUpperCase();
    if (raw.length === 4) {
      const channel = raw[3];
      const alphaHex = `${channel}${channel}`;
      const alpha = parseInt(alphaHex, 16);
      if (Number.isNaN(alpha)) {
        return null;
      }
      return { hex: hex2, alpha: clampUnit2(alpha / 255) };
    }
    return { hex: hex2 };
  }
  if (raw.length === 6) {
    return { hex: `#${raw.toUpperCase()}` };
  }
  if (raw.length === 8) {
    const rgb2 = raw.slice(0, 6);
    const alphaHex = raw.slice(6);
    const alpha = parseInt(alphaHex, 16);
    if (Number.isNaN(alpha)) {
      return null;
    }
    return { hex: `#${rgb2.toUpperCase()}`, alpha: clampUnit2(alpha / 255) };
  }
  return null;
}
function parseRgbColor(input) {
  const match = RGB_INPUT_PATTERN.exec(input);
  if (!match) {
    return null;
  }
  const r = clampChannel(Number(match[1]));
  const g = clampChannel(Number(match[2]));
  const b = clampChannel(Number(match[3]));
  const alpha = parseAlphaComponent(match[4]);
  return {
    hex: `#${toChannelHex(r)}${toChannelHex(g)}${toChannelHex(b)}`.toUpperCase(),
    alpha
  };
}
function parseColorTransformUnit(token) {
  const trimmed = token.trim();
  if (!trimmed) {
    return;
  }
  if (trimmed.endsWith("%")) {
    const numeric2 = Number(trimmed.slice(0, -1));
    return Number.isFinite(numeric2) ? numeric2 : undefined;
  }
  const numeric = Number(trimmed);
  return Number.isFinite(numeric) ? numeric : undefined;
}
function parseColorTransformSuffix(input) {
  const trimmed = input.trim();
  if (!trimmed || trimmed.includes("(")) {
    return null;
  }
  let working = trimmed;
  let opacity;
  let lighten;
  let darken;
  const opacityMatch = /^(.*)\/([\d.]+%?)$/.exec(working);
  if (opacityMatch) {
    working = opacityMatch[1]?.trim() ?? "";
    opacity = parseColorTransformUnit(opacityMatch[2] ?? "");
    if (opacity === undefined) {
      return null;
    }
  }
  const tintMatch = /^(.*?)([+-])([\d.]+%?)$/.exec(working);
  if (tintMatch) {
    working = tintMatch[1]?.trim() ?? "";
    const amount = parseColorTransformUnit(tintMatch[3] ?? "");
    if (amount === undefined) {
      return null;
    }
    if (tintMatch[2] === "+") {
      lighten = amount;
    } else {
      darken = amount;
    }
  }
  if (!working || opacity === undefined && lighten === undefined && darken === undefined) {
    return null;
  }
  return {
    base: working,
    transform: {
      opacity,
      lighten,
      darken
    }
  };
}
function resolveBaseColorString(input) {
  const trimmed = input.trim();
  if (!trimmed) {
    return null;
  }
  const lowered = trimmed.toLowerCase();
  const normalized = THEME_COLOR_ALIASES[lowered] ?? lowered;
  if (isThemeColorName(normalized)) {
    return {
      type: 2 /* COLOR_TYPE_SCHEME */,
      value: normalized
    };
  }
  if (lowered === "transparent") {
    return {
      type: 1 /* COLOR_TYPE_RGB */,
      value: DEFAULT_HEX,
      alpha: 0
    };
  }
  if (!trimmed.startsWith("#") && HEX_PATTERN.test(trimmed) && [3, 4, 6, 8].includes(trimmed.length)) {
    const hexCandidate2 = parseHexColor(`#${trimmed}`);
    if (hexCandidate2) {
      return {
        type: 1 /* COLOR_TYPE_RGB */,
        value: hexCandidate2.hex,
        alpha: hexCandidate2.alpha
      };
    }
  }
  const hexCandidate = parseHexColor(trimmed);
  if (hexCandidate) {
    return {
      type: 1 /* COLOR_TYPE_RGB */,
      value: hexCandidate.hex,
      alpha: hexCandidate.alpha
    };
  }
  const rgbCandidate = parseRgbColor(trimmed);
  if (rgbCandidate) {
    return {
      type: 1 /* COLOR_TYPE_RGB */,
      value: rgbCandidate.hex,
      alpha: rgbCandidate.alpha
    };
  }
  const tailwindCandidate = parseTailwindColorToken(trimmed);
  if (tailwindCandidate) {
    return {
      type: 1 /* COLOR_TYPE_RGB */,
      value: tailwindCandidate.hex,
      alpha: tailwindCandidate.alpha
    };
  }
  return null;
}

class Color4 {
  #data;
  #isSet = false;
  #hexCache;
  #runtime;
  constructor(config, runtime) {
    this.#runtime = runtime;
    this.#isSet = true;
    if (typeof config === "string") {
      this.#data = {
        type: 1 /* COLOR_TYPE_RGB */,
        value: config,
        transform: undefined,
        lastColor: undefined
      };
      this.#data.value = this.#tryResolveString(config);
    } else if (config?.type === "proto") {
      if (!config.proto || config.proto.type === 0 /* COLOR_TYPE_UNSPECIFIED */) {
        this.#data = {
          type: 0 /* COLOR_TYPE_UNSPECIFIED */,
          value: "",
          transform: undefined,
          lastColor: undefined
        };
        this.#isSet = false;
        this.#hexCache = undefined;
        return;
      } else {
        this.#data = {
          type: config.proto?.type,
          value: config.proto?.value,
          transform: config.proto?.transform,
          lastColor: config.proto?.lastColor
        };
        if (this.#data.type === 1 /* COLOR_TYPE_RGB */ && this.#data.value.length === 8) {
          this.#data.value = this.#data.value.slice(2);
        }
        if (this.#data.type === 1 /* COLOR_TYPE_RGB */) {
          this.#data.value = normalizeHexValue(this.#data.value);
        }
      }
    } else if (config?.type === "rgb") {
      const normalized = normalizeHexValue(config.value);
      this.#data = {
        type: 1 /* COLOR_TYPE_RGB */,
        value: normalized,
        transform: friendlyTransformToProto(config.transform),
        lastColor: undefined
      };
    } else if (config?.type === "theme") {
      this.#data = {
        type: 2 /* COLOR_TYPE_SCHEME */,
        value: config.value,
        transform: friendlyTransformToProto(config.transform),
        lastColor: undefined
      };
    } else {
      throw new Error("Invalid color config");
    }
    this.#recomputeHexCache();
  }
  get value() {
    return this.#data.value;
  }
  get hex() {
    if (!this.#isSet) {
      warn("Color.hex() is not available for unset colors; defaulting to #000000.");
      return DEFAULT_HEX;
    }
    if (this.#hexCache === undefined) {
      this.#recomputeHexCache();
    }
    return this.#hexCache ?? DEFAULT_HEX;
  }
  #tryResolveString(value) {
    const trimmed = value.trim();
    if (!trimmed) {
      warn("Color string cannot be empty; defaulting to #000000.");
      this.#data.type = 1 /* COLOR_TYPE_RGB */;
      this.#applyAlphaTransform(undefined);
      return DEFAULT_HEX;
    }
    const transformed = parseColorTransformSuffix(trimmed);
    const resolved = (transformed ? resolveBaseColorString(transformed.base) : null) ?? resolveBaseColorString(trimmed);
    if (resolved) {
      this.#data.type = resolved.type;
      this.#data.value = resolved.value;
      const transform = transformed?.transform;
      const combinedOpacity = typeof resolved.alpha === "number" || typeof transform?.opacity === "number" ? (resolved.alpha ?? 1) * normalizePercentLikeUnit(transform?.opacity ?? 1) : undefined;
      const nextTransform = friendlyTransformToProto({
        opacity: combinedOpacity,
        lighten: transform?.lighten,
        darken: transform?.darken
      });
      this.#data.transform = nextTransform;
      return resolved.value;
    }
    warn(`Unsupported color string "${value}"; defaulting to #000000.`);
    this.#data.type = 1 /* COLOR_TYPE_RGB */;
    this.#data.value = DEFAULT_HEX;
    this.#applyAlphaTransform(undefined);
    return DEFAULT_HEX;
  }
  #applyAlphaTransform(alpha) {
    if (alpha === undefined || Number.isNaN(alpha) || alpha >= 1) {
      if (!this.#data.transform) {
        this.#recomputeHexCache();
        return;
      }
      const { alpha: _ignored, ...rest } = this.#data.transform;
      const hasValues = Object.values(rest).some((val) => val !== undefined && val !== 0);
      this.#data.transform = hasValues ? rest : undefined;
      this.#recomputeHexCache();
      return;
    }
    const normalized = Math.max(0, Math.min(alpha, 1));
    const next = { ...this.#data.transform ?? {} };
    next.alpha = Math.round(normalized * 1e5);
    this.#data.transform = next;
    this.#recomputeHexCache();
  }
  get transform() {
    return this.#data.transform;
  }
  set transform(next) {
    this.#data.transform = next;
    this.#recomputeHexCache();
  }
  get type() {
    return PB_COLOR_TYPE_TO_COLOR_TYPE[this.#data.type];
  }
  toProto() {
    if (!this.#isSet) {
      return;
    }
    const value = this.#data.type === 1 /* COLOR_TYPE_RGB */ ? normalizeHexValue(this.#data.value).slice(1) : this.#data.value;
    return {
      type: this.#data.type,
      value,
      transform: this.#data.transform,
      lastColor: this.#data.lastColor
    };
  }
  toConfig() {
    if (!this.#isSet) {
      return;
    }
    if (this.type === "theme") {
      const friendly = protoTransformToFriendly(this.#data.transform);
      if (!friendly) {
        return this.#data.value;
      }
      return {
        type: "theme",
        value: this.#data.value,
        transform: friendly
      };
    }
    if (this.type === "rgb") {
      const transform = this.#data.transform;
      const alpha = transform?.alpha;
      const { alpha: _ignored, ...rest } = transform ?? {};
      const hasNonAlphaTransform = Object.values(rest).some((value) => value !== undefined && value !== 0);
      const normalized = normalizeHexValue(this.#data.value);
      const transformedHex = hasNonAlphaTransform ? applyTransformToHex(normalized, transform) : normalized;
      if (typeof alpha === "number") {
        const { r, g, b } = hexToRgb(transformedHex);
        const normalizedAlpha = clampUnit2(alpha / 1e5);
        return `rgba(${r}, ${g}, ${b}, ${normalizedAlpha})`;
      }
      return transformedHex;
    }
    if (this.type === "system") {
      const lastColor = this.#data.lastColor;
      return lastColor ? normalizeHexValue(lastColor) : DEFAULT_HEX;
    }
    return;
  }
  toMarkdown() {
    return this.hex;
  }
  clone() {
    return new Color4({ type: "proto", proto: this.#data });
  }
  #recomputeHexCache() {
    if (!this.#isSet) {
      this.#hexCache = undefined;
      return;
    }
    const type = this.#data.type ?? 0 /* COLOR_TYPE_UNSPECIFIED */;
    if (type === 1 /* COLOR_TYPE_RGB */) {
      this.#hexCache = applyTransformToHex(this.#data.value, this.#data.transform);
      return;
    }
    if (type === 3 /* COLOR_TYPE_SYSTEM */) {
      let lastColor = this.#data.lastColor;
      if (!lastColor) {
        warn("System color missing lastColor fallback; defaulting to #000000.");
        lastColor = DEFAULT_HEX;
      }
      this.#hexCache = applyTransformToHex(lastColor, this.#data.transform);
      return;
    }
    if (type === 2 /* COLOR_TYPE_SCHEME */) {
      const resolver = this.#runtime?.resolveThemeColor;
      if (!resolver) {
        warn("Color.hex() cannot resolve theme colors without a PresentationRuntime; defaulting to #000000.");
        this.#hexCache = DEFAULT_HEX;
        return;
      }
      const resolved = resolver(this.#data.value);
      if (!resolved) {
        warn(`Presentation runtime could not resolve theme color "${this.#data.value}"; defaulting to #000000.`);
        this.#hexCache = DEFAULT_HEX;
        return;
      }
      const normalized = normalizeHexValue(resolved);
      this.#hexCache = applyTransformToHex(normalized, this.#data.transform);
      return;
    }
    warn("Color has an unsupported type; defaulting to #000000.");
    this.#hexCache = DEFAULT_HEX;
  }
}
function normalizeHexValue(raw) {
  if (!raw) {
    warn("Color is missing a hex value; defaulting to #000000.");
    return DEFAULT_HEX;
  }
  const candidate = raw.startsWith("#") ? raw : `#${raw}`;
  const parsed = parseHexColor(candidate);
  if (!parsed) {
    warn(`Invalid hex color "${raw}"; defaulting to #000000.`);
    return DEFAULT_HEX;
  }
  return parsed.hex;
}
function applyTransformToHex(baseHex, transform) {
  const normalizedBase = normalizeHexValue(baseHex);
  if (!transform) {
    return normalizedBase.toUpperCase();
  }
  return rgbToHex(applyOpenXmlColorTransform(hexToRgb(normalizedBase), transform, "drawingml"));
}

// node_modules/@oai/granola/dist/models/presentation/pattern.js
var PATTERN_TYPE_TO_NAME_MAP = {
  [0 /* PATTERN_TYPE_UNSPECIFIED */]: null,
  [-1 /* UNRECOGNIZED */]: null
};
for (const [name, patternType] of Object.entries(PATTERN_NAME_TO_TYPE_MAP)) {
  PATTERN_TYPE_TO_NAME_MAP[patternType] = name;
}
var PATTERN_TYPE_TO_NAME = PATTERN_TYPE_TO_NAME_MAP;
var PATTERN_NAME_TO_TYPE = PATTERN_NAME_TO_TYPE_MAP;

class Pattern {
  #data = {
    patternType: 0 /* PATTERN_TYPE_UNSPECIFIED */
  };
  #color;
  #isSet = false;
  constructor(config) {
    if (config.type === "proto") {
      const proto = config.proto;
      if (!proto) {
        return;
      }
      this.#data.patternType = proto.patternType ?? 0 /* PATTERN_TYPE_UNSPECIFIED */;
      this.#color = proto.color ? new Color4({ type: "proto", proto: proto.color }) : undefined;
      this.#updateIsSet();
      return;
    }
    this.#data.patternType = PATTERN_NAME_TO_TYPE[config.type];
    this.#color = new Color4(config.color);
    this.#updateIsSet();
  }
  get type() {
    return PATTERN_TYPE_TO_NAME[this.#data.patternType];
  }
  set type(type) {
    this.#data.patternType = PATTERN_NAME_TO_TYPE[type];
    this.#updateIsSet();
  }
  get color() {
    return this.#color;
  }
  set color(color2) {
    this.#color = color2 instanceof Color4 ? color2 : new Color4(color2);
    this.#updateIsSet();
  }
  toProto() {
    if (!this.#isSet) {
      return null;
    }
    return {
      patternType: this.#data.patternType,
      color: this.#color?.toProto() ?? undefined
    };
  }
  toConfig() {
    if (!this.#isSet) {
      return;
    }
    const type = this.type;
    if (!type || !this.#color) {
      return;
    }
    const color2 = this.#color.toConfig();
    if (!color2) {
      return;
    }
    return { type, color: color2 };
  }
  #updateIsSet() {
    this.#isSet = this.#data.patternType !== 0 /* PATTERN_TYPE_UNSPECIFIED */ || !!this.#color;
  }
}

// node_modules/@oai/granola/dist/models/presentation/style-language/shared.js
var WHITESPACE = /\s/;
function splitTopLevel(value, separator) {
  const parts = [];
  let depth = 0;
  let quote = null;
  let current = "";
  for (let index = 0;index < value.length; index += 1) {
    const char = value[index];
    if (!char) {
      continue;
    }
    if (quote) {
      current += char;
      if (char === quote && value[index - 1] !== "\\") {
        quote = null;
      }
      continue;
    }
    if (char === '"' || char === "'") {
      quote = char;
      current += char;
      continue;
    }
    if (char === "(") {
      depth += 1;
      current += char;
      continue;
    }
    if (char === ")") {
      depth = Math.max(0, depth - 1);
      current += char;
      continue;
    }
    if (char === separator && depth === 0) {
      const trimmed2 = current.trim();
      if (trimmed2.length > 0) {
        parts.push(trimmed2);
      }
      current = "";
      continue;
    }
    current += char;
  }
  const trimmed = current.trim();
  if (trimmed.length > 0) {
    parts.push(trimmed);
  }
  return parts;
}
function splitTopLevelWhitespace(value) {
  const parts = [];
  let depth = 0;
  let quote = null;
  let current = "";
  const pushCurrent = () => {
    const trimmed = current.trim();
    if (trimmed.length > 0) {
      parts.push(trimmed);
    }
    current = "";
  };
  for (let index = 0;index < value.length; index += 1) {
    const char = value[index];
    if (!char) {
      continue;
    }
    if (quote) {
      current += char;
      if (char === quote && value[index - 1] !== "\\") {
        quote = null;
      }
      continue;
    }
    if (char === '"' || char === "'") {
      quote = char;
      current += char;
      continue;
    }
    if (char === "(") {
      depth += 1;
      current += char;
      continue;
    }
    if (char === ")") {
      depth = Math.max(0, depth - 1);
      current += char;
      continue;
    }
    if (depth === 0 && WHITESPACE.test(char)) {
      pushCurrent();
      continue;
    }
    current += char;
  }
  pushCurrent();
  return parts;
}
function stripFunctionCall(value, names) {
  const trimmed = value.trim();
  const openParen = trimmed.indexOf("(");
  if (openParen <= 0 || !trimmed.endsWith(")")) {
    return null;
  }
  const name = trimmed.slice(0, openParen).trim().toLowerCase();
  if (!names.includes(name)) {
    return null;
  }
  return trimmed.slice(openParen + 1, -1).trim();
}
function parsePixelLength(value) {
  const trimmed = value.trim().toLowerCase();
  const match = /^(-?\d+(?:\.\d+)?)(px)?$/.exec(trimmed);
  if (!match) {
    return null;
  }
  const numeric = Number(match[1]);
  return Number.isFinite(numeric) ? numeric : null;
}
function parseAngleDegrees(value) {
  const trimmed = value.trim().toLowerCase();
  const match = /^(-?\d+(?:\.\d+)?)deg$/.exec(trimmed);
  if (!match) {
    return null;
  }
  const numeric = Number(match[1]);
  return Number.isFinite(numeric) ? numeric : null;
}
function parsePercent(value) {
  const trimmed = value.trim();
  const match = /^(-?\d+(?:\.\d+)?)%$/.exec(trimmed);
  if (!match) {
    return null;
  }
  const numeric = Number(match[1]);
  return Number.isFinite(numeric) ? numeric : null;
}
function parsePercentLike(value) {
  const trimmed = value.trim();
  const normalized = trimmed.endsWith("%") ? trimmed.slice(0, -1) : trimmed;
  const numeric = Number(normalized);
  return Number.isFinite(numeric) ? numeric : null;
}
function unquote(value) {
  const trimmed = value.trim();
  if (trimmed.length >= 2 && (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'"))) {
    return trimmed.slice(1, -1);
  }
  return trimmed;
}

// node_modules/@oai/granola/dist/models/presentation/style-language/fill-string.js
function parseFillStyleString(value) {
  const trimmed = value.trim();
  if (!trimmed) {
    return null;
  }
  if (trimmed.toLowerCase() === "none") {
    return { type: "none" };
  }
  const linearBody = stripFunctionCall(trimmed, ["linear", "gradient"]);
  if (linearBody !== null) {
    return parseGradientFill(linearBody, "linear");
  }
  const pathBody = stripFunctionCall(trimmed, ["path", "radial"]);
  if (pathBody !== null) {
    return parseGradientFill(pathBody, "path");
  }
  return null;
}
function parseGradientFill(body, gradientKind) {
  const args = splitTopLevel(body, ",");
  if (args.length < 2) {
    throw new Error(`${gradientKind}(...) fill requires at least two color stops.`);
  }
  let angleDeg;
  let stopArgs = args;
  const firstAngle = parseAngleDegrees(args[0] ?? "");
  if (gradientKind === "linear" && firstAngle !== null) {
    angleDeg = firstAngle;
    stopArgs = args.slice(1);
  }
  if (stopArgs.length < 2) {
    throw new Error(`${gradientKind}(...) fill requires at least two color stops.`);
  }
  const parsedStops = stopArgs.map(parseGradientStop);
  const resolvedStops = resolveGradientStopOffsets(parsedStops);
  return {
    type: "gradient",
    gradientKind,
    angleDeg,
    stops: resolvedStops
  };
}
function parseGradientStop(value) {
  const trimmed = value.trim();
  if (!trimmed) {
    throw new Error("Gradient stop cannot be empty.");
  }
  let depth = 0;
  for (let index = trimmed.length - 1;index >= 0; index -= 1) {
    const char = trimmed[index];
    if (!char) {
      continue;
    }
    if (char === ")") {
      depth += 1;
      continue;
    }
    if (char === "(") {
      depth = Math.max(0, depth - 1);
      continue;
    }
    if (depth === 0 && /\s/.test(char)) {
      const color2 = trimmed.slice(0, index).trim();
      const maybeOffset = trimmed.slice(index + 1).trim();
      const percent = parsePercent(maybeOffset);
      if (color2.length > 0 && percent !== null) {
        return {
          color: color2,
          offset: percent
        };
      }
      break;
    }
  }
  return { color: trimmed };
}
function resolveGradientStopOffsets(stops) {
  if (stops.every((stop) => stop.offset !== undefined)) {
    return stops.map((stop) => ({
      color: stop.color,
      offset: percentToGradientOffset(stop.offset ?? 0)
    }));
  }
  const lastIndex = stops.length - 1;
  return stops.map((stop, index) => ({
    color: stop.color,
    offset: percentToGradientOffset(index / lastIndex * 100)
  }));
}
function percentToGradientOffset(percent) {
  return Math.max(0, Math.min(Math.round(percent * 1000), 1e5));
}
// node_modules/@oai/granola/dist/models/presentation/style-language/text-style-string.js
function looksLikeTextStyleDeclaration(value) {
  const trimmed = value.trim();
  return trimmed.includes(":") || trimmed.includes(";");
}
function parseTextStyleString(value) {
  const trimmed = value.trim();
  if (!trimmed) {
    return {};
  }
  const declarations = splitTopLevel(trimmed, ";");
  const style = {};
  declarations.forEach((declaration) => {
    const separator = declaration.indexOf(":");
    if (separator <= 0) {
      throw new Error(`Text style declaration "${declaration}" must use "key: value" syntax.`);
    }
    const rawKey = declaration.slice(0, separator).trim().toLowerCase();
    const rawValue = declaration.slice(separator + 1).trim();
    if (!rawValue) {
      return;
    }
    switch (rawKey) {
      case "font":
        applyFontShorthand(style, rawValue);
        return;
      case "size":
      case "font-size": {
        const size = parseFontSize(rawValue);
        if (size !== null) {
          style.fontSize = size;
        }
        return;
      }
      case "family":
      case "font-family":
      case "typeface":
        style.typeface = unquote(rawValue);
        return;
      case "weight":
      case "font-weight":
        style.bold = parseFontWeight(rawValue);
        return;
      case "italic":
      case "font-style":
        style.italic = parseBooleanLike(rawValue, "italic");
        return;
      case "color":
        style.color = rawValue;
        return;
      case "fill":
        style.fill = rawValue;
        return;
      case "leading":
      case "line-height": {
        const lineSpacing = parsePercentLike(rawValue);
        if (lineSpacing !== null) {
          style.lineSpacing = lineSpacing;
        }
        return;
      }
      case "align":
      case "alignment":
        style.alignment = rawValue;
        return;
      case "wrap":
        style.wrap = normalizeWrap(rawValue);
        return;
      case "underline":
        style.underline = parseUnderline(rawValue);
        return;
      case "inset":
      case "insets":
      case "padding":
        style.insets = parseInsets(rawValue);
        return;
      case "autofit":
      case "auto-fit":
        style.autoFit = normalizeAutoFit(rawValue);
        return;
      default:
        throw new Error(`Unsupported text style declaration key "${rawKey}".`);
    }
  });
  return style;
}
function normalizeComposeTextStyleRef(value) {
  if (typeof value !== "string") {
    return value;
  }
  return looksLikeTextStyleDeclaration(value) ? parseTextStyleString(value) : value;
}
function applyFontShorthand(style, value) {
  const tokens = splitTopLevelWhitespace(value);
  if (tokens.length === 0) {
    return;
  }
  let sizeIndex = -1;
  let lineHeight;
  tokens.forEach((token, index) => {
    if (sizeIndex >= 0) {
      return;
    }
    const [sizeToken, lineHeightToken] = token.split("/", 2);
    const size = parseFontShorthandSize(sizeToken ?? "");
    if (size === null) {
      return;
    }
    sizeIndex = index;
    style.fontSize = size;
    if (lineHeightToken) {
      const parsedLineHeight = parsePercentLike(lineHeightToken);
      if (parsedLineHeight !== null) {
        lineHeight = parsedLineHeight;
      }
    }
  });
  if (lineHeight !== undefined) {
    style.lineSpacing = lineHeight;
  }
  if (sizeIndex >= 0) {
    const prefix = tokens.slice(0, sizeIndex);
    const suffix = tokens.slice(sizeIndex + 1);
    prefix.forEach((token) => {
      const normalized = token.toLowerCase();
      if (normalized === "italic") {
        style.italic = true;
        return;
      }
      if (isFontWeightToken(normalized)) {
        style.bold = parseFontWeight(normalized);
      }
    });
    if (suffix.length > 0) {
      style.typeface = unquote(suffix.join(" "));
    }
    return;
  }
  style.typeface = unquote(tokens.join(" "));
}
function parseFontSize(value) {
  const trimmed = value.trim().toLowerCase();
  if (!trimmed) {
    return null;
  }
  if (trimmed.endsWith("pt")) {
    const numeric = Number(trimmed.slice(0, -2));
    if (!Number.isFinite(numeric)) {
      return null;
    }
    return numeric * 96 / 72;
  }
  return parsePixelLength(trimmed);
}
function parseFontShorthandSize(value) {
  const trimmed = value.trim().toLowerCase();
  if (!trimmed || !trimmed.endsWith("px") && !trimmed.endsWith("pt")) {
    return null;
  }
  return parseFontSize(trimmed);
}
function isFontWeightToken(value) {
  return value === "normal" || value === "regular" || value === "medium" || value === "semibold" || value === "bold" || /^\d+$/.test(value);
}
function parseFontWeight(value) {
  const normalized = value.trim().toLowerCase();
  if (normalized === "bold" || normalized === "semibold") {
    return true;
  }
  if (normalized === "medium" || normalized === "normal" || normalized === "regular") {
    return false;
  }
  const numeric = Number(normalized);
  if (!Number.isFinite(numeric)) {
    throw new Error(`Unsupported font weight "${value}".`);
  }
  return numeric >= 600;
}
function parseBooleanLike(value, truthyKeyword) {
  const normalized = value.trim().toLowerCase();
  if (normalized === truthyKeyword || normalized === "true" || normalized === "yes") {
    return true;
  }
  if (normalized === "normal" || normalized === "false" || normalized === "no") {
    return false;
  }
  throw new Error(`Unsupported boolean-like value "${value}".`);
}
function normalizeWrap(value) {
  const normalized = value.trim().toLowerCase();
  if (normalized === "square" || normalized === "wrap" || normalized === "wrapped") {
    return "square";
  }
  if (normalized === "none" || normalized === "nowrap" || normalized === "no-wrap") {
    return "none";
  }
  throw new Error(`Unsupported text wrap value "${value}".`);
}
function parseUnderline(value) {
  const normalized = value.trim().toLowerCase();
  if (normalized === "true" || normalized === "yes" || normalized === "underline") {
    return "sng";
  }
  if (normalized === "false" || normalized === "none") {
    return "none";
  }
  return value.trim();
}
function parseInsets(value) {
  const parts = splitTopLevelWhitespace(value);
  const numeric = parts.map((part) => parsePixelLength(part));
  if (numeric.some((part) => part === null)) {
    throw new Error(`Unsupported inset value "${value}".`);
  }
  const values = numeric;
  if (values.length === 1) {
    return {
      top: values[0],
      right: values[0],
      bottom: values[0],
      left: values[0]
    };
  }
  if (values.length === 2) {
    return {
      top: values[0],
      right: values[1],
      bottom: values[0],
      left: values[1]
    };
  }
  if (values.length === 3) {
    return {
      top: values[0],
      right: values[1],
      bottom: values[2],
      left: values[1]
    };
  }
  if (values.length === 4) {
    return {
      top: values[0],
      right: values[1],
      bottom: values[2],
      left: values[3]
    };
  }
  throw new Error(`Inset value "${value}" must contain 1-4 lengths.`);
}
function normalizeAutoFit(value) {
  const normalized = value.trim().toLowerCase();
  if (normalized === "none") {
    return "none";
  }
  if (normalized === "shrink" || normalized === "shrinktext" || normalized === "shrink-text") {
    return "shrinkText";
  }
  if (normalized === "resize" || normalized === "resizeshapetofittext" || normalized === "resize-shape") {
    return "resizeShapeToFitText";
  }
  throw new Error(`Unsupported autoFit value "${value}".`);
}
// node_modules/@oai/granola/dist/models/presentation/utils/consts.js
var EMUS_PER_PIXEL = 9525;
var PIXELS_PER_EMU = 1 / EMUS_PER_PIXEL;
var POINTS_PER_PIXEL = 72 / 96;
var DEFAULT_SLIDE_WIDTH_EMU = 9144000;
var DEFAULT_SLIDE_HEIGHT_EMU = 6858000;
var pixelsFromEmu = (value) => {
  if (value === undefined || value === null) {
    return 0;
  }
  return value * PIXELS_PER_EMU;
};
var emuFromPixels = (value) => {
  return Math.round(value * EMUS_PER_PIXEL);
};

// node_modules/@oai/granola/dist/models/presentation/style-language/shadow-string.js
function parseShadowStyleString(value) {
  const trimmed = value.trim();
  if (!trimmed) {
    return null;
  }
  if (trimmed.toLowerCase() === "none" || trimmed.toLowerCase() === "shadow-none") {
    return { kind: "none" };
  }
  const tokens = splitTopLevelWhitespace(trimmed);
  if (tokens.length < 3) {
    return null;
  }
  const offsetX = parsePixelLength(tokens[0] ?? "");
  const offsetY = parsePixelLength(tokens[1] ?? "");
  const blur = parsePixelLength(tokens[2] ?? "");
  if (offsetX === null || offsetY === null || blur === null) {
    return null;
  }
  let colorToken = tokens[3];
  if (!colorToken && tokens.length === 3) {
    colorToken = "#000000/0.18";
  } else if (!colorToken) {
    return null;
  }
  const color2 = new Color4(colorToken).toProto();
  const distance = Math.sqrt(offsetX * offsetX + offsetY * offsetY);
  const direction = Math.round(Math.atan2(offsetY, offsetX) * 180 * 60000 / Math.PI);
  return {
    kind: "custom",
    effectStyle: {
      effects: [
        {
          type: 1 /* EFFECT_TYPE_OUTER_SHADOW */,
          shadow: {
            color: color2 ?? undefined,
            blurRadius: emuFromPixels(blur),
            distance: emuFromPixels(distance),
            direction
          }
        }
      ]
    }
  };
}
// node_modules/@oai/granola/dist/models/presentation/fill.js
var MAP_GRADIENT_KIND = {
  [1 /* GRADIENT_KIND_LINEAR */]: "linear",
  [2 /* GRADIENT_KIND_PATH */]: "path",
  [0 /* GRADIENT_KIND_UNSPECIFIED */]: null,
  [-1 /* UNRECOGNIZED */]: null
};
var MAP_GRADIENT_KIND_TO_PROTO = {
  linear: 1 /* GRADIENT_KIND_LINEAR */,
  path: 2 /* GRADIENT_KIND_PATH */
};

class Fill2 {
  #relId;
  #transparency;
  #type;
  #color;
  #gradientStops;
  #gradientKind;
  #angleDeg;
  #pattern;
  #imageReference;
  #alphaModFix;
  #stretchFillRect;
  #fillRect;
  #pathType;
  #srcRect;
  #explicitProto = false;
  #explicitNone = false;
  constructor(config) {
    if (typeof config === "string") {
      const parsedStyle = parseFillStyleString(config);
      if (parsedStyle && typeof parsedStyle === "object" && parsedStyle.type === "none") {
        this.#explicitNone = true;
        this.#type = 0 /* FILL_TYPE_UNSPECIFIED */;
        this.#color = createEmptyColor();
        this.#gradientStops = undefined;
        this.#gradientKind = null;
        this.#angleDeg = null;
        this.#pattern = undefined;
        this.#imageReference = undefined;
        this.#alphaModFix = undefined;
        return;
      }
      if (parsedStyle && typeof parsedStyle === "object" && parsedStyle.type === "gradient") {
        this.#type = 2 /* FILL_TYPE_GRADIENT */;
        this.#color = createEmptyColor();
        this.#gradientStops = parsedStyle.stops.map((stop) => ({
          position: stop.offset,
          color: new Color4(stop.color).toProto() ?? undefined
        }));
        this.#gradientKind = parsedStyle.gradientKind ? MAP_GRADIENT_KIND_TO_PROTO[parsedStyle.gradientKind] : null;
        this.#angleDeg = parsedStyle.angleDeg ?? null;
        return;
      }
      const normalized = config.trim().toLowerCase();
      if (normalized === "none") {
        this.#explicitNone = true;
        this.#type = 0 /* FILL_TYPE_UNSPECIFIED */;
        this.#color = createEmptyColor();
        this.#gradientStops = undefined;
        this.#gradientKind = null;
        this.#angleDeg = null;
        this.#pattern = undefined;
        this.#imageReference = undefined;
        this.#alphaModFix = undefined;
        return;
      }
      this.#type = 1 /* FILL_TYPE_SOLID */;
      this.#color = new Color4(config);
    } else if (config?.type === "proto") {
      this.#explicitProto = config.proto !== undefined;
      this.#type = config.proto?.type ?? 0 /* FILL_TYPE_UNSPECIFIED */;
      this.#color = new Color4({
        type: "proto",
        proto: config.proto?.color
      });
      this.#pattern = new Pattern({
        type: "proto",
        proto: config.proto?.pattern
      });
      this.#relId = config.proto?.relId;
      this.#gradientStops = config.proto?.gradientStops ?? [];
      this.#gradientKind = config.proto?.gradientKind ?? null;
      this.#angleDeg = config.proto?.angleDeg ?? null;
      this.#imageReference = config.proto?.imageReference;
      this.#alphaModFix = config.proto?.alphaModFix;
      this.#stretchFillRect = config.proto?.stretchFillRect;
      this.#fillRect = config.proto?.fillRect;
      this.#pathType = config.proto?.pathType;
      this.#srcRect = config.proto?.srcRect;
    } else if (config?.type === "none") {
      this.#explicitNone = true;
      this.#type = 0 /* FILL_TYPE_UNSPECIFIED */;
      this.#color = createEmptyColor();
      this.#gradientStops = undefined;
      this.#gradientKind = null;
      this.#angleDeg = null;
      this.#pattern = undefined;
      this.#imageReference = undefined;
      this.#alphaModFix = undefined;
    } else if (config?.type === "solid") {
      this.#type = 1 /* FILL_TYPE_SOLID */;
      this.#color = new Color4(config.color);
      this.#pattern = config.pattern ? new Pattern(config.pattern) : undefined;
    } else if (config?.type === "gradient") {
      this.#type = 2 /* FILL_TYPE_GRADIENT */;
      this.#color = createEmptyColor();
      this.#gradientStops = config.stops.map((stop) => ({
        position: stop.offset,
        color: new Color4(stop.color).toProto() ?? undefined
      }));
      this.#gradientKind = config.gradientKind ? MAP_GRADIENT_KIND_TO_PROTO[config.gradientKind] : null;
      this.#angleDeg = config.angleDeg ?? null;
    } else if (config?.type === "image") {
      this.#type = 4 /* FILL_TYPE_PICTURE */;
      this.#color = createEmptyColor();
      this.#imageReference = config.imageReference;
      this.#alphaModFix = config.alphaModFix;
      this.#stretchFillRect = config.stretchFillRect;
      this.#fillRect = config.fillRect;
      this.#pathType = config.pathType;
      this.#srcRect = config.srcRect;
    } else {
      this.#type = 0 /* FILL_TYPE_UNSPECIFIED */;
      this.#color = createEmptyColor();
      this.#gradientStops = undefined;
      this.#gradientKind = null;
      this.#angleDeg = null;
      this.#pattern = undefined;
      this.#imageReference = undefined;
      this.#alphaModFix = undefined;
    }
  }
  get type() {
    return this.#type;
  }
  get isSet() {
    return this.#explicitNone || this.#type !== 0 /* FILL_TYPE_UNSPECIFIED */;
  }
  get relId() {
    return this.#relId;
  }
  get gradientKind() {
    return this.#gradientKind ? MAP_GRADIENT_KIND[this.#gradientKind] : null;
  }
  get angleDeg() {
    return this.#angleDeg ?? null;
  }
  get imageReference() {
    return this.#imageReference;
  }
  get stretchFillRect() {
    return this.#stretchFillRect;
  }
  get fillRect() {
    return this.#fillRect;
  }
  get srcRect() {
    return this.#srcRect;
  }
  get pathType() {
    return this.#pathType;
  }
  get alphaModFix() {
    return this.#alphaModFix;
  }
  get transparency() {
    return this.#transparency;
  }
  get gradientStops() {
    return this.#gradientStops;
  }
  get pattern() {
    return this.#pattern;
  }
  get color() {
    return this.#color;
  }
  set color(value) {
    this.#type = 1 /* FILL_TYPE_SOLID */;
    this.#color = new Color4(value);
    this.#gradientStops = [];
    this.#gradientKind = null;
    this.#angleDeg = null;
    this.#relId = undefined;
  }
  toProto() {
    const colorProto = this.#color.toProto();
    const patternProto = this.#pattern?.toProto();
    const gradientStops = this.#gradientStops;
    const type = patternProto && (this.#type === 1 /* FILL_TYPE_SOLID */ || this.#type === 0 /* FILL_TYPE_UNSPECIFIED */) ? 3 /* FILL_TYPE_PATTERN */ : this.#type;
    const payload = {
      type,
      color: colorProto ?? undefined,
      gradientStops: gradientStops ?? [],
      relId: this.#relId,
      gradientKind: this.#gradientKind ?? undefined,
      angleDeg: this.#angleDeg ?? undefined,
      pattern: patternProto ?? undefined,
      imageReference: this.#imageReference,
      alphaModFix: this.#alphaModFix,
      stretchFillRect: this.#stretchFillRect,
      fillRect: this.#fillRect,
      pathType: this.#pathType,
      srcRect: this.#srcRect
    };
    const hasCoreFields = type !== 0 /* FILL_TYPE_UNSPECIFIED */ || !!colorProto || !!patternProto || !!this.#relId || this.#gradientKind != null || this.#angleDeg != null || this.#imageReference !== undefined || this.#alphaModFix !== undefined || this.#stretchFillRect !== undefined || this.#fillRect !== undefined || this.#pathType !== undefined || this.#srcRect !== undefined;
    if (!hasCoreFields) {
      if (this.#explicitNone) {
        return {
          type: 0 /* FILL_TYPE_UNSPECIFIED */,
          color: undefined,
          gradientStops: []
        };
      }
      return this.#explicitProto ? {
        type: 0 /* FILL_TYPE_UNSPECIFIED */,
        color: undefined,
        gradientStops: []
      } : undefined;
    }
    return payload;
  }
  toConfig(options = {}) {
    if (this.#explicitNone) {
      return { type: "none" };
    }
    if (this.#explicitProto && options.preserveProto !== false) {
      return { type: "proto", proto: this.toProto() };
    }
    const pattern = this.#pattern?.toConfig();
    const color2 = this.#color.toConfig();
    const hasPattern = !!pattern;
    if (this.#type === 4 /* FILL_TYPE_PICTURE */ && this.#imageReference !== undefined) {
      return {
        type: "image",
        imageReference: this.#imageReference,
        alphaModFix: this.#alphaModFix,
        stretchFillRect: this.#stretchFillRect,
        fillRect: this.#fillRect,
        pathType: this.#pathType,
        srcRect: this.#srcRect
      };
    }
    if (this.#type === 2 /* FILL_TYPE_GRADIENT */) {
      const stops = this.#gradientStops?.map((stop) => ({
        offset: stop.position,
        color: new Color4({ type: "proto", proto: stop.color }).toConfig()
      })) ?? [];
      const gradientKind = this.#gradientKind !== undefined && this.#gradientKind !== null ? MAP_GRADIENT_KIND[this.#gradientKind] ?? undefined : undefined;
      return {
        type: "gradient",
        stops,
        angleDeg: this.#angleDeg ?? undefined,
        gradientKind
      };
    }
    if (!color2 && !hasPattern) {
      return;
    }
    if (!hasPattern && typeof color2 === "string") {
      return color2;
    }
    return {
      type: "solid",
      color: color2,
      pattern
    };
  }
}
function createEmptyColor() {
  return new Color4({ type: "proto", proto: undefined });
}

// node_modules/@oai/granola/dist/models/presentation/line.js
var coerceLineStyleConfig = (value) => {
  if (value === undefined || value === null) {
    return;
  }
  if (typeof value !== "string") {
    return;
  }
  const trimmed = value.trim();
  if (!trimmed) {
    return;
  }
  const normalized = trimmed.toLowerCase().replace(/[^a-z]+/g, "");
  switch (normalized) {
    case "solid":
      return "solid";
    case "dash":
    case "dashed":
      return "dashed";
    case "dot":
    case "dotted":
      return "dotted";
    case "dashdot":
      return "dash-dot";
    case "dashdotdot":
      return "dash-dot-dot";
    default:
      return;
  }
};
var MAP_LINE_STYLE = {
  solid: 1 /* LINE_STYLE_SOLID */,
  dashed: 2 /* LINE_STYLE_DASHED */,
  dotted: 3 /* LINE_STYLE_DOTTED */,
  "dash-dot": 4 /* LINE_STYLE_DASH_DOT */,
  "dash-dot-dot": 5 /* LINE_STYLE_DASH_DOT_DOT */
};
var MAP_PROTO_LINE_STYLE = {
  [0 /* LINE_STYLE_UNSPECIFIED */]: undefined,
  [1 /* LINE_STYLE_SOLID */]: "solid",
  [2 /* LINE_STYLE_DASHED */]: "dashed",
  [3 /* LINE_STYLE_DOTTED */]: "dotted",
  [4 /* LINE_STYLE_DASH_DOT */]: "dash-dot",
  [5 /* LINE_STYLE_DASH_DOT_DOT */]: "dash-dot-dot"
};

class Line4 {
  #width;
  #fill;
  #style;
  #styleProto;
  #onChange;
  #fillBeforeHide;
  #explicitProto = false;
  constructor(config) {
    if (!config) {
      this.#width = undefined;
      this.#fill = new Fill2;
      this.#style = undefined;
      this.#styleProto = undefined;
      return;
    }
    if ("type" in config) {
      this.#explicitProto = config.proto !== undefined;
      const protoWidth = config.proto?.widthEmu;
      this.#width = protoWidth === undefined ? undefined : pixelsFromEmu(protoWidth);
      this.#fill = new Fill2({ type: "proto", proto: config.proto?.fill });
      const protoStyle = config.proto?.style;
      this.#styleProto = protoStyle === undefined || protoStyle === 0 /* LINE_STYLE_UNSPECIFIED */ ? undefined : protoStyle;
      this.#style = this.#styleProto === undefined ? undefined : MAP_PROTO_LINE_STYLE[this.#styleProto] ?? undefined;
    } else {
      const width = config.width ?? config.weight;
      const fill = config.fill ?? config.color;
      const coercedStyle = typeof config.style === "string" ? coerceLineStyleConfig(config.style) : config.style;
      this.#width = width;
      this.#fill = new Fill2(fill);
      this.#style = coercedStyle;
      this.#styleProto = coercedStyle ? MAP_LINE_STYLE[coercedStyle] : undefined;
    }
  }
  get width() {
    return this.#width;
  }
  set width(value) {
    this.#width = value;
    this.#onChange?.(this);
  }
  get fill() {
    return this.#fill;
  }
  get format() {
    return { line: this };
  }
  get visible() {
    const fillProto = this.#fill.toProto();
    if (!fillProto) {
      return true;
    }
    const isExplicitNoFill = fillProto.type === 0 /* FILL_TYPE_UNSPECIFIED */ && fillProto.color === undefined;
    return !isExplicitNoFill;
  }
  set visible(value) {
    const wantsVisible = Boolean(value);
    if (!wantsVisible) {
      if (!this.visible) {
        return;
      }
      this.#fillBeforeHide = this.#fill.toConfig();
      this.fill = { type: "none" };
      return;
    }
    if (this.visible) {
      return;
    }
    this.fill = this.#fillBeforeHide;
  }
  get color() {
    const config = this.#fill.toConfig();
    if (typeof config === "string") {
      return config;
    }
    if (config && typeof config === "object" && "color" in config) {
      const color2 = config.color;
      return typeof color2 === "string" ? color2 : undefined;
    }
    return;
  }
  set color(value) {
    if (typeof value !== "string" || value.trim().length === 0) {
      return;
    }
    this.fill = value;
  }
  get style() {
    return this.#style;
  }
  set style(value) {
    const coerced = typeof value === "string" ? coerceLineStyleConfig(value) : value;
    this.#style = coerced;
    this.#styleProto = coerced ? MAP_LINE_STYLE[coerced] : undefined;
    this.#onChange?.(this);
  }
  set fill(value) {
    this.#fill = new Fill2(value);
    this.#onChange?.(this);
  }
  setChangeHandler(handler) {
    this.#onChange = handler;
  }
  #isSet() {
    return this.#width !== undefined || this.#fill.toProto() !== undefined || this.#style !== undefined || this.#styleProto !== undefined;
  }
  toProto() {
    if (!this.#isSet()) {
      return;
    }
    const style = this.#style !== undefined ? MAP_LINE_STYLE[this.#style] : this.#styleProto;
    const normalizedStyle = style === undefined ? 0 /* LINE_STYLE_UNSPECIFIED */ : style;
    return {
      widthEmu: this.#width === undefined ? undefined : emuFromPixels(this.#width),
      fill: this.#fill.toProto(),
      style: normalizedStyle
    };
  }
  toConfig(options = {}) {
    if (!this.#isSet()) {
      return;
    }
    if (this.#explicitProto && options.preserveProto !== false) {
      return {
        type: "proto",
        proto: this.toProto()
      };
    }
    return {
      style: this.#style ?? "solid",
      width: this.#width,
      fill: this.#fill.toConfig(options)
    };
  }
}

// node_modules/@oai/granola/dist/models/presentation/type-mappers.js
function mapDisplayBlanksAs(value) {
  switch (value) {
    case "gap":
      return 1 /* DISPLAY_BLANKS_AS_GAP */;
    case "zero":
      return 2 /* DISPLAY_BLANKS_AS_ZERO */;
    case "span":
      return 3 /* DISPLAY_BLANKS_AS_SPAN */;
    default:
      return 0 /* DISPLAY_BLANKS_AS_UNSPECIFIED */;
  }
}
function mapTreemapParentLabelLayout(layout) {
  switch (layout) {
    case "banner":
      return 2 /* PARENT_LABEL_LAYOUT_BANNER */;
    case "none":
      return 1 /* PARENT_LABEL_LAYOUT_NONE */;
    case "overlapping":
      return 3 /* PARENT_LABEL_LAYOUT_OVERLAPPING */;
    default:
      return 0 /* PARENT_LABEL_LAYOUT_UNSPECIFIED */;
  }
}
function mapTextHorizontalAlignment(alignment) {
  switch (alignment) {
    case "center":
      return 2 /* ALIGNMENT_TYPE_CENTER */;
    case "right":
      return 3 /* ALIGNMENT_TYPE_RIGHT */;
    case "justify":
      return 2 /* ALIGNMENT_TYPE_CENTER */;
    case "left":
    default:
      return 1 /* ALIGNMENT_TYPE_LEFT */;
  }
}
function mapProtoTextHorizontalAlignment(alignment) {
  switch (alignment) {
    case 2 /* ALIGNMENT_TYPE_CENTER */:
      return "center";
    case 3 /* ALIGNMENT_TYPE_RIGHT */:
      return "right";
    case 1 /* ALIGNMENT_TYPE_LEFT */:
      return "left";
    default:
      return;
  }
}
function mapTextVerticalAlignment(alignment) {
  switch (alignment) {
    case "middle":
      return 2 /* ANCHOR_TYPE_MIDDLE */;
    case "bottom":
      return 3 /* ANCHOR_TYPE_BOTTOM */;
    case "top":
    default:
      return 1 /* ANCHOR_TYPE_TOP */;
  }
}

// node_modules/@oai/granola/dist/models/presentation/utils/uuid.js
var UUID_PATTERN = /[xy]/g;
var AID_SUFFIX_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
var AID_SUFFIX_PATTERN = /^[A-Za-z0-9.-]+$/;
var HASH_MASK_64 = 0xffffffffffffffffn;
var FNV_OFFSET_64 = 0xcbf29ce484222325n;
var FNV_PRIME_64 = 0x100000001b3n;
var LCG_MULTIPLIER_64 = 6364136223846793005n;
var LCG_INCREMENT_64 = 1442695040888963407n;
function fallbackUuid() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(UUID_PATTERN, (char) => {
    const random = Math.floor(Math.random() * 16);
    const value = char === "x" ? random : random & 3 | 8;
    return value.toString(16);
  });
}
function generateUuid() {
  if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
    try {
      return crypto.randomUUID();
    } catch {}
  }
  return fallbackUuid();
}
function generateAidSuffix(length = 6) {
  const normalizedLength = Math.max(4, Math.floor(length));
  const bytes = new Uint8Array(normalizedLength);
  if (typeof crypto !== "undefined" && "getRandomValues" in crypto) {
    try {
      crypto.getRandomValues(bytes);
    } catch {}
  }
  if (bytes.every((value) => value === 0)) {
    for (let index = 0;index < bytes.length; index += 1) {
      bytes[index] = Math.floor(Math.random() * 256);
    }
  }
  let result = "";
  for (const value of bytes) {
    const offset = value % AID_SUFFIX_ALPHABET.length;
    result += AID_SUFFIX_ALPHABET[offset] ?? "a";
  }
  return result;
}
function isAidSuffix(value) {
  return Boolean(value) && AID_SUFFIX_PATTERN.test(value);
}
function deriveDeterministicAidSuffix(input, length = 8) {
  const normalizedLength = Math.max(4, Math.floor(length));
  let state = hashString64(input);
  let result = "";
  for (let index = 0;index < normalizedLength; index += 1) {
    state = state * LCG_MULTIPLIER_64 + LCG_INCREMENT_64 & HASH_MASK_64;
    const offset = Number(state & 0xffn) % AID_SUFFIX_ALPHABET.length;
    result += AID_SUFFIX_ALPHABET[offset] ?? "a";
  }
  return result;
}
function normalizeAidSuffix(prefix, id, length = 8) {
  if (!id) {
    return id;
  }
  const withoutPrefix = dropDuplicatePrefix(prefix, id);
  if (isAidSuffix(withoutPrefix)) {
    return withoutPrefix;
  }
  const normalizedUnderscore = withoutPrefix.replace(/_/g, "-");
  if (normalizedUnderscore !== withoutPrefix && isAidSuffix(normalizedUnderscore)) {
    return normalizedUnderscore;
  }
  return deriveDeterministicAidSuffix(withoutPrefix, length);
}
function generateGuid() {
  return `{${generateUuid().toUpperCase()}}`;
}
function generateSlideCreationId() {
  const max3 = 2147483647;
  const value = Math.max(1, Math.floor(Math.random() * max3));
  return String(value);
}
function generateElementId(existingIds = []) {
  let max3 = 0;
  for (const id of existingIds) {
    const value = Number(id);
    if (Number.isFinite(value)) {
      max3 = Math.max(max3, value);
    }
  }
  return String(max3 + 1);
}
function hashString64(input) {
  let hash = FNV_OFFSET_64;
  for (let index = 0;index < input.length; index += 1) {
    hash ^= BigInt(input.charCodeAt(index));
    hash = hash * FNV_PRIME_64 & HASH_MASK_64;
  }
  return hash;
}
function dropDuplicatePrefix(prefix, id) {
  if (!prefix) {
    return id;
  }
  const normalizedPrefix = prefix.toLowerCase();
  const normalizedId = id.toLowerCase();
  const underscorePrefix = `${normalizedPrefix}_`;
  const dashPrefix = `${normalizedPrefix}-`;
  if (normalizedId.startsWith(underscorePrefix)) {
    return id.slice(underscorePrefix.length);
  }
  if (normalizedId.startsWith(dashPrefix)) {
    return id.slice(dashPrefix.length);
  }
  return id;
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-area-options.js
class ChartAreaOptions {
  #grouping;
  #varyColors;
  constructor(proto) {
    this.#grouping = proto?.grouping ? AREA_GROUPING_FROM_PROTO[proto.grouping] : undefined;
    this.#varyColors = proto?.varyColors;
  }
  get grouping() {
    return this.#grouping;
  }
  set grouping(value) {
    this.#grouping = value;
  }
  get varyColors() {
    return this.#varyColors;
  }
  set varyColors(value) {
    this.#varyColors = value;
  }
  toProto() {
    const options = {};
    if (this.#grouping) {
      options.grouping = AREA_GROUPING_TO_PROTO[this.#grouping];
    }
    if (this.#varyColors) {
      options.varyColors = this.#varyColors;
    }
    return Object.keys(options).length > 0 ? options : undefined;
  }
}

// node_modules/@oai/granola/dist/models/presentation/text-style.util.js
function normalizeTextStyleAlignment(value) {
  if (value === undefined) {
    return;
  }
  if (typeof value === "number") {
    return normalizeProtoTextStyleAlignment(value);
  }
  if (value === "left" || value === "center" || value === "right" || value === "justify") {
    return mapTextHorizontalAlignment(value);
  }
  return normalizeProtoTextStyleAlignment(value);
}
function normalizeProtoTextStyleAlignment(value) {
  if (value === undefined || value === null) {
    return;
  }
  if (typeof value === "number") {
    if (!Number.isFinite(value) || !Number.isInteger(value)) {
      throw new Error("text alignment must be an integer enum value.");
    }
    return value;
  }
  const trimmed = value.trim();
  if (!trimmed) {
    return;
  }
  const normalized = trimmed.toLowerCase();
  if (normalized === "left") {
    return mapTextHorizontalAlignment("left");
  }
  if (normalized === "center" || normalized === "centre" || normalized === "middle") {
    return mapTextHorizontalAlignment("center");
  }
  if (normalized === "right") {
    return mapTextHorizontalAlignment("right");
  }
  if (normalized === "justify") {
    return mapTextHorizontalAlignment("justify");
  }
  if (/^-?\d+$/.test(trimmed)) {
    const numeric = Number(trimmed);
    if (!Number.isFinite(numeric) || !Number.isInteger(numeric)) {
      throw new Error(`Unsupported text alignment value: "${value}"`);
    }
    return numeric;
  }
  if (trimmed === "ALIGNMENT_TYPE_UNSPECIFIED") {
    return 0 /* ALIGNMENT_TYPE_UNSPECIFIED */;
  }
  if (trimmed === "ALIGNMENT_TYPE_LEFT") {
    return 1 /* ALIGNMENT_TYPE_LEFT */;
  }
  if (trimmed === "ALIGNMENT_TYPE_CENTER") {
    return 2 /* ALIGNMENT_TYPE_CENTER */;
  }
  if (trimmed === "ALIGNMENT_TYPE_RIGHT") {
    return 3 /* ALIGNMENT_TYPE_RIGHT */;
  }
  if (trimmed === "UNRECOGNIZED") {
    return -1 /* UNRECOGNIZED */;
  }
  throw new Error(`Unsupported text alignment value: "${value}"`);
}

// node_modules/@oai/granola/dist/models/presentation/text-style.js
var FONT_SCALE_UNIT = 1e5;
function fontScaleToRatio(value) {
  if (value === undefined) {
    return;
  }
  return value / FONT_SCALE_UNIT;
}
function ratioToFontScale(value) {
  if (value === undefined) {
    return;
  }
  return Math.round(value * FONT_SCALE_UNIT);
}
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
function applyTextStyleConfig(target, config) {
  if (!config) {
    return;
  }
  if ("anchor" in config)
    target.anchor = config.anchor;
  if ("vertical" in config)
    target.vertical = config.vertical;
  if ("rotation" in config)
    target.rotation = config.rotation;
  if ("bold" in config)
    target.bold = config.bold;
  if ("italic" in config)
    target.italic = config.italic;
  if ("fontSize" in config)
    target.fontSize = config.fontSize;
  if ("lineSpacing" in config)
    target.lineSpacing = config.lineSpacing;
  if ("alignment" in config)
    target.alignment = config.alignment;
  if ("underline" in config)
    target.underline = config.underline;
  if ("fill" in config && config.fill !== undefined)
    target.fill = config.fill;
  if ("color" in config)
    target.color = config.color;
  if ("useParagraphSpacing" in config)
    target.useParagraphSpacing = config.useParagraphSpacing;
  if ("wrap" in config)
    target.wrap = config.wrap;
  if ("autoFit" in config)
    target.autoFit = config.autoFit;
  if ("autoFitScale" in config)
    target.autoFitScale = config.autoFitScale;
  if ("autoFitLineSpaceReduction" in config)
    target.autoFitLineSpaceReduction = config.autoFitLineSpaceReduction;
  if ("name" in config)
    target.name = config.name;
  if ("family" in config)
    target.family = config.family;
  if ("scheme" in config)
    target.scheme = config.scheme;
  if ("typeface" in config)
    target.typeface = config.typeface;
  if ("insets" in config)
    target.insets = config.insets;
}
function coerceTextStyleConfig(value) {
  if (typeof value === "string") {
    return looksLikeTextStyleDeclaration(value) ? parseTextStyleString(value) : null;
  }
  if (!isRecord(value)) {
    return null;
  }
  return value;
}
function autoFitStateFromProto(autoFit) {
  if (autoFit?.noAutofit) {
    return { type: "none" };
  }
  if (autoFit?.normalAutoFit) {
    return {
      type: "shrinkText",
      scale: fontScaleToRatio(autoFit.normalAutoFit.fontScale),
      lineSpaceReduction: autoFit.normalAutoFit.lineSpaceReduction
    };
  }
  if (autoFit?.shapeAutoFit) {
    return { type: "resizeShapeToFitText" };
  }
  return {};
}
function autoFitStateToProto(state) {
  if (!state.type) {
    return;
  }
  if (state.type === "none") {
    return { noAutofit: {} };
  }
  if (state.type === "resizeShapeToFitText") {
    return { shapeAutoFit: {} };
  }
  if (state.type === "shrinkText") {
    return {
      normalAutoFit: {
        fontScale: ratioToFontScale(state.scale),
        lineSpaceReduction: state.lineSpaceReduction
      }
    };
  }
  return;
}

class TextStyle2 {
  #data;
  #fill;
  #autoFitType;
  #autoFitScale;
  #autoFitLineSpaceReduction;
  #lineSpacing;
  constructor(proto) {
    this.#fill = new Fill2({ type: "proto", proto: proto?.fill });
    const autoFitState = autoFitStateFromProto(proto?.autoFit);
    this.#data = {
      anchor: proto?.anchor,
      vertical: proto?.vertical,
      rotation: proto?.rotation,
      bold: proto?.bold,
      italic: proto?.italic,
      fontSize: proto?.fontSize,
      alignment: normalizeProtoTextStyleAlignment(proto?.alignment),
      underline: proto?.underline,
      bottomInset: proto?.bottomInset,
      leftInset: proto?.leftInset,
      rightInset: proto?.rightInset,
      topInset: proto?.topInset,
      useParagraphSpacing: proto?.useParagraphSpacing,
      wrap: proto?.wrap,
      name: proto?.name,
      family: proto?.family,
      scheme: proto?.scheme,
      typeface: proto?.typeface
    };
    this.#autoFitType = autoFitState.type;
    this.#autoFitScale = autoFitState.scale;
    this.#autoFitLineSpaceReduction = autoFitState.lineSpaceReduction;
    this.#lineSpacing = undefined;
  }
  get anchor() {
    return this.#data.anchor;
  }
  set anchor(value) {
    this.#data.anchor = value;
  }
  get vertical() {
    return this.#data.vertical;
  }
  set vertical(value) {
    this.#data.vertical = value;
  }
  get rotation() {
    return this.#data.rotation;
  }
  set rotation(value) {
    this.#data.rotation = value;
  }
  get bold() {
    return this.#data.bold;
  }
  set bold(value) {
    this.#data.bold = value;
  }
  get italic() {
    return this.#data.italic;
  }
  set italic(value) {
    this.#data.italic = value;
  }
  get fontSize() {
    const cp = this.#data.fontSize;
    if (cp === undefined)
      return;
    const pt = cp / 100;
    return pt * 96 / 72;
  }
  set fontSize(value) {
    if (value === undefined) {
      this.#data.fontSize = undefined;
      return;
    }
    const pt = value * 72 / 96;
    this.#data.fontSize = Math.round(pt * 100);
  }
  get alignment() {
    return this.#data.alignment;
  }
  set alignment(value) {
    this.#data.alignment = normalizeTextStyleAlignment(value);
  }
  get lineSpacing() {
    const raw = this.#lineSpacing;
    if (raw === undefined || !Number.isFinite(raw)) {
      return;
    }
    return raw / 1e5;
  }
  set lineSpacing(value) {
    if (value === undefined) {
      this.#lineSpacing = undefined;
      return;
    }
    this.#lineSpacing = Math.round(value * 1e5);
  }
  get underline() {
    return this.#data.underline;
  }
  set underline(value) {
    this.#data.underline = value;
  }
  get fill() {
    return this.#fill;
  }
  set fill(value) {
    this.#fill = new Fill2(value);
  }
  get color() {
    if (!this.#fill) {
      return;
    }
    return this.#fill.color.clone();
  }
  set color(value) {
    if (value === undefined) {
      this.#fill = new Fill2;
      return;
    }
    this.#fill = new Fill2({ type: "solid", color: value });
  }
  get useParagraphSpacing() {
    return this.#data.useParagraphSpacing;
  }
  set useParagraphSpacing(value) {
    this.#data.useParagraphSpacing = value;
  }
  get wrap() {
    const raw = this.#data.wrap;
    if (raw === undefined) {
      return;
    }
    return TEXT_WRAP_FROM_PROTO[raw];
  }
  set wrap(value) {
    if (value === undefined) {
      this.#data.wrap = undefined;
      return;
    }
    this.#data.wrap = TEXT_WRAP_TO_PROTO[value];
  }
  get autoFit() {
    return this.#autoFitType;
  }
  set autoFit(value) {
    this.#autoFitType = value;
    if (value !== "shrinkText") {
      this.#autoFitScale = undefined;
      this.#autoFitLineSpaceReduction = undefined;
    }
  }
  get autoFitScale() {
    return this.#autoFitScale;
  }
  set autoFitScale(value) {
    this.#autoFitScale = value;
  }
  get autoFitLineSpaceReduction() {
    return this.#autoFitLineSpaceReduction;
  }
  set autoFitLineSpaceReduction(value) {
    this.#autoFitLineSpaceReduction = value;
  }
  get name() {
    return this.#data.name;
  }
  set name(value) {
    this.#data.name = value;
  }
  get family() {
    return this.#data.family;
  }
  set family(value) {
    this.#data.family = value;
  }
  get scheme() {
    return this.#data.scheme;
  }
  set scheme(value) {
    this.#data.scheme = value;
  }
  get typeface() {
    return this.#data.typeface;
  }
  set typeface(value) {
    this.#data.typeface = value;
  }
  get insets() {
    const { topInset, rightInset, bottomInset, leftInset } = this.#data;
    if (topInset === undefined && rightInset === undefined && bottomInset === undefined && leftInset === undefined) {
      return;
    }
    return {
      top: topInset === undefined ? undefined : pixelsFromEmu(topInset),
      right: rightInset === undefined ? undefined : pixelsFromEmu(rightInset),
      bottom: bottomInset === undefined ? undefined : pixelsFromEmu(bottomInset),
      left: leftInset === undefined ? undefined : pixelsFromEmu(leftInset)
    };
  }
  set insets(value) {
    this.#data.topInset = value?.top === undefined ? undefined : emuFromPixels(value.top);
    this.#data.rightInset = value?.right === undefined ? undefined : emuFromPixels(value.right);
    this.#data.bottomInset = value?.bottom === undefined ? undefined : emuFromPixels(value.bottom);
    this.#data.leftInset = value?.left === undefined ? undefined : emuFromPixels(value.left);
  }
  toProto() {
    const { lineSpacing: _lineSpacing, ...protoData } = this.#data;
    const autoFit = autoFitStateToProto({
      type: this.#autoFitType,
      scale: this.#autoFitScale,
      lineSpaceReduction: this.#autoFitLineSpaceReduction
    });
    return {
      anchor: protoData.anchor,
      vertical: protoData.vertical,
      rotation: protoData.rotation,
      bold: protoData.bold,
      italic: protoData.italic,
      fontSize: protoData.fontSize,
      fill: this.#fill?.toProto(),
      alignment: protoData.alignment,
      underline: protoData.underline,
      bottomInset: protoData.bottomInset,
      leftInset: protoData.leftInset,
      rightInset: protoData.rightInset,
      topInset: protoData.topInset,
      useParagraphSpacing: protoData.useParagraphSpacing,
      wrap: protoData.wrap,
      autoFit,
      name: protoData.name,
      family: protoData.family,
      scheme: protoData.scheme,
      typeface: protoData.typeface
    };
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-axis.js
var hasMeaningfulTextFill = (fill) => {
  if (!fill) {
    return false;
  }
  return fill.type !== undefined && fill.type !== 0 || fill.color !== undefined || (fill.gradientStops?.length ?? 0) > 0 || fill.relId !== undefined || fill.gradientKind !== undefined || fill.angleDeg !== undefined || fill.pattern !== undefined || fill.imageReference !== undefined || fill.alphaModFix !== undefined || fill.stretchFillRect !== undefined || fill.fillRect !== undefined || fill.pathType !== undefined || fill.srcRect !== undefined;
};
var hasMeaningfulTextStyle = (style) => {
  if (!style) {
    return false;
  }
  return style.anchor !== undefined || style.vertical !== undefined || style.rotation !== undefined || style.bold !== undefined || style.italic !== undefined || style.fontSize !== undefined || style.alignment !== undefined || style.underline !== undefined || style.bottomInset !== undefined || style.leftInset !== undefined || style.rightInset !== undefined || style.topInset !== undefined || style.useParagraphSpacing !== undefined || style.wrap !== undefined || style.name !== undefined || style.family !== undefined || style.scheme !== undefined || style.typeface !== undefined || style.autoFit !== undefined || hasMeaningfulTextFill(style.fill);
};

class ChartAxisFormatProxy {
  #axis;
  constructor(axis) {
    this.#axis = axis;
  }
  get numberFormat() {
    return this.#axis.numberFormatCode;
  }
  set numberFormat(value) {
    this.#axis.numberFormatCode = value;
  }
}
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
var coerceTickLabelPositionConfig = (value) => {
  if (typeof value !== "string") {
    return value;
  }
  const trimmed = value.trim();
  if (!trimmed) {
    return;
  }
  switch (trimmed.toLowerCase()) {
    case "nextto":
      return "nextTo";
    case "nexttoaxis":
    case "next_to_axis":
    case "next-to-axis":
      return "nextTo";
    case "high":
      return "high";
    case "low":
      return "low";
    case "none":
      return "none";
    default:
      return trimmed;
  }
};

class ChartAxisTitle {
  #backing;
  constructor(backing) {
    this.#backing = backing;
  }
  get text() {
    return this.#backing.getText();
  }
  set text(value) {
    this.#backing.setText(value ?? undefined);
  }
  get textStyle() {
    return this.#backing.textStyle;
  }
}

class ChartAxis {
  #axisType;
  #tickLabelInterval;
  #tickLabelDistanceFromAxis;
  #titleText;
  #numberFormatCode;
  #numberFormatSourceLinked;
  #min;
  #max;
  #majorUnit;
  #minorUnit;
  #deleted = false;
  #titleTextStyle;
  #title;
  #textStyle;
  #line;
  #majorGridlines;
  #minorGridlines;
  #position;
  #orientation;
  #majorTickMark;
  #minorTickMark;
  #tickLabelPosition;
  #crossBetween;
  #crosses;
  #crossValue;
  #formatProxy;
  #markSpecified() {
    this.#deleted = false;
  }
  constructor(proto) {
    this.#titleText = proto?.title;
    this.#numberFormatCode = proto?.numberFormatCode;
    this.#numberFormatSourceLinked = proto?.numberFormatSourceLinked;
    this.#min = proto?.min;
    this.#max = proto?.max;
    this.#majorUnit = proto?.majorUnit;
    this.#minorUnit = proto?.minorUnit;
    this.#deleted = proto?.deleted ?? false;
    this.#titleTextStyle = new TextStyle2(proto?.titleTextStyle);
    this.#title = new ChartAxisTitle({
      getText: () => this.#titleText,
      setText: (value) => {
        this.#titleText = value ?? undefined;
        if (value !== undefined) {
          this.#markSpecified();
        }
      },
      textStyle: this.#titleTextStyle
    });
    this.#textStyle = new TextStyle2(proto?.textStyle);
    this.#line = new Line4({ type: "proto", proto: proto?.line });
    this.#line.setChangeHandler(() => this.#markSpecified());
    this.#majorGridlines = new Line4({
      type: "proto",
      proto: proto?.majorGridlines
    });
    this.#minorGridlines = new Line4({
      type: "proto",
      proto: proto?.minorGridlines
    });
    this.#position = proto?.position ? AXIS_POSITION_FROM_PROTO[proto.position] : undefined;
    this.#orientation = proto?.orientation ? AXIS_ORIENTATION_FROM_PROTO[proto.orientation] : undefined;
    this.#majorTickMark = proto?.majorTickMark ? TICK_MARK_FROM_PROTO[proto.majorTickMark] : undefined;
    this.#minorTickMark = proto?.minorTickMark ? TICK_MARK_FROM_PROTO[proto.minorTickMark] : undefined;
    this.#tickLabelPosition = proto?.tickLabelPosition ? TICK_LABEL_POSITION_FROM_PROTO[proto.tickLabelPosition] : undefined;
    this.#crossBetween = proto?.crossBetween ? CROSS_BETWEEN_FROM_PROTO[proto.crossBetween] : undefined;
    this.#crosses = proto?.crosses ? CROSSES_FROM_PROTO[proto.crosses] : undefined;
    this.#crossValue = proto?.crossValue;
    this.#formatProxy = new ChartAxisFormatProxy(this);
  }
  get format() {
    return this.#formatProxy;
  }
  get axisType() {
    return this.#axisType;
  }
  set axisType(value) {
    this.#axisType = value ?? undefined;
    if (value !== undefined) {
      this.#markSpecified();
    }
  }
  get tickLabelInterval() {
    return this.#tickLabelInterval;
  }
  set tickLabelInterval(value) {
    this.#tickLabelInterval = value ?? undefined;
    if (value !== undefined) {
      this.#markSpecified();
    }
  }
  get tickLabelDistanceFromAxis() {
    return this.#tickLabelDistanceFromAxis;
  }
  set tickLabelDistanceFromAxis(value) {
    this.#tickLabelDistanceFromAxis = value ?? undefined;
    if (value !== undefined) {
      this.#markSpecified();
    }
  }
  get line() {
    return this.#line;
  }
  set line(value) {
    this.#line = value;
    this.#line.setChangeHandler(() => this.#markSpecified());
    this.#markSpecified();
  }
  get title() {
    return this.#title;
  }
  set title(value) {
    if (typeof value === "string") {
      this.#title.text = value;
      return;
    }
    if (value == null) {
      this.#title.text = undefined;
      return;
    }
    if (!isRecord2(value)) {
      return;
    }
    this.#markSpecified();
    if ("text" in value) {
      const next = value.text;
      this.#title.text = typeof next === "string" ? next : undefined;
    }
    if ("textStyle" in value) {
      const style = value.textStyle;
      const coerced = coerceTextStyleConfig(style);
      if (coerced) {
        applyTextStyleConfig(this.#title.textStyle, coerced);
      }
    }
  }
  get numberFormatCode() {
    return this.#numberFormatCode;
  }
  set numberFormatCode(value) {
    this.#numberFormatCode = value ?? undefined;
    if (value !== undefined) {
      this.#markSpecified();
    }
  }
  get numberFormatSourceLinked() {
    return this.#numberFormatSourceLinked;
  }
  set numberFormatSourceLinked(value) {
    this.#numberFormatSourceLinked = value === undefined ? undefined : Boolean(value);
    if (value !== undefined) {
      this.#markSpecified();
    }
  }
  get min() {
    return this.#min;
  }
  get textStyle() {
    return this.#textStyle;
  }
  set textStyle(value) {
    this.#textStyle = value;
    this.#markSpecified();
  }
  get majorGridlines() {
    return this.#majorGridlines;
  }
  set majorGridlines(value) {
    if (!value) {
      this.#majorGridlines = new Line4;
    } else {
      this.#majorGridlines = value;
    }
  }
  get minorGridlines() {
    return this.#minorGridlines;
  }
  set minorGridlines(value) {
    this.#minorGridlines = value ?? new Line4;
  }
  get position() {
    return this.#position;
  }
  set position(value) {
    this.#position = value ?? undefined;
    if (value !== undefined) {
      this.#markSpecified();
    }
  }
  get orientation() {
    return this.#orientation;
  }
  set orientation(value) {
    this.#orientation = value ?? undefined;
    if (value !== undefined) {
      this.#markSpecified();
    }
  }
  get majorTickMark() {
    return this.#majorTickMark;
  }
  set majorTickMark(value) {
    this.#majorTickMark = value ?? undefined;
    if (value !== undefined) {
      this.#markSpecified();
    }
  }
  get minorTickMark() {
    return this.#minorTickMark;
  }
  set minorTickMark(value) {
    this.#minorTickMark = value ?? undefined;
    if (value !== undefined) {
      this.#markSpecified();
    }
  }
  get tickLabelPosition() {
    return this.#tickLabelPosition;
  }
  set tickLabelPosition(value) {
    const normalized = value === undefined ? undefined : coerceTickLabelPositionConfig(value);
    this.#tickLabelPosition = normalized ?? undefined;
    if (value !== undefined) {
      this.#markSpecified();
    }
  }
  get crossBetween() {
    return this.#crossBetween;
  }
  set crossBetween(value) {
    this.#crossBetween = value ?? undefined;
    if (value !== undefined) {
      this.#markSpecified();
    }
  }
  get crosses() {
    return this.#crosses;
  }
  set crosses(value) {
    this.#crosses = value ?? undefined;
    if (this.#crosses !== "at") {
      this.#crossValue = undefined;
    }
    if (value !== undefined) {
      this.#markSpecified();
    }
  }
  get crossesAt() {
    return this.#crossValue;
  }
  set crossesAt(value) {
    this.#crossValue = value ?? undefined;
    if (this.#crossValue !== undefined) {
      this.#crosses = "at";
      this.#markSpecified();
    }
  }
  set min(value) {
    this.#min = value ?? undefined;
    if (value !== undefined) {
      this.#markSpecified();
    }
  }
  get max() {
    return this.#max;
  }
  set max(value) {
    this.#max = value ?? undefined;
    if (value !== undefined) {
      this.#markSpecified();
    }
  }
  get majorUnit() {
    return this.#majorUnit;
  }
  set majorUnit(value) {
    this.#majorUnit = value ?? undefined;
    if (value !== undefined) {
      this.#markSpecified();
    }
  }
  get minorUnit() {
    return this.#minorUnit;
  }
  set minorUnit(value) {
    this.#minorUnit = value ?? undefined;
    if (value !== undefined) {
      this.#markSpecified();
    }
  }
  get deleted() {
    return this.#deleted;
  }
  set deleted(value) {
    this.#deleted = Boolean(value);
  }
  get visible() {
    return !this.#deleted;
  }
  set visible(value) {
    this.#deleted = !value;
  }
  toProto() {
    const axis = {};
    if (this.#titleText) {
      axis.title = this.#titleText;
    }
    if (this.#numberFormatCode) {
      axis.numberFormatCode = this.#numberFormatCode;
    }
    if (this.#numberFormatSourceLinked !== undefined) {
      axis.numberFormatSourceLinked = this.#numberFormatSourceLinked;
    }
    if (this.#min !== undefined) {
      axis.min = this.#min;
    }
    if (this.#max !== undefined) {
      axis.max = this.#max;
    }
    if (this.#majorUnit !== undefined) {
      axis.majorUnit = this.#majorUnit;
    }
    if (this.#minorUnit !== undefined) {
      axis.minorUnit = this.#minorUnit;
    }
    const textStyle = this.#textStyle.toProto();
    if (hasMeaningfulTextStyle(textStyle)) {
      axis.textStyle = textStyle;
    }
    const titleTextStyle = this.#titleTextStyle.toProto();
    if (hasMeaningfulTextStyle(titleTextStyle)) {
      axis.titleTextStyle = titleTextStyle;
    }
    const line = this.#line.toProto();
    if (line) {
      axis.line = line;
    }
    const majorGridlines = this.#majorGridlines.toProto();
    if (majorGridlines) {
      axis.majorGridlines = majorGridlines;
    }
    const minorGridlines = this.#minorGridlines.toProto();
    if (minorGridlines) {
      axis.minorGridlines = minorGridlines;
    }
    if (this.#position) {
      axis.position = AXIS_POSITION_TO_PROTO[this.#position];
    }
    if (this.#orientation) {
      axis.orientation = AXIS_ORIENTATION_TO_PROTO[this.#orientation];
    }
    if (this.#majorTickMark) {
      axis.majorTickMark = TICK_MARK_TO_PROTO[this.#majorTickMark];
    }
    if (this.#minorTickMark) {
      axis.minorTickMark = TICK_MARK_TO_PROTO[this.#minorTickMark];
    }
    if (this.#tickLabelPosition && this.#tickLabelPosition in TICK_LABEL_POSITION_TO_PROTO) {
      axis.tickLabelPosition = TICK_LABEL_POSITION_TO_PROTO[this.#tickLabelPosition];
    }
    if (this.#crossBetween) {
      axis.crossBetween = CROSS_BETWEEN_TO_PROTO[this.#crossBetween];
    }
    if (this.#crosses) {
      axis.crosses = CROSSES_TO_PROTO[this.#crosses];
    }
    if (this.#crossValue !== undefined) {
      axis.crossValue = this.#crossValue;
    }
    if (this.#deleted) {
      axis.deleted = true;
    }
    if (this.#axisType)
      axis.axisType = this.#axisType;
    if (this.#tickLabelInterval !== undefined)
      axis.tickLabelInterval = this.#tickLabelInterval;
    if (this.#tickLabelDistanceFromAxis !== undefined)
      axis.tickLabelDistanceFromAxis = this.#tickLabelDistanceFromAxis;
    return Object.keys(axis).length > 0 ? axis : undefined;
  }
}
function applyChartAxisConfig(axis, config) {
  if (!config) {
    return;
  }
  const hasExplicitVisibility = "deleted" in config && typeof config.deleted === "boolean" || "visible" in config && typeof config.visible === "boolean";
  const hasOtherAxisConfig = Object.keys(config).some((key) => key !== "deleted" && key !== "visible");
  if (!hasExplicitVisibility && hasOtherAxisConfig) {
    axis.deleted = false;
  }
  if ("deleted" in config && typeof config.deleted === "boolean") {
    axis.deleted = config.deleted;
  } else if ("visible" in config && typeof config.visible === "boolean") {
    axis.deleted = !config.visible;
  }
  if ("axisType" in config) {
    axis.axisType = config.axisType ?? undefined;
  }
  if ("tickLabelInterval" in config) {
    axis.tickLabelInterval = config.tickLabelInterval ?? undefined;
  }
  if ("tickLabelDistanceFromAxis" in config) {
    axis.tickLabelDistanceFromAxis = config.tickLabelDistanceFromAxis ?? undefined;
  }
  if ("numberFormatCode" in config) {
    axis.numberFormatCode = config.numberFormatCode ?? undefined;
  }
  if ("numberFormatSourceLinked" in config) {
    axis.numberFormatSourceLinked = config.numberFormatSourceLinked ?? undefined;
  }
  if ("min" in config) {
    axis.min = config.min ?? undefined;
  }
  if ("max" in config) {
    axis.max = config.max ?? undefined;
  }
  if ("majorUnit" in config) {
    axis.majorUnit = config.majorUnit ?? undefined;
  }
  if ("minorUnit" in config) {
    axis.minorUnit = config.minorUnit ?? undefined;
  }
  if ("position" in config) {
    axis.position = config.position ?? undefined;
  }
  if ("orientation" in config) {
    axis.orientation = config.orientation ?? undefined;
  }
  if ("majorTickMark" in config) {
    axis.majorTickMark = config.majorTickMark ?? undefined;
  }
  if ("minorTickMark" in config) {
    axis.minorTickMark = config.minorTickMark ?? undefined;
  }
  if ("tickLabelPosition" in config) {
    axis.tickLabelPosition = config.tickLabelPosition === undefined ? undefined : coerceTickLabelPositionConfig(config.tickLabelPosition) ?? undefined;
  }
  if ("crossBetween" in config) {
    axis.crossBetween = config.crossBetween ?? undefined;
  }
  if ("crosses" in config) {
    axis.crosses = config.crosses ?? undefined;
  }
  if ("crossesAt" in config) {
    axis.crossesAt = config.crossesAt ?? undefined;
  } else if ("crossValue" in config) {
    axis.crossesAt = config.crossValue ?? undefined;
  }
  if ("textStyle" in config && config.textStyle !== undefined) {
    const value = config.textStyle;
    applyTextStyleConfig(axis.textStyle, value);
  }
  if ("line" in config && config.line !== undefined) {
    const value = config.line;
    axis.line = value instanceof Line4 ? value : new Line4(value);
  }
  if ("majorGridlines" in config) {
    const value = config.majorGridlines;
    axis.majorGridlines = value == null ? undefined : value instanceof Line4 ? value : new Line4(value);
  }
  if ("minorGridlines" in config) {
    const value = config.minorGridlines;
    axis.minorGridlines = value == null ? undefined : value instanceof Line4 ? value : new Line4(value);
  }
  if (!("title" in config)) {
    return;
  }
  const title = config.title;
  if (typeof title === "string") {
    axis.title.text = title;
    return;
  }
  if (title == null) {
    axis.title.text = undefined;
    return;
  }
  if (!isRecord2(title)) {
    return;
  }
  if ("text" in title) {
    const next = title.text;
    axis.title.text = typeof next === "string" ? next : undefined;
  }
  if ("textStyle" in title) {
    const style = title.textStyle;
    const coerced = coerceTextStyleConfig(style);
    if (coerced) {
      applyTextStyleConfig(axis.title.textStyle, coerced);
    }
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-bar-options.js
class ChartBarOptions {
  #direction;
  #grouping;
  #varyColors = false;
  #gapWidth;
  #gapDepth;
  #overlap;
  #bar3dShape;
  constructor(proto) {
    this.#direction = proto?.direction ? BAR_DIRECTION_FROM_PROTO[proto.direction] : undefined;
    this.#grouping = proto?.grouping ? BAR_GROUPING_FROM_PROTO[proto.grouping] : undefined;
    this.#varyColors = proto?.varyColors ?? false;
    this.#gapWidth = proto?.gapWidth;
    this.#gapDepth = proto?.gapDepth;
    this.#overlap = proto?.overlap;
    this.#bar3dShape = proto?.bar3dShape;
  }
  get grouping() {
    return this.#grouping;
  }
  set grouping(value) {
    this.#grouping = value;
  }
  get direction() {
    return this.#direction;
  }
  set direction(value) {
    this.#direction = value;
  }
  get varyColors() {
    return this.#varyColors;
  }
  set varyColors(value) {
    this.#varyColors = value;
  }
  get gapWidth() {
    return this.#gapWidth;
  }
  set gapWidth(value) {
    this.#gapWidth = value;
  }
  get gapDepth() {
    return this.#gapDepth;
  }
  set gapDepth(value) {
    this.#gapDepth = value;
  }
  get overlap() {
    return this.#overlap;
  }
  set overlap(value) {
    this.#overlap = value;
  }
  get bar3dShape() {
    return this.#bar3dShape;
  }
  set bar3dShape(value) {
    this.#bar3dShape = value;
  }
  toProto() {
    const options = {};
    const direction = this.#direction ? BAR_DIRECTION_TO_PROTO[this.#direction] : undefined;
    if (direction !== 0 /* BAR_DIRECTION_UNSPECIFIED */) {
      options.direction = direction;
    }
    const grouping = this.#grouping ? BAR_GROUPING_TO_PROTO[this.#grouping] : undefined;
    if (grouping !== undefined && grouping !== 0 /* BAR_GROUPING_UNSPECIFIED */) {
      options.grouping = grouping;
    }
    if (this.#varyColors) {
      options.varyColors = true;
    }
    if (this.#gapWidth !== undefined) {
      options.gapWidth = this.#gapWidth;
    }
    if (this.#gapDepth !== undefined) {
      options.gapDepth = this.#gapDepth;
    }
    if (this.#overlap !== undefined) {
      options.overlap = this.#overlap;
    }
    if (this.#bar3dShape !== undefined) {
      options.bar3dShape = this.#bar3dShape;
    }
    return Object.keys(options).length > 0 ? options : undefined;
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-box-whisker-options.js
class ChartBoxWhiskerOptions {
  showMeanLine;
  showMeanMarker;
  showNonOutliers;
  showOutliers;
  #quartileMethod;
  constructor(proto) {
    this.showMeanLine = proto?.showMeanLine;
    this.showMeanMarker = proto?.showMeanMarker;
    this.showNonOutliers = proto?.showNonOutliers;
    this.showOutliers = proto?.showOutliers;
    this.#quartileMethod = proto?.quartileMethod ? BOX_WHISKER_QUARTILE_METHOD_FROM_PROTO[proto.quartileMethod] : undefined;
  }
  get quartileMethod() {
    return this.#quartileMethod;
  }
  set quartileMethod(value) {
    this.#quartileMethod = value;
  }
  toProto() {
    const options = {};
    if (this.showMeanLine !== undefined) {
      options.showMeanLine = this.showMeanLine;
    }
    if (this.showMeanMarker !== undefined) {
      options.showMeanMarker = this.showMeanMarker;
    }
    if (this.showNonOutliers !== undefined) {
      options.showNonOutliers = this.showNonOutliers;
    }
    if (this.showOutliers !== undefined) {
      options.showOutliers = this.showOutliers;
    }
    if (this.#quartileMethod !== undefined) {
      options.quartileMethod = BOX_WHISKER_QUARTILE_METHOD_TO_PROTO[this.#quartileMethod];
    }
    return Object.keys(options).length > 0 ? options : undefined;
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-data-labels.js
class ChartDataLabels {
  #position;
  #showValue = false;
  #showSeriesName = false;
  #showCategoryName = false;
  #showPercent = false;
  #showLeaderLines = false;
  #fill;
  textStyle;
  #stroke;
  constructor(proto) {
    this.textStyle = new TextStyle2(proto?.textStyle);
    this.#stroke = new Line4({ type: "proto", proto: proto?.stroke });
    this.#position = proto?.position ? DATA_LABEL_POSITION_FROM_PROTO[proto.position] : undefined;
    this.#showValue = proto?.showValue ?? false;
    this.#showSeriesName = proto?.showSeriesName ?? false;
    this.#showCategoryName = proto?.showCategoryName ?? false;
    this.#showPercent = proto?.showPercent ?? false;
    this.#showLeaderLines = proto?.showLeaderLines ?? false;
  }
  get position() {
    return this.#position;
  }
  set position(value) {
    this.#position = value ?? undefined;
  }
  get showValue() {
    return this.#showValue;
  }
  set showValue(value) {
    this.#showValue = Boolean(value);
  }
  get showSeriesName() {
    return this.#showSeriesName;
  }
  set showSeriesName(value) {
    this.#showSeriesName = Boolean(value);
  }
  get showCategoryName() {
    return this.#showCategoryName;
  }
  set showCategoryName(value) {
    this.#showCategoryName = Boolean(value);
  }
  get showPercent() {
    return this.#showPercent;
  }
  set showPercent(value) {
    this.#showPercent = Boolean(value);
  }
  get showLeaderLines() {
    return this.#showLeaderLines;
  }
  set showLeaderLines(value) {
    this.#showLeaderLines = Boolean(value);
  }
  get stroke() {
    return this.#stroke;
  }
  set stroke(value) {
    this.#stroke = new Line4(value);
  }
  get line() {
    return this.stroke;
  }
  set line(value) {
    this.stroke = value;
  }
  get fill() {
    return this.#fill;
  }
  set fill(value) {
    this.#fill = new Fill2(value);
  }
  toProto() {
    const position = this.#position && this.#position in DATA_LABEL_POSITION_TO_PROTO ? DATA_LABEL_POSITION_TO_PROTO[this.#position] : undefined;
    const textStyle = this.textStyle.toProto();
    const fill = this.#fill?.toProto();
    const stroke = this.#stroke.toProto();
    const hasExtendedPosition = this.#position !== undefined && !(this.#position in DATA_LABEL_POSITION_TO_PROTO);
    const hasAny = this.#showValue || this.#showSeriesName || this.#showCategoryName || this.#showPercent || this.#showLeaderLines || position !== 0 /* DATA_LABEL_POSITION_UNSPECIFIED */ || hasExtendedPosition || Boolean(textStyle) || Boolean(fill) || Boolean(stroke);
    if (!hasAny) {
      return;
    }
    const labels = {
      showValue: this.#showValue,
      showSeriesName: this.#showSeriesName,
      showCategoryName: this.#showCategoryName,
      showPercent: this.#showPercent,
      showLegendKey: false,
      showBubbleSize: false,
      showLeaderLines: this.#showLeaderLines,
      position: position ?? 0 /* DATA_LABEL_POSITION_UNSPECIFIED */,
      textStyle: textStyle ?? undefined,
      leaderLine: undefined,
      fill: fill ?? undefined,
      stroke: stroke ?? undefined
    };
    if (hasExtendedPosition) {
      labels.positionName = this.#position;
      if (this.#position === "dataCallout") {
        labels.kind = "dataCallout";
      }
    }
    return labels;
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-data-table.js
class ChartDataTable {
  #visible = false;
  #showLegendKey = false;
  #fill;
  #stroke;
  #textStyle;
  constructor() {
    this.#textStyle = new TextStyle2;
  }
  get visible() {
    return this.#visible;
  }
  set visible(value) {
    this.#visible = Boolean(value);
  }
  get showLegendKey() {
    return this.#showLegendKey;
  }
  set showLegendKey(value) {
    this.#showLegendKey = Boolean(value);
  }
  get fill() {
    return this.#fill;
  }
  set fill(value) {
    this.#fill = value ? new Fill2(value) : undefined;
  }
  get stroke() {
    return this.#stroke;
  }
  set stroke(value) {
    this.#stroke = value ? new Line4(value) : undefined;
  }
  get line() {
    return this.stroke;
  }
  set line(value) {
    this.stroke = value;
  }
  get textStyle() {
    return this.#textStyle;
  }
  toProto() {
    const textStyle = this.#textStyle.toProto();
    const fill = this.#fill?.toProto();
    const stroke = this.#stroke?.toProto();
    const hasAny = this.#visible || this.#showLegendKey || Boolean(textStyle) || Boolean(fill) || Boolean(stroke);
    if (!hasAny)
      return;
    return {
      visible: this.#visible,
      showLegendKey: this.#showLegendKey,
      textStyle,
      fill,
      stroke
    };
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-doughnut-options.js
class ChartDoughnutOptions {
  #holeSize;
  #firstSliceAngle;
  constructor(proto) {
    this.#holeSize = proto?.holeSize;
    this.#firstSliceAngle = proto?.firstSliceAngle;
  }
  get holeSize() {
    return this.#holeSize;
  }
  set holeSize(value) {
    this.#holeSize = value;
  }
  get firstSliceAngle() {
    return this.#firstSliceAngle;
  }
  set firstSliceAngle(value) {
    this.#firstSliceAngle = value;
  }
  toProto() {
    const options = {};
    if (this.#holeSize !== undefined) {
      options.holeSize = this.#holeSize;
    }
    if (this.#firstSliceAngle !== undefined) {
      options.firstSliceAngle = this.#firstSliceAngle;
    }
    return Object.keys(options).length > 0 ? options : undefined;
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-funnel-options.js
class ChartFunnelOptions {
  #gapWidth;
  constructor(proto) {
    this.#gapWidth = proto?.gapWidth;
  }
  get gapWidth() {
    return this.#gapWidth;
  }
  set gapWidth(value) {
    this.#gapWidth = value;
  }
  toProto() {
    if (this.#gapWidth === undefined) {
      return;
    }
    return {
      gapWidth: this.#gapWidth
    };
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-legend.js
var coerceLegendPositionConfig = (value) => {
  if (typeof value !== "string") {
    return value;
  }
  const trimmed = value.trim();
  if (!trimmed) {
    return;
  }
  switch (trimmed.toLowerCase()) {
    case "left":
      return "left";
    case "top":
      return "top";
    case "topright":
    case "top_right":
    case "top-right":
      return "topRight";
    case "right":
      return "right";
    case "bottom":
      return "bottom";
    default:
      return;
  }
};

class ChartLegend {
  #position;
  #overlay = false;
  #fill;
  #textStyle;
  #stroke;
  #host;
  constructor(proto, host) {
    this.#position = proto?.position ? LEGEND_POSITION_FROM_PROTO[proto.position] : undefined;
    this.#overlay = proto?.overlay ?? false;
    this.#fill = new Fill2({ type: "proto", proto: proto?.fill });
    this.#textStyle = new TextStyle2(proto?.textStyle);
    this.#stroke = new Line4;
    this.#host = host;
    Object.preventExtensions(this);
  }
  get position() {
    return this.#position;
  }
  set position(value) {
    const coerced = coerceLegendPositionConfig(value);
    if (!coerced) {
      throw new Error(`Unsupported legend position: ${String(value)}`);
    }
    this.#position = coerced;
  }
  get overlay() {
    return this.#overlay;
  }
  get textStyle() {
    return this.#textStyle;
  }
  set overlay(value) {
    this.#overlay = Boolean(value);
  }
  get fill() {
    return this.#fill;
  }
  set fill(value) {
    this.#fill = new Fill2(value);
  }
  get stroke() {
    return this.#stroke;
  }
  set stroke(value) {
    this.#stroke = new Line4(value);
  }
  get line() {
    return this.stroke;
  }
  set line(value) {
    this.stroke = value;
  }
  get visible() {
    return Boolean(this.#host?.getHasLegend());
  }
  set visible(value) {
    if (!this.#host) {
      throw new Error("legend.visible is not available without a chart host.");
    }
    if (typeof value !== "boolean") {
      throw new Error("legend.visible must be a boolean.");
    }
    this.#host.setHasLegend(value);
  }
  toProto() {
    const legend = {};
    const protoPosition = this.#position ? LEGEND_POSITION_TO_PROTO[this.#position] : undefined;
    legend.position = protoPosition ?? 0;
    legend.overlay = this.#overlay;
    legend.textStyle = this.textStyle.toProto();
    const fill = this.#fill?.toProto();
    if (fill) {
      legend.fill = fill;
    }
    const stroke = this.#stroke.toProto();
    if (stroke) {
      legend.stroke = stroke;
    }
    if (legend.position === undefined && legend.overlay === undefined && !legend.textStyle && !legend.fill && !legend.stroke) {
      return;
    }
    return legend;
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-line-options.js
class ChartLineOptions {
  #grouping;
  #smooth = false;
  #varyColors = false;
  constructor(proto) {
    this.#grouping = proto?.grouping ? LINE_GROUPING_FROM_PROTO[proto.grouping] : undefined;
    this.#smooth = proto?.smooth ?? false;
    this.#varyColors = proto?.varyColors ?? false;
  }
  get grouping() {
    return this.#grouping;
  }
  set grouping(value) {
    this.#grouping = value;
  }
  get smooth() {
    return this.#smooth;
  }
  set smooth(value) {
    this.#smooth = value;
  }
  get varyColors() {
    return this.#varyColors;
  }
  set varyColors(value) {
    this.#varyColors = value;
  }
  toProto() {
    const options = {};
    if (this.#grouping) {
      options.grouping = LINE_GROUPING_TO_PROTO[this.#grouping];
    }
    if (this.#smooth) {
      options.smooth = this.#smooth;
    }
    if (this.#varyColors) {
      options.varyColors = this.#varyColors;
    }
    return Object.keys(options).length > 0 ? options : undefined;
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-map-options.js
class ChartMapOptions {
  #mapArea;
  #projection;
  #labelLayout;
  #dataLevel;
  #showUnknown;
  #onlyRegionsWithData;
  constructor(proto) {
    this.#mapArea = proto?.mapArea ? MAP_AREA_FROM_PROTO[proto.mapArea] : undefined;
    this.#projection = proto?.projection ? MAP_PROJECTION_FROM_PROTO[proto.projection] : undefined;
    this.#labelLayout = proto?.labelLayout ? MAP_LABEL_LAYOUT_FROM_PROTO[proto.labelLayout] : undefined;
    this.#dataLevel = proto?.dataLevel ? MAP_DATA_LEVEL_FROM_PROTO[proto.dataLevel] : undefined;
    this.#showUnknown = proto?.showUnknown;
    this.#onlyRegionsWithData = proto?.onlyRegionsWithData;
  }
  get mapArea() {
    return this.#mapArea;
  }
  set mapArea(value) {
    this.#mapArea = value;
  }
  get projection() {
    return this.#projection;
  }
  set projection(value) {
    this.#projection = value;
  }
  get labelLayout() {
    return this.#labelLayout;
  }
  set labelLayout(value) {
    this.#labelLayout = value;
  }
  get dataLevel() {
    return this.#dataLevel;
  }
  set dataLevel(value) {
    this.#dataLevel = value;
  }
  get showUnknown() {
    return this.#showUnknown;
  }
  set showUnknown(value) {
    this.#showUnknown = value;
  }
  get onlyRegionsWithData() {
    return this.#onlyRegionsWithData;
  }
  set onlyRegionsWithData(value) {
    this.#onlyRegionsWithData = value;
  }
  toProto() {
    const mapArea = this.#mapArea ? MAP_AREA_TO_PROTO[this.#mapArea] : undefined;
    const projection = this.#projection ? MAP_PROJECTION_TO_PROTO[this.#projection] : undefined;
    const labelLayout = this.#labelLayout ? MAP_LABEL_LAYOUT_TO_PROTO[this.#labelLayout] : undefined;
    const dataLevel = this.#dataLevel ? MAP_DATA_LEVEL_TO_PROTO[this.#dataLevel] : undefined;
    const options = {
      colorScale: []
    };
    const hasArea = mapArea !== 0 /* MAP_AREA_UNSPECIFIED */;
    const hasProjection = projection !== 0 /* MAP_PROJECTION_UNSPECIFIED */;
    const hasLabelLayout = labelLayout !== 0 /* MAP_LABEL_LAYOUT_UNSPECIFIED */;
    const hasDataLevel = dataLevel !== 0 /* MAP_DATA_LEVEL_UNSPECIFIED */;
    if (hasArea) {
      options.mapArea = mapArea;
    }
    if (hasProjection) {
      options.projection = projection;
    }
    if (hasLabelLayout) {
      options.labelLayout = labelLayout;
    }
    if (hasDataLevel) {
      options.dataLevel = dataLevel;
    }
    if (this.#showUnknown !== undefined) {
      options.showUnknown = this.#showUnknown;
    }
    if (this.#onlyRegionsWithData !== undefined) {
      options.onlyRegionsWithData = this.#onlyRegionsWithData;
    }
    const hasAny = hasArea || hasProjection || hasLabelLayout || hasDataLevel || this.#showUnknown !== undefined || this.#onlyRegionsWithData !== undefined;
    return hasAny ? options : undefined;
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-pie-options.js
class ChartPieOptions {
  #firstSliceAngle;
  constructor(proto) {
    this.#firstSliceAngle = proto?.firstSliceAngle;
  }
  get firstSliceAngle() {
    return this.#firstSliceAngle;
  }
  set firstSliceAngle(value) {
    this.#firstSliceAngle = value;
  }
  toProto() {
    if (this.#firstSliceAngle === undefined) {
      return;
    }
    return {
      firstSliceAngle: this.#firstSliceAngle
    };
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-scatter-options.js
class ChartScatterOptions {
  #style;
  #varyColors;
  constructor(proto) {
    this.#style = proto?.style ? SCATTER_STYLE_FROM_PROTO[proto.style] : undefined;
    this.#varyColors = proto?.varyColors ?? false;
  }
  get style() {
    return this.#style;
  }
  set style(value) {
    this.#style = value;
  }
  get varyColors() {
    return this.#varyColors;
  }
  set varyColors(value) {
    this.#varyColors = value;
  }
  toProto() {
    const options = {};
    const style = this.#style ? SCATTER_STYLE_TO_PROTO[this.#style] : undefined;
    options.style = style;
    options.varyColors = this.#varyColors;
    return options;
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-series-data-label-override.js
class ChartSeriesDataLabelOverride {
  #idx;
  #text;
  #position;
  #fill;
  #showValue;
  #showSeriesName;
  #showCategoryName;
  #showPercent;
  textStyle;
  #stroke;
  constructor(proto) {
    this.#idx = proto?.idx;
    this.textStyle = new TextStyle2(proto?.textStyle);
    this.#stroke = new Line4({ type: "proto", proto: proto?.stroke });
    this.#position = proto?.position ? DATA_LABEL_POSITION_FROM_PROTO[proto.position] : undefined;
    this.#text = proto?.text;
    this.#fill = proto?.fill ? new Fill2({ type: "proto", proto: proto.fill }) : undefined;
    this.#showValue = proto?.showValue;
    this.#showSeriesName = proto?.showSeriesName;
    this.#showCategoryName = proto?.showCategoryName;
    this.#showPercent = proto?.showPercent;
  }
  get idx() {
    return this.#idx;
  }
  set idx(value) {
    this.#idx = value ?? undefined;
  }
  get text() {
    return this.#text;
  }
  set text(value) {
    this.#text = value ?? undefined;
  }
  get position() {
    return this.#position;
  }
  set position(value) {
    this.#position = value ?? undefined;
  }
  get fill() {
    return this.#fill;
  }
  set fill(value) {
    this.#fill = value ? new Fill2(value) : undefined;
  }
  get stroke() {
    return this.#stroke;
  }
  set stroke(value) {
    this.#stroke = new Line4(value);
  }
  get line() {
    return this.stroke;
  }
  set line(value) {
    this.stroke = value;
  }
  get showValue() {
    return this.#showValue ?? false;
  }
  set showValue(value) {
    this.#showValue = Boolean(value);
  }
  get showSeriesName() {
    return this.#showSeriesName ?? false;
  }
  set showSeriesName(value) {
    this.#showSeriesName = Boolean(value);
  }
  get showCategoryName() {
    return this.#showCategoryName ?? false;
  }
  set showCategoryName(value) {
    this.#showCategoryName = Boolean(value);
  }
  get showPercent() {
    return this.#showPercent ?? false;
  }
  set showPercent(value) {
    this.#showPercent = Boolean(value);
  }
  toProto() {
    const idx = this.#idx;
    if (idx === undefined || idx === null) {
      return;
    }
    const textStyle = this.textStyle.toProto();
    const fill = this.#fill?.toProto();
    const stroke = this.#stroke.toProto();
    const position = this.#position && this.#position in DATA_LABEL_POSITION_TO_PROTO ? DATA_LABEL_POSITION_TO_PROTO[this.#position] : undefined;
    const dataLabel = { idx };
    if (this.#text !== undefined) {
      dataLabel.text = this.#text;
    }
    if (position !== 0 /* DATA_LABEL_POSITION_UNSPECIFIED */) {
      dataLabel.position = position;
    }
    if (this.#position && !(this.#position in DATA_LABEL_POSITION_TO_PROTO)) {
      dataLabel.positionName = this.#position;
      if (this.#position === "dataCallout") {
        dataLabel.kind = "dataCallout";
      }
    }
    if (this.#showValue) {
      dataLabel.showValue = this.#showValue;
    }
    if (this.#showSeriesName) {
      dataLabel.showSeriesName = this.#showSeriesName;
    }
    if (this.#showCategoryName) {
      dataLabel.showCategoryName = this.#showCategoryName;
    }
    if (this.#showPercent) {
      dataLabel.showPercent = this.#showPercent;
    }
    if (textStyle) {
      dataLabel.textStyle = textStyle;
    }
    if (fill) {
      dataLabel.fill = fill;
    }
    if (stroke) {
      dataLabel.stroke = stroke;
    }
    return dataLabel;
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-series-data-label-override-collection.js
class ChartSeriesDataLabelOverrideCollection {
  #items;
  constructor(proto) {
    this.#items = [];
    if (proto) {
      this.#items = proto.map((override) => new ChartSeriesDataLabelOverride(override));
    }
  }
  add(idx) {
    const override = new ChartSeriesDataLabelOverride({ idx });
    this.#items.push(override);
    return override;
  }
  get length() {
    return this.#items.length;
  }
  toProto() {
    return this.#items.map((override) => override.toProto()).filter((override) => Boolean(override));
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-series-marker.js
class ChartSeriesMarker {
  #symbol;
  #size;
  constructor(proto) {
    this.#symbol = proto?.symbol ? MARKER_SYMBOL_FROM_PROTO[proto.symbol] : undefined;
    this.#size = proto?.size;
  }
  get symbol() {
    return this.#symbol;
  }
  set symbol(value) {
    this.#symbol = value;
  }
  get size() {
    return this.#size;
  }
  set size(value) {
    this.#size = value;
  }
  toProto() {
    const symbol2 = this.#symbol ? MARKER_SYMBOL_TO_PROTO[this.#symbol] : undefined;
    const size = this.#size;
    if (symbol2 === undefined && size === undefined) {
      return;
    }
    return {
      symbol: symbol2,
      size
    };
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-series-point.js
class ChartSeriesPoint {
  #idx;
  #fill;
  #stroke;
  constructor(proto) {
    this.#idx = proto?.idx;
    this.#fill = proto?.fill ? new Fill2({ type: "proto", proto: proto.fill }) : undefined;
    this.#stroke = new Line4({ type: "proto", proto: proto?.stroke });
  }
  get idx() {
    return this.#idx;
  }
  set idx(value) {
    this.#idx = value ?? undefined;
  }
  get fill() {
    return this.#fill;
  }
  set fill(value) {
    this.#fill = new Fill2(value);
  }
  get stroke() {
    return this.#stroke;
  }
  set stroke(value) {
    this.#stroke = new Line4(value);
  }
  get line() {
    return this.stroke;
  }
  set line(value) {
    this.stroke = value;
  }
  toProto() {
    const idx = this.#idx;
    if (idx === undefined || idx === null) {
      return;
    }
    const fill = this.#fill?.toProto();
    const stroke = this.#stroke.toProto();
    if (!fill && !stroke) {
      return;
    }
    return {
      idx,
      fill,
      stroke
    };
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-series-point-collection.js
class ChartSeriesPointCollection {
  #items;
  constructor(proto) {
    this.#items = [];
    if (proto) {
      this.#items = proto.map((point3) => new ChartSeriesPoint(point3));
    }
  }
  get items() {
    return [...this.#items];
  }
  add(idx) {
    const point3 = new ChartSeriesPoint({
      idx,
      fill: undefined,
      stroke: undefined
    });
    this.#items.push(point3);
    return point3;
  }
  toProto() {
    return this.#items.map((point3) => point3.toProto()).filter((point3) => Boolean(point3));
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-trendline.js
class ChartTrendlineLabel {
  #text;
  #numberFormatCode;
  #numberFormatSourceLinked;
  #manualLayout;
  #textStyle;
  #fill;
  #stroke;
  #textRuns;
  constructor(proto) {
    this.#text = proto?.text ?? undefined;
    this.#numberFormatCode = proto?.numberFormatCode ?? undefined;
    this.#numberFormatSourceLinked = proto?.numberFormatSourceLinked ?? undefined;
    this.#manualLayout = proto?.manualLayout ?? undefined;
    this.#textStyle = new TextStyle2(proto?.textStyle);
    this.#fill = proto?.fill ? new Fill2({ type: "proto", proto: proto.fill }) : undefined;
    this.#stroke = proto?.stroke ? new Line4({ type: "proto", proto: proto.stroke }) : undefined;
    this.#textRuns = (proto?.textRuns ?? []).map((run) => ({
      text: run.text ?? "",
      textStyle: run.textStyle ? new TextStyle2(run.textStyle) : undefined
    }));
  }
  get text() {
    return this.#text;
  }
  set text(value) {
    this.#text = value ?? undefined;
  }
  get numberFormatCode() {
    return this.#numberFormatCode;
  }
  set numberFormatCode(value) {
    this.#numberFormatCode = value ?? undefined;
  }
  get numberFormatSourceLinked() {
    return this.#numberFormatSourceLinked;
  }
  set numberFormatSourceLinked(value) {
    this.#numberFormatSourceLinked = value === undefined ? undefined : Boolean(value);
  }
  get manualLayout() {
    return this.#manualLayout;
  }
  set manualLayout(value) {
    this.#manualLayout = value ?? undefined;
  }
  get textStyle() {
    return this.#textStyle;
  }
  set textStyle(value) {
    this.#textStyle = value;
  }
  get fill() {
    return this.#fill;
  }
  set fill(value) {
    this.#fill = value ? new Fill2(value) : undefined;
  }
  get stroke() {
    return this.#stroke;
  }
  set stroke(value) {
    this.#stroke = value ? new Line4(value) : undefined;
  }
  get line() {
    return this.stroke;
  }
  set line(value) {
    this.stroke = value;
  }
  get textRuns() {
    return this.#textRuns.map((run) => ({
      text: run.text,
      textStyle: run.textStyle ? new TextStyle2(run.textStyle.toProto()) : undefined
    }));
  }
  set textRuns(value) {
    const runs = value ?? [];
    this.#textRuns = runs.map((run) => {
      const text = run.text ?? "";
      const style = new TextStyle2;
      const ts = run.textStyle;
      if (ts) {
        if (ts.fontSize !== undefined)
          style.fontSize = ts.fontSize;
        if (ts.fill !== undefined)
          style.fill = ts.fill;
        if (ts.bold !== undefined)
          style.bold = ts.bold;
        if (ts.italic !== undefined)
          style.italic = ts.italic;
        if (ts.underline !== undefined)
          style.underline = ts.underline;
        if (ts.name !== undefined)
          style.name = ts.name;
        if (ts.family !== undefined)
          style.family = ts.family;
        if (ts.alignment !== undefined)
          style.alignment = ts.alignment;
      }
      return {
        text,
        textStyle: ts ? style : undefined
      };
    });
  }
  toProto() {
    const textStyle = this.#textStyle.toProto();
    const fill = this.#fill?.toProto();
    const stroke = this.#stroke?.toProto();
    const textRuns = this.#textRuns.map((run) => {
      const text = run.text ?? "";
      const runStyle = run.textStyle?.toProto();
      if (!text.trim() && !runStyle) {
        return null;
      }
      const pb = { text };
      if (runStyle)
        pb.textStyle = runStyle;
      return pb;
    }).filter((v) => v !== null);
    const hasAny = this.#text !== undefined || this.#numberFormatCode !== undefined || this.#numberFormatSourceLinked !== undefined || this.#manualLayout !== undefined || Boolean(textStyle) || Boolean(fill) || Boolean(stroke) || textRuns.length > 0;
    if (!hasAny)
      return;
    const label = { textRuns };
    if (this.#text !== undefined)
      label.text = this.#text;
    if (this.#numberFormatCode !== undefined)
      label.numberFormatCode = this.#numberFormatCode;
    if (this.#numberFormatSourceLinked !== undefined)
      label.numberFormatSourceLinked = this.#numberFormatSourceLinked;
    if (this.#manualLayout !== undefined)
      label.manualLayout = this.#manualLayout;
    if (textStyle)
      label.textStyle = textStyle;
    if (fill)
      label.fill = fill;
    if (stroke)
      label.stroke = stroke;
    return label;
  }
}

class ChartTrendline {
  #type;
  #name;
  #order;
  #period;
  #forward;
  #backward;
  #intercept;
  #displayEquation;
  #displayRSquared;
  #stroke;
  #label;
  constructor(proto) {
    this.#type = proto?.type ? TRENDLINE_TYPE_FROM_PROTO[proto.type] : undefined;
    this.#name = proto?.name ?? undefined;
    this.#order = proto?.order ?? undefined;
    this.#period = proto?.period ?? undefined;
    this.#forward = proto?.forward ?? undefined;
    this.#backward = proto?.backward ?? undefined;
    this.#intercept = proto?.intercept ?? undefined;
    this.#displayEquation = proto?.displayEquation ?? undefined;
    this.#displayRSquared = proto?.displayRSquared ?? undefined;
    this.#stroke = proto?.stroke ? new Line4({ type: "proto", proto: proto.stroke }) : undefined;
    this.#label = new ChartTrendlineLabel(proto?.label);
  }
  get type() {
    return this.#type;
  }
  set type(value) {
    this.#type = value ?? undefined;
  }
  get name() {
    return this.#name;
  }
  set name(value) {
    this.#name = value ?? undefined;
  }
  get polynomialOrder() {
    return this.#order;
  }
  set polynomialOrder(value) {
    this.#order = value ?? undefined;
  }
  get movingAveragePeriod() {
    return this.#period;
  }
  set movingAveragePeriod(value) {
    this.#period = value ?? undefined;
  }
  get forecastForward() {
    return this.#forward;
  }
  set forecastForward(value) {
    this.#forward = value ?? undefined;
  }
  get forecastBackward() {
    return this.#backward;
  }
  set forecastBackward(value) {
    this.#backward = value ?? undefined;
  }
  get intercept() {
    return this.#intercept;
  }
  set intercept(value) {
    this.#intercept = value ?? undefined;
  }
  get displayEquation() {
    return this.#displayEquation;
  }
  set displayEquation(value) {
    this.#displayEquation = value === undefined ? undefined : Boolean(value);
  }
  get displayRSquared() {
    return this.#displayRSquared;
  }
  set displayRSquared(value) {
    this.#displayRSquared = value === undefined ? undefined : Boolean(value);
  }
  get stroke() {
    if (!this.#stroke) {
      this.#stroke = new Line4;
    }
    return this.#stroke;
  }
  set stroke(value) {
    this.#stroke = new Line4(value);
  }
  get line() {
    return this.stroke;
  }
  set line(value) {
    this.stroke = value;
  }
  get label() {
    return this.#label;
  }
  set label(value) {
    this.#label = value;
  }
  toProto() {
    if (!this.#type) {
      return;
    }
    const stroke = this.#stroke?.toProto();
    const label = this.#label.toProto();
    const trendline = {
      type: TRENDLINE_TYPE_TO_PROTO[this.#type]
    };
    if (this.#name !== undefined)
      trendline.name = this.#name;
    if (this.#order !== undefined)
      trendline.order = this.#order;
    if (this.#period !== undefined)
      trendline.period = this.#period;
    if (this.#forward !== undefined)
      trendline.forward = this.#forward;
    if (this.#backward !== undefined)
      trendline.backward = this.#backward;
    if (this.#intercept !== undefined)
      trendline.intercept = this.#intercept;
    if (this.#displayEquation !== undefined)
      trendline.displayEquation = this.#displayEquation;
    if (this.#displayRSquared !== undefined)
      trendline.displayRSquared = this.#displayRSquared;
    if (stroke)
      trendline.stroke = stroke;
    if (label)
      trendline.label = label;
    return trendline;
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-trendline-collection.js
class ChartTrendlineCollection {
  #items;
  constructor(proto) {
    this.#items = (proto ?? []).map((t) => new ChartTrendline(t));
  }
  get items() {
    return [...this.#items];
  }
  get length() {
    return this.#items.length;
  }
  add(type, config) {
    const trendline = new ChartTrendline;
    trendline.type = type;
    if (config) {
      if (config.name !== undefined)
        trendline.name = config.name;
      if (config.polynomialOrder !== undefined)
        trendline.polynomialOrder = config.polynomialOrder;
      if (config.movingAveragePeriod !== undefined)
        trendline.movingAveragePeriod = config.movingAveragePeriod;
      if (config.forecastForward !== undefined)
        trendline.forecastForward = config.forecastForward;
      if (config.forecastBackward !== undefined)
        trendline.forecastBackward = config.forecastBackward;
      if (config.intercept !== undefined)
        trendline.intercept = config.intercept;
      if (config.displayEquation !== undefined)
        trendline.displayEquation = config.displayEquation;
      if (config.displayRSquared !== undefined)
        trendline.displayRSquared = config.displayRSquared;
      if (config.line !== undefined)
        trendline.stroke = config.line;
      else if (config.stroke !== undefined)
        trendline.stroke = config.stroke;
      if (config.label)
        applyLabelConfig(trendline.label, config.label);
    }
    this.#items.push(trendline);
    return trendline;
  }
  clear() {
    this.#items = [];
  }
  toProto() {
    return this.#items.map((t) => t.toProto()).filter((t) => Boolean(t));
  }
}
function applyLabelConfig(label, config) {
  if (config.text !== undefined)
    label.text = config.text;
  if (config.numberFormatCode !== undefined)
    label.numberFormatCode = config.numberFormatCode;
  if (config.numberFormatSourceLinked !== undefined)
    label.numberFormatSourceLinked = config.numberFormatSourceLinked;
  if (config.manualLayout !== undefined) {
    label.manualLayout = {
      x: config.manualLayout.x,
      y: config.manualLayout.y,
      w: config.manualLayout.w,
      h: config.manualLayout.h
    };
  }
  if (config.textStyle) {
    const style = label.textStyle;
    const ts = config.textStyle;
    if (ts.fontSize !== undefined)
      style.fontSize = ts.fontSize;
    if (ts.fill !== undefined)
      style.fill = ts.fill;
    if (ts.bold !== undefined)
      style.bold = ts.bold;
    if (ts.italic !== undefined)
      style.italic = ts.italic;
    if (ts.underline !== undefined)
      style.underline = ts.underline;
    if (ts.name !== undefined)
      style.name = ts.name;
    if (ts.family !== undefined)
      style.family = ts.family;
    if (ts.alignment !== undefined)
      style.alignment = ts.alignment;
  }
  if (config.fill !== undefined)
    label.fill = config.fill;
  if (config.line !== undefined)
    label.stroke = config.line;
  else if (config.stroke !== undefined)
    label.stroke = config.stroke;
  if (config.textRuns !== undefined)
    label.textRuns = config.textRuns;
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-error-bars.js
class ChartErrorBars {
  #type = "none";
  #value;
  #endStyle;
  #line;
  constructor() {
    this.#line = new Line4;
  }
  get type() {
    return this.#type;
  }
  set type(value) {
    this.#type = value;
  }
  get value() {
    return this.#value;
  }
  set value(value) {
    this.#value = value ?? undefined;
  }
  get endStyle() {
    return this.#endStyle;
  }
  set endStyle(value) {
    this.#endStyle = value ?? undefined;
  }
  get line() {
    return this.#line;
  }
  set line(value) {
    this.#line = new Line4(value);
  }
  toProto() {
    if (this.#type === "none") {
      return;
    }
    const line = this.#line.toProto();
    return {
      type: this.#type,
      value: this.#value,
      endStyle: this.#endStyle,
      line
    };
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-series.js
class ChartSeriesFillFormat {
  #series;
  constructor(series) {
    this.#series = series;
  }
  clear() {
    this.#series.fill = { type: "none" };
  }
  setSolidColor(value) {
    this.#series.fill = value;
  }
  get color() {
    const fill = this.#series.fill;
    const config = fill?.toConfig();
    return typeof config === "string" ? config : undefined;
  }
  set color(value) {
    if (typeof value !== "string" || value.trim().length === 0) {
      return;
    }
    this.#series.fill = value;
  }
}

class ChartSeriesLineFormat {
  #series;
  constructor(series) {
    this.#series = series;
  }
  get visible() {
    return this.#series.stroke.visible;
  }
  set visible(value) {
    this.#series.stroke.visible = value;
  }
  get color() {
    return this.#series.stroke.color;
  }
  set color(value) {
    this.#series.stroke.color = value;
  }
  get style() {
    return this.#series.stroke.style;
  }
  set style(value) {
    this.#series.stroke.style = value;
  }
  get weight() {
    return this.#series.stroke.width;
  }
  set weight(value) {
    this.#series.stroke.width = value;
  }
}

class ChartSeriesFormat {
  #series;
  #fill;
  #line;
  constructor(series) {
    this.#series = series;
    this.#fill = new ChartSeriesFillFormat(series);
    this.#line = new ChartSeriesLineFormat(series);
  }
  get fill() {
    return this.#fill;
  }
  set fill(value) {
    this.#series.fill = value;
  }
  get line() {
    return this.#line;
  }
  set line(value) {
    this.#series.stroke = value;
  }
}

class ChartSeries {
  #name;
  #values;
  #categories;
  #xValues;
  #xFormula;
  #bubbleSizes;
  #categoryPaths;
  #valuesFormatCode;
  #xValuesFormatCode;
  #fill;
  #explosion;
  #categoryNormalizer;
  #stroke;
  #format;
  #marker;
  #points;
  #dataLabelOverrides;
  #trendlines;
  #errorBars;
  #formula;
  #stringCache;
  #categoryFormula;
  #deleted = false;
  #onChange;
  constructor(proto, onChange) {
    this.#name = proto?.name ?? "";
    this.#values = proto?.values;
    this.#categories = proto?.categories;
    this.#xValues = proto?.xValues;
    this.#xFormula = proto?.xFormula;
    this.#bubbleSizes = proto?.bubbleSizes;
    this.#categoryPaths = proto?.categoryPaths?.map((path3) => path3.levels) ?? [];
    this.#valuesFormatCode = proto?.valuesFormatCode;
    this.#xValuesFormatCode = proto?.xValuesFormatCode;
    this.#fill = proto?.fill ? new Fill2({ type: "proto", proto: proto.fill }) : undefined;
    this.#explosion = proto?.explosion;
    this.#stroke = new Line4({ type: "proto", proto: proto?.stroke });
    this.#marker = new ChartSeriesMarker(proto?.marker);
    this.#points = new ChartSeriesPointCollection(proto?.points);
    this.#dataLabelOverrides = new ChartSeriesDataLabelOverrideCollection(proto?.dataLabelOverrides);
    this.#trendlines = new ChartTrendlineCollection(proto?.trendlines);
    this.#errorBars = new ChartErrorBars;
    this.#formula = proto?.formula;
    this.#stringCache = proto?.stringCache;
    this.#categoryFormula = proto?.categoryFormula;
    this.#onChange = onChange;
  }
  setChangeHandler(onChange) {
    this.#onChange = onChange;
  }
  get name() {
    return this.#name;
  }
  set name(value) {
    this.#name = value;
    this.#onChange?.();
  }
  get values() {
    return this.#values;
  }
  set values(values) {
    this.#values = values;
    this.#onChange?.();
  }
  get categories() {
    return this.#categories ?? [];
  }
  set categories(categories) {
    this.#categories = this.#applyCategoryNormalizer(categories);
    this.#onChange?.();
  }
  get xValues() {
    return this.#xValues;
  }
  set xValues(values) {
    this.#xValues = values;
    this.#onChange?.();
  }
  get xFormula() {
    return this.#xFormula;
  }
  set xFormula(value) {
    this.#xFormula = value ?? undefined;
    this.#onChange?.();
  }
  get categoryPaths() {
    return this.#categoryPaths?.map((path3) => [...path3]) ?? [];
  }
  get marker() {
    return this.#marker;
  }
  set marker(marker) {
    this.#marker = marker;
  }
  set categoryPaths(paths) {
    this.#categoryPaths = (paths ?? []).map((path3) => [...path3 ?? []]);
    this.#onChange?.();
  }
  get bubbleSizes() {
    return this.#bubbleSizes;
  }
  set bubbleSizes(values) {
    this.#bubbleSizes = values;
    this.#onChange?.();
  }
  get valuesFormatCode() {
    return this.#valuesFormatCode;
  }
  set valuesFormatCode(value) {
    this.#valuesFormatCode = value ?? undefined;
    this.#onChange?.();
  }
  get xValuesFormatCode() {
    return this.#xValuesFormatCode;
  }
  set xValuesFormatCode(value) {
    this.#xValuesFormatCode = value ?? undefined;
    this.#onChange?.();
  }
  get fill() {
    return this.#fill;
  }
  set fill(value) {
    this.#fill = value ? new Fill2(value) : undefined;
    this.#onChange?.();
  }
  get format() {
    if (!this.#format) {
      this.#format = new ChartSeriesFormat(this);
    }
    return this.#format;
  }
  get explosion() {
    return this.#explosion;
  }
  set explosion(value) {
    this.#explosion = value ?? undefined;
    this.#onChange?.();
  }
  get stroke() {
    return this.#stroke;
  }
  set stroke(value) {
    this.#stroke = new Line4(value);
    this.#onChange?.();
  }
  get line() {
    return this.stroke;
  }
  set line(value) {
    this.stroke = value;
  }
  setCategoryNormalizer(normalizer) {
    this.#categoryNormalizer = normalizer;
    if (normalizer) {
      this.#categories = this.#categories ? normalizer(this.#categories) : undefined;
    }
    this.#onChange?.();
  }
  #applyCategoryNormalizer(values) {
    const coerceScalar = (value) => value == null ? "" : typeof value === "string" ? value : String(value);
    const coerceFromArray = (input) => {
      if (input.length === 0)
        return [];
      if (Array.isArray(input[0])) {
        const rows = input;
        const rowCount = rows.length;
        const maxCols = Math.max(0, ...rows.map((row) => Array.isArray(row) ? row.length : 0));
        if (rowCount === 1) {
          return (rows[0] ?? []).map(coerceScalar);
        }
        if (maxCols === 1) {
          return rows.map((row) => coerceScalar(row?.[0]));
        }
        return rows.map((row) => coerceScalar(row?.[0]));
      }
      return input.map(coerceScalar);
    };
    const coerceCategories = (input) => {
      if (input == null)
        return [];
      if (Array.isArray(input))
        return coerceFromArray(input);
      if (typeof input === "string")
        return [input];
      if (typeof input === "object") {
        const maybeValues = input.values;
        if (Array.isArray(maybeValues))
          return coerceFromArray(maybeValues);
        const iterable = input;
        if (typeof iterable[Symbol.iterator] === "function") {
          return Array.from(input, coerceScalar);
        }
      }
      throw new TypeError("ChartSeries.categories must be a string[] (e.g. ['2020','2021']). " + "If you have a Range, pass range.values and flatten to 1D first.");
    };
    const categories = coerceCategories(values);
    const normalized = this.#categoryNormalizer ? this.#categoryNormalizer(categories) : categories;
    return [...normalized];
  }
  get dataLabelOverrides() {
    return this.#dataLabelOverrides;
  }
  set dataLabelOverrides(value) {
    this.#dataLabelOverrides = value;
    this.#onChange?.();
  }
  get trendlines() {
    return this.#trendlines;
  }
  set trendlines(value) {
    this.#trendlines = value;
    this.#onChange?.();
  }
  get errorBars() {
    return this.#errorBars;
  }
  set errorBars(value) {
    if (value instanceof ChartErrorBars) {
      this.#errorBars = value;
      this.#onChange?.();
      return;
    }
    if (value.type !== undefined)
      this.#errorBars.type = value.type;
    if (value.value !== undefined)
      this.#errorBars.value = value.value;
    if (value.endStyle !== undefined)
      this.#errorBars.endStyle = value.endStyle;
    if (value.line !== undefined)
      this.#errorBars.line = value.line;
    this.#onChange?.();
  }
  get points() {
    return this.#points;
  }
  set points(value) {
    this.#points = value;
    this.#onChange?.();
  }
  get formula() {
    return this.#formula;
  }
  set formula(value) {
    this.#formula = value ?? undefined;
    this.#onChange?.();
  }
  get categoryFormula() {
    return this.#categoryFormula;
  }
  set categoryFormula(value) {
    this.#categoryFormula = value ?? undefined;
    this.#onChange?.();
  }
  get isNullObject() {
    return false;
  }
  delete() {
    this.#deleted = true;
    this.#onChange?.();
  }
  __isDeleted() {
    return this.#deleted;
  }
  toProto() {
    if (this.#deleted) {
      return;
    }
    const categories = this.#categories && this.#categories.length > 0 ? [...this.#categories] : [];
    const marker = this.#marker.toProto();
    const fill = this.#fill?.toProto();
    const stroke = this.#stroke.toProto();
    const points = this.#points.toProto();
    const dataLabelOverrides = this.#dataLabelOverrides.toProto();
    const trendlines = this.#trendlines.toProto();
    const errorBars = this.#errorBars.toProto();
    const categoryPaths = this.#categoryPaths?.map((levels) => ({
      levels
    }));
    const series = {
      name: this.#name ?? "",
      values: this.#values ?? [],
      xFormula: this.#xFormula ?? "",
      categories,
      valuesFormatCode: this.#valuesFormatCode,
      xValues: this.#xValues ?? [],
      xValuesFormatCode: this.#xValuesFormatCode,
      bubbleSizes: this.#bubbleSizes ?? [],
      bubbleSizeFormula: "",
      categoryPaths: categoryPaths ?? [],
      dataLabelOverrides,
      trendlines,
      points,
      explosion: this.#explosion,
      fill,
      stroke,
      marker,
      formula: this.#formula ?? "",
      stringCache: this.#stringCache ?? "",
      categoryFormula: this.#categoryFormula ?? ""
    };
    if (errorBars) {
      series.errorBars = errorBars;
    }
    return series;
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-series-collection.js
class ChartSeriesCollection {
  #items;
  #onChange;
  constructor(proto, onChange) {
    this.#onChange = onChange;
    this.#items = [];
    if (proto) {
      this.#items = proto.map((series) => this.#attachSeries(new ChartSeries(series)));
    }
  }
  add(name) {
    const series = this.#attachSeries(new ChartSeries({ name }));
    this.#items.push(series);
    this.#onChange?.();
    return series;
  }
  setChangeHandler(onChange) {
    this.#onChange = onChange;
    for (const series of this.#items) {
      series.setChangeHandler(() => this.#onChange?.());
    }
  }
  getItemAt(index) {
    const items = this.#items.filter((series2) => !series2.__isDeleted());
    const series = items[index];
    if (!series) {
      throw new Error(`Chart series at index ${index} not found`);
    }
    return series;
  }
  deleteAt(index) {
    this.getItemAt(index).delete();
  }
  get items() {
    return this.#items.filter((series) => !series.__isDeleted());
  }
  clear() {
    if (this.#items.length === 0) {
      return;
    }
    this.#items = [];
    this.#onChange?.();
  }
  deleteAll() {
    this.clear();
  }
  toProto() {
    return this.#items.map((series) => series.toProto()).filter((series) => Boolean(series));
  }
  get length() {
    return this.#items.filter((series) => !series.__isDeleted()).length;
  }
  #attachSeries(series) {
    series.setChangeHandler(() => this.#onChange?.());
    return series;
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-style-options.js
class ChartStyleOptions {
  #styleId;
  #colorStyleId;
  #palette;
  #themeName;
  constructor(proto) {
    this.#styleId = proto?.styleId;
    this.#colorStyleId = proto?.colorStyleId;
    this.#palette = proto?.palette.map((color2) => new Color4({ type: "proto", proto: color2 })) ?? [];
    this.#themeName = proto?.themeName;
  }
  get styleId() {
    return this.#styleId;
  }
  set styleId(value) {
    this.#styleId = value;
  }
  get colorStyleId() {
    return this.#colorStyleId;
  }
  set colorStyleId(value) {
    this.#colorStyleId = value;
  }
  set palette(value) {
    this.#palette = value;
  }
  get themeName() {
    return this.#themeName;
  }
  toProto() {
    if (this.#styleId === undefined && this.#colorStyleId === undefined) {
      return;
    }
    const style = {
      styleId: this.#styleId,
      colorStyleId: this.#colorStyleId,
      palette: this.#palette.map((color2) => color2.toProto()),
      themeName: this.#themeName
    };
    return style;
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-treemap-options.js
class ChartTreemapOptions {
  #parentLabelLayout;
  constructor(proto) {
    this.#parentLabelLayout = proto?.parentLabelLayout ? TREEMAP_PARENT_LABEL_LAYOUT_FROM_PROTO[proto.parentLabelLayout] : undefined;
  }
  get parentLabelLayout() {
    return this.#parentLabelLayout;
  }
  set parentLabelLayout(value) {
    this.#parentLabelLayout = value;
  }
  toProto() {
    if (!this.#parentLabelLayout) {
      return;
    }
    const layout = mapTreemapParentLabelLayout(this.#parentLabelLayout);
    if (layout === 0 /* PARENT_LABEL_LAYOUT_UNSPECIFIED */) {
      return;
    }
    return {
      parentLabelLayout: layout
    };
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart-view3d.js
class ChartView3d {
  rotX;
  rotY;
  perspective;
  rightAngleAxes;
  constructor(proto) {
    this.rotX = proto?.rotX;
    this.rotY = proto?.rotY;
    this.perspective = proto?.perspective;
    this.rightAngleAxes = proto?.rightAngleAxes;
  }
  toProto() {
    if (this.rotX === undefined && this.rotY === undefined && this.perspective === undefined && this.rightAngleAxes === undefined) {
      return;
    }
    return {
      rotX: this.rotX,
      rotY: this.rotY,
      perspective: this.perspective,
      rightAngleAxes: this.rightAngleAxes
    };
  }
}

// node_modules/@oai/granola/dist/models/presentation/charts/chart.js
class Chart2 {
  #id;
  #type;
  #title;
  #titlePlacement;
  #styleIndex;
  #categories = [];
  #hasLegend;
  #displayBlanksAs;
  #showDlblsOverMax = false;
  #chartFill;
  #chartSpaceFill;
  #plotAreaFill;
  #histogramOptions;
  #style;
  #chartLine;
  #chartSpaceLine;
  #plotAreaLine;
  #roundedCorners;
  #legend;
  #dataLabels;
  #dataTable;
  #titleTextStyle;
  #xAxis;
  #yAxis;
  #barOptions;
  #lineOptions;
  #areaOptions;
  #scatterOptions;
  #pieOptions;
  #boxWhiskerOptions;
  #doughnutOptions;
  #funnelOptions;
  #treemapOptions;
  #mapOptions;
  #view3d;
  #series;
  constructor(proto) {
    this.#id = proto?.id ?? generateUuid();
    this.#type = proto?.type ? CHART_TYPE_FROM_PROTO[proto.type] : undefined;
    this.#hasLegend = proto?.hasLegend;
    this.#title = proto?.title;
    this.#styleIndex = proto?.styleIndex;
    this.#style = new ChartStyleOptions(proto?.style);
    this.#chartLine = new Line4({ type: "proto", proto: proto?.chartLine });
    this.#chartSpaceLine = new Line4({
      type: "proto",
      proto: proto?.chartSpaceLine
    });
    this.#chartSpaceFill = proto?.chartSpaceFill ? new Fill2({ type: "proto", proto: proto.chartSpaceFill }) : undefined;
    this.#roundedCorners = proto?.roundedCorners;
    this.#plotAreaLine = new Line4({
      type: "proto",
      proto: proto?.plotAreaLine
    });
    this.#legend = new ChartLegend(proto?.legend, {
      getHasLegend: () => this.#hasLegend,
      setHasLegend: (value) => {
        this.#hasLegend = value;
      }
    });
    this.#dataLabels = new ChartDataLabels(proto?.dataLabels);
    this.#dataTable = new ChartDataTable;
    this.#titleTextStyle = new TextStyle2(proto?.titleTextStyle);
    this.#xAxis = new ChartAxis(proto?.xAxis);
    this.#yAxis = new ChartAxis(proto?.yAxis);
    this.#barOptions = new ChartBarOptions(proto?.barOptions);
    this.#lineOptions = new ChartLineOptions(proto?.lineOptions);
    this.#areaOptions = new ChartAreaOptions(proto?.areaOptions);
    this.#scatterOptions = new ChartScatterOptions(proto?.scatterOptions);
    this.#pieOptions = new ChartPieOptions(proto?.pieOptions);
    this.#boxWhiskerOptions = new ChartBoxWhiskerOptions(proto?.boxWhiskerOptions);
    this.#doughnutOptions = new ChartDoughnutOptions(proto?.doughnutOptions);
    this.#funnelOptions = new ChartFunnelOptions(proto?.funnelOptions);
    this.#treemapOptions = new ChartTreemapOptions(proto?.treemapOptions);
    this.#mapOptions = new ChartMapOptions(proto?.mapOptions);
    this.#view3d = new ChartView3d(proto?.view3d);
    this.#series = new ChartSeriesCollection(proto?.series);
  }
  get id() {
    return this.#id;
  }
  get type() {
    return this.#type;
  }
  set type(value) {
    if (this.#type === value) {
      return;
    }
    this.#type = value;
  }
  get funnelOptions() {
    return this.#funnelOptions;
  }
  set funnelOptions(value) {
    this.#funnelOptions = value;
  }
  get title() {
    return this.#title;
  }
  set title(value) {
    this.#title = value ?? "";
  }
  get titlePlacement() {
    return this.#titlePlacement;
  }
  set titlePlacement(value) {
    this.#titlePlacement = value ?? undefined;
  }
  get styleIndex() {
    return this.#styleIndex;
  }
  set styleIndex(value) {
    this.#styleIndex = value ?? undefined;
  }
  get categories() {
    return [...this.#categories];
  }
  set categories(value) {
    const coerceScalar = (entry) => entry == null ? "" : typeof entry === "string" ? entry : String(entry);
    const coerceFromArray = (input2) => {
      if (input2.length === 0)
        return [];
      if (Array.isArray(input2[0])) {
        const rows = input2;
        const rowCount = rows.length;
        const maxCols = Math.max(0, ...rows.map((row) => Array.isArray(row) ? row.length : 0));
        if (rowCount === 1)
          return (rows[0] ?? []).map(coerceScalar);
        if (maxCols === 1)
          return rows.map((row) => coerceScalar(row?.[0]));
        return rows.map((row) => coerceScalar(row?.[0]));
      }
      return input2.map(coerceScalar);
    };
    const input = value;
    if (input == null) {
      this.#categories = [];
      return;
    }
    if (Array.isArray(input)) {
      this.#categories = coerceFromArray(input);
      return;
    }
    if (typeof input === "string") {
      this.#categories = [input];
      return;
    }
    if (typeof input === "object") {
      const maybeValues = input.values;
      if (Array.isArray(maybeValues)) {
        this.#categories = coerceFromArray(maybeValues);
        return;
      }
      const iterable = input;
      if (typeof iterable[Symbol.iterator] === "function") {
        this.#categories = Array.from(input, coerceScalar);
        return;
      }
    }
    throw new TypeError("Chart.categories must be a string[] (e.g. ['2020','2021']). " + "If you have a Range, pass range.values and flatten to 1D first.");
  }
  get yAxis() {
    return this.#yAxis;
  }
  get valueAxis() {
    return this.#yAxis;
  }
  set yAxis(value) {
    if (value instanceof ChartAxis) {
      this.#yAxis = value;
      return;
    }
    if (value && typeof value === "object") {
      applyChartAxisConfig(this.#yAxis, value);
    }
  }
  get barOptions() {
    return this.#barOptions;
  }
  set barOptions(value) {
    this.#barOptions = value;
  }
  get lineOptions() {
    return this.#lineOptions;
  }
  set lineOptions(value) {
    this.#lineOptions = value;
  }
  get areaOptions() {
    return this.#areaOptions;
  }
  set areaOptions(value) {
    this.#areaOptions = value;
  }
  get scatterOptions() {
    return this.#scatterOptions;
  }
  set scatterOptions(value) {
    this.#scatterOptions = value;
  }
  get pieOptions() {
    return this.#pieOptions;
  }
  set pieOptions(value) {
    this.#pieOptions = value;
  }
  get boxWhiskerOptions() {
    return this.#boxWhiskerOptions;
  }
  set boxWhiskerOptions(value) {
    this.#boxWhiskerOptions = value;
  }
  get doughnutOptions() {
    return this.#doughnutOptions;
  }
  set doughnutOptions(value) {
    this.#doughnutOptions = value;
  }
  get xAxis() {
    return this.#xAxis;
  }
  get categoryAxis() {
    return this.#xAxis;
  }
  set xAxis(value) {
    if (value instanceof ChartAxis) {
      this.#xAxis = value;
      return;
    }
    if (value && typeof value === "object") {
      applyChartAxisConfig(this.#xAxis, value);
    }
  }
  get legend() {
    return this.#legend;
  }
  set legend(value) {
    this.#legend = value;
  }
  get hasLegend() {
    return this.#hasLegend;
  }
  get mapOptions() {
    return this.#mapOptions;
  }
  set mapOptions(value) {
    this.#mapOptions = value;
  }
  get dataLabels() {
    return this.#dataLabels;
  }
  set dataLabels(value) {
    this.#dataLabels = value;
  }
  get dataTable() {
    return this.#dataTable;
  }
  set dataTable(value) {
    this.#dataTable = value;
  }
  get titleTextStyle() {
    return this.#titleTextStyle;
  }
  get style() {
    return this.#style;
  }
  get chartLine() {
    return this.#chartLine;
  }
  get chartSpaceLine() {
    return this.#chartSpaceLine;
  }
  get treemapOptions() {
    return this.#treemapOptions;
  }
  set chartLine(value) {
    this.#chartLine = value;
  }
  set chartSpaceLine(value) {
    this.#chartSpaceLine = value;
  }
  get plotAreaLine() {
    return this.#plotAreaLine;
  }
  set hasLegend(value) {
    this.#hasLegend = value;
  }
  set titleTextStyle(value) {
    this.#titleTextStyle = value;
  }
  get displayBlanksAs() {
    return this.#displayBlanksAs;
  }
  set displayBlanksAs(value) {
    this.#displayBlanksAs = value ?? undefined;
  }
  get showDlblsOverMax() {
    return this.#showDlblsOverMax;
  }
  set showDlblsOverMax(value) {
    this.#showDlblsOverMax = Boolean(value);
  }
  get chartFill() {
    return this.#chartFill;
  }
  set chartFill(value) {
    this.#chartFill = new Fill2(value);
  }
  get chartSpaceFill() {
    return this.#chartSpaceFill;
  }
  set chartSpaceFill(value) {
    this.#chartSpaceFill = new Fill2(value);
  }
  get plotAreaFill() {
    return this.#plotAreaFill;
  }
  set plotAreaFill(value) {
    this.#plotAreaFill = new Fill2(value);
  }
  get histogramOptions() {
    return this.#histogramOptions ? { ...this.#histogramOptions } : undefined;
  }
  set histogramOptions(value) {
    this.#histogramOptions = value ? { ...value } : undefined;
  }
  get series() {
    return this.#series;
  }
  get roundedCorners() {
    return this.#roundedCorners;
  }
  set roundedCorners(value) {
    this.#roundedCorners = value ?? undefined;
  }
  buildTrendlineRenderCache() {
    const bySeriesIndex = new Map;
    const isXYChart = this.#type === "scatter" || this.#type === "bubble";
    const seriesItems = this.#series.items;
    for (let seriesIndex = 0;seriesIndex < seriesItems.length; seriesIndex++) {
      const series = seriesItems[seriesIndex];
      const trendlines = series.trendlines.items;
      if (trendlines.length === 0)
        continue;
      const points = (() => {
        if (isXYChart) {
          const xs = series.xValues ?? [];
          const ys2 = series.values ?? [];
          const raw2 = xs.map((x2, i) => ({ x: x2, y: ys2[i] })).filter((p) => typeof p.y === "number").filter((p) => Number.isFinite(p.x) && Number.isFinite(p.y)).map((p) => ({ x: p.x, y: p.y }));
          return raw2.slice().sort((a, b) => a.x - b.x);
        }
        const ys = series.values ?? [];
        const raw = ys.map((y2, i) => ({ x: i, y: y2 })).filter((p) => typeof p.y === "number").filter((p) => Number.isFinite(p.x) && Number.isFinite(p.y)).map((p) => ({ x: p.x, y: p.y }));
        return raw;
      })();
      const computed = trendlines.map((t) => computeTrendlinePaths({
        type: t.type ?? "linear",
        points,
        polynomialOrder: t.polynomialOrder,
        movingAveragePeriod: t.movingAveragePeriod,
        forecastForward: t.forecastForward,
        forecastBackward: t.forecastBackward,
        intercept: t.intercept,
        displayEquation: t.displayEquation,
        displayRSquared: t.displayRSquared
      }));
      if (computed.some((v) => v !== null)) {
        bySeriesIndex.set(seriesIndex, computed);
      }
    }
    return { bySeriesIndex };
  }
  get view3d() {
    return this.#view3d;
  }
  set view3d(value) {
    this.#view3d = value;
  }
  toProto() {
    const categories = [...this.#categories];
    const series = this.#series.toProto();
    const style = this.#style.toProto();
    const legend = this.#legend.toProto();
    const dataLabels = this.#dataLabels.toProto();
    const titleTextStyle = this.#titleTextStyle.toProto();
    const xAxis = this.#xAxis.toProto();
    const yAxis = this.#yAxis.toProto();
    const chartFill = this.#chartFill?.toProto();
    const chartSpaceFill = this.#chartSpaceFill?.toProto();
    const plotAreaFill = this.#plotAreaFill?.toProto();
    const chartLine = this.#chartLine.toProto();
    const chartSpaceLine = this.#chartSpaceLine.toProto();
    const plotAreaLine = this.#plotAreaLine.toProto();
    const barOptions = this.#barOptions.toProto();
    const lineOptions = this.#lineOptions.toProto();
    const areaOptions = this.#areaOptions.toProto();
    const scatterOptions = this.#scatterOptions.toProto();
    const pieOptions = this.#pieOptions.toProto();
    const boxWhiskerOptions = this.#boxWhiskerOptions.toProto();
    const doughnutOptions = this.#doughnutOptions.toProto();
    const funnelOptions = this.#funnelOptions.toProto();
    const treemapOptions = this.#treemapOptions.toProto();
    const mapOptions = this.#mapOptions.toProto();
    const view3d = this.#view3d.toProto();
    const type = this.#type ? CHART_TYPE_TO_PROTO[this.#type] : undefined;
    if (type === undefined) {
      return;
    }
    const chart = {
      id: this.#id,
      title: this.#title ?? "",
      categories,
      series,
      type,
      barDirection: this.barOptions.direction ? BAR_DIRECTION_TO_PROTO[this.barOptions.direction] : 0 /* BAR_DIRECTION_UNSPECIFIED */,
      styleIndex: this.#styleIndex ?? 0,
      hasLegend: this.#hasLegend ?? false,
      pivotFormats: [],
      bbox: undefined,
      xAxis,
      yAxis,
      legend
    };
    if (this.#titlePlacement) {
      chart.titlePlacement = this.#titlePlacement;
    }
    const dataTable = this.#dataTable.toProto();
    if (dataTable) {
      chart.dataTable = dataTable;
    }
    if (dataLabels) {
      chart.dataLabels = dataLabels;
    }
    if (titleTextStyle && this.#title) {
      chart.titleTextStyle = titleTextStyle;
    }
    if (chartFill) {
      chart.chartFill = chartFill;
    }
    if (chartLine) {
      chart.chartLine = chartLine;
    }
    if (chartSpaceFill) {
      chart.chartSpaceFill = chartSpaceFill;
    }
    if (chartSpaceLine) {
      chart.chartSpaceLine = chartSpaceLine;
    }
    chart.roundedCorners = this.#roundedCorners ?? false;
    if (plotAreaFill) {
      chart.plotAreaFill = plotAreaFill;
    }
    if (plotAreaLine) {
      chart.plotAreaLine = plotAreaLine;
    }
    if (mapOptions) {
      chart.mapOptions = mapOptions;
    }
    if (style) {
      chart.style = style;
    }
    if (this.#displayBlanksAs !== undefined) {
      chart.displayBlanksAs = mapDisplayBlanksAs(this.#displayBlanksAs);
    }
    if (this.#showDlblsOverMax) {
      chart.showDlblsOverMax = true;
    }
    if (view3d) {
      chart.view3d = view3d;
    }
    if (barOptions) {
      chart.barOptions = barOptions;
    }
    if (lineOptions) {
      chart.lineOptions = lineOptions;
    }
    if (areaOptions) {
      chart.areaOptions = areaOptions;
    }
    if (pieOptions) {
      chart.pieOptions = pieOptions;
    }
    if (boxWhiskerOptions) {
      chart.boxWhiskerOptions = boxWhiskerOptions;
    }
    if (doughnutOptions) {
      chart.doughnutOptions = doughnutOptions;
    }
    if (funnelOptions) {
      chart.funnelOptions = funnelOptions;
    }
    if (scatterOptions) {
      chart.scatterOptions = scatterOptions;
    }
    if (treemapOptions) {
      chart.treemapOptions = treemapOptions;
    }
    if (this.#histogramOptions) {
      chart.histogramOptions = { ...this.#histogramOptions };
    }
    return chart;
  }
}

// node_modules/@oai/granola/dist/models/presentation/chart-collection.js
var CHART_TYPES_WITHOUT_AXES = new Set([
  "pie",
  "pie3D",
  "doughnut",
  "treemap",
  "sunburst",
  "map",
  "funnel",
  "ofPie"
]);
var DEFAULT_UNSTYLED_CHART_AXIS_LINE_COLOR = "#D4D4D4";
var DEFAULT_UNSTYLED_CHART_TEXT_COLOR = "#666666";

class ChartCollection {
  #items;
  #byId;
  constructor(_context, proto) {
    this.#items = (proto ?? []).map((chart) => new Chart2(chart ?? {}));
    this.#byId = new Map(this.#items.map((chart) => [chart.id, chart]));
  }
  get items() {
    return [...this.#items];
  }
  getById(id) {
    if (!id) {
      return;
    }
    return this.#byId.get(id);
  }
  add(type) {
    const chart = new Chart2({ type: CHART_TYPE_TO_PROTO[type] });
    chart.hasLegend = true;
    chart.legend.position = "bottom";
    if (!CHART_TYPES_WITHOUT_AXES.has(type)) {
      chart.xAxis.line.width = 1;
      chart.xAxis.line.style = "solid";
      chart.xAxis.line.fill = DEFAULT_UNSTYLED_CHART_AXIS_LINE_COLOR;
      chart.xAxis.textStyle.fill = DEFAULT_UNSTYLED_CHART_TEXT_COLOR;
      chart.yAxis.line.width = 1;
      chart.yAxis.line.style = "solid";
      chart.yAxis.line.fill = DEFAULT_UNSTYLED_CHART_AXIS_LINE_COLOR;
      chart.yAxis.textStyle.fill = DEFAULT_UNSTYLED_CHART_TEXT_COLOR;
      chart.yAxis.deleted = true;
    }
    if (type === "scatter" && chart.scatterOptions.style === undefined) {
      chart.scatterOptions.style = "marker";
    }
    this.#items.push(chart);
    this.#byId.set(chart.id, chart);
    return chart;
  }
  attach(chart) {
    const existing = this.#byId.get(chart.id);
    if (existing) {
      return existing;
    }
    this.#items.push(chart);
    this.#byId.set(chart.id, chart);
    return chart;
  }
  replace(proto) {
    this.#items = (proto ?? []).map((chart) => new Chart2(chart ?? {}));
    this.#byId = new Map(this.#items.map((chart) => [chart.id, chart]));
  }
  toProto() {
    return this.#items.map((chart) => chart.toProto()).filter((chart) => Boolean(chart));
  }
}

// node_modules/@oai/granola/dist/models/presentation/image.js
var SVG_CONTENT_TYPE = "image/svg+xml";
var UNSUPPORTED_CONTENT_TYPES = new Set([
  "image/emf",
  "image/x-emf",
  "application/emf",
  "application/x-emf",
  "image/wmf",
  "image/x-wmf",
  "application/wmf",
  "application/x-wmf"
]);
var cloneBytes = (view) => {
  if (view.buffer instanceof ArrayBuffer) {
    return view;
  }
  const copy2 = new Uint8Array(view.byteLength);
  copy2.set(view);
  return copy2;
};
var addSvgIntrinsicSize2 = (text, width, height) => {
  if (/\bwidth\s*=|\bheight\s*=/.test(text)) {
    return new Blob([text], { type: SVG_CONTENT_TYPE });
  }
  const patched = text.replace(/<svg\b([^>]*)>/, `<svg$1 width="${width}" height="${height}">`);
  return new Blob([patched], { type: SVG_CONTENT_TYPE });
};
var devicePixelRatio = () => {
  if (typeof window === "undefined") {
    return 1;
  }
  return window.devicePixelRatio || 1;
};
var normalizeDimension = (value) => {
  const rounded = Math.round(value ?? 1);
  return rounded > 0 ? rounded : 1;
};
var getDomImageConstructor2 = () => {
  const globalImage = globalThis.Image;
  if (globalImage) {
    return globalImage;
  }
  return typeof window !== "undefined" ? window.Image : undefined;
};
var createBitmapFromDomImage2 = async (blob, options) => {
  const DomImage = getDomImageConstructor2();
  if (!DomImage || typeof URL === "undefined" || typeof URL.createObjectURL !== "function") {
    return;
  }
  const url = URL.createObjectURL(blob);
  try {
    const img = new DomImage;
    if (typeof img.decode === "function") {
      img.src = url;
      await img.decode();
    } else {
      const loaded = new Promise((resolve2, reject) => {
        img.onload = () => resolve2();
        img.onerror = () => reject(new Error("Failed to decode SVG image payload."));
      });
      img.src = url;
      await loaded;
    }
    return await createImageBitmap(img, options);
  } finally {
    if (typeof URL.revokeObjectURL === "function") {
      URL.revokeObjectURL(url);
    }
  }
};
var createBitmapFromSvgBlob2 = async (blob, options) => {
  try {
    const domBitmap = await createBitmapFromDomImage2(blob, options);
    if (domBitmap) {
      return domBitmap;
    }
  } catch {}
  return createImageBitmap(blob, options);
};
var isUnsupportedContentType = (type) => {
  if (!type) {
    return false;
  }
  return UNSUPPORTED_CONTENT_TYPES.has(type.toLowerCase());
};
var createBitmapFromSource = async (source, width, height) => {
  const contentType = source.contentType || "";
  if (isUnsupportedContentType(contentType)) {
    console.warn(`Unsupported image: ${contentType}`);
    return;
  }
  if (source.contentType === SVG_CONTENT_TYPE) {
    const normalizedWidth = normalizeDimension(width);
    const normalizedHeight = normalizeDimension(height);
    const dpr = devicePixelRatio();
    const decoder = new TextDecoder;
    const svgText = decoder.decode(source.data);
    const sizedBlob = addSvgIntrinsicSize2(svgText, normalizedWidth, normalizedHeight);
    try {
      return await createBitmapFromSvgBlob2(sizedBlob, {
        resizeWidth: Math.max(1, Math.round(normalizedWidth * dpr)),
        resizeHeight: Math.max(1, Math.round(normalizedHeight * dpr))
      });
    } catch (error) {
      console.warn(`Unsupported SVG payload (${source.data?.byteLength ?? 0} bytes)`, error);
      return;
    }
  }
  const blob = new Blob([cloneBytes(source.data)], {
    type: contentType || "application/octet-stream"
  });
  try {
    return await createImageBitmap(blob);
  } catch (error) {
    console.warn(`Unsupported image payload: ${contentType || "unknown mime"} (${source.data?.byteLength ?? 0} bytes)`, error);
    return;
  }
};
var decodeBase64 = (value) => {
  const globalBuffer = globalThis["Buffer"];
  if (globalBuffer && typeof globalBuffer.from === "function") {
    return cloneBytes(globalBuffer.from(value, "base64"));
  }
  if (typeof atob === "function") {
    const binary = atob(value);
    const bytes = new Uint8Array(binary.length);
    for (let index = 0;index < binary.length; index += 1) {
      bytes[index] = binary.charCodeAt(index);
    }
    return bytes;
  }
  return new Uint8Array;
};
var decodeDataUrl = (value) => {
  const match = /^data:([^;,]+);base64,(.+)$/i.exec(value);
  if (!match) {
    return;
  }
  const contentType = match[1]?.trim().toLowerCase();
  const base64 = match[2];
  if (!contentType || !base64) {
    return;
  }
  return {
    contentType,
    data: decodeBase64(base64)
  };
};
var createBitmapFromUri = async (source, width, height) => {
  if (!source.uri) {
    return;
  }
  const dataUrlSource = source.uri.startsWith("data:") ? decodeDataUrl(source.uri) : undefined;
  if (dataUrlSource) {
    return createBitmapFromSource(dataUrlSource, width, height);
  }
  return;
};

class Image2 {
  #data;
  #bitmapCache;
  constructor(_context, proto) {
    const id = proto?.id && proto.id.length > 0 ? proto.id : generateUuid();
    this.#data = {
      id,
      contentType: proto?.contentType ?? "",
      data: proto?.data ? new Uint8Array(proto.data) : new Uint8Array,
      prompt: proto?.prompt ?? undefined,
      uri: proto?.uri ?? undefined
    };
    this.#bitmapCache = new Map;
  }
  get id() {
    return this.#data.id;
  }
  get contentType() {
    return this.#data.contentType;
  }
  set contentType(value) {
    this.#data.contentType = value;
    this.#invalidateBitmapCache();
  }
  get data() {
    return new Uint8Array(this.#data.data);
  }
  set data(value) {
    this.#data.data = new Uint8Array(value);
    this.#invalidateBitmapCache();
  }
  get prompt() {
    return this.#data.prompt;
  }
  set prompt(value) {
    this.#data.prompt = value ?? undefined;
  }
  get uri() {
    return this.#data.uri;
  }
  set uri(value) {
    this.#data.uri = value ?? undefined;
    this.#invalidateBitmapCache();
  }
  toProto() {
    return {
      id: this.#data.id,
      contentType: this.#data.contentType,
      data: new Uint8Array(this.#data.data),
      prompt: this.#data.prompt,
      uri: this.#data.uri
    };
  }
  async getBitmap(width, height) {
    const cacheKey = this.#bitmapCacheKey(width, height);
    const cached = this.#bitmapCache.get(cacheKey);
    if (cached) {
      return cached;
    }
    const bitmapPromise = this.#createBitmap(width, height).catch(async () => {
      console.warn(`Failed to create bitmap for image`);
      return;
    });
    this.#bitmapCache.set(cacheKey, bitmapPromise);
    return bitmapPromise;
  }
  #bitmapCacheKey(width, height) {
    const base = `${this.#data.id}:${this.#data.data.byteLength}:${this.#data.contentType}:${this.#data.uri ?? ""}`;
    if (this.#isSvg()) {
      const normalizedWidth = normalizeDimension(width);
      const normalizedHeight = normalizeDimension(height);
      const dpr = devicePixelRatio();
      return `${base}:${normalizedWidth}x${normalizedHeight}@${Math.round(dpr * 100) / 100}`;
    }
    return base;
  }
  #invalidateBitmapCache() {
    this.#bitmapCache.clear();
  }
  async#createBitmap(width, height) {
    if (this.#data.data.byteLength === 0 && this.#data.uri) {
      return createBitmapFromUri({
        contentType: this.#data.contentType,
        uri: this.#data.uri
      }, width, height);
    }
    const source = {
      contentType: this.#data.contentType,
      data: this.#data.data
    };
    return createBitmapFromSource(source, width, height);
  }
  #isSvg() {
    return this.#data.contentType === SVG_CONTENT_TYPE;
  }
}

// node_modules/@oai/granola/dist/models/presentation/image-collection.js
class ImageCollection {
  #context;
  #items;
  #byId;
  constructor(context, proto) {
    this.#context = context;
    this.#items = (proto ?? []).map((image) => {
      const instance = new Image2(this.#imageContext(), image ?? {});
      return instance;
    });
    this.#byId = new Map(this.#items.map((image) => [image.id, image]));
  }
  get items() {
    return [...this.#items];
  }
  getById(id) {
    if (!id) {
      return;
    }
    return this.#byId.get(id);
  }
  add(init = {}) {
    const pbImage = {
      id: init.id ?? "",
      contentType: init.contentType ?? "",
      data: init.data ? new Uint8Array(init.data) : new Uint8Array,
      prompt: init.prompt,
      uri: init.uri
    };
    const image = new Image2(this.#imageContext(), pbImage);
    this.#items.push(image);
    this.#byId.set(image.id, image);
    return image;
  }
  replace(proto) {
    this.#items = (proto ?? []).map((image) => new Image2(this.#imageContext(), image ?? {}));
    this.#byId = new Map(this.#items.map((image) => [image.id, image]));
  }
  toProto() {
    return this.#items.map((image) => image.toProto());
  }
  #imageContext() {
    return this.#context;
  }
}

// node_modules/@oai/granola/dist/models/presentation/background.js
class SlideBackground {
  #context;
  #data;
  #fill;
  constructor(context, proto) {
    this.#context = context;
    this.#fill = new Fill2({ type: "proto", proto: proto?.fill });
    this.#data = {
      ref: proto?.ref
    };
  }
  get isSet() {
    return this.#fill.isSet || this.#data.ref !== undefined;
  }
  get fill() {
    return this.#fill;
  }
  get ref() {
    return this.#data.ref;
  }
  set ref(value) {
    this.#data.ref = value;
    this.#recordBackgroundSet({ ref: value });
  }
  set fill(fill) {
    this.#fill = new Fill2(fill);
    this.#recordBackgroundSet({ fill });
  }
  toProto() {
    if (!this.isSet) {
      return;
    }
    return {
      fill: this.#fill.toProto(),
      ref: this.#data.ref
    };
  }
  #recordBackgroundSet(values) {
    const recordOp = this.#context.recordOp;
    const target = this.#context.getTargetRef?.();
    if (!recordOp || !target) {
      return;
    }
    const patch = {};
    if (values.fill !== undefined) {
      const fill = this.#fill.toConfig();
      if (fill && isPatchFillConfig(fill)) {
        patch.fill = fill;
      }
    }
    if (values.ref !== undefined) {
      const ref = formatBackgroundRef(values.ref);
      if (ref !== undefined) {
        patch.ref = ref;
      }
    }
    if (patch.fill === undefined && patch.ref === undefined) {
      return;
    }
    recordOp({
      op: "slide.background.set",
      target,
      ...patch
    });
  }
}
var BACKGROUND_REF_SEPARATOR = ":";
function formatBackgroundRef(ref) {
  const index = Number(ref.index);
  const schemeColor = ref.schemeColor?.trim();
  if (Number.isFinite(index) && schemeColor) {
    return `${index}${BACKGROUND_REF_SEPARATOR}${schemeColor}`;
  }
  if (schemeColor) {
    return schemeColor;
  }
  if (Number.isFinite(index)) {
    return String(index);
  }
  return;
}
function isPatchFillConfig(value) {
  if (!value || typeof value !== "object") {
    return true;
  }
  if ("type" in value && value.type === "proto") {
    return false;
  }
  return true;
}

// node_modules/@oai/granola/dist/models/presentation/text-run.js
var DEFAULT_HYPERLINK_ACTION = "";

class TextRun2 {
  #context;
  #data;
  #textStyle;
  constructor(context, proto) {
    this.#context = context;
    this.#data = {
      id: proto.id ?? "",
      text: proto.text ?? "",
      hyperlink: proto.hyperlink ? { ...proto.hyperlink } : undefined,
      citations: [...proto.citations ?? []],
      reviewMarkIds: [...proto.reviewMarkIds ?? []]
    };
    this.#textStyle = proto.textStyle ? new TextStyle2(proto.textStyle) : undefined;
  }
  get id() {
    return this.#data.id;
  }
  set id(value) {
    this.#data.id = value;
  }
  get text() {
    return this.#data.text;
  }
  set text(value) {
    this.#data.text = value;
  }
  get textStyle() {
    return this.#textStyle;
  }
  set textStyle(value) {
    this.#textStyle = value;
  }
  get resolvedTextStyle() {
    const paragraph = this.#context.getParagraph?.();
    if (!paragraph) {
      return;
    }
    return this.#context.getResolvedRunTextStyle?.(paragraph, this);
  }
  get citations() {
    return [...this.#data.citations];
  }
  set citations(values) {
    this.#data.citations = [...values];
  }
  addCitation(id) {
    this.#data.citations.push(id);
  }
  clearCitations() {
    this.#data.citations = [];
  }
  get reviewMarkIds() {
    return [...this.#data.reviewMarkIds];
  }
  set reviewMarkIds(values) {
    this.#data.reviewMarkIds = [...values];
  }
  get hyperlink() {
    return this.#data.hyperlink ? { ...this.#data.hyperlink } : undefined;
  }
  set hyperlink(value) {
    if (!value) {
      this.#data.hyperlink = undefined;
      return;
    }
    const normalized = this.#normalizeHyperlink(value);
    this.#data.hyperlink = { ...normalized };
  }
  toProto() {
    return {
      id: this.#data.id,
      text: this.#data.text,
      textStyle: this.#textStyle?.toProto(),
      hyperlink: this.#data.hyperlink ? { ...this.#data.hyperlink } : undefined,
      citations: [...this.#data.citations],
      reviewMarkIds: [...this.#data.reviewMarkIds]
    };
  }
  #normalizeHyperlink(value) {
    const current = this.#data.hyperlink;
    const uri = value?.uri ?? current?.uri ?? "";
    const isExternal = value?.isExternal ?? value?.isExternal ?? current?.isExternal ?? false;
    const action = value?.action ?? value?.action ?? current?.action ?? DEFAULT_HYPERLINK_ACTION;
    return {
      ...current ?? {},
      ...value,
      uri,
      isExternal,
      action
    };
  }
}

// node_modules/@oai/granola/dist/models/presentation/text-run-collection.js
class TextRunCollection {
  #context;
  #items;
  constructor(context, proto = []) {
    this.#context = context;
    this.#items = (proto ?? []).map((run) => new TextRun2(this.#textRunContext(), run));
  }
  get items() {
    return [...this.#items];
  }
  get length() {
    return this.#items.length;
  }
  getItem(index) {
    if (index < 0 || index >= this.#items.length) {
      return;
    }
    return this.#items[index];
  }
  add(text = "") {
    const run = new TextRun2(this.#textRunContext(), { id: "", text });
    this.#items.push(run);
    return run;
  }
  replace(runs) {
    this.#items = [...runs];
  }
  cloneWithText(source, text) {
    const proto = source.toProto();
    proto.id = "";
    proto.text = text;
    return new TextRun2(this.#textRunContext(), proto);
  }
  clear() {
    this.#items = [];
  }
  toProto() {
    return this.#items.map((run) => run.toProto());
  }
  #textRunContext() {
    return this.#context;
  }
}

// node_modules/@oai/granola/dist/models/presentation/paragraph.js
class Paragraph2 {
  #context;
  #data;
  #runs;
  #textStyle;
  constructor(context, proto) {
    this.#context = context;
    this.#data = {
      id: proto.id ?? "",
      bulletCharacter: proto.bulletCharacter,
      marginLeft: proto.marginLeft,
      indent: proto.indent,
      spaceAfter: proto.spaceAfter,
      spaceBefore: proto.spaceBefore,
      styleId: proto.styleId,
      docxSectionBreakCarrier: proto.docxSectionBreakCarrier,
      paragraphStyle: proto.paragraphStyle ? { ...proto.paragraphStyle } : undefined
    };
    this.#runs = new TextRunCollection(this.#textRunCollectionContext(), proto.runs ?? []);
    this.#textStyle = proto.textStyle ? new TextStyle2(proto.textStyle) : undefined;
  }
  get id() {
    return this.#data.id;
  }
  set id(value) {
    this.#data.id = value;
  }
  get bulletCharacter() {
    return this.#data.bulletCharacter;
  }
  set bulletCharacter(value) {
    this.#data.bulletCharacter = value;
    this.#mergeParagraphStyle({ bulletCharacter: value });
  }
  get marginLeft() {
    return this.#data.marginLeft;
  }
  set marginLeft(value) {
    this.#data.marginLeft = value;
    this.#mergeParagraphStyle({ marginLeft: value });
  }
  get indent() {
    return this.#data.indent;
  }
  set indent(value) {
    this.#data.indent = value;
    this.#mergeParagraphStyle({ indent: value });
  }
  get lineSpacingPercent() {
    return this.#data.paragraphStyle?.lineSpacingPercent;
  }
  set lineSpacingPercent(value) {
    this.#mergeParagraphStyle({ lineSpacingPercent: value });
  }
  get spaceAfter() {
    return this.#data.spaceAfter;
  }
  set spaceAfter(value) {
    this.#data.spaceAfter = value;
  }
  get spaceBefore() {
    return this.#data.spaceBefore;
  }
  set spaceBefore(value) {
    this.#data.spaceBefore = value;
  }
  get style() {
    return {
      bulletCharacter: this.#data.bulletCharacter,
      marginLeft: this.#data.marginLeft,
      indent: this.#data.indent,
      spaceBefore: this.#data.spaceBefore,
      spaceAfter: this.#data.spaceAfter
    };
  }
  set style(value) {
    if (value.bulletCharacter !== undefined) {
      this.bulletCharacter = value.bulletCharacter;
    }
    if (value.marginLeft !== undefined) {
      this.marginLeft = value.marginLeft;
    }
    if (value.indent !== undefined) {
      this.indent = value.indent;
    }
    if (value.spaceBefore !== undefined) {
      this.spaceBefore = value.spaceBefore;
    }
    if (value.spaceAfter !== undefined) {
      this.spaceAfter = value.spaceAfter;
    }
  }
  get styleId() {
    return this.#data.styleId;
  }
  set styleId(value) {
    this.#data.styleId = value;
  }
  get docxSectionBreakCarrier() {
    return this.#data.docxSectionBreakCarrier === true;
  }
  get paragraphStyle() {
    return this.#data.paragraphStyle ? { ...this.#data.paragraphStyle } : undefined;
  }
  set paragraphStyle(value) {
    this.#data.paragraphStyle = value ? { ...value } : undefined;
  }
  get resolvedTextStyle() {
    return this.#context.getResolvedParagraphTextStyle?.(this);
  }
  get resolvedParagraphStyle() {
    const resolved = this.#context.getResolvedParagraphStyle?.(this);
    return resolved ? { ...resolved } : undefined;
  }
  get runs() {
    return this.#runs;
  }
  addRun(text = "") {
    return this.#runs.add(text);
  }
  get textStyle() {
    return this.#textStyle;
  }
  set textStyle(value) {
    this.#textStyle = value;
  }
  toPlainText() {
    return this.#runs.items.map((run) => run.text).join("");
  }
  setPlainText(value) {
    const run = new TextRun2(this.#textRunCollectionContext(), {
      id: "",
      text: value
    });
    this.#runs.replace([run]);
  }
  toProto() {
    return {
      id: this.#data.id,
      runs: this.#runs.toProto(),
      textStyle: this.#textStyle?.toProto(),
      bulletCharacter: this.#data.bulletCharacter,
      marginLeft: this.#data.marginLeft,
      indent: this.#data.indent,
      spaceAfter: this.#data.spaceAfter,
      spaceBefore: this.#data.spaceBefore,
      styleId: this.#data.styleId,
      docxSectionBreakCarrier: this.#data.docxSectionBreakCarrier,
      paragraphStyle: this.#data.paragraphStyle ? { ...this.#data.paragraphStyle } : undefined
    };
  }
  #textRunCollectionContext() {
    return {
      ...this.#context,
      getParagraph: () => this
    };
  }
  #mergeParagraphStyle(patch) {
    const current = this.#data.paragraphStyle ? { ...this.#data.paragraphStyle } : {};
    for (const [key, value] of Object.entries(patch)) {
      if (value === undefined) {
        delete current[key];
      } else {
        current[key] = value;
      }
    }
    this.#data.paragraphStyle = Object.keys(current).length > 0 ? current : undefined;
  }
}

// node_modules/@oai/granola/dist/models/presentation/paragraph-collection.js
class ParagraphCollection {
  #context;
  #items;
  constructor(context, proto = []) {
    this.#context = context;
    this.#items = (proto ?? []).map((paragraph) => new Paragraph2(this.#paragraphContext(), paragraph));
  }
  get items() {
    return [...this.#items];
  }
  get length() {
    return this.#items.length;
  }
  getItem(index) {
    if (index < 0 || index >= this.#items.length) {
      return;
    }
    return this.#items[index];
  }
  add() {
    const paragraph = new Paragraph2(this.#paragraphContext(), {
      id: "",
      runs: []
    });
    this.#items.push(paragraph);
    return paragraph;
  }
  append(proto) {
    const paragraph = new Paragraph2(this.#paragraphContext(), proto);
    this.#items.push(paragraph);
    return paragraph;
  }
  insertAt(index, proto) {
    const paragraph = new Paragraph2(this.#paragraphContext(), proto);
    if (index < 0 || index >= this.#items.length) {
      this.#items.push(paragraph);
    } else {
      this.#items.splice(index, 0, paragraph);
    }
    return paragraph;
  }
  removeAt(index) {
    if (index < 0 || index >= this.#items.length) {
      return;
    }
    const [removed] = this.#items.splice(index, 1);
    return removed;
  }
  clear() {
    this.#items = [];
  }
  setFromLines(lines) {
    const normalized = lines ?? [];
    if (normalized.length === 0) {
      const paragraph = new Paragraph2(this.#paragraphContext(), {
        id: "",
        runs: []
      });
      paragraph.setPlainText("");
      this.#items = [paragraph];
      return;
    }
    this.#items = normalized.map((line) => {
      const paragraph = new Paragraph2(this.#paragraphContext(), {
        id: "",
        runs: []
      });
      paragraph.setPlainText(line ?? "");
      return paragraph;
    });
  }
  toPlainText() {
    return this.#items.map((paragraph) => paragraph.toPlainText()).join(`
`);
  }
  setFromPlainText(value) {
    const lines = value.length === 0 ? [] : value.split(/\r?\n/).map((line) => line.replace(/\r$/, ""));
    if (lines.length === 0) {
      const paragraph = new Paragraph2(this.#paragraphContext(), {
        id: "",
        runs: []
      });
      paragraph.setPlainText("");
      this.#items = [paragraph];
      return;
    }
    this.#items = lines.map((line) => {
      const paragraph = new Paragraph2(this.#paragraphContext(), {
        id: "",
        runs: []
      });
      paragraph.setPlainText(line);
      return paragraph;
    });
  }
  toProto() {
    return this.#items.map((paragraph) => paragraph.toProto());
  }
  #paragraphContext() {
    return this.#context;
  }
}

// node_modules/@oai/granola/dist/models/presentation/list-presets.js
var BULLET_CHARACTER = "•";
var BULLET_MARGIN_LEFT = 285750;
var BULLET_INDENT = -285750;
var NUMBERED_MARGIN_LEFT = 342900;
var NUMBERED_INDENT = -342900;
var NUMBERED_AUTO_TYPE = "arabicPeriod";
function applyListPreset(paragraph, preset) {
  if (preset === "list") {
    paragraph.bulletCharacter = BULLET_CHARACTER;
    paragraph.marginLeft = BULLET_MARGIN_LEFT;
    paragraph.indent = BULLET_INDENT;
    const current = paragraph.paragraphStyle ?? {};
    paragraph.paragraphStyle = {
      ...current,
      autoNumberType: undefined
    };
    return;
  }
  if (preset === "numberedList") {
    paragraph.bulletCharacter = undefined;
    paragraph.marginLeft = NUMBERED_MARGIN_LEFT;
    paragraph.indent = NUMBERED_INDENT;
    const current = paragraph.paragraphStyle ?? {};
    paragraph.paragraphStyle = {
      ...current,
      autoNumberType: NUMBERED_AUTO_TYPE
    };
  }
}

// node_modules/@oai/granola/dist/models/presentation/utils/tailwind/parse-tailwind-font-weight-token.js
var TAILWIND_BOLD_TOKENS = new Set(["font-bold", "font-semibold", "font-black"]);
var TAILWIND_NORMAL_TOKENS = new Set([
  "font-normal",
  "font-light",
  "font-medium",
  "font-thin",
  "font-extralight",
  "font-extrabold"
]);
function parseTailwindFontWeightToken(input) {
  const trimmed = input.trim();
  if (!trimmed)
    return null;
  const normalized = trimmed.toLowerCase();
  if (TAILWIND_BOLD_TOKENS.has(normalized)) {
    return true;
  }
  if (TAILWIND_NORMAL_TOKENS.has(normalized)) {
    return false;
  }
  return null;
}

// node_modules/@oai/granola/dist/models/presentation/utils/tailwind/parse-tailwind-leading-token.js
var TAILWIND_LEADING_RATIO_BY_TOKEN = {
  "leading-none": 1,
  "leading-tight": 1.25,
  "leading-snug": 1.375,
  "leading-normal": 1.5,
  "leading-relaxed": 1.625,
  "leading-loose": 2
};
var TAILWIND_LEADING_PX_BY_SCALE = {
  "leading-3": 12,
  "leading-4": 16,
  "leading-5": 20,
  "leading-6": 24,
  "leading-7": 28,
  "leading-8": 32,
  "leading-9": 36,
  "leading-10": 40
};
var parseArbitraryLeading = (token) => {
  const unitlessMatch = /^leading-\[([0-9]+(?:\.[0-9]+)?)\]$/.exec(token);
  if (unitlessMatch) {
    const numeric = Number(unitlessMatch[1]);
    return Number.isFinite(numeric) && numeric > 0 ? numeric : null;
  }
  const percentMatch = /^leading-\[([0-9]+(?:\.[0-9]+)?)%\]$/.exec(token);
  if (percentMatch) {
    const numeric = Number(percentMatch[1]);
    if (!Number.isFinite(numeric) || numeric <= 0) {
      return null;
    }
    return numeric / 100;
  }
  return null;
};
var parseAbsolutePxLeading = (token, fontSizePx) => {
  const pxMatch = /^leading-\[([0-9]+(?:\.[0-9]+)?)px\]$/.exec(token);
  if (!pxMatch) {
    return null;
  }
  const lineHeightPx = Number(pxMatch[1]);
  if (!Number.isFinite(lineHeightPx) || lineHeightPx <= 0) {
    return null;
  }
  const baseFontPx = fontSizePx !== undefined && Number.isFinite(fontSizePx) && fontSizePx > 0 ? fontSizePx : 16;
  return lineHeightPx / baseFontPx;
};
function parseTailwindLeadingToken(input, options = {}) {
  const token = input.trim().toLowerCase();
  if (!token) {
    return null;
  }
  const named2 = TAILWIND_LEADING_RATIO_BY_TOKEN[token];
  if (typeof named2 === "number") {
    return named2;
  }
  const arbitrary = parseArbitraryLeading(token);
  if (arbitrary !== null) {
    return arbitrary;
  }
  const absolutePx = parseAbsolutePxLeading(token, options.fontSizePx);
  if (absolutePx !== null) {
    return absolutePx;
  }
  const scaledPx = TAILWIND_LEADING_PX_BY_SCALE[token];
  if (typeof scaledPx === "number") {
    const baseFontPx = options.fontSizePx !== undefined && Number.isFinite(options.fontSizePx) && options.fontSizePx > 0 ? options.fontSizePx : 16;
    return scaledPx / baseFontPx;
  }
  return null;
}

// node_modules/@oai/granola/dist/models/presentation/utils/tailwind/parse-tailwind-text-size-token.js
var TAILWIND_TEXT_SIZE_PX_BY_TOKEN = {
  "text-xs": 12,
  "text-sm": 14,
  "text-base": 16,
  "text-lg": 18,
  "text-xl": 20,
  "text-2xl": 24,
  "text-3xl": 30,
  "text-4xl": 36,
  "text-5xl": 48,
  "text-6xl": 60
};
function parseTailwindTextSizeToken(input) {
  const trimmed = input.trim();
  if (!trimmed)
    return null;
  const normalized = trimmed.toLowerCase();
  const tokenSize = TAILWIND_TEXT_SIZE_PX_BY_TOKEN[normalized];
  if (typeof tokenSize === "number") {
    return tokenSize;
  }
  const arbitraryMatch = /^text-\[([0-9]+(?:\.[0-9]+)?)px\]$/.exec(normalized);
  if (!arbitraryMatch) {
    return null;
  }
  const numeric = Number(arbitraryMatch[1]);
  if (!Number.isFinite(numeric) || numeric <= 0) {
    return null;
  }
  return numeric;
}

// node_modules/@oai/granola/dist/models/presentation/utils/tailwind/parse-tailwind-text-classname.js
function parseTailwindTextClassName(className) {
  const tokens = className.split(/\s+/).map((token) => token.trim()).filter((token) => token.length > 0);
  if (tokens.length === 0) {
    return null;
  }
  const parsed = {};
  let changed = false;
  for (const token of tokens) {
    const fontWeight = parseTailwindFontWeightToken(token);
    if (fontWeight !== null) {
      parsed.bold = fontWeight;
      changed = true;
      continue;
    }
    if (token === "italic") {
      parsed.italic = true;
      changed = true;
      continue;
    }
    const textSize = parseTailwindTextSizeToken(token);
    if (textSize !== null) {
      parsed.fontSize = textSize;
      changed = true;
      continue;
    }
    const leading = parseTailwindLeadingToken(token, {
      fontSizePx: parsed.fontSize
    });
    if (leading !== null) {
      parsed.lineSpacing = leading;
      changed = true;
      continue;
    }
    if (token.startsWith("text-")) {
      const colorToken = token.slice("text-".length);
      const color2 = parseTailwindColorToken(colorToken);
      if (color2) {
        parsed.color = {
          type: "rgb",
          value: color2.hex,
          transform: color2.alpha === undefined ? undefined : { opacity: color2.alpha }
        };
        changed = true;
      }
    }
  }
  return changed ? parsed : null;
}

// node_modules/@oai/granola/dist/models/presentation/text-style-config.util.js
function toPatchColorConfig(value) {
  if (value === undefined) {
    return;
  }
  if (typeof value === "string") {
    return value;
  }
  if ("type" in value && value.type !== "proto") {
    return value;
  }
  const normalized = new Color4(value).toConfig();
  if (!normalized) {
    return;
  }
  if (typeof normalized === "object" && "type" in normalized) {
    return normalized.type === "proto" ? undefined : normalized;
  }
  return normalized;
}
function textStylePatchFromConfig(config) {
  const patch = {};
  const className = resolveTextClassName(config);
  if (className !== undefined) {
    patch.className = className;
  }
  if ("bold" in config) {
    patch.bold = config.bold;
  }
  if ("italic" in config) {
    patch.italic = config.italic;
  }
  if ("underline" in config) {
    patch.underline = config.underline;
  }
  if ("fontSize" in config) {
    patch.fontSize = config.fontSize;
  }
  if ("lineSpacing" in config) {
    patch.lineSpacing = config.lineSpacing;
  }
  if ("alignment" in config) {
    patch.alignment = resolvePatchAlignment(config.alignment);
  }
  if ("anchor" in config) {
    patch.verticalAlignment = config.anchor ? TEXT_VERTICAL_ALIGNMENT_FROM_PROTO[config.anchor] : undefined;
  }
  if ("autoFit" in config) {
    patch.autoFit = config.autoFit;
  }
  if ("wrap" in config) {
    patch.wrap = config.wrap;
  }
  if ("insets" in config) {
    patch.insets = config.insets;
  }
  const styleName = resolveTextStyleName(config);
  if (styleName !== undefined) {
    patch.style = styleName;
  }
  const colorConfig = resolveTextStyleConfigColor(config);
  if ("color" in config || "fill" in config || colorConfig !== undefined) {
    patch.color = toPatchColorConfig(colorConfig);
  }
  return patch;
}
function textRangeStylePatchFromConfig(config) {
  const patch = {};
  const className = resolveTextClassName(config);
  if (className !== undefined) {
    patch.className = className;
  }
  if ("bold" in config) {
    patch.bold = config.bold;
  }
  if ("italic" in config) {
    patch.italic = config.italic;
  }
  if ("underline" in config) {
    patch.underline = config.underline;
  }
  if ("fontSize" in config) {
    patch.fontSize = config.fontSize;
  }
  if ("lineSpacing" in config) {
    patch.lineSpacing = config.lineSpacing;
  }
  if ("alignment" in config) {
    patch.alignment = resolvePatchAlignment(config.alignment);
  }
  const styleName = resolveTextStyleName(config);
  if (styleName !== undefined) {
    patch.style = styleName;
  }
  const colorConfig = resolveTextStyleConfigColor(config);
  if ("color" in config || "fill" in config || colorConfig !== undefined) {
    patch.color = toPatchColorConfig(colorConfig);
  }
  return patch;
}
function applyTextStyleConfigToParagraph(paragraph, config) {
  const styleName = resolveTextStyleName(config);
  if (styleName !== undefined) {
    paragraph.styleId = styleName;
    applyListPreset(paragraph, styleName);
    for (const run of paragraph.runs.items) {
      run.textStyle = undefined;
    }
  }
  const style = paragraph.textStyle ? new TextStyle2(paragraph.textStyle.toProto()) : new TextStyle2;
  applyTextStyleConfig(style, config);
  paragraph.textStyle = style;
  if ("lineSpacing" in config) {
    paragraph.lineSpacingPercent = config.lineSpacing === undefined ? undefined : Math.round(config.lineSpacing * 1e5);
  }
}
function resolveTextStyleName(config) {
  const value = config["style"];
  if (typeof value !== "string") {
    return;
  }
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : undefined;
}
function normalizeTextClassName(value) {
  const normalized = value?.trim();
  return normalized && normalized.length > 0 ? normalized : undefined;
}
function resolveTextStyleConfigForApply(config) {
  const className = resolveTextClassName(config);
  const classStyle = className ? parseTailwindTextClassName(className) : null;
  const styleConfig = {};
  if (classStyle) {
    Object.assign(styleConfig, classStyle);
  }
  for (const [key, value] of Object.entries(config)) {
    if (key === "className") {
      continue;
    }
    styleConfig[key] = value;
  }
  return { className, styleConfig };
}
function resolveTextStyleConfigColor(config) {
  if ("color" in config) {
    return config.color;
  }
  if (!("fill" in config)) {
    return;
  }
  const style = new TextStyle2;
  applyTextStyleConfig(style, { fill: config.fill });
  return style.color?.toConfig();
}
function resolveTextClassName(config) {
  const value = config["className"];
  if (typeof value !== "string") {
    return;
  }
  return normalizeTextClassName(value);
}
function resolvePatchAlignment(value) {
  return mapProtoTextHorizontalAlignment(normalizeTextStyleAlignment(value));
}

// node_modules/@oai/granola/dist/models/presentation/text-range.js
class TextRange {
  #paragraphs;
  #segments;
  #options;
  #hasNormalizedRuns = false;
  #className;
  constructor(paragraphs, segments, options = {}) {
    this.#paragraphs = paragraphs;
    this.#segments = segments.map((segment) => ({ ...segment })).filter((segment) => segment.startOffset < segment.endOffset).sort((a, b) => {
      if (a.paragraphIndex !== b.paragraphIndex) {
        return a.paragraphIndex - b.paragraphIndex;
      }
      return a.startOffset - b.startOffset;
    });
    this.#options = { ...options };
  }
  static empty(paragraphs, options = {}) {
    return new TextRange(paragraphs, [], options);
  }
  get isEmpty() {
    return this.#segments.length === 0;
  }
  get bold() {
    return this.#getUniformRunValue((style) => style.bold);
  }
  set bold(value) {
    this.#applyToRuns((run, paragraph) => {
      this.#ensureRunStyle(paragraph, run).bold = value;
    });
    this.#recordStylePatch({ bold: value });
  }
  get italic() {
    return this.#getUniformRunValue((style) => style.italic);
  }
  set italic(value) {
    this.#applyToRuns((run, paragraph) => {
      this.#ensureRunStyle(paragraph, run).italic = value;
    });
    this.#recordStylePatch({ italic: value });
  }
  get fontSize() {
    return this.#getUniformRunValue((style) => style.fontSize);
  }
  set fontSize(value) {
    this.#applyToRuns((run, paragraph) => {
      this.#ensureRunStyle(paragraph, run).fontSize = value;
    });
    this.#recordStylePatch({ fontSize: value });
  }
  get underline() {
    return this.#getUniformRunValue((style) => style.underline);
  }
  set underline(value) {
    this.#applyToRuns((run, paragraph) => {
      this.#ensureRunStyle(paragraph, run).underline = value;
    });
    this.#recordStylePatch({ underline: value });
  }
  get color() {
    return this.#getUniformRunValue((style) => {
      const color2 = style.color;
      return color2?.toProto() ? color2 : undefined;
    }, (left, right) => this.#colorEquals(left, right));
  }
  set color(value) {
    this.#applyToRuns((run, paragraph) => {
      const style = this.#ensureRunStyle(paragraph, run);
      style.fill = { type: "solid", color: value };
    });
    this.#recordStylePatch({ color: toPatchColorConfig(value) });
  }
  get hyperlink() {
    return this.#getUniformRunRawValue((run, _paragraph) => run.hyperlink, (left, right) => this.#areHyperlinksEqual(left, right));
  }
  set hyperlink(value) {
    this.#applyToRuns((run) => {
      run.hyperlink = value ? { ...value } : undefined;
    });
    this.#recordStylePatch({ link: value ? { ...value } : null });
  }
  get link() {
    return this.hyperlink;
  }
  set link(value) {
    this.hyperlink = value;
  }
  get citations() {
    return this.#getUniformRunRawValue((run) => run.citations, (left, right) => this.#arrayEquals(left, right));
  }
  set citations(values) {
    const normalized = values ? [...values] : [];
    this.#applyToRuns((run) => {
      run.citations = normalized;
    });
  }
  set reviewMarks(values) {
    const ids = (values ?? []).map((entry) => typeof entry === "string" ? entry : entry.id).filter((id) => Boolean(id));
    this.#applyToRuns((run) => {
      run.reviewMarkIds = ids;
    });
  }
  get alignment() {
    return this.#getUniformParagraphValue((style) => mapProtoTextHorizontalAlignment(style.alignment));
  }
  set alignment(value) {
    this.#applyToParagraphs((paragraph) => {
      const style = this.#ensureParagraphStyle(paragraph);
      style.alignment = value;
    });
    this.#recordStylePatch({ alignment: value });
  }
  get spacingBefore() {
    return this.#getUniformParagraphRawValue((paragraph) => paragraph.spaceBefore);
  }
  set spacingBefore(value) {
    this.#applyToParagraphs((paragraph) => {
      paragraph.spaceBefore = value;
    });
    this.#recordStylePatch({ spacingBefore: value });
  }
  get lineSpacing() {
    const value = this.#getUniformParagraphRawValue((paragraph) => paragraph.lineSpacingPercent);
    if (value === undefined) {
      return;
    }
    return value / 1e5;
  }
  set lineSpacing(value) {
    this.#applyToParagraphs((paragraph) => {
      paragraph.lineSpacingPercent = value === undefined ? undefined : Math.round(value * 1e5);
    });
    this.#recordStylePatch({ lineSpacing: value });
  }
  get spacingAfter() {
    return this.#getUniformParagraphRawValue((paragraph) => paragraph.spaceAfter);
  }
  set spacingAfter(value) {
    this.#applyToParagraphs((paragraph) => {
      paragraph.spaceAfter = value;
    });
    this.#recordStylePatch({ spacingAfter: value });
  }
  get indentLeft() {
    return this.#getUniformParagraphRawValue((paragraph) => paragraph.marginLeft);
  }
  set indentLeft(value) {
    this.#applyToParagraphs((paragraph) => {
      paragraph.marginLeft = value;
    });
    this.#recordStylePatch({ indentLeft: value });
  }
  get indentFirstLine() {
    return this.#getUniformParagraphRawValue((paragraph) => paragraph.indent);
  }
  set indentFirstLine(value) {
    this.#applyToParagraphs((paragraph) => {
      paragraph.indent = value;
    });
    this.#recordStylePatch({ indentFirstLine: value });
  }
  get style() {
    const explicit = this.#getUniformParagraphRawValue((paragraph) => paragraph.styleId);
    if (explicit !== undefined) {
      return explicit;
    }
    const paragraphs = this.#collectParagraphs();
    const hasExplicit = paragraphs.some((paragraph) => {
      const styleId = paragraph.styleId;
      return styleId !== undefined && styleId !== "";
    });
    if (hasExplicit) {
      return;
    }
    const fallback = this.#getDefaultTextStyle();
    return fallback?.name;
  }
  set style(value) {
    const styleConfig = coerceTextStyleConfig(value);
    if (styleConfig) {
      this.#applyStyleConfig(styleConfig);
      return;
    }
    if (value !== undefined && typeof value !== "string") {
      return;
    }
    const normalized = typeof value === "string" && value.trim().length > 0 ? value : undefined;
    const resolved = normalized ? this.#options.resolveTextStyle?.(normalized) : undefined;
    this.#applyToParagraphs((paragraph) => {
      paragraph.styleId = normalized;
      paragraph.textStyle = resolved;
      applyListPreset(paragraph, normalized);
      this.#clearInlineFormatting(paragraph);
    });
    this.#options.setDefaultTextStyle?.(resolved);
    this.#invalidateLayout();
    this.#recordStylePatch({ style: normalized });
  }
  get className() {
    return this.#className;
  }
  set className(value) {
    const normalized = normalizeTextClassName(value);
    this.#className = normalized;
    if (!normalized) {
      return;
    }
    this.#applyStyleConfig({ className: normalized });
  }
  #applyStyleConfig(config) {
    const { className, styleConfig } = resolveTextStyleConfigForApply(config);
    if (className !== undefined) {
      this.#className = className;
    }
    this.#applyToRuns((run, paragraph) => {
      const style = this.#ensureRunStyle(paragraph, run);
      applyTextStyleConfig(style, styleConfig);
    });
    this.#applyToParagraphs((paragraph) => {
      applyTextStyleConfigToParagraph(paragraph, styleConfig);
    });
    const nextDefault = this.#nextDefaultTextStyle(styleConfig);
    this.#options.setDefaultTextStyle?.(nextDefault);
    this.#invalidateLayout();
    this.#recordStylePatch(textRangeStylePatchFromConfig(config));
  }
  #nextDefaultTextStyle(config) {
    const fallback = this.#getDefaultTextStyle();
    const next = fallback ? new TextStyle2(fallback.toProto()) : new TextStyle2;
    applyTextStyleConfig(next, config);
    return next;
  }
  getTextRange() {
    if (this.isEmpty) {
      return;
    }
    if (this.#segments.length === 0) {
      return;
    }
    const startSegment = this.#segments[0];
    const endSegment = this.#segments[this.#segments.length - 1];
    const offsets = this.#paragraphOffsets();
    const startCp = (offsets[startSegment.paragraphIndex] ?? 0) + startSegment.startOffset;
    const endCp = (offsets[endSegment.paragraphIndex] ?? 0) + endSegment.endOffset;
    return {
      startCp,
      length: Math.max(0, endCp - startCp)
    };
  }
  replace(value) {
    if (this.isEmpty) {
      return;
    }
    const selection = this.#getSingleParagraphSelection();
    if (!selection) {
      return;
    }
    this.#ensureSplitAtBoundaries();
    const { paragraph, paragraphIndex, startOffset, endOffset } = selection;
    const runsCollection = paragraph.runs;
    const runs = runsCollection.items;
    if (runs.length === 0) {
      return;
    }
    const targetedRuns = [];
    let cursor = 0;
    for (const run of runs) {
      const text = run.text;
      const runLength = text.length;
      const runStart = cursor;
      const runEnd = runStart + runLength;
      if (runLength > 0 && runStart >= startOffset && runEnd <= endOffset) {
        targetedRuns.push(run);
      }
      cursor = runEnd;
    }
    if (targetedRuns.length === 0) {
      return;
    }
    const replacementSourceParagraph = this.#extractSingleParagraph(value);
    const paragraphLength = paragraph.toPlainText().length;
    const replacesEntireParagraph = startOffset === 0 && endOffset === paragraphLength;
    const replacementRuns = this.#buildReplacementRuns(value, runsCollection, targetedRuns[0]);
    const nextRuns = [];
    cursor = 0;
    let inserted = replacementRuns.length === 0;
    for (const run of runs) {
      const text = run.text;
      const runLength = text.length;
      const runStart = cursor;
      const runEnd = runStart + runLength;
      const inside = runLength > 0 && runStart >= startOffset && runEnd <= endOffset;
      if (!inside) {
        nextRuns.push(run);
      } else if (!inserted) {
        for (const replacement of replacementRuns) {
          nextRuns.push(replacement);
        }
        inserted = true;
      }
      cursor = runEnd;
    }
    if (!inserted) {
      for (const replacement of replacementRuns) {
        nextRuns.push(replacement);
      }
    }
    runsCollection.replace(nextRuns);
    if (replacesEntireParagraph && replacementSourceParagraph) {
      this.#applyParagraphMetadata(paragraph, replacementSourceParagraph);
    }
    const insertedLength = this.#runsLength(replacementRuns);
    if (insertedLength === 0) {
      this.#segments = [];
    } else {
      this.#segments = [
        {
          paragraphIndex,
          startOffset,
          endOffset: startOffset + insertedLength
        }
      ];
    }
    this.#hasNormalizedRuns = false;
    this.#invalidateLayout();
  }
  insertAfter(value) {
    if (this.isEmpty) {
      return TextRange.empty(this.#paragraphs, this.#rangeOptions());
    }
    const selection = this.#getSingleParagraphSelection();
    if (!selection) {
      return TextRange.empty(this.#paragraphs, this.#rangeOptions());
    }
    this.#ensureSplitAtBoundaries();
    const { paragraph, paragraphIndex, endOffset } = selection;
    const runsCollection = paragraph.runs;
    const runs = runsCollection.items;
    if (runs.length === 0) {
      return TextRange.empty(this.#paragraphs, this.#rangeOptions());
    }
    const targetedIndices = [];
    const targetedRuns = [];
    let cursor = 0;
    for (const [index, run] of runs.entries()) {
      const text = run.text;
      const runLength = text.length;
      const runStart = cursor;
      const runEnd = runStart + runLength;
      if (runLength > 0 && runStart >= selection.startOffset && runEnd <= endOffset) {
        targetedIndices.push(index);
        targetedRuns.push(run);
      }
      cursor = runEnd;
    }
    if (targetedRuns.length === 0) {
      return TextRange.empty(this.#paragraphs, this.#rangeOptions());
    }
    const templateRun = targetedRuns[targetedRuns.length - 1];
    const insertionRuns = this.#buildReplacementRuns(value, runsCollection, templateRun);
    if (insertionRuns.length === 0) {
      return TextRange.empty(this.#paragraphs, this.#rangeOptions());
    }
    const lastTargetedIndex = targetedIndices[targetedIndices.length - 1];
    const nextRuns = [];
    runs.forEach((run, index) => {
      nextRuns.push(run);
      if (index === lastTargetedIndex) {
        for (const insertion of insertionRuns) {
          nextRuns.push(insertion);
        }
      }
    });
    runsCollection.replace(nextRuns);
    this.#hasNormalizedRuns = false;
    this.#invalidateLayout();
    const insertedLength = this.#runsLength(insertionRuns);
    const segments = insertedLength === 0 ? [] : [
      {
        paragraphIndex,
        startOffset: endOffset,
        endOffset: endOffset + insertedLength
      }
    ];
    return new TextRange(this.#paragraphs, segments, this.#rangeOptions());
  }
  #applyToRuns(handler) {
    if (this.isEmpty) {
      return;
    }
    this.#ensureSplitAtBoundaries();
    this.#forEachRun(handler);
    this.#invalidateLayout();
  }
  #applyToParagraphs(handler) {
    if (this.isEmpty) {
      return;
    }
    this.#forEachParagraph(handler);
    this.#invalidateLayout();
  }
  #recordStylePatch(props) {
    if (!this.#options.recordOp) {
      return;
    }
    if (!Object.values(props).some((value) => value !== undefined)) {
      return;
    }
    const anchor = this.#options.getAnchorId?.();
    if (!anchor) {
      return;
    }
    const range2 = this.getTextRange();
    if (!range2 || range2.length <= 0) {
      return;
    }
    const target = this.#buildTextRangeAnchor(anchor, range2);
    if (!target) {
      return;
    }
    this.#options.recordOp({
      op: "textrange.style.set",
      target,
      props
    });
  }
  #buildTextRangeAnchor(anchor, range2) {
    if (anchor.startsWith("@")) {
      return `tr/${anchor}/${range2.startCp}/${range2.length}`;
    }
    const slashIndex = anchor.indexOf("/");
    if (slashIndex <= 0 || slashIndex === anchor.length - 1) {
      return;
    }
    const prefix = anchor.slice(0, slashIndex);
    const suffix = anchor.slice(slashIndex + 1);
    if (!prefix || !suffix) {
      return;
    }
    return `tr/${prefix}/${suffix}/${range2.startCp}/${range2.length}`;
  }
  #getUniformRunValue(getter, equality = this.#primitiveEquals) {
    return this.#getUniformRunRawValue((run, paragraph) => {
      const style = run.textStyle;
      if (style) {
        const value = getter(style);
        if (value !== undefined) {
          return value;
        }
      }
      const paragraphStyle = paragraph.textStyle;
      if (paragraphStyle) {
        const value = getter(paragraphStyle);
        if (value !== undefined) {
          return value;
        }
      }
      const fallback = this.#getDefaultTextStyle();
      return fallback ? getter(fallback) : undefined;
    }, equality);
  }
  #getUniformRunRawValue(getter, equality = this.#primitiveEquals) {
    const entries = this.#collectRunEntries();
    if (entries.length === 0) {
      return;
    }
    let result;
    let initialized = false;
    for (const { run, paragraph } of entries) {
      const value = getter(run, paragraph);
      if (!initialized) {
        initialized = true;
        result = value;
        continue;
      }
      if (!equality(result, value)) {
        return;
      }
    }
    return result;
  }
  #getUniformParagraphValue(getter, equality = this.#primitiveEquals) {
    return this.#getUniformParagraphRawValue((paragraph) => {
      const style = paragraph.textStyle;
      if (style) {
        const value = getter(style);
        if (value !== undefined) {
          return value;
        }
      }
      const fallback = this.#getDefaultTextStyle();
      return fallback ? getter(fallback) : undefined;
    }, equality);
  }
  #getUniformParagraphRawValue(getter, equality = this.#primitiveEquals) {
    const paragraphs = this.#collectParagraphs();
    if (paragraphs.length === 0) {
      return;
    }
    let result;
    let initialized = false;
    for (const paragraph of paragraphs) {
      const value = getter(paragraph);
      if (!initialized) {
        initialized = true;
        result = value;
        continue;
      }
      if (!equality(result, value)) {
        return;
      }
    }
    return result;
  }
  #collectParagraphs() {
    const paragraphs = [];
    const seen = new Set;
    this.#forEachParagraph((paragraph) => {
      if (!seen.has(paragraph)) {
        seen.add(paragraph);
        paragraphs.push(paragraph);
      }
    });
    return paragraphs;
  }
  #collectRunEntries() {
    const entries = [];
    const seen = new Set;
    this.#ensureSplitAtBoundaries();
    this.#forEachRun((run, paragraph) => {
      if (!seen.has(run)) {
        seen.add(run);
        entries.push({ run, paragraph });
      }
    });
    return entries;
  }
  #forEachRun(handler) {
    const segmentsByParagraph = this.#groupSegmentsByParagraph();
    for (const [index, segments] of segmentsByParagraph.entries()) {
      const paragraph = this.#paragraphs.getItem(index);
      if (!paragraph) {
        continue;
      }
      const runs = paragraph.runs.items;
      if (runs.length === 0) {
        continue;
      }
      const orderedSegments = [...segments].sort((a, b) => a.startOffset - b.startOffset);
      let cursor = 0;
      let segmentIndex = 0;
      for (const run of runs) {
        const text = run.text;
        const runLength = text.length;
        if (runLength === 0) {
          continue;
        }
        const runStart = cursor;
        const runEnd = runStart + runLength;
        while (segmentIndex < orderedSegments.length) {
          const candidate = orderedSegments[segmentIndex];
          if (candidate.endOffset > runStart) {
            break;
          }
          segmentIndex += 1;
        }
        const segment = orderedSegments[segmentIndex];
        if (!segment) {
          break;
        }
        if (segment.startOffset <= runStart && runEnd <= segment.endOffset && segment.startOffset !== segment.endOffset) {
          handler(run, paragraph);
        }
        cursor = runEnd;
      }
    }
  }
  #forEachParagraph(handler) {
    const segmentsByParagraph = this.#groupSegmentsByParagraph();
    for (const index of segmentsByParagraph.keys()) {
      const paragraph = this.#paragraphs.getItem(index);
      if (paragraph) {
        handler(paragraph);
      }
    }
  }
  #groupSegmentsByParagraph() {
    const map3 = new Map;
    for (const segment of this.#segments) {
      if (!map3.has(segment.paragraphIndex)) {
        map3.set(segment.paragraphIndex, []);
      }
      map3.get(segment.paragraphIndex).push(segment);
    }
    return map3;
  }
  #ensureRunStyle(paragraph, run) {
    let style = run.textStyle;
    if (!style) {
      const fallback = paragraph.textStyle ?? this.#getDefaultTextStyle();
      style = fallback ? new TextStyle2(fallback.toProto()) : new TextStyle2;
      run.textStyle = style;
    }
    return style;
  }
  #ensureParagraphStyle(paragraph) {
    let style = paragraph.textStyle;
    if (!style) {
      const fallback = this.#getDefaultTextStyle();
      style = fallback ? new TextStyle2(fallback.toProto()) : new TextStyle2;
      paragraph.textStyle = style;
    }
    return style;
  }
  #getDefaultTextStyle() {
    return this.#options.getDefaultTextStyle?.();
  }
  #clearInlineFormatting(paragraph) {
    const runs = paragraph.runs.items;
    for (const run of runs) {
      run.textStyle = undefined;
    }
  }
  #ensureSplitAtBoundaries() {
    if (this.#hasNormalizedRuns || this.isEmpty) {
      return;
    }
    const segmentsByParagraph = this.#groupSegmentsByParagraph();
    for (const [index, segments] of segmentsByParagraph.entries()) {
      const paragraph = this.#paragraphs.getItem(index);
      if (!paragraph) {
        continue;
      }
      const runsCollection = paragraph.runs;
      const runs = runsCollection.items;
      if (runs.length === 0) {
        continue;
      }
      const boundarySet = new Set;
      for (const segment of segments) {
        boundarySet.add(segment.startOffset);
        boundarySet.add(segment.endOffset);
      }
      const boundaries = [...boundarySet].sort((a, b) => a - b);
      const nextRuns = [];
      let cursor = 0;
      for (const run of runs) {
        const text = run.text;
        const runLength = text.length;
        const runStart = cursor;
        const runEnd = runStart + runLength;
        const innerBoundaries = boundaries.filter((point3) => point3 > runStart && point3 < runEnd);
        if (innerBoundaries.length === 0) {
          nextRuns.push(run);
          cursor = runEnd;
          continue;
        }
        let previousOffset = 0;
        let originalUsed = false;
        const splits = [...innerBoundaries, runEnd];
        for (const split of splits) {
          const relative = split - runStart;
          const slice3 = text.slice(previousOffset, relative);
          if (slice3.length === 0) {
            previousOffset = relative;
            continue;
          }
          if (!originalUsed) {
            run.text = slice3;
            nextRuns.push(run);
            originalUsed = true;
          } else {
            nextRuns.push(runsCollection.cloneWithText(run, slice3));
          }
          previousOffset = relative;
        }
        if (!originalUsed) {
          run.text = "";
          nextRuns.push(run);
        }
        cursor = runEnd;
      }
      runsCollection.replace(nextRuns);
    }
    this.#hasNormalizedRuns = true;
  }
  #primitiveEquals(left, right) {
    return Object.is(left, right);
  }
  #arrayEquals(left, right) {
    if (!left && !right) {
      return true;
    }
    if (!left || !right) {
      return false;
    }
    if (left.length !== right.length) {
      return false;
    }
    return left.every((value, index) => Object.is(value, right[index]));
  }
  #paragraphOffsets() {
    const offsets = [];
    const paragraphs = this.#paragraphs.items;
    let cursor = 0;
    paragraphs.forEach((paragraph, index) => {
      offsets[index] = cursor;
      cursor += paragraph.toPlainText().length;
      if (index < paragraphs.length - 1) {
        cursor += 1;
      }
    });
    return offsets;
  }
  #areHyperlinksEqual(left, right) {
    if (left === right) {
      return true;
    }
    if (!left || !right) {
      return false;
    }
    return JSON.stringify(left) === JSON.stringify(right);
  }
  #colorEquals(left, right) {
    if (!left && !right) {
      return true;
    }
    if (!left || !right) {
      return false;
    }
    const a = left.toProto();
    const b = right.toProto();
    if (!a && !b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    return JSON.stringify(a) === JSON.stringify(b);
  }
  #getSingleParagraphSelection() {
    if (this.isEmpty) {
      return;
    }
    const uniqueParagraphIndices = new Set(this.#segments.map((segment) => segment.paragraphIndex));
    if (uniqueParagraphIndices.size !== 1) {
      return;
    }
    const [paragraphIndex] = uniqueParagraphIndices;
    if (paragraphIndex === undefined) {
      return;
    }
    const paragraph = this.#paragraphs.getItem(paragraphIndex);
    if (!paragraph) {
      return;
    }
    const segments = this.#segments.filter((segment) => segment.paragraphIndex === paragraphIndex);
    if (segments.length === 0) {
      return;
    }
    const startOffset = Math.min(...segments.map((segment) => segment.startOffset));
    const endOffset = Math.max(...segments.map((segment) => segment.endOffset));
    return {
      paragraph,
      paragraphIndex,
      startOffset,
      endOffset
    };
  }
  #buildReplacementRuns(value, runsCollection, templateRun) {
    if (this.#isTextFacade(value)) {
      const paragraphs = value.paragraphs.items;
      if (paragraphs.length === 0) {
        return [];
      }
      const firstParagraph = paragraphs[0];
      if (!firstParagraph) {
        return [];
      }
      const runs = firstParagraph.runs.items;
      if (runs.length === 0) {
        return [];
      }
      return runs.map((run) => runsCollection.cloneWithText(run, run.text));
    }
    const text = value ?? "";
    const normalized = typeof text === "string" ? text : String(text);
    if (normalized.length === 0) {
      return [];
    }
    return [runsCollection.cloneWithText(templateRun, normalized)];
  }
  #extractSingleParagraph(value) {
    if (!this.#isTextFacade(value)) {
      return;
    }
    const paragraphs = value.paragraphs.items;
    if (paragraphs.length === 0) {
      return;
    }
    return paragraphs[0];
  }
  #applyParagraphMetadata(target, source) {
    target.styleId = source.styleId;
    const sourceTextStyle = source.textStyle;
    target.textStyle = sourceTextStyle ? new TextStyle2(sourceTextStyle.toProto()) : undefined;
    target.bulletCharacter = source.bulletCharacter;
    target.marginLeft = source.marginLeft;
    target.indent = source.indent;
    target.spaceAfter = source.spaceAfter;
    target.spaceBefore = source.spaceBefore;
    target.paragraphStyle = source.paragraphStyle ? { ...source.paragraphStyle } : undefined;
  }
  #runsLength(runs) {
    return runs.reduce((length, run) => length + run.text.length, 0);
  }
  #isTextFacade(value) {
    if (typeof value !== "object" || value === null) {
      return false;
    }
    const candidate = value;
    if (!candidate.paragraphs) {
      return false;
    }
    return candidate.paragraphs instanceof ParagraphCollection;
  }
  #rangeOptions() {
    return { ...this.#options };
  }
  #invalidateLayout() {
    this.#options.onLayoutInvalidated?.();
  }
}

// node_modules/@oai/granola/dist/models/presentation/text-input.js
var FONT_SIZE_PATTERN = /^(-?\d+(?:\.\d+)?)(pt|px)$/i;
function isStructuredTextInput(value) {
  if (isStructuredTextParagraphInput(value)) {
    return true;
  }
  if (!Array.isArray(value)) {
    return false;
  }
  if (isRootParagraphRunsInput(value)) {
    return true;
  }
  return value.every(isStructuredTextParagraphValue);
}
function parseFontSizeToPx(value) {
  const match = FONT_SIZE_PATTERN.exec(value.trim());
  if (!match) {
    throw new Error(`Unsupported font size "${value}". Use unit strings like "11pt" or "16px".`);
  }
  const numeric = Number(match[1]);
  const unit2 = match[2]?.toLowerCase();
  if (Number.isNaN(numeric)) {
    throw new Error(`Invalid font size "${value}".`);
  }
  if (unit2 === "px") {
    return numeric;
  }
  if (unit2 === "pt") {
    return numeric * 96 / 72;
  }
  throw new Error(`Unsupported font size unit in "${value}".`);
}
function buildParagraphProtosFromInput(input) {
  if (Array.isArray(input) && input.length === 0) {
    return [];
  }
  const paragraphs = Array.isArray(input) && !isParagraphRunsInput(input) ? input : [input];
  if (paragraphs.length === 0) {
    return [];
  }
  return paragraphs.map((value) => isParagraphRunsInput(value) ? paragraphRunsToProto(value) : paragraphInputToProto(value));
}
function paragraphRunsToProto(runs) {
  const proto = {
    id: "",
    runs: runs.map((run) => normalizeRunInput(run)).map((run) => runInputToProto(run))
  };
  return proto;
}
function paragraphInputToProto(input) {
  return {
    id: "",
    runs: (input.runs ?? []).map((run) => normalizeRunInput(run)).map((run) => runInputToProto(run)),
    bulletCharacter: input.bulletCharacter,
    marginLeft: input.marginLeft,
    indent: input.indent,
    spaceBefore: input.spaceBefore,
    spaceAfter: input.spaceAfter,
    styleId: input.styleId,
    paragraphStyle: input.paragraphStyle ? { ...input.paragraphStyle } : undefined
  };
}
function normalizeRunInput(entry) {
  if (isTextRunInput(entry)) {
    return entry;
  }
  return {
    run: String(entry)
  };
}
function runInputToProto(input) {
  const proto = {
    id: "",
    text: input.run ?? "",
    hyperlink: input.link ? {
      ...input.link,
      action: input.link.action ?? ""
    } : undefined,
    citations: [],
    reviewMarkIds: []
  };
  const styles = buildTextStyleProto(input.textStyle);
  if (styles) {
    proto.textStyle = styles;
  }
  return proto;
}
function buildTextStyleProto(input) {
  if (!input) {
    return;
  }
  const style = new TextStyle2;
  if (input.bold !== undefined) {
    style.bold = input.bold;
  }
  if (input.italic !== undefined) {
    style.italic = input.italic;
  }
  if (input.underline !== undefined) {
    style.underline = input.underline;
  }
  if (input.fontSize) {
    style.fontSize = parseFontSizeToPx(input.fontSize);
  }
  if (input.color !== undefined) {
    style.fill = normalizeColorInput(input.color);
  }
  const proto = style.toProto();
  const hasValues = Object.values(proto).some((value) => {
    if (value === undefined || value === null) {
      return false;
    }
    if (Array.isArray(value)) {
      return value.length > 0;
    }
    if (typeof value === "object") {
      return Object.keys(value).length > 0;
    }
    return true;
  });
  return hasValues ? proto : undefined;
}
function normalizeColorInput(input) {
  if (typeof input === "string") {
    return input;
  }
  if (input.type === "solid") {
    return { ...input };
  }
  return input;
}
function isTextRunInput(entry) {
  if (!entry || typeof entry !== "object") {
    return false;
  }
  return "run" in entry;
}
function isParagraphRunsInput(entry) {
  return Array.isArray(entry) && entry.every(isStructuredRunEntry);
}
function isStructuredTextParagraphInput(entry) {
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
    return false;
  }
  return "runs" in entry || "bulletCharacter" in entry || "marginLeft" in entry || "indent" in entry || "spaceBefore" in entry || "spaceAfter" in entry || "styleId" in entry || "paragraphStyle" in entry;
}
function isStructuredTextParagraphValue(entry) {
  return isParagraphRunsInput(entry) || isStructuredTextParagraphInput(entry);
}
function isRootParagraphRunsInput(entry) {
  return Array.isArray(entry) && entry.every(isStructuredRunEntry) && entry.some((value) => isTextRunInput(value));
}
function isStructuredRunEntry(entry) {
  if (typeof entry === "string" || typeof entry === "number") {
    return true;
  }
  return isTextRunInput(entry);
}
function paragraphProtoToInput(proto) {
  const runs = (proto.runs ?? []).map((run) => textRunProtoToInput(run));
  if (!hasParagraphMetadata(proto)) {
    return runs.length > 0 ? runs : [""];
  }
  return {
    runs: runs.length > 0 ? runs : [""],
    bulletCharacter: proto.bulletCharacter,
    marginLeft: proto.marginLeft,
    indent: proto.indent,
    spaceBefore: proto.spaceBefore,
    spaceAfter: proto.spaceAfter,
    styleId: proto.styleId,
    paragraphStyle: proto.paragraphStyle ? { ...proto.paragraphStyle } : undefined
  };
}
function textRunProtoToInput(proto) {
  const styles = proto.textStyle;
  const textStyle = {};
  const style = styles ? new TextStyle2(styles) : undefined;
  if (styles?.bold !== undefined) {
    textStyle.bold = styles.bold;
  }
  if (styles?.italic !== undefined) {
    textStyle.italic = styles.italic;
  }
  if (styles?.underline !== undefined) {
    textStyle.underline = styles.underline;
  }
  if (style?.fontSize !== undefined) {
    textStyle.fontSize = `${style.fontSize}px`;
  }
  const fill = fillConfigToInput(style?.fill?.toConfig({ preserveProto: false }));
  if (fill !== undefined) {
    textStyle.color = fill;
  }
  const hasTextStyle = Object.keys(textStyle).length > 0;
  const hasLink = proto.hyperlink !== undefined;
  if (!hasTextStyle && !hasLink) {
    return proto.text ?? "";
  }
  return {
    run: proto.text ?? "",
    textStyle: hasTextStyle ? textStyle : undefined,
    link: hasLink ? {
      uri: proto.hyperlink?.uri ?? "",
      isExternal: proto.hyperlink?.isExternal ?? false,
      action: proto.hyperlink?.action ?? ""
    } : undefined
  };
}
function hasParagraphMetadata(proto) {
  return proto.bulletCharacter !== undefined || proto.marginLeft !== undefined || proto.indent !== undefined || proto.spaceBefore !== undefined || proto.spaceAfter !== undefined || proto.styleId !== undefined || proto.paragraphStyle !== undefined;
}
function fillConfigToInput(fill) {
  if (fill === undefined) {
    return;
  }
  if (typeof fill === "string") {
    return fill;
  }
  if (fill.type === "proto") {
    return;
  }
  if (fill.type === "none") {
    return fill;
  }
  if (fill.type === "image") {
    return fill;
  }
  if (fill.type === "solid") {
    const color2 = colorConfigToInput(fill.color);
    if (color2 === undefined) {
      return;
    }
    return {
      type: "solid",
      color: color2,
      pattern: patternConfigToInput(fill.pattern)
    };
  }
  return {
    type: "gradient",
    angleDeg: fill.angleDeg,
    gradientKind: fill.gradientKind,
    stops: fill.stops.flatMap((stop) => {
      const color2 = colorConfigToInput(stop.color);
      return color2 === undefined ? [] : [{ offset: stop.offset, color: color2 }];
    })
  };
}
function colorConfigToInput(color2) {
  if (color2 === undefined || typeof color2 === "string") {
    return color2;
  }
  if (color2.type === "proto") {
    return;
  }
  return color2;
}
function patternConfigToInput(pattern) {
  if (pattern === undefined || pattern.type === "proto") {
    return;
  }
  const color2 = colorConfigToInput(pattern.color);
  if (color2 === undefined) {
    return;
  }
  return {
    type: pattern.type,
    color: color2
  };
}

// node_modules/@oai/granola/dist/models/presentation/text.js
var DEFAULT_PARAGRAPH_CONTEXT = {
  stub: () => {},
  getImageById: () => {
    return;
  },
  createImageAsset: () => {
    throw new Error("createImageAsset is not available in detached text contexts.");
  },
  getChartById: () => {
    return;
  },
  getTextStyleByName: () => {
    return;
  },
  createChartAsset: () => {
    throw new Error("createChartAsset is not available in detached text contexts.");
  },
  attachChartAsset: (_chart) => {
    throw new Error("attachChartAsset is not available in detached text contexts.");
  }
};

class Text {
  #paragraphs;
  #getDefaultTextStyle;
  #setDefaultTextStyle;
  #resolveTextStyle;
  #styleName;
  #className;
  #onLayoutInvalidated;
  #onMutated;
  #recordOp;
  #getTargetRef;
  #getAnchorId;
  constructor(paragraphs, options = {}) {
    this.#paragraphs = paragraphs;
    this.#getDefaultTextStyle = options.getDefaultTextStyle;
    this.#setDefaultTextStyle = options.setDefaultTextStyle;
    this.#resolveTextStyle = options.resolveTextStyle;
    this.#onLayoutInvalidated = options.onLayoutInvalidated;
    this.#onMutated = options.onMutated;
    this.#recordOp = options.record?.recordOp;
    this.#getTargetRef = options.record?.getTargetRef;
    this.#getAnchorId = options.record?.getAnchorId;
    this.#styleName = this.#deriveUniformStyleName(this.#paragraphs.items);
    if (!this.#styleName) {
      const initialDefaultStyle = this.defaultTextStyle;
      if (initialDefaultStyle?.name) {
        this.#styleName = initialDefaultStyle.name;
      }
    }
    if (options.autoFit !== undefined) {
      this.#mutateDefaultTextStyle(options.autoFit, (style, next) => {
        style.autoFit = next;
      });
    }
  }
  static create(value = "", context = DEFAULT_PARAGRAPH_CONTEXT) {
    const paragraphs = new ParagraphCollection(context, []);
    const text = new Text(paragraphs, {
      resolveTextStyle: (name) => context.getTextStyleByName(name)
    });
    text.set(value);
    return text;
  }
  toString() {
    return this.#paragraphs.toPlainText();
  }
  get(query) {
    if (!query) {
      return TextRange.empty(this.#paragraphs, this.#rangeOptions());
    }
    const haystack = this.toString();
    const startIndex = haystack.indexOf(query);
    if (startIndex === -1) {
      return TextRange.empty(this.#paragraphs, this.#rangeOptions());
    }
    const endIndex = startIndex + query.length;
    const segments = this.#buildSegments(startIndex, endIndex);
    return new TextRange(this.#paragraphs, segments, this.#rangeOptions());
  }
  getRange(start, length) {
    const normalizedStart = Math.max(0, Math.floor(start));
    const normalizedLength = Math.max(0, Math.floor(length));
    if (normalizedLength === 0) {
      return TextRange.empty(this.#paragraphs, this.#rangeOptions());
    }
    const endIndex = normalizedStart + normalizedLength;
    const segments = this.#buildSegments(normalizedStart, endIndex);
    if (segments.length === 0) {
      return TextRange.empty(this.#paragraphs, this.#rangeOptions());
    }
    return new TextRange(this.#paragraphs, segments, this.#rangeOptions());
  }
  selectRunRanges(ranges) {
    if (!Array.isArray(ranges) || ranges.length === 0) {
      return TextRange.empty(this.#paragraphs, this.#rangeOptions());
    }
    const segments = this.#segmentsFromRunRanges(ranges);
    if (segments.length === 0) {
      return TextRange.empty(this.#paragraphs, this.#rangeOptions());
    }
    return new TextRange(this.#paragraphs, segments, this.#rangeOptions());
  }
  set(value) {
    this.#recordTextSet(value);
    if (value instanceof Text) {
      this.#replaceWith(value);
      this.#invalidateLayout();
      return;
    }
    if (isStructuredTextInput(value)) {
      this.#setStructured(value);
      this.#invalidateLayout();
      return;
    }
    if (Array.isArray(value)) {
      if (isStructuredTextInput(value)) {
        this.#setStructured(value);
        this.#invalidateLayout();
        return;
      }
      this.#setLinesPreservingStyle(value);
      this.#invalidateLayout();
      return;
    }
    this.#setPlainTextPreservingStyle(value);
    this.#invalidateLayout();
  }
  add(value) {
    if (value === undefined || value === null) {
      return;
    }
    if (Array.isArray(value)) {
      if (isStructuredTextInput(value)) {
        this.#appendStructured(value);
        this.#invalidateLayout();
        return;
      }
      for (const item of value) {
        this.add(item);
      }
      return;
    }
    if (value instanceof Text) {
      this.#appendText(value);
      this.#invalidateLayout();
      return;
    }
    this.#appendString(String(value));
    this.#invalidateLayout();
  }
  get paragraphs() {
    return this.#paragraphs;
  }
  replace(query, value) {
    if (!query) {
      return;
    }
    this.#recordTextReplace(query, value);
    const range2 = this.get(query);
    if (range2.isEmpty) {
      return;
    }
    range2.replace(value);
    this.#invalidateLayout();
  }
  get bold() {
    const range2 = this.#entireRange();
    const value = range2.bold;
    if (value !== undefined) {
      return value;
    }
    return this.defaultTextStyle?.bold;
  }
  set bold(value) {
    const range2 = this.#entireRange();
    if (!range2.isEmpty) {
      range2.bold = value;
    }
    this.#mutateDefaultTextStyle(value, (style, next) => {
      style.bold = next;
    });
    this.#recordTextStyle({ bold: value });
  }
  get italic() {
    const range2 = this.#entireRange();
    const value = range2.italic;
    if (value !== undefined) {
      return value;
    }
    return this.defaultTextStyle?.italic;
  }
  set italic(value) {
    const range2 = this.#entireRange();
    if (!range2.isEmpty) {
      range2.italic = value;
    }
    this.#mutateDefaultTextStyle(value, (style, next) => {
      style.italic = next;
    });
    this.#recordTextStyle({ italic: value });
  }
  get fontSize() {
    const range2 = this.#entireRange();
    const value = range2.fontSize;
    if (value !== undefined) {
      return value;
    }
    return this.defaultTextStyle?.fontSize;
  }
  set fontSize(value) {
    const range2 = this.#entireRange();
    if (!range2.isEmpty) {
      range2.fontSize = value;
    }
    this.#mutateDefaultTextStyle(value, (style, next) => {
      style.fontSize = next;
    });
    this.#recordTextStyle({ fontSize: value });
  }
  get lineSpacing() {
    const range2 = this.#entireRange();
    const value = range2.lineSpacing;
    if (value !== undefined) {
      return value;
    }
    return this.defaultTextStyle?.lineSpacing;
  }
  set lineSpacing(value) {
    const range2 = this.#entireRange();
    if (!range2.isEmpty) {
      range2.lineSpacing = value;
    }
    this.#mutateDefaultTextStyle(value, (style, next) => {
      style.lineSpacing = next;
    });
    this.#recordTextStyle({ lineSpacing: value });
  }
  get underline() {
    const range2 = this.#entireRange();
    const value = range2.underline;
    if (value !== undefined) {
      return value;
    }
    return this.defaultTextStyle?.underline;
  }
  set underline(value) {
    const range2 = this.#entireRange();
    if (!range2.isEmpty) {
      range2.underline = value;
    }
    this.#mutateDefaultTextStyle(value, (style, next) => {
      style.underline = next;
    });
    this.#recordTextStyle({ underline: value });
  }
  get color() {
    const range2 = this.#entireRange();
    const value = range2.color;
    if (value !== undefined) {
      return value;
    }
    const style = this.defaultTextStyle;
    const color2 = style?.color;
    return color2?.toProto() ? color2 : undefined;
  }
  set color(value) {
    const range2 = this.#entireRange();
    if (!range2.isEmpty) {
      range2.color = value;
    }
    this.#mutateDefaultTextStyle(value, (style, next) => {
      if (next) {
        style.fill = { type: "solid", color: next };
      }
    });
    this.#recordTextStyle({ color: toPatchColorConfig(value) });
  }
  get alignment() {
    const range2 = this.#entireRange();
    const value = range2.alignment;
    if (value !== undefined) {
      return value;
    }
    const style = this.defaultTextStyle;
    return style ? mapProtoTextHorizontalAlignment(style.alignment) : undefined;
  }
  set alignment(value) {
    const range2 = this.#entireRange();
    if (!range2.isEmpty) {
      range2.alignment = value;
    }
    this.#mutateDefaultTextStyle(value, (style, next) => {
      style.alignment = next;
    });
    this.#recordTextStyle({ alignment: value });
  }
  get verticalAlignment() {
    const style = this.defaultTextStyle;
    return style?.anchor ? TEXT_VERTICAL_ALIGNMENT_FROM_PROTO[style.anchor] : undefined;
  }
  set verticalAlignment(value) {
    this.#mutateDefaultTextStyle(value, (style, next) => {
      style.anchor = next ? mapTextVerticalAlignment(next) : undefined;
    });
    this.#invalidateLayout();
    this.#recordTextStyle({ verticalAlignment: value });
  }
  get autoFit() {
    return this.defaultTextStyle?.autoFit;
  }
  set autoFit(value) {
    this.#mutateDefaultTextStyle(value, (style, next) => {
      style.autoFit = next;
    });
    this.#invalidateLayout();
    this.#recordTextStyle({ autoFit: value });
  }
  get wrap() {
    return this.defaultTextStyle?.wrap;
  }
  set wrap(value) {
    this.#mutateDefaultTextStyle(value, (style, next) => {
      style.wrap = next;
    });
    this.#invalidateLayout();
    this.#recordTextStyle({ wrap: value });
  }
  get insets() {
    return this.defaultTextStyle?.insets;
  }
  set insets(value) {
    this.#mutateDefaultTextStyle(value, (style, next) => {
      style.insets = next;
    });
    this.#invalidateLayout();
    this.#recordTextStyle({ insets: value });
  }
  get style() {
    const paragraphs = this.#paragraphs.items;
    const uniform = this.#deriveUniformStyleName(paragraphs);
    if (uniform !== undefined) {
      this.#styleName = uniform ?? this.#styleName;
      return uniform;
    }
    return this.#styleName ?? this.defaultTextStyle?.name;
  }
  set style(name) {
    const styleConfig = coerceTextStyleConfig(name);
    if (styleConfig) {
      this.#applyShapeTextStyleConfig(styleConfig);
      return;
    }
    if (name !== undefined && typeof name !== "string") {
      return;
    }
    this.#applyStyleName(name);
  }
  #applyStyleName(name, options = {}) {
    const paragraphs = this.#paragraphs.items;
    const normalized = name !== undefined && name.trim().length > 0 ? name : undefined;
    const resolved = normalized ? this.#resolveTextStyle?.(normalized) : undefined;
    this.#styleName = normalized ?? undefined;
    const previousDefault = this.defaultTextStyle ? new TextStyle2(this.defaultTextStyle.toProto()) : undefined;
    const resolvedClone = resolved ? new TextStyle2(resolved.toProto()) : undefined;
    const mergedProto = normalized !== undefined ? this.#mergeTextStyleProto(resolvedClone?.toProto(), previousDefault?.toProto()) : previousDefault?.toProto();
    const nextDefault = mergedProto ? new TextStyle2(mergedProto) : undefined;
    if (paragraphs.length > 0) {
      for (const paragraph of paragraphs) {
        paragraph.styleId = normalized;
        paragraph.textStyle = nextDefault ? new TextStyle2(nextDefault.toProto()) : undefined;
        applyListPreset(paragraph, normalized);
        this.#clearInlineFormatting(paragraph);
      }
    }
    this.defaultTextStyle = nextDefault;
    if (options.record ?? true) {
      this.#recordTextStyle({ style: normalized });
      this.#notifyMutated();
    }
  }
  get className() {
    return this.#className;
  }
  set className(value) {
    const normalized = normalizeTextClassName(value);
    this.#className = normalized;
    if (!normalized) {
      return;
    }
    this.#applyStyleConfig({ className: normalized });
  }
  get defaultTextStyle() {
    return this.#getDefaultTextStyle?.();
  }
  set defaultTextStyle(style) {
    this.#setDefaultTextStyle?.(style);
  }
  #applyShapeTextStyleConfig(config) {
    const styleName = this.#resolveShapeTextStyleName(config);
    if (styleName !== undefined) {
      this.#applyStyleName(styleName, { record: false });
    }
    const contentConfig = this.#buildTextStyleConfig(config);
    if (Object.keys(contentConfig).length > 0) {
      this.#applyStyleConfig(contentConfig, { record: false });
    }
    this.#applyTextBoxStyleConfig(config);
    this.#recordTextStyle(this.#buildTextStylePatch(config, styleName));
  }
  #applyStyleConfig(config, options = {}) {
    const { className, styleConfig } = resolveTextStyleConfigForApply(config);
    if (className !== undefined) {
      this.#className = className;
    }
    const styleName = resolveTextStyleName(styleConfig);
    if (styleName !== undefined) {
      this.#styleName = styleName;
    }
    if (Object.keys(styleConfig).length > 0) {
      const range2 = this.#entireRange({ recordOps: false });
      if (!range2.isEmpty) {
        range2.style = styleConfig;
      }
      this.#mutateDefaultTextStyle(styleConfig, (style, next) => {
        if (!next) {
          return;
        }
        applyTextStyleConfig(style, next);
      });
      this.#invalidateLayout();
    }
    const patch = textStylePatchFromConfig(config);
    if ("lineSpacing" in styleConfig) {
      patch.lineSpacing = styleConfig.lineSpacing;
    }
    if (options.record ?? true) {
      this.#recordTextStyle(patch);
    }
  }
  #resolveShapeTextStyleName(config) {
    if (config.styleName !== undefined) {
      const normalized2 = config.styleName.trim();
      return normalized2.length > 0 ? normalized2 : undefined;
    }
    const legacyStyle = config.style;
    if (legacyStyle === undefined) {
      return;
    }
    const normalized = legacyStyle.trim();
    return normalized.length > 0 ? normalized : undefined;
  }
  #buildTextStyleConfig(config) {
    const styleConfig = {};
    if (config.anchor !== undefined) {
      styleConfig.anchor = config.anchor;
    }
    if (config.vertical !== undefined) {
      styleConfig.vertical = config.vertical;
    }
    if (config.rotation !== undefined) {
      styleConfig.rotation = config.rotation;
    }
    if (config.className !== undefined) {
      styleConfig.className = config.className;
    }
    if (config.bold !== undefined) {
      styleConfig.bold = config.bold;
    }
    if (config.italic !== undefined) {
      styleConfig.italic = config.italic;
    }
    if (config.underline !== undefined) {
      styleConfig.underline = config.underline;
    }
    if (config.fill !== undefined) {
      styleConfig.fill = config.fill;
    }
    if (config.fontSize !== undefined) {
      styleConfig.fontSize = config.fontSize;
    }
    if (config.lineSpacing !== undefined) {
      styleConfig.lineSpacing = config.lineSpacing;
    }
    if (config.color !== undefined) {
      styleConfig.color = config.color;
    }
    if (config.alignment !== undefined) {
      styleConfig.alignment = config.alignment;
    }
    if (config.useParagraphSpacing !== undefined) {
      styleConfig.useParagraphSpacing = config.useParagraphSpacing;
    }
    if (config.autoFitScale !== undefined) {
      styleConfig.autoFitScale = config.autoFitScale;
    }
    if (config.autoFitLineSpaceReduction !== undefined) {
      styleConfig.autoFitLineSpaceReduction = config.autoFitLineSpaceReduction;
    }
    if (config.name !== undefined) {
      styleConfig.name = config.name;
    }
    if (config.family !== undefined) {
      styleConfig.family = config.family;
    }
    if (config.scheme !== undefined) {
      styleConfig.scheme = config.scheme;
    }
    if (config.typeface !== undefined) {
      styleConfig.typeface = config.typeface;
    }
    return styleConfig;
  }
  #applyTextBoxStyleConfig(config) {
    let invalidateLayout = false;
    if (config.verticalAlignment !== undefined) {
      this.#mutateDefaultTextStyle(config.verticalAlignment, (style, next) => {
        style.anchor = next ? mapTextVerticalAlignment(next) : undefined;
      });
      invalidateLayout = true;
    }
    if (config.autoFit !== undefined) {
      this.#mutateDefaultTextStyle(config.autoFit, (style, next) => {
        style.autoFit = next;
      });
      invalidateLayout = true;
    }
    if (config.wrap !== undefined) {
      this.#mutateDefaultTextStyle(config.wrap, (style, next) => {
        style.wrap = next;
      });
      invalidateLayout = true;
    }
    if (config.insets !== undefined) {
      this.#mutateDefaultTextStyle(config.insets, (style, next) => {
        style.insets = next;
      });
      invalidateLayout = true;
    }
    if (invalidateLayout) {
      this.#invalidateLayout();
    }
  }
  #buildTextStylePatch(config, styleName) {
    const patch = textStylePatchFromConfig(this.#buildTextStyleConfig(config));
    if (styleName !== undefined) {
      patch.style = styleName;
    }
    if (config.verticalAlignment !== undefined) {
      patch.verticalAlignment = config.verticalAlignment;
    }
    if (config.autoFit !== undefined) {
      patch.autoFit = config.autoFit;
    }
    if (config.wrap !== undefined) {
      patch.wrap = config.wrap;
    }
    if (config.insets !== undefined) {
      patch.insets = config.insets;
    }
    return patch;
  }
  #clearInlineFormatting(paragraph) {
    const runs = paragraph.runs.items;
    for (const run of runs) {
      run.textStyle = undefined;
    }
  }
  #recordTextSet(value) {
    if (!this.#recordOp) {
      return;
    }
    const target = this.#getTargetRef?.();
    if (!target) {
      return;
    }
    this.#recordOp({
      op: "text.set",
      target,
      value: this.#serializeTextValue(value)
    });
  }
  #recordTextReplace(query, value) {
    if (!this.#recordOp || !query) {
      return;
    }
    const target = this.#getTargetRef?.();
    if (!target) {
      return;
    }
    this.#recordOp({
      op: "text.replace",
      target,
      find: query,
      value: this.#serializeTextValue(value)
    });
  }
  #recordTextStyle(props) {
    if (!Object.values(props).some((value) => value !== undefined)) {
      return;
    }
    this.#notifyMutated();
    if (!this.#recordOp) {
      return;
    }
    const target = this.#getTargetRef?.();
    if (!target) {
      return;
    }
    this.#recordOp({
      op: "text.style.set",
      target,
      props
    });
  }
  #serializeTextValue(value) {
    if (value instanceof Text) {
      return this.#serializeText(value);
    }
    if (isStructuredTextInput(value)) {
      return value;
    }
    if (Array.isArray(value)) {
      return value.map((entry) => String(entry ?? ""));
    }
    return String(value ?? "");
  }
  #serializeText(text) {
    const paragraphs = text.paragraphs.items;
    if (paragraphs.length === 0) {
      return "";
    }
    const serialized = paragraphs.map((paragraph) => paragraphProtoToInput(paragraph.toProto()));
    const allRunArrays = serialized.every((value) => isParagraphRunsInput(value));
    const plainRunArrays = serialized.filter((value) => isParagraphRunsInput(value));
    const isPlain = allRunArrays && plainRunArrays.every((runs) => runs.every((entry) => typeof entry === "string" || typeof entry === "number"));
    if (isPlain) {
      const lines = plainRunArrays.map((runs) => runs.map((entry) => String(entry)).join(""));
      return lines.length === 1 ? lines[0] ?? "" : lines;
    }
    if (serialized.length === 1) {
      return serialized[0] ?? "";
    }
    return serialized;
  }
  #replaceWith(other) {
    const paragraphs = other.paragraphs.items;
    const previousDefaultStyle = this.defaultTextStyle ? new TextStyle2(this.defaultTextStyle.toProto()) : undefined;
    const otherDefaultStyle = other.defaultTextStyle ? new TextStyle2(other.defaultTextStyle.toProto()) : undefined;
    this.#paragraphs.clear();
    if (paragraphs.length === 0) {
      this.#paragraphs.setFromPlainText("");
      this.defaultTextStyle = otherDefaultStyle ?? previousDefaultStyle;
      this.#styleName = other.style ?? this.#styleName;
      this.#applyDefaultStyleToParagraphs();
      return;
    }
    for (const paragraph of paragraphs) {
      const clone = this.#cloneParagraphProto(paragraph);
      this.#paragraphs.append(clone);
    }
    this.defaultTextStyle = otherDefaultStyle ?? previousDefaultStyle;
    const uniformStyle = this.#deriveUniformStyleName(this.#paragraphs.items);
    this.#styleName = other.style ?? uniformStyle ?? this.#styleName;
    this.#applyDefaultStyleToParagraphs();
  }
  #entireRange(options) {
    const segments = this.#paragraphs.items.map((paragraph, index) => {
      const length = paragraph.toPlainText().length;
      if (length === 0) {
        return;
      }
      return {
        paragraphIndex: index,
        startOffset: 0,
        endOffset: length
      };
    }).filter((segment) => Boolean(segment));
    const rangeOptions = this.#rangeOptions();
    if (options?.recordOps === false) {
      rangeOptions.recordOp = undefined;
    }
    return new TextRange(this.#paragraphs, segments, rangeOptions);
  }
  #mutateDefaultTextStyle(value, mutator) {
    let style = this.defaultTextStyle;
    if (!style) {
      if (value === undefined) {
        return;
      }
      style = new TextStyle2;
      this.defaultTextStyle = style;
    }
    mutator(style, value);
  }
  #appendString(value) {
    const paragraph = this.#paragraphs.add();
    paragraph.setPlainText(value);
    this.#applyDefaultStyleToParagraph(paragraph);
  }
  #setPlainTextPreservingStyle(value) {
    const lines = value.length === 0 ? [] : value.split(/\r?\n/).map((line) => line.replace(/\r$/, ""));
    this.#setLinesPreservingStyle(lines);
  }
  #setLinesPreservingStyle(lines) {
    const normalized = (lines ?? []).map((line) => String(line ?? ""));
    const targetLines = normalized.length === 0 ? [""] : normalized;
    const paragraphs = this.#paragraphs.items;
    const templateParagraph = paragraphs[paragraphs.length - 1];
    for (let index = 0;index < targetLines.length; index += 1) {
      const line = targetLines[index] ?? "";
      const paragraph = paragraphs[index];
      if (paragraph) {
        this.#replaceParagraphText(paragraph, line);
        continue;
      }
      const proto = this.#buildParagraphProtoFromTemplate(templateParagraph, line);
      this.#paragraphs.append(proto);
    }
    for (let index = paragraphs.length - 1;index >= targetLines.length; index -= 1) {
      this.#paragraphs.removeAt(index);
    }
    this.#applyDefaultStyleToParagraphs();
  }
  #replaceParagraphText(paragraph, text) {
    const runsCollection = paragraph.runs;
    const runs = runsCollection.items;
    if (runs.length === 0) {
      paragraph.setPlainText(text);
      return;
    }
    const templateRun = runs.find((run) => run.text.length > 0) ?? runs[0];
    if (!templateRun) {
      paragraph.setPlainText(text);
      return;
    }
    runsCollection.replace([runsCollection.cloneWithText(templateRun, text)]);
  }
  #buildParagraphProtoFromTemplate(template, text) {
    if (!template) {
      return {
        id: "",
        runs: [{ id: "", text, citations: [], reviewMarkIds: [] }]
      };
    }
    const proto = this.#cloneParagraphProto(template);
    const runs = proto.runs ?? [];
    if (runs.length === 0) {
      proto.runs = [{ id: "", text, citations: [], reviewMarkIds: [] }];
      return proto;
    }
    const templateRun = runs.find((run) => (run.text ?? "").length > 0) ?? runs[0];
    proto.runs = [
      {
        ...templateRun,
        id: "",
        text
      }
    ];
    return proto;
  }
  #setStructured(value) {
    const protos = buildParagraphProtosFromInput(value);
    this.#paragraphs.clear();
    if (protos.length === 0) {
      this.#paragraphs.setFromPlainText("");
    } else {
      for (const proto of protos) {
        this.#paragraphs.append(proto);
      }
    }
    this.#applyDefaultStyleToParagraphs();
  }
  #appendStructured(value) {
    const protos = buildParagraphProtosFromInput(value);
    if (protos.length === 0) {
      return;
    }
    for (const proto of protos) {
      this.#paragraphs.append(proto);
    }
    this.#applyDefaultStyleToParagraphs();
  }
  #appendText(value) {
    const paragraphs = value.paragraphs.items;
    if (paragraphs.length === 0) {
      this.#appendString("");
      return;
    }
    for (const paragraph of paragraphs) {
      const proto = this.#cloneParagraphProto(paragraph);
      this.#paragraphs.append(proto);
    }
  }
  #applyDefaultStyleToParagraphs() {
    const paragraphs = this.#paragraphs.items;
    for (const paragraph of paragraphs) {
      this.#applyDefaultStyleToParagraph(paragraph);
    }
  }
  #applyDefaultStyleToParagraph(paragraph) {
    const styleName = this.#styleName ? this.#styleName.trim() : undefined;
    const defaultStyle = this.defaultTextStyle;
    if (styleName && (!paragraph.styleId || paragraph.styleId.length === 0)) {
      paragraph.styleId = styleName;
      applyListPreset(paragraph, styleName);
    }
    if (defaultStyle && !paragraph.textStyle) {
      paragraph.textStyle = new TextStyle2(defaultStyle.toProto());
    }
  }
  #deriveUniformStyleName(paragraphs) {
    if (paragraphs.length === 0) {
      return;
    }
    let styleId;
    let initialized = false;
    for (const paragraph of paragraphs) {
      const current = paragraph.styleId;
      if (!initialized) {
        initialized = true;
        styleId = current;
        continue;
      }
      if (!Object.is(styleId, current)) {
        return;
      }
    }
    return styleId;
  }
  #mergeTextStyleProto(base, overrides) {
    if (!base && !overrides) {
      return;
    }
    const result = {
      ...base ?? {}
    };
    if (overrides) {
      for (const [key, value] of Object.entries(overrides)) {
        if (value !== undefined) {
          result[key] = value;
        }
      }
    }
    return result;
  }
  #cloneParagraphProto(paragraph) {
    const proto = paragraph.toProto();
    proto.id = "";
    if (proto.runs) {
      proto.runs = proto.runs.map((run) => ({
        ...run,
        id: ""
      }));
    }
    return proto;
  }
  #buildSegments(startIndex, endIndex) {
    const segments = [];
    const paragraphs = this.#paragraphs.items;
    let cursor = 0;
    paragraphs.forEach((paragraph, index) => {
      const text = paragraph.toPlainText();
      const paragraphStart = cursor;
      const paragraphEnd = paragraphStart + text.length;
      const segmentStart = Math.max(paragraphStart, startIndex);
      const segmentEnd = Math.min(paragraphEnd, endIndex);
      if (segmentStart < segmentEnd) {
        segments.push({
          paragraphIndex: index,
          startOffset: segmentStart - paragraphStart,
          endOffset: segmentEnd - paragraphStart
        });
      }
      cursor = paragraphEnd;
      if (index < paragraphs.length - 1) {
        cursor += 1;
      }
    });
    return segments;
  }
  #segmentsFromRunRanges(ranges) {
    const segments = [];
    for (const range2 of ranges) {
      const paragraph = this.#paragraphs.getItem(range2.paragraphIndex);
      if (!paragraph)
        continue;
      const runs = paragraph.runs.items;
      if (range2.runIndex < 0 || range2.runIndex >= runs.length)
        continue;
      const run = runs[range2.runIndex];
      if (!run)
        continue;
      const text = run.text ?? "";
      const baseOffset = this.#paragraphRunOffset(paragraph, range2.runIndex);
      const startOffset = baseOffset + this.#graphemeOffset(text, range2.start);
      const endOffset = baseOffset + this.#graphemeOffset(text, range2.end);
      if (endOffset <= startOffset)
        continue;
      segments.push({
        paragraphIndex: range2.paragraphIndex,
        startOffset,
        endOffset
      });
    }
    return segments;
  }
  #paragraphRunOffset(paragraph, runIndex) {
    const runs = paragraph.runs.items;
    let offset = 0;
    const limit = Math.max(0, Math.min(runIndex, runs.length));
    for (let index = 0;index < limit; index += 1) {
      const run = runs[index];
      if (run?.text) {
        offset += run.text.length;
      }
    }
    return offset;
  }
  #graphemeOffset(text, graphemeIndex) {
    if (!text || graphemeIndex <= 0) {
      return 0;
    }
    const segments = splitGraphemes(text);
    const limit = Math.max(0, Math.min(graphemeIndex, segments.length));
    let offset = 0;
    for (let i = 0;i < limit; i += 1) {
      offset += segments[i]?.length ?? 0;
    }
    return offset;
  }
  #rangeOptions() {
    return {
      getDefaultTextStyle: this.#getDefaultTextStyle,
      setDefaultTextStyle: this.#setDefaultTextStyle,
      resolveTextStyle: this.#resolveTextStyle,
      onLayoutInvalidated: this.#onLayoutInvalidated,
      recordOp: this.#recordOp,
      getAnchorId: this.#getAnchorId
    };
  }
  #invalidateLayout() {
    this.#notifyMutated();
    this.#onLayoutInvalidated?.();
  }
  #notifyMutated() {
    this.#onMutated?.();
  }
}

// node_modules/@oai/granola/dist/models/presentation/position.js
var normalizePixels = (value) => {
  if (value === undefined || value === null || Number.isNaN(value)) {
    return;
  }
  return Number(value);
};
var normalizeRotation = (value) => {
  if (value === undefined || value === null || Number.isNaN(value)) {
    return;
  }
  return Number(value);
};
var pixelsFromEmuOptional = (value) => {
  if (value === undefined || value === null) {
    return;
  }
  return pixelsFromEmu(value);
};

class Position {
  #left;
  #top;
  #width;
  #height;
  #rotation;
  #horizontalFlip;
  #verticalFlip;
  #previewConfig;
  #bboxStruct;
  #dirty = false;
  #onChange;
  constructor(config, isDirty = false) {
    if (!config) {
      this.#left = undefined;
      this.#top = undefined;
      this.#width = undefined;
      this.#height = undefined;
      this.#rotation = undefined;
      this.#horizontalFlip = undefined;
      this.#verticalFlip = undefined;
      this.#dirty = isDirty;
      return;
    }
    if (config.left !== undefined) {
      this.#left = normalizePixels(config.left);
    }
    if (config.top !== undefined) {
      this.#top = normalizePixels(config.top);
    }
    if (config.width !== undefined) {
      this.#width = normalizePixels(config.width);
    }
    if (config.height !== undefined) {
      this.#height = normalizePixels(config.height);
    }
    if (config.rotation !== undefined) {
      this.#rotation = normalizeRotation(config.rotation);
    }
    if (config.horizontalFlip !== undefined) {
      this.#horizontalFlip = Boolean(config.horizontalFlip);
    }
    if (config.verticalFlip !== undefined) {
      this.#verticalFlip = Boolean(config.verticalFlip);
    }
    this.#dirty = isDirty;
  }
  static fromProto(bbox) {
    if (!bbox) {
      return new Position;
    }
    const rect = {
      left: bbox.xEmu !== undefined ? pixelsFromEmu(bbox.xEmu) : undefined,
      top: bbox.yEmu !== undefined ? pixelsFromEmu(bbox.yEmu) : undefined,
      width: bbox.widthEmu !== undefined ? pixelsFromEmu(bbox.widthEmu) : undefined,
      height: bbox.heightEmu !== undefined ? pixelsFromEmu(bbox.heightEmu) : undefined,
      rotation: emuRotationToDegrees(bbox.rotation) ?? undefined,
      horizontalFlip: bbox.horizontalFlip ?? undefined,
      verticalFlip: bbox.verticalFlip ?? undefined
    };
    return new Position(rect, true);
  }
  bindToBboxStruct(bbox, seed) {
    this.#bboxStruct = bbox;
    if (seed && bbox.size === 0) {
      this.#seedBboxStruct(bbox, seed);
    }
  }
  clone() {
    const rect = this.#toRect();
    const copy2 = new Position(rect, this.#dirtySnapshot());
    copy2.#onChange = this.#onChange;
    return copy2;
  }
  setChangeHandler(handler) {
    this.#onChange = handler;
  }
  setPreview(value) {
    if (!value) {
      this.#previewConfig = undefined;
      return;
    }
    const next = {};
    if (value.left !== undefined) {
      const normalized = normalizePixels(value.left);
      if (normalized !== undefined) {
        next.left = normalized;
      }
    }
    if (value.top !== undefined) {
      const normalized = normalizePixels(value.top);
      if (normalized !== undefined) {
        next.top = normalized;
      }
    }
    if (value.width !== undefined) {
      const normalized = normalizePixels(value.width);
      if (normalized !== undefined) {
        next.width = normalized;
      }
    }
    if (value.height !== undefined) {
      const normalized = normalizePixels(value.height);
      if (normalized !== undefined) {
        next.height = normalized;
      }
    }
    if (value.rotation !== undefined) {
      const normalized = normalizeRotation(value.rotation);
      if (normalized !== undefined) {
        next.rotation = normalized;
      }
    }
    if (value.horizontalFlip !== undefined) {
      next.horizontalFlip = Boolean(value.horizontalFlip);
    }
    if (value.verticalFlip !== undefined) {
      next.verticalFlip = Boolean(value.verticalFlip);
    }
    if (Object.keys(next).length === 0) {
      this.#previewConfig = undefined;
      return;
    }
    this.#previewConfig = next;
  }
  clearPreview() {
    this.#previewConfig = undefined;
  }
  getPreviewRect() {
    if (!this.#previewConfig) {
      return;
    }
    const rect = this.#toRect();
    return {
      ...rect,
      ...this.#previewConfig
    };
  }
  #emitChange(patch) {
    if (this.#onChange) {
      this.#onChange(patch);
    }
  }
  #dirtySnapshot() {
    return this.#bboxStruct ? this.#bboxStruct.size > 0 : this.#dirty;
  }
  #getBboxNumber(key) {
    if (!this.#bboxStruct) {
      return;
    }
    const value = this.#bboxStruct.get(key);
    return typeof value === "number" ? value : undefined;
  }
  #getBboxBoolean(key) {
    if (!this.#bboxStruct) {
      return;
    }
    const value = this.#bboxStruct.get(key);
    if (value === undefined) {
      return;
    }
    return Boolean(value);
  }
  #getPreviewPixelValue(key) {
    if (!this.#previewConfig) {
      return;
    }
    switch (key) {
      case "xEmu":
        return this.#previewConfig.left;
      case "yEmu":
        return this.#previewConfig.top;
      case "widthEmu":
        return this.#previewConfig.width;
      case "heightEmu":
        return this.#previewConfig.height;
      default:
        return;
    }
  }
  #getPreviewRotationValue() {
    return this.#previewConfig?.rotation;
  }
  #getPreviewFlipValue(key) {
    if (!this.#previewConfig) {
      return;
    }
    return this.#previewConfig[key];
  }
  #getPreviewEmu(key) {
    const preview = this.#getPreviewPixelValue(key);
    if (preview === undefined) {
      return;
    }
    return emuFromPixels(preview);
  }
  #getPixelValue(key, fallback) {
    if (this.#bboxStruct) {
      return pixelsFromEmuOptional(this.#getBboxNumber(key));
    }
    return fallback;
  }
  #getRotationValue(fallback) {
    if (this.#bboxStruct) {
      return emuRotationToDegrees(this.#getBboxNumber("rotation"));
    }
    return fallback;
  }
  #getFlipValue(key, fallback) {
    if (this.#bboxStruct) {
      return this.#getBboxBoolean(key);
    }
    return fallback;
  }
  #toRect() {
    const rect = {};
    const left = this.#getPixelValue("xEmu", this.#left);
    if (left !== undefined) {
      rect.left = left;
    }
    const top = this.#getPixelValue("yEmu", this.#top);
    if (top !== undefined) {
      rect.top = top;
    }
    const width = this.#getPixelValue("widthEmu", this.#width);
    if (width !== undefined) {
      rect.width = width;
    }
    const height = this.#getPixelValue("heightEmu", this.#height);
    if (height !== undefined) {
      rect.height = height;
    }
    const rotation = this.#getRotationValue(this.#rotation);
    if (rotation !== undefined) {
      rect.rotation = rotation;
    }
    const horizontalFlip = this.#getFlipValue("horizontalFlip", this.#horizontalFlip);
    if (horizontalFlip !== undefined) {
      rect.horizontalFlip = horizontalFlip;
    }
    const verticalFlip = this.#getFlipValue("verticalFlip", this.#verticalFlip);
    if (verticalFlip !== undefined) {
      rect.verticalFlip = verticalFlip;
    }
    return rect;
  }
  #seedBboxStruct(bbox, seed) {
    if (seed.xEmu !== undefined)
      bbox.set("xEmu", seed.xEmu);
    if (seed.yEmu !== undefined)
      bbox.set("yEmu", seed.yEmu);
    if (seed.widthEmu !== undefined)
      bbox.set("widthEmu", seed.widthEmu);
    if (seed.heightEmu !== undefined)
      bbox.set("heightEmu", seed.heightEmu);
    if (seed.rotation !== undefined)
      bbox.set("rotation", seed.rotation);
    if (seed.horizontalFlip !== undefined) {
      bbox.set("horizontalFlip", seed.horizontalFlip);
    }
    if (seed.verticalFlip !== undefined) {
      bbox.set("verticalFlip", seed.verticalFlip);
    }
  }
  reset() {
    if (this.#bboxStruct) {
      this.#bboxStruct.delete("xEmu");
      this.#bboxStruct.delete("yEmu");
      this.#bboxStruct.delete("widthEmu");
      this.#bboxStruct.delete("heightEmu");
      this.#bboxStruct.delete("rotation");
      this.#bboxStruct.delete("horizontalFlip");
      this.#bboxStruct.delete("verticalFlip");
    }
    this.#left = undefined;
    this.#top = undefined;
    this.#width = undefined;
    this.#height = undefined;
    this.#rotation = undefined;
    this.#horizontalFlip = undefined;
    this.#verticalFlip = undefined;
    this.#previewConfig = undefined;
    this.#dirty = false;
  }
  set(value) {
    if (value instanceof Position) {
      const rect = value.#toRect();
      const dirty = value.#dirtySnapshot();
      this.reset();
      this.merge(rect);
      this.#dirty = dirty;
      return;
    }
    this.reset();
    if (value) {
      this.merge(value);
    }
  }
  merge(value) {
    if (value.left !== undefined) {
      const normalized = normalizePixels(value.left);
      if (this.#bboxStruct) {
        if (normalized === undefined) {
          this.#bboxStruct.delete("xEmu");
        } else {
          this.#bboxStruct.set("xEmu", emuFromPixels(normalized));
        }
      } else {
        this.#left = normalized;
      }
      this.#dirty = true;
    }
    if (value.top !== undefined) {
      const normalized = normalizePixels(value.top);
      if (this.#bboxStruct) {
        if (normalized === undefined) {
          this.#bboxStruct.delete("yEmu");
        } else {
          this.#bboxStruct.set("yEmu", emuFromPixels(normalized));
        }
      } else {
        this.#top = normalized;
      }
      this.#dirty = true;
    }
    if (value.width !== undefined) {
      const normalized = normalizePixels(value.width);
      if (this.#bboxStruct) {
        if (normalized === undefined) {
          this.#bboxStruct.delete("widthEmu");
        } else {
          this.#bboxStruct.set("widthEmu", emuFromPixels(normalized));
        }
      } else {
        this.#width = normalized;
      }
      this.#dirty = true;
    }
    if (value.height !== undefined) {
      const normalized = normalizePixels(value.height);
      if (this.#bboxStruct) {
        if (normalized === undefined) {
          this.#bboxStruct.delete("heightEmu");
        } else {
          this.#bboxStruct.set("heightEmu", emuFromPixels(normalized));
        }
      } else {
        this.#height = normalized;
      }
      this.#dirty = true;
    }
    if (value.rotation !== undefined) {
      const normalized = normalizeRotation(value.rotation);
      if (this.#bboxStruct) {
        if (normalized === undefined) {
          this.#bboxStruct.delete("rotation");
        } else {
          const rotationEmu = degreesToEmuRotation(normalized);
          if (rotationEmu !== undefined) {
            this.#bboxStruct.set("rotation", rotationEmu);
          } else {
            this.#bboxStruct.delete("rotation");
          }
        }
      } else {
        this.#rotation = normalized;
      }
      this.#dirty = true;
    }
    if (value.horizontalFlip !== undefined) {
      const normalized = Boolean(value.horizontalFlip);
      if (this.#bboxStruct) {
        this.#bboxStruct.set("horizontalFlip", normalized);
      } else {
        this.#horizontalFlip = normalized;
      }
      this.#dirty = true;
    }
    if (value.verticalFlip !== undefined) {
      const normalized = Boolean(value.verticalFlip);
      if (this.#bboxStruct) {
        this.#bboxStruct.set("verticalFlip", normalized);
      } else {
        this.#verticalFlip = normalized;
      }
      this.#dirty = true;
    }
  }
  toProto() {
    const hasPreview = this.#previewConfig !== undefined && (this.#previewConfig.left !== undefined || this.#previewConfig.top !== undefined || this.#previewConfig.width !== undefined || this.#previewConfig.height !== undefined || this.#previewConfig.rotation !== undefined || this.#previewConfig.horizontalFlip !== undefined || this.#previewConfig.verticalFlip !== undefined);
    if (this.#bboxStruct) {
      const bbox2 = {};
      const left = this.#getPreviewEmu("xEmu") ?? this.#getBboxNumber("xEmu");
      if (left !== undefined) {
        bbox2.xEmu = left;
      }
      const top = this.#getPreviewEmu("yEmu") ?? this.#getBboxNumber("yEmu");
      if (top !== undefined) {
        bbox2.yEmu = top;
      }
      const width = this.#getPreviewEmu("widthEmu") ?? this.#getBboxNumber("widthEmu");
      if (width !== undefined) {
        bbox2.widthEmu = width;
      }
      const height = this.#getPreviewEmu("heightEmu") ?? this.#getBboxNumber("heightEmu");
      if (height !== undefined) {
        bbox2.heightEmu = height;
      }
      const previewRotation2 = this.#getPreviewRotationValue();
      const rotation = previewRotation2 !== undefined ? degreesToEmuRotation(previewRotation2) : this.#getBboxNumber("rotation");
      if (rotation !== undefined && Number.isFinite(rotation)) {
        bbox2.rotation = rotation;
      }
      const horizontalFlip = this.#getPreviewFlipValue("horizontalFlip") ?? this.#getBboxBoolean("horizontalFlip");
      if (horizontalFlip !== undefined) {
        bbox2.horizontalFlip = horizontalFlip;
      }
      const verticalFlip = this.#getPreviewFlipValue("verticalFlip") ?? this.#getBboxBoolean("verticalFlip");
      if (verticalFlip !== undefined) {
        bbox2.verticalFlip = verticalFlip;
      }
      if (Object.keys(bbox2).length === 0) {
        return;
      }
      return bbox2;
    }
    if (!this.#dirty && !hasPreview) {
      return;
    }
    const bbox = {};
    const previewLeft = this.#getPreviewEmu("xEmu");
    if (previewLeft !== undefined) {
      bbox.xEmu = previewLeft;
    } else if (this.#left !== undefined) {
      bbox.xEmu = emuFromPixels(this.#left);
    }
    const previewTop = this.#getPreviewEmu("yEmu");
    if (previewTop !== undefined) {
      bbox.yEmu = previewTop;
    } else if (this.#top !== undefined) {
      bbox.yEmu = emuFromPixels(this.#top);
    }
    const previewWidth = this.#getPreviewEmu("widthEmu");
    if (previewWidth !== undefined) {
      bbox.widthEmu = previewWidth;
    } else if (this.#width !== undefined) {
      bbox.widthEmu = emuFromPixels(this.#width);
    }
    const previewHeight = this.#getPreviewEmu("heightEmu");
    if (previewHeight !== undefined) {
      bbox.heightEmu = previewHeight;
    } else if (this.#height !== undefined) {
      bbox.heightEmu = emuFromPixels(this.#height);
    }
    const previewRotation = this.#getPreviewRotationValue();
    if (previewRotation !== undefined || this.#rotation !== undefined) {
      const rotationEmu = degreesToEmuRotation(previewRotation ?? this.#rotation);
      if (rotationEmu !== undefined) {
        bbox.rotation = rotationEmu;
      }
    }
    const previewHorizontalFlip = this.#getPreviewFlipValue("horizontalFlip");
    if (previewHorizontalFlip !== undefined || this.#horizontalFlip !== undefined) {
      bbox.horizontalFlip = previewHorizontalFlip ?? this.#horizontalFlip;
    }
    const previewVerticalFlip = this.#getPreviewFlipValue("verticalFlip");
    if (previewVerticalFlip !== undefined || this.#verticalFlip !== undefined) {
      bbox.verticalFlip = previewVerticalFlip ?? this.#verticalFlip;
    }
    if (Object.keys(bbox).length === 0) {
      return;
    }
    return bbox;
  }
  toJSON() {
    return {
      left: this.left,
      top: this.top,
      width: this.width,
      height: this.height,
      rotation: this.rotation,
      horizontalFlip: this.horizontalFlip,
      verticalFlip: this.verticalFlip
    };
  }
  get left() {
    return this.#getPixelValue("xEmu", this.#left) ?? 0;
  }
  set left(value) {
    const normalized = normalizePixels(value);
    if (this.#bboxStruct) {
      if (normalized === undefined) {
        this.#bboxStruct.delete("xEmu");
      } else {
        this.#bboxStruct.set("xEmu", emuFromPixels(normalized));
      }
    } else {
      this.#left = normalized;
    }
    this.#dirty = true;
    if (normalized !== undefined) {
      this.#emitChange({ left: normalized });
    }
  }
  get top() {
    return this.#getPixelValue("yEmu", this.#top) ?? 0;
  }
  set top(value) {
    const normalized = normalizePixels(value);
    if (this.#bboxStruct) {
      if (normalized === undefined) {
        this.#bboxStruct.delete("yEmu");
      } else {
        this.#bboxStruct.set("yEmu", emuFromPixels(normalized));
      }
    } else {
      this.#top = normalized;
    }
    this.#dirty = true;
    if (normalized !== undefined) {
      this.#emitChange({ top: normalized });
    }
  }
  get width() {
    return this.#getPixelValue("widthEmu", this.#width) ?? 0;
  }
  set width(value) {
    const normalized = normalizePixels(value);
    if (this.#bboxStruct) {
      if (normalized === undefined) {
        this.#bboxStruct.delete("widthEmu");
      } else {
        this.#bboxStruct.set("widthEmu", emuFromPixels(normalized));
      }
    } else {
      this.#width = normalized;
    }
    this.#dirty = true;
    if (normalized !== undefined) {
      this.#emitChange({ width: normalized });
    }
  }
  get height() {
    return this.#getPixelValue("heightEmu", this.#height) ?? 0;
  }
  set height(value) {
    const normalized = normalizePixels(value);
    if (this.#bboxStruct) {
      if (normalized === undefined) {
        this.#bboxStruct.delete("heightEmu");
      } else {
        this.#bboxStruct.set("heightEmu", emuFromPixels(normalized));
      }
    } else {
      this.#height = normalized;
    }
    this.#dirty = true;
    if (normalized !== undefined) {
      this.#emitChange({ height: normalized });
    }
  }
  get rotation() {
    return this.#getRotationValue(this.#rotation);
  }
  set rotation(value) {
    const normalized = normalizeRotation(value);
    if (this.#bboxStruct) {
      if (normalized === undefined) {
        this.#bboxStruct.delete("rotation");
      } else {
        const rotationEmu = degreesToEmuRotation(normalized);
        if (rotationEmu !== undefined) {
          this.#bboxStruct.set("rotation", rotationEmu);
        } else {
          this.#bboxStruct.delete("rotation");
        }
      }
    } else {
      this.#rotation = normalized;
    }
    this.#dirty = true;
    if (normalized !== undefined) {
      this.#emitChange({ rotation: normalized });
    }
  }
  get horizontalFlip() {
    return this.#getFlipValue("horizontalFlip", this.#horizontalFlip);
  }
  set horizontalFlip(value) {
    const normalized = value === undefined || value === null ? undefined : Boolean(value);
    if (this.#bboxStruct) {
      if (normalized === undefined) {
        this.#bboxStruct.delete("horizontalFlip");
      } else {
        this.#bboxStruct.set("horizontalFlip", normalized);
      }
    } else {
      this.#horizontalFlip = normalized;
    }
    this.#dirty = true;
    if (normalized !== undefined) {
      this.#emitChange({ horizontalFlip: normalized });
    }
  }
  get verticalFlip() {
    return this.#getFlipValue("verticalFlip", this.#verticalFlip);
  }
  set verticalFlip(value) {
    const normalized = value === undefined || value === null ? undefined : Boolean(value);
    if (this.#bboxStruct) {
      if (normalized === undefined) {
        this.#bboxStruct.delete("verticalFlip");
      } else {
        this.#bboxStruct.set("verticalFlip", normalized);
      }
    } else {
      this.#verticalFlip = normalized;
    }
    this.#dirty = true;
    if (normalized !== undefined) {
      this.#emitChange({ verticalFlip: normalized });
    }
  }
}

// node_modules/@oai/granola/dist/models/presentation/text-autofit.js
function measureTextLayout(params) {
  const { element, presentation, slide, wrap, textScale } = params;
  const schemeRemap = getMasterSchemeRemap(presentation, slide);
  const themeMap = buildThemeMap(presentation.theme, schemeRemap);
  const ctx = getSharedMeasurementContext();
  const bbox = getBBox(element, presentation, slide);
  const resolvedStyle = params.resolvedStyle ?? resolveStyles(element, presentation, slide);
  const paddingPx = resolveTextPaddingPx(resolvedStyle);
  const layout = drawText(element, ctx, themeMap, undefined, {
    mode: "layout",
    resolvedStyle,
    masterDefaults: getMasterLevelDefaults(element, presentation, slide),
    bboxPx: bbox,
    paddingPx,
    textScale,
    wrap
  });
  const contentWidthPx = Math.max(0, bbox.width - (paddingPx.left + paddingPx.right));
  const contentHeightPx = Math.max(0, bbox.height - (paddingPx.top + paddingPx.bottom));
  const lines = layout?.lines ?? [];
  const maxLineWidthPx = lines.reduce((max3, line) => Math.max(max3, line.widthPx), 0);
  const textHeightPx = layout?.unrotatedHeight ?? layout?.height ?? 0;
  return {
    contentWidthPx,
    contentHeightPx,
    maxLineWidthPx,
    textHeightPx,
    paddingPx
  };
}
function computeShrinkTextScale(params) {
  const { element, presentation, slide, wrap } = params;
  const minScale = params.minScale ?? 0.1;
  const maxIterations = params.maxIterations ?? 20;
  let low = minScale;
  let high = 1;
  let best = minScale;
  for (let iteration = 0;iteration < maxIterations; iteration += 1) {
    const mid = (low + high) / 2;
    const metrics = measureTextLayout({
      element,
      presentation,
      slide,
      wrap,
      textScale: mid
    });
    const fits = metrics.maxLineWidthPx <= metrics.contentWidthPx && metrics.textHeightPx <= metrics.contentHeightPx;
    if (fits) {
      best = mid;
      low = mid;
    } else {
      high = mid;
    }
  }
  return best;
}
function computeShapeAutoFitBounds(params) {
  const metrics = measureTextLayout({
    element: params.element,
    presentation: params.presentation,
    slide: params.slide,
    wrap: params.wrap,
    textScale: 1,
    resolvedStyle: params.resolvedStyle
  });
  return {
    width: metrics.maxLineWidthPx + metrics.paddingPx.left + metrics.paddingPx.right,
    height: metrics.textHeightPx + metrics.paddingPx.top + metrics.paddingPx.bottom
  };
}
function computeShapeAutoFitHeight(params) {
  return computeShapeAutoFitBounds(params).height;
}

// node_modules/@oai/granola/dist/models/presentation/element-aid.js
var ELEMENT_AID_SUFFIX_LENGTH = 8;
function buildElementAid(prefix, slideId, localId) {
  const sourceId = slideId ? `${slideId}.${localId}` : localId;
  const suffix = deriveDeterministicAidSuffix(`${prefix}:${sourceId}`, ELEMENT_AID_SUFFIX_LENGTH);
  return `${prefix}/${suffix}`;
}
function resolveElementLocalId(value, options) {
  const trimmed = value.trim();
  if (!trimmed) {
    return;
  }
  const suffix = parseAidSuffix(trimmed, options.prefix, options.aliases ?? []);
  if (!suffix) {
    return;
  }
  const localIds = Array.from(options.localIds).filter((localId) => typeof localId === "string" && localId.length > 0);
  if (localIds.length === 0) {
    return;
  }
  if (localIds.includes(suffix)) {
    return suffix;
  }
  if (!options.slideId) {
    return;
  }
  const expectedAid = `${options.prefix}/${suffix}`;
  return localIds.find((localId) => buildElementAid(options.prefix, options.slideId, localId) === expectedAid);
}
function parseAidSuffix(value, prefix, aliases) {
  const slashIndex = value.indexOf("/");
  if (slashIndex === -1) {
    return value;
  }
  if (slashIndex <= 0 || slashIndex === value.length - 1) {
    return;
  }
  const prefixToken = value.slice(0, slashIndex).trim().toLowerCase();
  const validPrefixes = new Set([
    prefix,
    ...aliases.map((alias) => alias.toLowerCase())
  ]);
  if (!validPrefixes.has(prefixToken)) {
    return;
  }
  return value.slice(slashIndex + 1).trim();
}

// node_modules/@oai/granola/dist/models/presentation/element.js
class Element2 {
  context;
  data;
  #paragraphs;
  #text;
  #textStyle;
  #position;
  #textLayoutDirty = false;
  #autoFitUpdating = false;
  constructor(context, proto) {
    this.context = context;
    this.#position = Position.fromProto(proto.bbox);
    this.#position.setChangeHandler((patch) => {
      this.recordPositionSet(patch);
    });
    const elementId = this.#resolveElementId(proto.id);
    this.data = {
      id: elementId,
      name: proto.name ?? "",
      zIndex: proto.zIndex,
      type: proto.type ?? 0 /* ELEMENT_TYPE_UNSPECIFIED */,
      effects: proto.effects ?? [],
      children: proto.children ?? [],
      levelsStyles: proto.levelsStyles ?? [],
      citations: proto.citations ?? [],
      placeholderIndex: proto.placeholderIndex,
      placeholderType: proto.placeholderType,
      hyperlink: proto.hyperlink,
      fill: proto.fill,
      lineReference: proto.lineReference,
      fillReference: proto.fillReference,
      effectReference: proto.effectReference,
      fontReference: proto.fontReference,
      shape: proto.shape,
      chartReference: proto.chartReference,
      imageReference: proto.imageReference,
      video: proto.video,
      table: proto.table,
      codeBlock: proto.codeBlock,
      connector: proto.connector,
      creationId: proto.creationId ?? generateGuid()
    };
    this.#paragraphs = new ParagraphCollection(this.#paragraphCollectionContext(), proto.paragraphs ?? []);
    this.#textStyle = proto.textStyle ? new TextStyle2(proto.textStyle) : undefined;
  }
  get name() {
    return this.data.name ?? "";
  }
  set name(value) {
    this.data.name = value;
    this.recordShapeSet({ name: value });
  }
  get slideId() {
    return this.context.getSlide?.().id;
  }
  get paragraphs() {
    return this.#paragraphs;
  }
  get placeholderIndex() {
    return this.data.placeholderIndex;
  }
  get placeholderType() {
    return this.data.placeholderType;
  }
  get text() {
    if (!this.#text) {
      this.#text = new Text(this.#paragraphs, {
        getDefaultTextStyle: () => this.#textStyle,
        setDefaultTextStyle: (style) => {
          if (style instanceof TextStyle2 || style === undefined) {
            this.#textStyle = style ?? undefined;
            return;
          }
          if (style === null) {
            this.#textStyle = undefined;
            return;
          }
          this.#textStyle = new TextStyle2(style);
        },
        resolveTextStyle: (name) => this.context.getTextStyleByName(name),
        onLayoutInvalidated: () => this.#handleTextLayoutInvalidated(),
        record: {
          recordOp: (op) => this.recordPatchOp(op),
          getTargetRef: () => this.recordTargetRef(),
          getAnchorId: () => this.recordTargetRef()
        }
      });
    }
    return this.#text;
  }
  set text(value) {
    this.text.set(value);
  }
  get textStyle() {
    return this.#textStyle;
  }
  set textStyle(value) {
    this.#textStyle = value;
  }
  get rotation() {
    return this.#position.rotation;
  }
  get zIndex() {
    return this.data.zIndex;
  }
  set zIndex(value) {
    this.data.zIndex = value;
    this.recordShapeSet({ zIndex: value });
  }
  set rotation(value) {
    if (value === undefined || value === null) {
      this.#position.rotation = undefined;
      return;
    }
    this.#position.rotation = value;
    this.recordShapeSet({ position: { rotation: value } });
  }
  get levelsStyles() {
    return this.data.levelsStyles;
  }
  get position() {
    return this.#position;
  }
  set position(value) {
    if (value === undefined) {
      this.#position.reset();
      this.#handleTextLayoutInvalidated();
      return;
    }
    if (value instanceof Position) {
      this.#position = value.clone();
      this.#handleTextLayoutInvalidated();
      return;
    }
    this.#position.merge(value);
    this.#handleTextLayoutInvalidated();
    this.recordPositionSet(this.#normalizePositionPatch(value));
  }
  get frame() {
    const { left, top, width, height } = this.position;
    if (left === undefined || top === undefined || width === undefined || height === undefined) {
      return;
    }
    return { left, top, width, height };
  }
  set frame(value) {
    if (value === undefined) {
      this.#position.reset();
      this.#handleTextLayoutInvalidated();
      return;
    }
    const next = {};
    if (value.left !== undefined) {
      next.left = value.left;
    }
    if (value.top !== undefined) {
      next.top = value.top;
    }
    if (value.width !== undefined) {
      next.width = value.width;
    }
    if (value.height !== undefined) {
      next.height = value.height;
    }
    if (Object.keys(next).length === 0) {
      return;
    }
    this.#position.merge(next);
    this.#handleTextLayoutInvalidated();
    this.recordPositionSet(next);
  }
  get previewFrame() {
    return this.#position.getPreviewRect();
  }
  set previewFrame(value) {
    this.#position.setPreview(value);
  }
  clearPreviewFrame() {
    this.#position.clearPreview();
  }
  commitPreviewFrame() {
    const preview = this.#position.getPreviewRect();
    if (!preview) {
      return;
    }
    this.frame = preview;
    this.#position.clearPreview();
  }
  #resolveElementId(id) {
    const slide = this.context.getSlide?.();
    if (id && id.trim().length > 0 && (!slide?.id || isNumericId(id))) {
      return id;
    }
    const existingIds = slide?.elements?.items.map((element) => element.id) ?? [];
    return generateElementId(existingIds);
  }
  getParagraphs() {
    return this.#paragraphs;
  }
  #paragraphCollectionContext() {
    return {
      ...this.context,
      getResolvedParagraphTextStyle: (paragraph) => this.context.getResolvedParagraphTextStyle?.(paragraph, this.#textStyle),
      getResolvedParagraphStyle: (paragraph) => this.context.getResolvedParagraphStyle?.(paragraph),
      getResolvedRunTextStyle: (paragraph, run) => this.context.getResolvedRunTextStyle?.(paragraph, run, this.#textStyle)
    };
  }
  toProto() {
    if (this.#textLayoutDirty) {
      this.#applyAutoFit();
    }
    const proto = {
      ...this.data,
      textStyle: this.#textStyle?.toProto(),
      paragraphs: this.#paragraphs.toProto()
    };
    const bbox = this.#position.toProto();
    if (bbox) {
      proto.bbox = bbox;
    }
    return proto;
  }
  #handleTextLayoutInvalidated() {
    if (this.#autoFitUpdating) {
      return;
    }
    this.#textLayoutDirty = true;
    this.#applyAutoFit();
  }
  #applyAutoFit() {
    const textStyle = this.#textStyle;
    if (!textStyle) {
      this.#textLayoutDirty = false;
      return;
    }
    const autoFit = textStyle.autoFit;
    if (!autoFit) {
      textStyle.autoFitScale = undefined;
      textStyle.autoFitLineSpaceReduction = undefined;
      this.#textLayoutDirty = false;
      return;
    }
    if (this.#paragraphs.toPlainText().length === 0) {
      textStyle.autoFitScale = undefined;
      textStyle.autoFitLineSpaceReduction = undefined;
      this.#textLayoutDirty = false;
      return;
    }
    const presentation = this.context.getPresentation?.();
    const slide = this.context.getSlide?.();
    if (!presentation || !slide) {
      return;
    }
    const elementProto = this.#buildTextElementProto();
    const wrap = textStyle.wrap !== "none";
    this.#autoFitUpdating = true;
    try {
      if (autoFit === "shrinkText") {
        const scale = computeShrinkTextScale({
          element: elementProto,
          presentation,
          slide,
          wrap
        });
        textStyle.autoFitScale = scale;
      } else if (autoFit === "resizeShapeToFitText") {
        const targetHeight = computeShapeAutoFitHeight({
          element: elementProto,
          presentation,
          slide,
          wrap
        });
        const frame = this.frame;
        const frameHeight = frame?.height;
        if (frameHeight !== undefined && targetHeight > frameHeight) {
          this.#position.merge({ height: targetHeight });
        }
      } else {
        textStyle.autoFitScale = undefined;
        textStyle.autoFitLineSpaceReduction = undefined;
      }
    } finally {
      this.#autoFitUpdating = false;
      this.#textLayoutDirty = false;
    }
  }
  #buildTextElementProto() {
    const proto = {
      ...this.data,
      textStyle: this.#textStyle?.toProto(),
      paragraphs: this.#paragraphs.toProto()
    };
    const bbox = this.#position.toProto();
    if (bbox) {
      proto.bbox = bbox;
    }
    return proto;
  }
  recordShapeSet(props) {
    if (!Object.values(props).some((value) => value !== undefined)) {
      return;
    }
    const anchor = this.#elementAnchor();
    if (!anchor || !anchor.startsWith("sh/")) {
      return;
    }
    const target = this.recordTargetRef(anchor);
    if (!target) {
      return;
    }
    this.recordPatchOp({
      op: "shape.set",
      target,
      props
    });
  }
  recordPositionSet(position) {
    this.recordShapeSet({ position });
  }
  elementAnchor() {
    return this.#elementAnchor();
  }
  recordTargetRef(anchorOverride) {
    const anchor = anchorOverride ?? this.#elementAnchor();
    if (!anchor) {
      return;
    }
    const recorder = this.context.getPresentation?.()?.getRecorder?.();
    if (!recorder) {
      return anchor;
    }
    return recorder.targetRefForElement(this, anchor);
  }
  recordPatchOp(op) {
    const presentation = this.context.getPresentation?.();
    presentation?.queuePresentationCollabPublish();
    const recorder = presentation?.getRecorder?.();
    if (!recorder) {
      return;
    }
    recorder.record(op);
  }
  #elementAnchor() {
    const prefix = this.#elementAnchorPrefix();
    if (!prefix) {
      return;
    }
    const slideId = this.context.getSlide?.().id;
    if (!slideId || !this.data.id) {
      return;
    }
    return buildElementAid(prefix, slideId, this.data.id);
  }
  #elementAnchorPrefix() {
    switch (this.data.type) {
      case 5 /* ELEMENT_TYPE_SHAPE */:
      case 1 /* ELEMENT_TYPE_TEXT */:
      case 2 /* ELEMENT_TYPE_TEXT_GROUP */:
        return "sh";
      case 4 /* ELEMENT_TYPE_CHART */:
      case 6 /* ELEMENT_TYPE_CHART_REFERENCE */:
        return "ch";
      case 3 /* ELEMENT_TYPE_IMAGE */:
      case 7 /* ELEMENT_TYPE_IMAGE_REFERENCE */:
        return "im";
      case 9 /* ELEMENT_TYPE_TABLE */:
        return "tb";
      default:
        return;
    }
  }
  #normalizePositionPatch(value) {
    if (!value || value instanceof Position) {
      return;
    }
    const patch = {};
    if (value.left !== undefined)
      patch.left = value.left;
    if (value.top !== undefined)
      patch.top = value.top;
    if (value.width !== undefined)
      patch.width = value.width;
    if (value.height !== undefined)
      patch.height = value.height;
    if (value.rotation !== undefined)
      patch.rotation = value.rotation;
    if (value.horizontalFlip !== undefined) {
      patch.horizontalFlip = value.horizontalFlip;
    }
    if (value.verticalFlip !== undefined) {
      patch.verticalFlip = value.verticalFlip;
    }
    return Object.keys(patch).length > 0 ? patch : undefined;
  }
}
var isNumericId = (value) => {
  const trimmed = value.trim();
  if (!trimmed) {
    return false;
  }
  const numeric = Number(trimmed);
  return Number.isFinite(numeric) && numeric > 0;
};

// node_modules/@oai/granola/dist/models/presentation/chart-element.js
var DEFAULT_CHART_FRAME = {
  left: 60,
  top: 80,
  width: 640,
  height: 360
};

class ChartElement extends Element2 {
  type = "chart";
  #chart;
  constructor(context, proto) {
    super(context, proto);
    if (this.data.type === undefined || this.data.type === 0 /* ELEMENT_TYPE_UNSPECIFIED */) {
      this.data.type = 6 /* ELEMENT_TYPE_CHART_REFERENCE */;
    }
    const existing = proto.chartReference?.id ? this.context.getChartById(proto.chartReference.id) : undefined;
    if (existing) {
      this.#chart = existing;
      this.data.chartReference = { id: existing.id };
    } else if (proto.chartReference?.id) {
      this.data.chartReference = { id: proto.chartReference.id };
    }
  }
  get id() {
    return this.data.id;
  }
  toSnapshot() {
    const slideId = this.slideId;
    const localId = this.id;
    return {
      aid: buildSlideChildAid("ch", slideId, localId),
      kind: "chart",
      id: localId,
      slideId,
      name: this.name,
      title: this.title ?? "",
      chartType: this.chartType,
      frame: this.frame
    };
  }
  get chart() {
    return this.#chart ?? this.#resolveChart();
  }
  get chartType() {
    return this.#ensureChart().type;
  }
  set chartType(value) {
    this.#ensureChart().type = value;
  }
  get title() {
    return this.#ensureChart().title;
  }
  set title(value) {
    this.#ensureChart().title = value;
  }
  get titleTextStyle() {
    return this.#ensureChart().titleTextStyle;
  }
  get titlePlacement() {
    return this.#ensureChart().titlePlacement;
  }
  set titlePlacement(value) {
    this.#ensureChart().titlePlacement = value;
  }
  get styleIndex() {
    return this.#ensureChart().styleIndex;
  }
  set styleIndex(value) {
    this.#ensureChart().styleIndex = value;
  }
  get categories() {
    return this.#ensureChart().categories;
  }
  set categories(value) {
    this.#ensureChart().categories = value;
  }
  get hasLegend() {
    return this.#ensureChart().hasLegend;
  }
  set hasLegend(value) {
    this.#ensureChart().hasLegend = value;
  }
  get displayBlanksAs() {
    return this.#ensureChart().displayBlanksAs;
  }
  set displayBlanksAs(value) {
    this.#ensureChart().displayBlanksAs = value;
  }
  get showDlblsOverMax() {
    return this.#ensureChart().showDlblsOverMax;
  }
  set showDlblsOverMax(value) {
    this.#ensureChart().showDlblsOverMax = value;
  }
  get style() {
    return this.#ensureChart().style;
  }
  get chartFill() {
    return this.#ensureChart().chartFill;
  }
  set chartFill(value) {
    this.#ensureChart().chartFill = value;
  }
  get chartLine() {
    return this.#ensureChart().chartLine;
  }
  get plotAreaFill() {
    return this.#ensureChart().plotAreaFill;
  }
  set plotAreaFill(value) {
    this.#ensureChart().plotAreaFill = value;
  }
  get plotAreaLine() {
    return this.#ensureChart().plotAreaLine;
  }
  get legend() {
    return this.#ensureChart().legend;
  }
  set legend(value) {
    const chart = this.#ensureChart();
    if (value instanceof ChartLegend) {
      chart.legend = value;
      return;
    }
    applyLegendConfig(chart.legend, value);
  }
  get dataLabels() {
    return this.#ensureChart().dataLabels;
  }
  set dataLabels(value) {
    const chart = this.#ensureChart();
    if (value instanceof ChartDataLabels) {
      chart.dataLabels = value;
      return;
    }
    applyDataLabelsConfig(chart.dataLabels, value);
  }
  get dataTable() {
    return this.#ensureChart().dataTable;
  }
  set dataTable(value) {
    const chart = this.#ensureChart();
    if (value instanceof ChartDataTable) {
      chart.dataTable = value;
      return;
    }
    applyDataTableConfig(chart.dataTable, value);
  }
  get xAxis() {
    return this.#ensureChart().xAxis;
  }
  set xAxis(value) {
    const chart = this.#ensureChart();
    if (value instanceof ChartAxis) {
      chart.xAxis = value;
      return;
    }
    applyAxisConfig(chart.xAxis, value);
  }
  get yAxis() {
    return this.#ensureChart().yAxis;
  }
  set yAxis(value) {
    const chart = this.#ensureChart();
    if (value instanceof ChartAxis) {
      chart.yAxis = value;
      return;
    }
    applyAxisConfig(chart.yAxis, value);
  }
  get barOptions() {
    return this.#ensureChart().barOptions;
  }
  get lineOptions() {
    return this.#ensureChart().lineOptions;
  }
  get areaOptions() {
    return this.#ensureChart().areaOptions;
  }
  get scatterOptions() {
    return this.#ensureChart().scatterOptions;
  }
  get pieOptions() {
    return this.#ensureChart().pieOptions;
  }
  set pieOptions(value) {
    const chart = this.#ensureChart();
    if (value instanceof ChartPieOptions) {
      chart.pieOptions = value;
      return;
    }
    applyPieOptionsConfig(chart.pieOptions, value);
  }
  get doughnutOptions() {
    return this.#ensureChart().doughnutOptions;
  }
  set doughnutOptions(value) {
    const chart = this.#ensureChart();
    if (value instanceof ChartDoughnutOptions) {
      chart.doughnutOptions = value;
      return;
    }
    applyDoughnutOptionsConfig(chart.doughnutOptions, value);
  }
  get treemapOptions() {
    return this.#ensureChart().treemapOptions;
  }
  get mapOptions() {
    return this.#ensureChart().mapOptions;
  }
  get funnelOptions() {
    return this.#ensureChart().funnelOptions;
  }
  get boxWhiskerOptions() {
    return this.#ensureChart().boxWhiskerOptions;
  }
  get histogramOptions() {
    return this.#ensureChart().histogramOptions;
  }
  set histogramOptions(value) {
    const chart = this.#ensureChart();
    applyHistogramOptionsConfig(chart, value);
  }
  get series() {
    return this.#ensureChart().series;
  }
  get view3d() {
    return this.#ensureChart().view3d;
  }
  set view3d(value) {
    this.#ensureChart().view3d = value;
  }
  setChartReference(id) {
    this.data.chartReference = id ? { id } : undefined;
    this.#chart = id ? this.context.getChartById(id) : undefined;
  }
  apply(config) {
    if (!config)
      return;
    if (!config.position && this.frame === undefined) {
      this.position = DEFAULT_CHART_FRAME;
    }
    if (config.position)
      this.position = config.position;
    if (config.title !== undefined)
      this.title = config.title;
    if (config.titlePlacement !== undefined)
      this.titlePlacement = config.titlePlacement;
    if (config.titleTextStyle)
      applyTextStyleConfig2(this.titleTextStyle, config.titleTextStyle);
    if (config.styleIndex !== undefined)
      this.styleIndex = config.styleIndex;
    if (config.displayBlanksAs !== undefined)
      this.displayBlanksAs = config.displayBlanksAs;
    if (config.showDlblsOverMax !== undefined)
      this.showDlblsOverMax = config.showDlblsOverMax;
    if (config.chartFill !== undefined)
      this.chartFill = config.chartFill;
    if (config.chartLine !== undefined)
      applyLineConfig(this.chartLine, config.chartLine);
    if (config.plotAreaFill !== undefined)
      this.plotAreaFill = config.plotAreaFill;
    if (config.plotAreaLine !== undefined)
      applyLineConfig(this.plotAreaLine, config.plotAreaLine);
    if (config.categories)
      this.categories = [...config.categories];
    if (config.series) {
      this.series.clear();
      for (const seriesConfig of config.series) {
        const series = this.series.add(seriesConfig.name);
        if (seriesConfig.values !== undefined)
          series.values = seriesConfig.values;
        if (seriesConfig.xValues !== undefined)
          series.xValues = seriesConfig.xValues;
        if (seriesConfig.bubbleSizes !== undefined)
          series.bubbleSizes = seriesConfig.bubbleSizes;
        if (seriesConfig.categoryPaths !== undefined)
          series.categoryPaths = seriesConfig.categoryPaths;
        if (seriesConfig.categories) {
          series.categories = seriesConfig.categories;
        } else if (config.categories) {
          series.categories = this.categories;
        }
        if (seriesConfig.fill !== undefined)
          series.fill = seriesConfig.fill;
        if (seriesConfig.line !== undefined)
          series.stroke = seriesConfig.line;
        else if (seriesConfig.stroke !== undefined)
          series.stroke = seriesConfig.stroke;
        if (seriesConfig.valuesFormatCode !== undefined)
          series.valuesFormatCode = seriesConfig.valuesFormatCode;
        if (seriesConfig.xValuesFormatCode !== undefined)
          series.xValuesFormatCode = seriesConfig.xValuesFormatCode;
        if (seriesConfig.explosion !== undefined)
          series.explosion = seriesConfig.explosion;
        if (seriesConfig.marker?.symbol !== undefined)
          series.marker.symbol = seriesConfig.marker.symbol;
        if (seriesConfig.marker?.size !== undefined)
          series.marker.size = seriesConfig.marker.size;
        if (seriesConfig.points) {
          for (const pointConfig of seriesConfig.points) {
            const point3 = series.points.add(pointConfig.idx);
            if (pointConfig.fill !== undefined)
              point3.fill = pointConfig.fill;
            if (pointConfig.line !== undefined)
              point3.stroke = pointConfig.line;
            else if (pointConfig.stroke !== undefined)
              point3.stroke = pointConfig.stroke;
          }
        }
        if (seriesConfig.dataLabelOverrides) {
          for (const dataLabelConfig of seriesConfig.dataLabelOverrides) {
            const dataLabel = series.dataLabelOverrides.add(dataLabelConfig.idx);
            if (dataLabelConfig.text !== undefined)
              dataLabel.text = dataLabelConfig.text;
            if (dataLabelConfig.position !== undefined)
              dataLabel.position = dataLabelConfig.position;
            if (dataLabelConfig.fill !== undefined)
              dataLabel.fill = dataLabelConfig.fill;
            if (dataLabelConfig.line !== undefined)
              dataLabel.stroke = dataLabelConfig.line;
            else if (dataLabelConfig.stroke !== undefined)
              dataLabel.stroke = dataLabelConfig.stroke;
            if (dataLabelConfig.showValue !== undefined)
              dataLabel.showValue = dataLabelConfig.showValue;
            if (dataLabelConfig.showSeriesName !== undefined)
              dataLabel.showSeriesName = dataLabelConfig.showSeriesName;
            if (dataLabelConfig.showCategoryName !== undefined)
              dataLabel.showCategoryName = dataLabelConfig.showCategoryName;
            if (dataLabelConfig.showPercent !== undefined)
              dataLabel.showPercent = dataLabelConfig.showPercent;
            if (dataLabelConfig.textStyle) {
              applyTextStyleConfig2(dataLabel.textStyle, dataLabelConfig.textStyle);
            }
          }
        }
        if (seriesConfig.trendlines) {
          for (const trendlineConfig of seriesConfig.trendlines) {
            const trendlineType = trendlineConfig.type ?? "linear";
            const trend = series.trendlines.add(trendlineType);
            if (trendlineConfig.name !== undefined)
              trend.name = trendlineConfig.name;
            if (trendlineConfig.polynomialOrder !== undefined)
              trend.polynomialOrder = trendlineConfig.polynomialOrder;
            if (trendlineConfig.movingAveragePeriod !== undefined)
              trend.movingAveragePeriod = trendlineConfig.movingAveragePeriod;
            if (trendlineConfig.forecastForward !== undefined)
              trend.forecastForward = trendlineConfig.forecastForward;
            if (trendlineConfig.forecastBackward !== undefined)
              trend.forecastBackward = trendlineConfig.forecastBackward;
            if (trendlineConfig.intercept !== undefined)
              trend.intercept = trendlineConfig.intercept;
            if (trendlineConfig.displayEquation !== undefined)
              trend.displayEquation = trendlineConfig.displayEquation;
            if (trendlineConfig.displayRSquared !== undefined)
              trend.displayRSquared = trendlineConfig.displayRSquared;
            if (trendlineConfig.line !== undefined)
              trend.stroke = trendlineConfig.line;
            else if (trendlineConfig.stroke !== undefined)
              trend.stroke = trendlineConfig.stroke;
            if (trendlineConfig.label) {
              if (trendlineConfig.label.text !== undefined)
                trend.label.text = trendlineConfig.label.text;
              if (trendlineConfig.label.numberFormatCode !== undefined)
                trend.label.numberFormatCode = trendlineConfig.label.numberFormatCode;
              if (trendlineConfig.label.numberFormatSourceLinked !== undefined)
                trend.label.numberFormatSourceLinked = trendlineConfig.label.numberFormatSourceLinked;
              if (trendlineConfig.label.manualLayout !== undefined) {
                trend.label.manualLayout = {
                  x: trendlineConfig.label.manualLayout.x,
                  y: trendlineConfig.label.manualLayout.y,
                  w: trendlineConfig.label.manualLayout.w,
                  h: trendlineConfig.label.manualLayout.h
                };
              }
              if (trendlineConfig.label.textStyle) {
                applyTextStyleConfig2(trend.label.textStyle, trendlineConfig.label.textStyle);
              }
              if (trendlineConfig.label.fill !== undefined)
                trend.label.fill = trendlineConfig.label.fill;
              if (trendlineConfig.label.line !== undefined)
                trend.label.stroke = trendlineConfig.label.line;
              else if (trendlineConfig.label.stroke !== undefined)
                trend.label.stroke = trendlineConfig.label.stroke;
              if (trendlineConfig.label.textRuns !== undefined)
                trend.label.textRuns = trendlineConfig.label.textRuns;
            }
          }
        }
        if (seriesConfig.errorBars) {
          if (seriesConfig.errorBars.type !== undefined)
            series.errorBars.type = seriesConfig.errorBars.type;
          if (seriesConfig.errorBars.value !== undefined)
            series.errorBars.value = seriesConfig.errorBars.value;
          if (seriesConfig.errorBars.endStyle !== undefined)
            series.errorBars.endStyle = seriesConfig.errorBars.endStyle;
          if (seriesConfig.errorBars.line !== undefined)
            series.errorBars.line = seriesConfig.errorBars.line;
        }
      }
    }
    if (config.hasLegend !== undefined) {
      this.hasLegend = config.hasLegend;
    } else if (config.legend) {
      this.hasLegend = true;
    }
    if (config.legend)
      this.legend = config.legend;
    if (config.dataLabels)
      this.dataLabels = config.dataLabels;
    if (config.dataTable)
      this.dataTable = config.dataTable;
    if (config.xAxis)
      this.xAxis = config.xAxis;
    if (config.yAxis)
      this.yAxis = config.yAxis;
    if (config.lineOptions)
      applyLineOptionsConfig(this.lineOptions, config.lineOptions);
    if (config.areaOptions)
      applyAreaOptionsConfig(this.areaOptions, config.areaOptions);
    if (config.scatterOptions)
      applyScatterOptionsConfig(this.scatterOptions, config.scatterOptions);
    if (config.pieOptions)
      this.pieOptions = config.pieOptions;
    if (config.doughnutOptions)
      this.doughnutOptions = config.doughnutOptions;
    if (config.treemapOptions)
      applyTreemapOptionsConfig(this.treemapOptions, config.treemapOptions);
    if (config.mapOptions)
      applyMapOptionsConfig(this.mapOptions, config.mapOptions);
    if (config.view3d)
      applyView3dConfig(this.view3d, config.view3d);
    if (config.funnelOptions)
      applyFunnelOptionsConfig(this.funnelOptions, config.funnelOptions);
    if (config.boxWhiskerOptions)
      applyBoxWhiskerOptionsConfig(this.boxWhiskerOptions, config.boxWhiskerOptions);
    if (config.barOptions)
      applyBarOptionsConfig(this.barOptions, config.barOptions);
    if (config.histogramOptions)
      applyHistogramOptionsConfig(this.#ensureChart(), config.histogramOptions);
  }
  toProto() {
    const proto = super.toProto();
    if (!proto.bbox) {
      proto.bbox = {
        xEmu: emuFromPixels(DEFAULT_CHART_FRAME.left ?? 0),
        yEmu: emuFromPixels(DEFAULT_CHART_FRAME.top ?? 0),
        widthEmu: emuFromPixels(DEFAULT_CHART_FRAME.width ?? 0),
        heightEmu: emuFromPixels(DEFAULT_CHART_FRAME.height ?? 0)
      };
    }
    const chart = this.#chart ?? this.#resolveChart();
    if (chart) {
      const reference = { id: chart.id };
      proto.chartReference = reference;
      this.data.chartReference = reference;
    }
    return proto;
  }
  #resolveChart() {
    const referenceId = this.data.chartReference?.id;
    if (!referenceId) {
      return;
    }
    const resolved = this.context.getChartById(referenceId);
    if (resolved) {
      this.#chart = resolved;
      return resolved;
    }
    return;
  }
  #ensureChart() {
    const existing = this.#resolveChart();
    if (existing) {
      return existing;
    }
    const created = this.context.createChartAsset("line");
    this.data.chartReference = { id: created.id };
    this.#chart = created;
    return created;
  }
}
function applyTextStyleConfig2(style, config) {
  if (!config)
    return;
  if (config.fontSize !== undefined)
    style.fontSize = config.fontSize;
  if (config.fill !== undefined)
    style.fill = config.fill;
  if (config.bold !== undefined)
    style.bold = config.bold;
  if (config.italic !== undefined)
    style.italic = config.italic;
  if (config.underline !== undefined)
    style.underline = config.underline;
  if (config.name !== undefined)
    style.name = config.name;
  if (config.family !== undefined)
    style.family = config.family;
  if (config.alignment !== undefined)
    style.alignment = config.alignment;
}
function applyLegendConfig(legend, config) {
  if (!config)
    return;
  if (config.position !== undefined)
    legend.position = config.position;
  if (config.overlay !== undefined)
    legend.overlay = config.overlay;
  if (config.fill !== undefined)
    legend.fill = config.fill;
  if (config.line !== undefined)
    legend.stroke = config.line;
  else if (config.stroke !== undefined)
    legend.stroke = config.stroke;
  if (config.textStyle)
    applyTextStyleConfig2(legend.textStyle, config.textStyle);
}
function applyDataLabelsConfig(labels, config) {
  if (!config)
    return;
  if (config.position !== undefined)
    labels.position = config.position;
  if (config.showValue !== undefined)
    labels.showValue = config.showValue;
  if (config.showSeriesName !== undefined)
    labels.showSeriesName = config.showSeriesName;
  if (config.showCategoryName !== undefined)
    labels.showCategoryName = config.showCategoryName;
  if (config.showPercent !== undefined)
    labels.showPercent = config.showPercent;
  if (config.showLeaderLines !== undefined)
    labels.showLeaderLines = config.showLeaderLines;
  if (config.fill !== undefined)
    labels.fill = config.fill;
  if (config.line !== undefined)
    labels.stroke = config.line;
  else if (config.stroke !== undefined)
    labels.stroke = config.stroke;
  if (config.textStyle)
    applyTextStyleConfig2(labels.textStyle, config.textStyle);
}
function applyAxisConfig(axis, config) {
  if (!config)
    return;
  const hasExplicitVisibility = typeof config.deleted === "boolean" || typeof config.visible === "boolean";
  const hasOtherAxisConfig = Object.keys(config).some((key) => key !== "deleted" && key !== "visible");
  if (!hasExplicitVisibility && hasOtherAxisConfig) {
    axis.deleted = false;
  }
  if (config.axisType !== undefined)
    axis.axisType = config.axisType;
  if (config.title !== undefined) {
    if (typeof config.title === "string") {
      axis.title.text = config.title;
    } else {
      if (config.title.text !== undefined)
        axis.title.text = config.title.text;
      if (config.title.textStyle)
        applyTextStyleConfig2(axis.title.textStyle, config.title.textStyle);
    }
  }
  if (config.numberFormatCode !== undefined)
    axis.numberFormatCode = config.numberFormatCode;
  if (config.numberFormatSourceLinked !== undefined)
    axis.numberFormatSourceLinked = config.numberFormatSourceLinked;
  if (config.min !== undefined)
    axis.min = config.min;
  if (config.max !== undefined)
    axis.max = config.max;
  if (config.majorUnit !== undefined)
    axis.majorUnit = config.majorUnit;
  if (config.minorUnit !== undefined)
    axis.minorUnit = config.minorUnit;
  if (config.deleted !== undefined)
    axis.deleted = config.deleted;
  if (config.position !== undefined)
    axis.position = config.position;
  if (config.orientation !== undefined)
    axis.orientation = config.orientation;
  if (config.majorTickMark !== undefined)
    axis.majorTickMark = config.majorTickMark;
  if (config.minorTickMark !== undefined)
    axis.minorTickMark = config.minorTickMark;
  if (config.tickLabelPosition !== undefined)
    axis.tickLabelPosition = config.tickLabelPosition;
  if (config.tickLabelInterval !== undefined)
    axis.tickLabelInterval = config.tickLabelInterval;
  if (config.tickLabelDistanceFromAxis !== undefined)
    axis.tickLabelDistanceFromAxis = config.tickLabelDistanceFromAxis;
  if (config.crossBetween !== undefined)
    axis.crossBetween = config.crossBetween;
  if (config.crosses !== undefined)
    axis.crosses = config.crosses;
  if (config.crossesAt !== undefined)
    axis.crossesAt = config.crossesAt;
  if (config.line !== undefined)
    axis.line = new Line4(config.line);
  if (config.majorGridlines !== undefined)
    axis.majorGridlines = config.majorGridlines === null ? undefined : new Line4(config.majorGridlines);
  if (config.minorGridlines !== undefined)
    axis.minorGridlines = config.minorGridlines === null ? undefined : new Line4(config.minorGridlines);
  if (config.textStyle)
    applyTextStyleConfig2(axis.textStyle, config.textStyle);
}
function applyDataTableConfig(table, config) {
  if (!config)
    return;
  if (config.visible !== undefined)
    table.visible = config.visible;
  if (config.showLegendKey !== undefined)
    table.showLegendKey = config.showLegendKey;
  if (config.fill !== undefined)
    table.fill = config.fill;
  if (config.line !== undefined)
    table.stroke = config.line;
  else if (config.stroke !== undefined)
    table.stroke = config.stroke;
  if (config.textStyle)
    applyTextStyleConfig2(table.textStyle, config.textStyle);
}
function applyLineConfig(line, config) {
  if (!config)
    return;
  const next = new Line4(config);
  line.width = next.width;
  line.fill = next.fill.toConfig();
  line.style = next.style;
}
function applyBarOptionsConfig(options, config) {
  if (config.direction !== undefined)
    options.direction = config.direction;
  if (config.grouping !== undefined)
    options.grouping = config.grouping;
  if (config.varyColors !== undefined)
    options.varyColors = config.varyColors;
  if (config.gapWidth !== undefined)
    options.gapWidth = config.gapWidth;
  if (config.gapDepth !== undefined)
    options.gapDepth = config.gapDepth;
  if (config.overlap !== undefined)
    options.overlap = config.overlap;
  if (config.bar3dShape !== undefined)
    options.bar3dShape = config.bar3dShape;
}
function applyLineOptionsConfig(options, config) {
  if (!config)
    return;
  if (config.grouping !== undefined)
    options.grouping = config.grouping;
  if (config.smooth !== undefined)
    options.smooth = config.smooth;
  if (config.varyColors !== undefined)
    options.varyColors = config.varyColors;
}
function applyAreaOptionsConfig(options, config) {
  if (!config)
    return;
  if (config.grouping !== undefined)
    options.grouping = config.grouping;
  if (config.varyColors !== undefined)
    options.varyColors = config.varyColors;
}
function applyScatterOptionsConfig(options, config) {
  if (!config)
    return;
  if (config.style !== undefined)
    options.style = config.style;
  if (config.varyColors !== undefined)
    options.varyColors = config.varyColors;
}
function applyPieOptionsConfig(options, config) {
  if (!config)
    return;
  if (config.firstSliceAngle !== undefined) {
    options.firstSliceAngle = config.firstSliceAngle;
  }
}
function applyTreemapOptionsConfig(options, config) {
  if (!config)
    return;
  if (config.parentLabelLayout !== undefined) {
    options.parentLabelLayout = config.parentLabelLayout;
  }
}
function applyMapOptionsConfig(options, config) {
  if (!config)
    return;
  if (config.mapArea !== undefined)
    options.mapArea = config.mapArea;
  if (config.projection !== undefined)
    options.projection = config.projection;
  if (config.labelLayout !== undefined)
    options.labelLayout = config.labelLayout;
  if (config.dataLevel !== undefined)
    options.dataLevel = config.dataLevel;
  if (config.showUnknown !== undefined)
    options.showUnknown = config.showUnknown;
  if (config.onlyRegionsWithData !== undefined)
    options.onlyRegionsWithData = config.onlyRegionsWithData;
}
function applyView3dConfig(options, config) {
  if (!config)
    return;
  if (config.rotX !== undefined)
    options.rotX = config.rotX;
  if (config.rotY !== undefined)
    options.rotY = config.rotY;
  if (config.perspective !== undefined)
    options.perspective = config.perspective;
  if (config.rightAngleAxes !== undefined)
    options.rightAngleAxes = config.rightAngleAxes;
}
function applyDoughnutOptionsConfig(options, config) {
  if (!config)
    return;
  if (config.holeSize !== undefined) {
    options.holeSize = config.holeSize;
  }
  if (config.firstSliceAngle !== undefined) {
    options.firstSliceAngle = config.firstSliceAngle;
  }
}
function applyFunnelOptionsConfig(options, config) {
  if (!config)
    return;
  if (config.gapWidth !== undefined)
    options.gapWidth = config.gapWidth;
}
function applyBoxWhiskerOptionsConfig(options, config) {
  if (!config)
    return;
  if (config.showMeanLine !== undefined)
    options.showMeanLine = config.showMeanLine;
  if (config.showMeanMarker !== undefined)
    options.showMeanMarker = config.showMeanMarker;
  if (config.showNonOutliers !== undefined)
    options.showNonOutliers = config.showNonOutliers;
  if (config.showOutliers !== undefined)
    options.showOutliers = config.showOutliers;
  if (config.quartileMethod !== undefined)
    options.quartileMethod = config.quartileMethod;
}
function applyHistogramOptionsConfig(chart, config) {
  if (!config)
    return;
  const next = { ...chart.histogramOptions ?? {} };
  let changed = false;
  if (config.binWidth !== undefined) {
    next.binWidth = config.binWidth;
    changed = true;
  }
  if (config.intervalClosed !== undefined) {
    next.intervalClosed = config.intervalClosed;
    changed = true;
  }
  if (config.aggregated !== undefined) {
    next.aggregated = config.aggregated;
    changed = true;
  }
  if (changed) {
    chart.histogramOptions = next;
  }
}
function buildSlideChildAid(prefix, slideId, localId) {
  return buildElementAid(prefix, slideId, localId);
}

// node_modules/@oai/granola/dist/models/presentation/chart-element-collection.js
class ChartElementCollection {
  #context;
  #items;
  constructor(context, proto) {
    this.#context = context;
    this.#items = [];
    proto.forEach((element) => {
      this.add({ proto: element });
    });
  }
  get items() {
    return [...this.#items];
  }
  add(input, config) {
    if (typeof input === "object") {
      const chartElement = new ChartElement(this.#context, input.proto);
      this.#items.push(chartElement);
      this.#context._register(chartElement);
      return chartElement;
    }
    const asset = this.#context.createChartAsset(input);
    asset.type = input;
    const attached = this.#attachChartToSlide(asset);
    attached.apply(config);
    return attached;
  }
  attach(chart) {
    const attached = this.#context.attachChartAsset(chart);
    return this.#attachChartToSlide(attached);
  }
  toProto() {
    return this.#items.map((chart) => chart.toProto());
  }
  #attachChartToSlide(chart) {
    const element = {
      id: "",
      name: "",
      type: 6 /* ELEMENT_TYPE_CHART_REFERENCE */,
      chartReference: { id: chart.id }
    };
    const chartElement = new ChartElement(this.#context, element);
    chartElement.setChartReference(chart.id);
    if (chartElement.frame === undefined) {
      chartElement.position = { left: 60, top: 80, width: 640, height: 360 };
    }
    this.#items.push(chartElement);
    this.#context._register(chartElement);
    return chartElement;
  }
}

// node_modules/@oai/granola/dist/models/presentation/images/image-content-type.js
var normalizeContentType = (value) => {
  if (!value) {
    return;
  }
  return value.split(";")[0]?.trim().toLowerCase();
};
var detectContentTypeFromBytes = (data) => {
  if (!data || data.byteLength < 4) {
    return;
  }
  if (data.byteLength >= 8 && data[0] === 137 && data[1] === 80 && data[2] === 78 && data[3] === 71 && data[4] === 13 && data[5] === 10 && data[6] === 26 && data[7] === 10) {
    return "image/png";
  }
  if (data[0] === 255 && data[1] === 216 && data[2] === 255) {
    return "image/jpeg";
  }
  if (data.byteLength >= 4 && data[0] === 71 && data[1] === 73 && data[2] === 70 && data[3] === 56) {
    return "image/gif";
  }
  if (data.byteLength >= 12 && data[0] === 82 && data[1] === 73 && data[2] === 70 && data[3] === 70 && data[8] === 87 && data[9] === 69 && data[10] === 66 && data[11] === 80) {
    return "image/webp";
  }
  return;
};

// node_modules/@oai/granola/dist/models/presentation/images/image-dimensions.js
var JPEG_SOF_MARKERS = new Set([
  192,
  193,
  194,
  195,
  197,
  198,
  199,
  201,
  202,
  203,
  205,
  206,
  207
]);
var matchesAscii = (data, offset, text) => {
  if (offset + text.length > data.byteLength) {
    return false;
  }
  for (let index = 0;index < text.length; index += 1) {
    if (data[offset + index] !== text.charCodeAt(index)) {
      return false;
    }
  }
  return true;
};
var readPngDimensions = (data) => {
  if (data.byteLength < 24) {
    return;
  }
  if (data[0] !== 137 || data[1] !== 80 || data[2] !== 78 || data[3] !== 71) {
    return;
  }
  const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  const width = view.getUint32(16);
  const height = view.getUint32(20);
  if (width <= 0 || height <= 0) {
    return;
  }
  return { width, height };
};
var readGifDimensions = (data) => {
  if (data.byteLength < 10) {
    return;
  }
  if (!matchesAscii(data, 0, "GIF")) {
    return;
  }
  const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  const width = view.getUint16(6, true);
  const height = view.getUint16(8, true);
  if (width <= 0 || height <= 0) {
    return;
  }
  return { width, height };
};
var readJpegDimensions = (data) => {
  if (data.byteLength < 4) {
    return;
  }
  const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  if (view.getUint8(0) !== 255 || view.getUint8(1) !== 216) {
    return;
  }
  let offset = 2;
  while (offset + 9 < data.byteLength) {
    if (view.getUint8(offset) !== 255) {
      offset += 1;
      continue;
    }
    let marker = view.getUint8(offset + 1);
    while (marker === 255 && offset + 2 < data.byteLength) {
      offset += 1;
      marker = view.getUint8(offset + 1);
    }
    if (marker === 217 || marker === 218) {
      break;
    }
    const length = (view.getUint8(offset + 2) << 8) + view.getUint8(offset + 3);
    if (length < 2 || offset + 2 + length > data.byteLength) {
      break;
    }
    if (JPEG_SOF_MARKERS.has(marker)) {
      const height = (view.getUint8(offset + 5) << 8) + view.getUint8(offset + 6);
      const width = (view.getUint8(offset + 7) << 8) + view.getUint8(offset + 8);
      if (width <= 0 || height <= 0) {
        return;
      }
      return { width, height };
    }
    offset += 2 + length;
  }
  return;
};
var readWebpDimensions = (data) => {
  if (data.byteLength < 30) {
    return;
  }
  if (!matchesAscii(data, 0, "RIFF") || !matchesAscii(data, 8, "WEBP")) {
    return;
  }
  const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  const chunkType = String.fromCharCode(view.getUint8(12), view.getUint8(13), view.getUint8(14), view.getUint8(15));
  const chunkDataOffset = 20;
  switch (chunkType) {
    case "VP8X": {
      if (data.byteLength < chunkDataOffset + 10) {
        return;
      }
      const width = 1 + (view.getUint8(chunkDataOffset + 4) | view.getUint8(chunkDataOffset + 5) << 8 | view.getUint8(chunkDataOffset + 6) << 16);
      const height = 1 + (view.getUint8(chunkDataOffset + 7) | view.getUint8(chunkDataOffset + 8) << 8 | view.getUint8(chunkDataOffset + 9) << 16);
      if (width <= 0 || height <= 0) {
        return;
      }
      return { width, height };
    }
    case "VP8L": {
      if (data.byteLength < chunkDataOffset + 5) {
        return;
      }
      if (view.getUint8(chunkDataOffset) !== 47) {
        return;
      }
      const bits = view.getUint32(chunkDataOffset + 1, true);
      const width = (bits & 16383) + 1;
      const height = (bits >> 14 & 16383) + 1;
      if (width <= 0 || height <= 0) {
        return;
      }
      return { width, height };
    }
    case "VP8 ": {
      if (data.byteLength < chunkDataOffset + 10) {
        return;
      }
      const startCode = chunkDataOffset + 3;
      if (view.getUint8(startCode) !== 157 || view.getUint8(startCode + 1) !== 1 || view.getUint8(startCode + 2) !== 42) {
        return;
      }
      const width = (view.getUint8(startCode + 3) | view.getUint8(startCode + 4) << 8) & 16383;
      const height = (view.getUint8(startCode + 5) | view.getUint8(startCode + 6) << 8) & 16383;
      if (width <= 0 || height <= 0) {
        return;
      }
      return { width, height };
    }
    default:
      return;
  }
};
var resolveImageDimensions = (data, contentType) => {
  const normalized = normalizeContentType(contentType) ?? detectContentTypeFromBytes(data);
  switch (normalized) {
    case "image/png":
      return readPngDimensions(data);
    case "image/jpeg":
    case "image/jpg":
      return readJpegDimensions(data);
    case "image/gif":
      return readGifDimensions(data);
    case "image/webp":
      return readWebpDimensions(data);
    default:
      return;
  }
};

// node_modules/@oai/granola/dist/models/presentation/images/image-fit.js
var clamp6 = (value, min2, max3) => {
  if (Number.isNaN(value)) {
    return min2;
  }
  return Math.min(Math.max(value, min2), max3);
};
var toFillRect = (leftPct, topPct, rightPct, bottomPct) => ({
  l: Math.round(clamp6(leftPct, 0, 1) * 1e5),
  t: Math.round(clamp6(topPct, 0, 1) * 1e5),
  r: Math.round(clamp6(rightPct, 0, 1) * 1e5),
  b: Math.round(clamp6(bottomPct, 0, 1) * 1e5)
});
var resolveFitRects = (fit, frameWidth, frameHeight, imageRatio) => {
  const frameRatio = frameWidth / frameHeight;
  if (fit === "contain") {
    let insetX = 0;
    let insetY = 0;
    if (imageRatio > frameRatio) {
      const scaledHeight = frameWidth / imageRatio;
      insetY = (frameHeight - scaledHeight) / 2 / frameHeight;
    } else if (imageRatio < frameRatio) {
      const scaledWidth = frameHeight * imageRatio;
      insetX = (frameWidth - scaledWidth) / 2 / frameWidth;
    }
    return {
      srcRect: toFillRect(0, 0, 0, 0),
      stretchFillRect: toFillRect(insetX, insetY, insetX, insetY)
    };
  }
  let cropX = 0;
  let cropY = 0;
  if (imageRatio > frameRatio) {
    cropX = (1 - frameRatio / imageRatio) / 2;
  } else if (imageRatio < frameRatio) {
    cropY = (1 - imageRatio / frameRatio) / 2;
  }
  return {
    srcRect: toFillRect(cropX, cropY, cropX, cropY),
    stretchFillRect: toFillRect(0, 0, 0, 0)
  };
};
var resolveContainFrame = (frameWidth, frameHeight, imageRatio) => {
  if (frameWidth <= 0 || frameHeight <= 0 || imageRatio <= 0) {
    return { width: 0, height: 0, offsetX: 0, offsetY: 0 };
  }
  const frameRatio = frameWidth / frameHeight;
  let width = frameWidth;
  let height = frameHeight;
  if (imageRatio > frameRatio) {
    height = frameWidth / imageRatio;
  } else if (imageRatio < frameRatio) {
    width = frameHeight * imageRatio;
  }
  const offsetX = (frameWidth - width) / 2;
  const offsetY = (frameHeight - height) / 2;
  return { width, height, offsetX, offsetY };
};

// node_modules/@oai/granola/dist/models/presentation/utils/tailwind/parse-tailwind-radius-token.js
var TAILWIND_RADIUS_PX_BY_TOKEN = {
  rounded: 4,
  "rounded-none": 0,
  "rounded-sm": 2,
  "rounded-md": 6,
  "rounded-lg": 8,
  "rounded-xl": 12,
  "rounded-2xl": 16,
  "rounded-3xl": 24,
  "rounded-full": 9999
};
function parseTailwindRadiusToken(input) {
  const trimmed = input.trim();
  if (!trimmed)
    return null;
  const normalized = trimmed.toLowerCase();
  const radius = TAILWIND_RADIUS_PX_BY_TOKEN[normalized];
  return typeof radius === "number" ? radius : null;
}

// node_modules/@oai/granola/dist/models/presentation/utils/tailwind/parse-tailwind-shadow-token.js
function parseTailwindShadowToken(input) {
  const trimmed = input.trim();
  if (!trimmed)
    return null;
  const normalized = trimmed.toLowerCase();
  switch (normalized) {
    case "shadow-none":
    case "shadow-sm":
    case "shadow":
    case "shadow-md":
    case "shadow-lg":
    case "shadow-xl":
    case "shadow-2xl":
      return normalized;
    default:
      return null;
  }
}

// node_modules/@oai/granola/dist/models/presentation/utils/tailwind/parse-tailwind-shape-classname.js
function parseTailwindShapeClassName(className) {
  const tokens = className.split(/\s+/).map((token) => token.trim()).filter((token) => token.length > 0);
  if (tokens.length === 0) {
    return null;
  }
  const parsed = {};
  let changed = false;
  for (const token of tokens) {
    if (token.startsWith("bg-")) {
      const colorToken = token.slice("bg-".length);
      const color2 = parseTailwindColorToken(colorToken);
      if (color2) {
        parsed.fill = new Fill2({
          type: "solid",
          color: {
            type: "rgb",
            value: color2.hex,
            transform: color2.alpha === undefined ? undefined : { opacity: color2.alpha }
          }
        }).toConfig();
        changed = true;
      }
      continue;
    }
    const radius = parseTailwindRadiusToken(token);
    if (radius !== null) {
      parsed.borderRadius = radius;
      changed = true;
      continue;
    }
    const shadow = parseTailwindShadowToken(token);
    if (shadow) {
      parsed.shadow = shadow;
      changed = true;
    }
  }
  return changed ? parsed : null;
}

// node_modules/@oai/granola/dist/models/presentation/shape.util.js
function normalizeShapeClassName(value) {
  const normalized = value?.trim();
  return normalized && normalized.length > 0 ? normalized : undefined;
}
function mergeShapeClassNameStyle(className) {
  if (!className) {
    return null;
  }
  return parseTailwindShapeClassName(className);
}
function borderRadiusPxFromConfig(value) {
  if (typeof value === "number") {
    if (!Number.isFinite(value) || value < 0) {
      throw new Error("borderRadius must be a non-negative finite number (px).");
    }
    return value;
  }
  const trimmed = value.trim();
  if (!trimmed) {
    throw new Error("borderRadius cannot be an empty string.");
  }
  const tokenRadius = parseTailwindRadiusToken(trimmed);
  if (tokenRadius !== null) {
    return tokenRadius;
  }
  const numeric = Number(trimmed);
  if (Number.isFinite(numeric) && numeric >= 0) {
    return numeric;
  }
  throw new Error(`Unsupported borderRadius token: "${value}"`);
}
function resolveEffectReferenceForShadow(shadow, theme) {
  if (shadow === undefined) {
    return;
  }
  const parsed = parseTailwindShadowToken(shadow);
  if (parsed) {
    if (parsed === "shadow-none") {
      return;
    }
    const indexByToken = {
      "shadow-none": 0,
      "shadow-sm": 4,
      shadow: 5,
      "shadow-md": 6,
      "shadow-lg": 7,
      "shadow-xl": 8,
      "shadow-2xl": 9
    };
    const index = indexByToken[parsed];
    if (!Number.isFinite(index) || index <= 0) {
      return;
    }
    return { index: String(index), color: undefined };
  }
  const parsedCustom = parseShadowStyleString(shadow);
  if (!parsedCustom || parsedCustom.kind === "none") {
    return;
  }
  if (!theme) {
    throw new Error(`Custom shadow "${shadow}" requires a presentation theme context.`);
  }
  return {
    index: theme.ensureEffectStyle(parsedCustom.effectStyle),
    color: undefined
  };
}
function buildOrthogonalFallbackPoints(start, end) {
  if (almostEqual(start.x, end.x) || almostEqual(start.y, end.y)) {
    return [start, end];
  }
  const midX = (start.x + end.x) / 2;
  return [start, { x: midX, y: start.y }, { x: midX, y: end.y }, end];
}
function commandsToPoints(commands) {
  const points = [];
  for (const command of commands) {
    if (command.cmd === "moveTo" || command.cmd === "lineTo") {
      points.push({ x: command.x, y: command.y });
    } else if (command.cmd === "cubicBezTo") {
      points.push({ x: command.x, y: command.y });
    }
  }
  return simplifyRoutePoints(points);
}
function simplifyRoutePoints(points) {
  if (points.length < 2) {
    return points;
  }
  const deduped = [];
  for (const point3 of points) {
    const last = deduped[deduped.length - 1];
    if (last && almostEqualPoint(last, point3)) {
      continue;
    }
    deduped.push(point3);
  }
  if (deduped.length <= 2) {
    return deduped;
  }
  const simplified = [deduped[0]];
  for (let i = 1;i < deduped.length - 1; i += 1) {
    const prev = simplified[simplified.length - 1];
    const current = deduped[i];
    const next = deduped[i + 1];
    if (!prev || !current || !next) {
      continue;
    }
    if (isCollinear(prev, current, next)) {
      continue;
    }
    simplified.push(current);
  }
  simplified.push(deduped[deduped.length - 1]);
  return simplified;
}
function almostEqual(a, b) {
  return Math.abs(a - b) < 0.001;
}
function routeBounds(points) {
  let minX = Number.POSITIVE_INFINITY;
  let minY = Number.POSITIVE_INFINITY;
  let maxX = Number.NEGATIVE_INFINITY;
  let maxY = Number.NEGATIVE_INFINITY;
  for (const point3 of points) {
    minX = Math.min(minX, point3.x);
    minY = Math.min(minY, point3.y);
    maxX = Math.max(maxX, point3.x);
    maxY = Math.max(maxY, point3.y);
  }
  return { minX, minY, maxX, maxY };
}
function bboxCenter2(rect) {
  return {
    x: rect.x + rect.width / 2,
    y: rect.y + rect.height / 2
  };
}
function resolveFallbackConnectorAnchor(rect, siteIndex, oppositeCenter) {
  const direct = fallbackAnchorForSiteIndex(rect, siteIndex);
  if (direct) {
    return direct;
  }
  const center = bboxCenter2(rect);
  const inferredSite = inferFallbackSiteIndex(center, oppositeCenter);
  const inferredAnchor = fallbackAnchorForSiteIndex(rect, inferredSite);
  if (inferredAnchor) {
    return inferredAnchor;
  }
  const vectorToOther = normalizeRouteVector({
    x: oppositeCenter.x - center.x,
    y: oppositeCenter.y - center.y
  });
  return { point: center, normal: vectorToOther };
}
function inferFallbackSiteIndex(fromCenter, toCenter) {
  const deltaX = toCenter.x - fromCenter.x;
  const deltaY = toCenter.y - fromCenter.y;
  if (Math.abs(deltaX) >= Math.abs(deltaY)) {
    return deltaX >= 0 ? 3 : 1;
  }
  return deltaY >= 0 ? 2 : 0;
}
function offsetRoutePoint(point3, normal, distance) {
  return {
    x: point3.x + normal.x * distance,
    y: point3.y + normal.y * distance
  };
}
function isMonotoneRoute(points) {
  for (let i = 0;i < points.length - 1; i += 1) {
    const a = points[i];
    const b = points[i + 1];
    const dx = b.x - a.x;
    const dy = b.y - a.y;
    if (!almostEqual(dx, 0) && !almostEqual(dy, 0)) {
      return false;
    }
    if (dx < -0.001 || dy < -0.001) {
      return false;
    }
  }
  return true;
}
function computeAdj(value, total) {
  if (value === undefined || !Number.isFinite(value)) {
    return;
  }
  if (!Number.isFinite(total) || total <= 0) {
    return;
  }
  const ratio = value / total;
  const scaled = Math.round(ratio * 1e5);
  return clampAdj(scaled);
}
function almostEqualPoint(a, b) {
  return Math.abs(a.x - b.x) < 0.001 && Math.abs(a.y - b.y) < 0.001;
}
function isCollinear(a, b, c) {
  const sameX = almostEqual(a.x, b.x) && almostEqual(b.x, c.x);
  const sameY = almostEqual(a.y, b.y) && almostEqual(b.y, c.y);
  return sameX || sameY;
}
function fallbackAnchorForSiteIndex(rect, siteIndex) {
  switch (siteIndex) {
    case 0:
      return {
        point: { x: rect.x + rect.width / 2, y: rect.y },
        normal: { x: 0, y: -1 }
      };
    case 1:
      return {
        point: { x: rect.x, y: rect.y + rect.height / 2 },
        normal: { x: -1, y: 0 }
      };
    case 2:
      return {
        point: { x: rect.x + rect.width / 2, y: rect.y + rect.height },
        normal: { x: 0, y: 1 }
      };
    case 3:
      return {
        point: { x: rect.x + rect.width, y: rect.y + rect.height / 2 },
        normal: { x: 1, y: 0 }
      };
    default:
      return null;
  }
}
function normalizeRouteVector(point3) {
  const magnitude = Math.hypot(point3.x, point3.y);
  if (magnitude < 0.001) {
    return { x: 0, y: 0 };
  }
  return {
    x: point3.x / magnitude,
    y: point3.y / magnitude
  };
}
function clampAdj(value) {
  if (value < 0) {
    return 0;
  }
  if (value > 1e5) {
    return 1e5;
  }
  return value;
}

// node_modules/@oai/granola/dist/models/presentation/utils/shape-adjustments.js
var MAX_ROUND_RECT_ADJ = 50000;
var clampRoundRectAdj = (value) => {
  if (value < 0)
    return 0;
  if (value > MAX_ROUND_RECT_ADJ)
    return MAX_ROUND_RECT_ADJ;
  return value;
};
var buildRoundRectAdjustmentListForCornerRadiusPx = (options) => {
  const { widthPx, heightPx, radiusPx } = options;
  if (!Number.isFinite(widthPx) || widthPx <= 0) {
    return;
  }
  if (!Number.isFinite(heightPx) || heightPx <= 0) {
    return;
  }
  if (!Number.isFinite(radiusPx) || radiusPx < 0) {
    return;
  }
  const shortSide = Math.min(widthPx, heightPx);
  const scaled = Math.round(radiusPx / shortSide * 1e5);
  const adj = clampRoundRectAdj(scaled);
  return [{ name: "adj", formula: `val ${adj}` }];
};

// node_modules/@oai/granola/dist/models/presentation/image-element.js
var DEFAULT_BINARY_CONTENT_TYPE = "application/octet-stream";
var EXTENSION_TO_CONTENT_TYPE = {
  ".png": "image/png",
  ".jpg": "image/jpeg",
  ".jpeg": "image/jpeg",
  ".gif": "image/gif",
  ".webp": "image/webp",
  ".svg": "image/svg+xml"
};
function normalizePath(value) {
  const sanitized = value.split(/[?#]/)[0] ?? value;
  return sanitized.trim().toLowerCase();
}
function guessContentTypeFromFilename(value) {
  const normalized = normalizePath(value);
  const entries = Object.entries(EXTENSION_TO_CONTENT_TYPE);
  for (const [extension, contentType] of entries) {
    if (normalized.endsWith(extension)) {
      return contentType;
    }
  }
  return;
}
function decodeBase642(value) {
  const globalObject = globalThis;
  const globalBuffer = globalObject["Buffer"];
  if (globalBuffer && typeof globalBuffer.from === "function") {
    const buffer = globalBuffer.from(value, "base64");
    return buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
  }
  const globalAtob = globalObject["atob"];
  if (typeof globalAtob === "function") {
    const binary = globalAtob(value);
    const output = new Uint8Array(binary.length);
    for (let index = 0;index < binary.length; index += 1) {
      output[index] = binary.charCodeAt(index);
    }
    return output;
  }
  return new Uint8Array;
}
function encodeBase64(value) {
  const globalObject = globalThis;
  const globalBuffer = globalObject["Buffer"];
  if (globalBuffer && typeof globalBuffer.from === "function") {
    return globalBuffer.from(value).toString("base64");
  }
  const globalBtoa = globalObject["btoa"];
  if (typeof globalBtoa === "function") {
    let binary = "";
    for (const byte of value) {
      binary += String.fromCharCode(byte);
    }
    return globalBtoa(binary);
  }
  return "";
}
function isImageBlobData(value) {
  return value instanceof ArrayBuffer || value instanceof Uint8Array;
}
function imageBlobDataToBytes(value) {
  return value instanceof Uint8Array ? new Uint8Array(value) : new Uint8Array(value);
}
function decodeDataUrl2(value) {
  const match = /^data:([^;,]+);base64,(.+)$/i.exec(value);
  if (!match) {
    return;
  }
  const mime = match[1];
  const base64 = match[2];
  if (!mime || !base64) {
    return;
  }
  const data = decodeBase642(base64);
  return {
    data,
    contentType: mime.toLowerCase()
  };
}
function resolveImageAssetPayload(options) {
  const payload = {};
  if ("contentType" in options && typeof options.contentType === "string") {
    const normalized = options.contentType.trim().toLowerCase();
    if (normalized) {
      payload.contentType = normalized;
    }
  }
  if ("prompt" in options && typeof options.prompt === "string") {
    payload.prompt = options.prompt;
  }
  if ("dataUrl" in options && typeof options.dataUrl === "string") {
    const decoded = decodeDataUrl2(options.dataUrl);
    if (decoded) {
      payload.data = decoded.data;
      payload.contentType = decoded.contentType;
    }
  }
  if ("blob" in options && isImageBlobData(options.blob)) {
    payload.data = imageBlobDataToBytes(options.blob);
  }
  if ("uri" in options && typeof options.uri === "string") {
    payload.uri = options.uri;
    const guessed = guessContentTypeFromFilename(options.uri);
    if (guessed) {
      payload.contentType = guessed;
    }
  }
  if ("path" in options && typeof options.path === "string") {
    payload.uri = options.path;
    const guessed = guessContentTypeFromFilename(options.path);
    if (guessed) {
      payload.contentType = guessed;
    }
  }
  if (payload.data) {
    const sniffed = detectContentTypeFromBytes(payload.data);
    if (sniffed) {
      payload.contentType = sniffed;
    } else if (payload.data.byteLength < 32 && !payload.contentType) {
      payload.data = undefined;
    } else if (!payload.contentType) {
      payload.contentType = DEFAULT_BINARY_CONTENT_TYPE;
    }
  }
  if (payload.data && !payload.contentType) {
    payload.contentType = DEFAULT_BINARY_CONTENT_TYPE;
  }
  return payload;
}
function toRecordableImageAddOptions(options) {
  return toRecordableImageOptions(options);
}
function toRecordableImageReplaceOptions(options) {
  return toRecordableImageOptions(options);
}
function hasAssetPayload(payload) {
  return Boolean(payload.data && payload.data.length > 0) || typeof payload.prompt === "string" || typeof payload.uri === "string";
}
function toRecordableImageOptions(options) {
  const next = {};
  const payload = "blob" in options && isImageBlobData(options.blob) ? resolveImageAssetPayload(options) : undefined;
  if ("alt" in options && options.alt !== undefined) {
    next["alt"] = options.alt;
  }
  if ("fit" in options && options.fit !== undefined) {
    next["fit"] = options.fit;
  }
  if (payload?.contentType) {
    next["contentType"] = payload.contentType;
  } else if ("contentType" in options && options.contentType !== undefined) {
    next["contentType"] = options.contentType;
  }
  if ("position" in options && options.position !== undefined) {
    next["position"] = { ...options.position };
  }
  if ("frame" in options && options.frame !== undefined) {
    next["frame"] = { ...options.frame };
  }
  if ("crop" in options && options.crop !== undefined) {
    next["crop"] = { ...options.crop };
  }
  if ("geometry" in options && options.geometry !== undefined) {
    next["geometry"] = options.geometry;
  }
  if (payload?.prompt !== undefined) {
    next["prompt"] = payload.prompt;
  } else if ("prompt" in options && typeof options.prompt === "string") {
    next["prompt"] = options.prompt;
  }
  if ("path" in options && typeof options.path === "string") {
    next["path"] = options.path;
  }
  if ("uri" in options && typeof options.uri === "string") {
    next["uri"] = options.uri;
  }
  if ("dataUrl" in options && typeof options.dataUrl === "string") {
    next["dataUrl"] = options.dataUrl;
  }
  if (payload?.data && payload.data.length > 0 && payload.contentType) {
    next["dataUrl"] = `data:${payload.contentType};base64,${encodeBase64(payload.data)}`;
  }
  return next;
}
var clamp7 = (value, min2, max3) => {
  if (Number.isNaN(value)) {
    return min2;
  }
  return Math.min(Math.max(value, min2), max3);
};
var IMAGE_GEOMETRY_FROM_PROTO = Object.entries(SHAPE_GEOMETRY_NAME_TO_PROTO).reduce((acc, [name, proto]) => {
  if (name === "custom" || name === "connector" || name === "textbox") {
    return acc;
  }
  if (acc[proto] === undefined) {
    acc[proto] = name;
  }
  return acc;
}, {});
var hasConcreteSource = (options) => {
  return "path" in options || "blob" in options || "dataUrl" in options || "uri" in options;
};
function resolveImageReplaceOptionsForFrame(args) {
  const { options } = args;
  if ("fit" in options && options.fit !== undefined) {
    return options;
  }
  if (!hasConcreteSource(options)) {
    return options;
  }
  if ((args.frameWidth ?? 0) <= 0 || (args.frameHeight ?? 0) <= 0) {
    return options;
  }
  return {
    ...options,
    fit: args.currentFit ?? "cover"
  };
}

class ImageElement2 extends Element2 {
  type = "image";
  #lockAspectRatio;
  #fit;
  #alt;
  #prompt;
  #isPlaceholder;
  #crop;
  #maskGeometry;
  #maskBorderRadius;
  #intrinsicRatio;
  #suppressPatchRecording = false;
  constructor(context, proto) {
    super(context, proto);
    this.data.imageReference = proto.imageReference?.id ? { id: proto.imageReference.id } : undefined;
    if (this.data.type === undefined || this.data.type === 0 /* ELEMENT_TYPE_UNSPECIFIED */) {
      this.data.type = 7 /* ELEMENT_TYPE_IMAGE_REFERENCE */;
    }
    const imageProto = proto.image;
    this.#alt = imageProto?.alt ?? "";
    this.#prompt = undefined;
    this.#fit = undefined;
    this.#lockAspectRatio = false;
    this.#isPlaceholder = false;
    this.#crop = this.#readCropFromProto(proto);
    this.#maskGeometry = this.#readMaskGeometryFromProto(proto);
    this.#maskBorderRadius = undefined;
    this.#intrinsicRatio = undefined;
    if (!this.data.imageReference && imageProto) {
      const assetPayload = {};
      if (imageProto.data && imageProto.data.length > 0) {
        assetPayload.data = new Uint8Array(imageProto.data);
        assetPayload.contentType = imageProto.contentType && imageProto.contentType.length > 0 ? imageProto.contentType : DEFAULT_BINARY_CONTENT_TYPE;
      } else if (imageProto.contentType) {
        assetPayload.contentType = imageProto.contentType;
      }
      const asset = this.context.createImageAsset(assetPayload);
      this.setImageReference(asset.id);
    }
    this.data.shape = undefined;
    this.data.image = undefined;
    this.#syncPromptAndPlaceholderFromAsset();
  }
  get id() {
    return this.data.id;
  }
  get aid() {
    return this.slideId ? buildSlideChildAid2("im", this.slideId, this.id) : undefined;
  }
  toSnapshot() {
    this.#syncPromptAndPlaceholderFromAsset();
    const slideId = this.slideId;
    const localId = this.id;
    return {
      aid: buildSlideChildAid2("im", slideId, localId),
      kind: "image",
      id: localId,
      slideId,
      name: this.name,
      alt: this.alt,
      prompt: this.prompt,
      isPlaceholder: this.isPlaceholder,
      contentType: this.image?.contentType,
      fit: this.fit,
      geometry: this.geometry,
      crop: this.crop,
      rotation: this.rotation,
      flipHorizontal: this.flipHorizontal,
      flipVertical: this.flipVertical,
      lockAspectRatio: this.lockAspectRatio,
      frame: this.frame
    };
  }
  get image() {
    const referenceId = this.data.imageReference?.id;
    if (!referenceId) {
      return;
    }
    return this.context.getImageById(referenceId);
  }
  async getBitmap() {
    const asset = this.image;
    if (!asset) {
      if (this.prompt || this.isPlaceholder) {
        return;
      }
      console.warn("Image element missing asset", { elementId: this.id });
      return;
    }
    if (this.#isPromptOnlyPlaceholder(asset)) {
      return;
    }
    const frame = this.position;
    const width = frame?.width ?? 0;
    const height = frame?.height ?? 0;
    try {
      return await asset.getBitmap(width, height);
    } catch (error) {
      console.warn("Image element asset decode failure", {
        elementId: this.id,
        assetId: asset.id,
        contentType: asset.contentType,
        uri: asset.uri ?? null
      }, error);
      return;
    }
  }
  get alt() {
    return this.#alt;
  }
  set alt(value) {
    this.#alt = value ?? "";
    this.#recordImageSet({ alt: this.#alt });
  }
  get prompt() {
    this.#syncPromptAndPlaceholderFromAsset();
    return this.#prompt;
  }
  set prompt(value) {
    const normalizedPrompt = this.#normalizePrompt(value);
    if (normalizedPrompt) {
      this.#ensureImageAsset().prompt = normalizedPrompt;
    } else {
      const asset = this.image;
      if (asset) {
        asset.prompt = undefined;
      }
    }
    this.#prompt = normalizedPrompt;
    this.#isPlaceholder = Boolean(normalizedPrompt && !this.#assetHasConcreteSource(this.image));
    this.#queueCollaborativePublish();
  }
  get isPlaceholder() {
    this.#syncPromptAndPlaceholderFromAsset();
    return this.#isPlaceholder;
  }
  set isPlaceholder(value) {
    this.#isPlaceholder = Boolean(value);
    this.#queueCollaborativePublish();
  }
  get fit() {
    return this.#fit;
  }
  set fit(value) {
    this.#fit = value;
    this.#recordImageSet({ fit: value });
  }
  get geometry() {
    return this.#maskGeometry;
  }
  set geometry(value) {
    if (!value) {
      this.#maskGeometry = undefined;
      this.#maskBorderRadius = undefined;
      this.data.shape = undefined;
      this.#recordImageSet({ geometry: undefined });
      return;
    }
    this.#maskGeometry = value;
    if (value !== "roundRect") {
      this.#maskBorderRadius = undefined;
    }
    this.data.shape = undefined;
    this.#recordImageSet({ geometry: value });
  }
  get borderRadius() {
    return this.#maskBorderRadius;
  }
  set borderRadius(value) {
    if (value === undefined) {
      this.#maskBorderRadius = undefined;
      this.#queueCollaborativePublish();
      return;
    }
    if (this.#maskGeometry !== undefined && this.#maskGeometry !== "rect" && this.#maskGeometry !== "roundRect") {
      throw new Error("image.borderRadius only supports rect or roundRect image masks.");
    }
    const radiusPx = borderRadiusPxFromConfig(value);
    this.#maskBorderRadius = value;
    if (radiusPx > 0) {
      this.#maskGeometry = "roundRect";
    } else if (this.#maskGeometry === "roundRect") {
      this.#maskGeometry = undefined;
    }
    this.data.shape = undefined;
    this.#queueCollaborativePublish();
  }
  get lockAspectRatio() {
    return this.#lockAspectRatio;
  }
  set lockAspectRatio(value) {
    this.#lockAspectRatio = Boolean(value);
    this.#recordImageSet({ lockAspectRatio: this.#lockAspectRatio });
  }
  get crop() {
    if (!this.#crop) {
      return;
    }
    return { ...this.#crop };
  }
  set crop(value) {
    if (!value) {
      this.#crop = undefined;
      if (this.data.fill?.srcRect) {
        this.data.fill = {
          ...this.data.fill,
          srcRect: undefined
        };
      }
      this.#recordImageSet({ crop: undefined });
      return;
    }
    const next = {
      left: clamp7(value.left, 0, 1),
      top: clamp7(value.top, 0, 1),
      right: clamp7(value.right, 0, 1),
      bottom: clamp7(value.bottom, 0, 1)
    };
    this.#crop = next;
    const toProtoUnits = (val) => Math.round(clamp7(val, 0, 1) * 1e5);
    const fill = this.data.fill ?? {
      id: "",
      type: 0,
      color: undefined,
      gradientStops: []
    };
    fill.type = fill.type ?? 0;
    if (!Array.isArray(fill.gradientStops)) {
      fill.gradientStops = [];
    }
    fill.srcRect = {
      l: toProtoUnits(next.left),
      t: toProtoUnits(next.top),
      r: toProtoUnits(next.right),
      b: toProtoUnits(next.bottom)
    };
    this.data.fill = fill;
    this.#recordImageSet({ crop: next });
  }
  get width() {
    return this.position.width;
  }
  set width(value) {
    const width = Number.isFinite(value) ? Math.max(0, value) : 0;
    const current = this.#currentPosition();
    const ratio = this.#lockAspectRatio ? this.#computeAspectRatio(current) : undefined;
    current.width = width;
    if (ratio && ratio > 0 && this.#lockAspectRatio) {
      current.height = width / ratio;
    }
    this.position = current;
  }
  get height() {
    return this.position.height;
  }
  set height(value) {
    const height = Number.isFinite(value) ? Math.max(0, value) : 0;
    const current = this.#currentPosition();
    const ratio = this.#lockAspectRatio ? this.#computeAspectRatio(current) : undefined;
    current.height = height;
    if (ratio && ratio > 0 && this.#lockAspectRatio) {
      current.width = height * ratio;
    }
    this.position = current;
  }
  get size() {
    return {
      width: this.position.width,
      height: this.position.height
    };
  }
  set size(value) {
    const current = this.#currentPosition();
    if (value.width !== undefined) {
      current.width = value.width;
    }
    if (value.height !== undefined) {
      current.height = value.height;
    }
    this.position = current;
  }
  get flipHorizontal() {
    return this.position.horizontalFlip;
  }
  set flipHorizontal(value) {
    this.position.horizontalFlip = Boolean(value);
  }
  get flipVertical() {
    return this.position.verticalFlip;
  }
  set flipVertical(value) {
    this.position.verticalFlip = Boolean(value);
  }
  replace(options) {
    const effectiveOptions = resolveImageReplaceOptionsForFrame({
      options,
      currentFit: this.fit,
      frameWidth: this.position.width,
      frameHeight: this.position.height
    });
    this.#withPatchRecordingSuppressed(() => {
      if ("alt" in effectiveOptions && effectiveOptions.alt !== undefined) {
        this.alt = effectiveOptions.alt;
      }
      if ("fit" in effectiveOptions && effectiveOptions.fit !== undefined) {
        this.fit = effectiveOptions.fit;
        this.lockAspectRatio = true;
      }
      if ("prompt" in effectiveOptions) {
        this.prompt = effectiveOptions.prompt;
      } else if (hasConcreteSource(effectiveOptions)) {
        this.prompt = undefined;
      }
      const payload = resolveImageAssetPayload(effectiveOptions);
      this.applyAssetPayload(payload);
      this.#syncPromptAndPlaceholderFromAsset();
    });
    this.#recordImageReplace(effectiveOptions);
  }
  regenerate(options = {}) {
    const presentation = this.context.getPresentation?.();
    if (!presentation) {
      throw new Error("Image regeneration is not available in this context.");
    }
    const aid = this.elementAnchor();
    const slideId = this.slideId;
    if (!aid || !aid.startsWith("im/") || !slideId) {
      throw new Error("Image regeneration requires a slide-anchored image.");
    }
    const promptSource = options.prompt ?? this.prompt ?? this.image?.prompt;
    const prompt = typeof promptSource === "string" && promptSource.trim().length > 0 ? promptSource.trim() : undefined;
    if (!prompt) {
      throw new Error("image.regenerate requires a prompt. Set image.prompt or pass { prompt }.");
    }
    this.prompt = prompt;
    const request = {
      requestId: `imggen_${generateAidSuffix()}`,
      aid,
      slideId,
      elementId: this.id,
      prompt,
      kind: options.kind ?? "content",
      fit: options.fit ?? this.fit ?? "contain",
      frameWidthPx: this.frame?.width,
      frameHeightPx: this.frame?.height,
      size: options.size,
      quality: options.quality,
      background: options.background,
      outputFormat: options.outputFormat,
      source: "image.regenerate"
    };
    presentation.queueImageGenerationRequest(request);
  }
  delete() {
    const anchor = this.elementAnchor();
    if (anchor && anchor.startsWith("im/")) {
      const target = this.recordTargetRef(anchor);
      if (target) {
        this.recordPatchOp({
          op: "image.remove",
          target
        });
      }
    }
    this.context.deleteElement?.(this.id);
  }
  setImageReference(id) {
    this.data.imageReference = id ? { id } : undefined;
    this.#intrinsicRatio = undefined;
    this.#syncPromptAndPlaceholderFromAsset();
  }
  toProto() {
    const proto = super.toProto();
    if (proto.image) {
      proto.image = undefined;
    }
    if (proto.imageReference && !proto.imageReference.id) {
      proto.imageReference = undefined;
    }
    if (proto.shape) {
      proto.shape = undefined;
    }
    this.#applyFitToProto(proto);
    const mask = this.#buildImageMaskProto();
    proto.imageMask = mask;
    return proto;
  }
  applyAssetPayload(payload) {
    if (!hasAssetPayload(payload)) {
      return;
    }
    const asset = this.#ensureImageAsset();
    this.#applyAssetPayload(asset, payload);
    this.#syncPromptAndPlaceholderFromAsset();
  }
  recordPositionSet(position) {
    this.#recordImageSet({ position });
  }
  #currentPosition() {
    return this.position.toJSON();
  }
  #computeAspectRatio(position) {
    const width = position.width ?? 0;
    const height = position.height ?? 0;
    if (width <= 0 || height <= 0) {
      return;
    }
    return width / height;
  }
  #getImageAspectRatio() {
    if (this.#intrinsicRatio !== undefined) {
      return this.#intrinsicRatio;
    }
    const asset = this.image;
    if (!asset) {
      return;
    }
    const data = asset.data;
    const dimensions = data && data.byteLength > 0 ? resolveImageDimensions(data, asset.contentType) : undefined;
    if (!dimensions) {
      return;
    }
    const ratio = dimensions.width / dimensions.height;
    if (!Number.isFinite(ratio) || ratio <= 0) {
      return;
    }
    this.#intrinsicRatio = ratio;
    return ratio;
  }
  #applyFitToProto(proto) {
    if (!this.#fit || !this.#lockAspectRatio) {
      return;
    }
    const frameWidth = this.position.width;
    const frameHeight = this.position.height;
    if (frameWidth <= 0 || frameHeight <= 0) {
      return;
    }
    const ratio = this.#getImageAspectRatio();
    if (!ratio) {
      return;
    }
    if (this.#fit === "contain") {
      const { width, height, offsetX, offsetY } = resolveContainFrame(frameWidth, frameHeight, ratio);
      if (width > 0 && height > 0) {
        const bbox = proto.bbox ? { ...proto.bbox } : {};
        const frameLeft = this.position.left;
        const frameTop = this.position.top;
        bbox.xEmu = emuFromPixels(frameLeft + offsetX);
        bbox.yEmu = emuFromPixels(frameTop + offsetY);
        bbox.widthEmu = emuFromPixels(width);
        bbox.heightEmu = emuFromPixels(height);
        proto.bbox = bbox;
      }
      if (proto.fill) {
        proto.fill = {
          ...proto.fill,
          srcRect: undefined,
          stretchFillRect: undefined
        };
      }
      return;
    }
    const rects = resolveFitRects(this.#fit, frameWidth, frameHeight, ratio);
    const fill = proto.fill ? { ...proto.fill } : {
      id: "",
      type: 0,
      color: undefined,
      gradientStops: []
    };
    fill.type = fill.type ?? 0;
    if (!Array.isArray(fill.gradientStops)) {
      fill.gradientStops = [];
    }
    fill.srcRect = rects.srcRect;
    fill.stretchFillRect = rects.stretchFillRect;
    proto.fill = fill;
  }
  #ensureImageAsset() {
    let asset = this.image;
    if (!asset) {
      asset = this.context.createImageAsset();
      this.setImageReference(asset.id);
    }
    return asset;
  }
  #applyAssetPayload(asset, payload) {
    if (payload.data || payload.uri !== undefined || payload.contentType) {
      this.#intrinsicRatio = undefined;
    }
    if (payload.data) {
      asset.data = payload.data;
      if (!payload.contentType) {
        payload.contentType = DEFAULT_BINARY_CONTENT_TYPE;
      }
      asset.uri = payload.uri ?? undefined;
      asset.prompt = payload.prompt ?? undefined;
    }
    if (payload.contentType) {
      asset.contentType = payload.contentType;
    }
    if (payload.uri !== undefined) {
      asset.uri = payload.uri;
      if (!payload.data) {
        asset.data = new Uint8Array;
      }
    } else if (payload.data) {
      asset.uri = undefined;
    }
    if (payload.prompt !== undefined) {
      asset.prompt = payload.prompt;
    } else if (payload.data || payload.uri) {
      asset.prompt = undefined;
    }
  }
  #syncPromptAndPlaceholderFromAsset() {
    const asset = this.image;
    const normalizedPrompt = this.#normalizePrompt(asset?.prompt ?? this.#prompt);
    this.#prompt = normalizedPrompt;
    this.#isPlaceholder = Boolean(normalizedPrompt && !this.#assetHasConcreteSource(asset));
  }
  #normalizePrompt(value) {
    if (typeof value !== "string") {
      return;
    }
    const trimmed = value.trim();
    return trimmed.length > 0 ? trimmed : undefined;
  }
  #assetHasConcreteSource(asset) {
    if (!asset) {
      return false;
    }
    if (asset.data.byteLength > 0) {
      return true;
    }
    return typeof asset.uri === "string" && asset.uri.trim().length > 0;
  }
  #isPromptOnlyPlaceholder(asset) {
    return Boolean(this.prompt && !this.#assetHasConcreteSource(asset));
  }
  #readCropFromProto(proto) {
    const srcRect = proto.fill?.srcRect;
    if (!srcRect) {
      return;
    }
    const fromProtoUnits = (value) => {
      if (value === undefined) {
        return 0;
      }
      return clamp7(value, 0, 1e5) / 1e5;
    };
    return {
      left: fromProtoUnits(srcRect.l),
      top: fromProtoUnits(srcRect.t),
      right: fromProtoUnits(srcRect.r),
      bottom: fromProtoUnits(srcRect.b)
    };
  }
  #readMaskGeometryFromProto(proto) {
    const protoWithMask = proto;
    const maskGeometry = protoWithMask.imageMask?.geometry;
    if (maskGeometry !== undefined) {
      if (maskGeometry in SHAPE_GEOMETRY_NAME_TO_PROTO && maskGeometry !== "custom" && maskGeometry !== "connector") {
        return maskGeometry;
      }
    }
    const legacyMaskGeometry = protoWithMask.image?.mask?.geometry;
    if (typeof legacyMaskGeometry === "string") {
      if (legacyMaskGeometry in SHAPE_GEOMETRY_NAME_TO_PROTO && legacyMaskGeometry !== "custom" && legacyMaskGeometry !== "connector") {
        return legacyMaskGeometry;
      }
    }
    const shapeGeometry = proto.shape?.geometry;
    if (shapeGeometry === undefined || shapeGeometry === 0 /* SHAPE_GEOMETRY_UNSPECIFIED */ || shapeGeometry === -1 /* UNRECOGNIZED */) {
      return;
    }
    return IMAGE_GEOMETRY_FROM_PROTO[shapeGeometry];
  }
  #buildImageMaskProto() {
    if (!this.#maskGeometry || this.#maskGeometry === "rect") {
      return;
    }
    const mask = {
      geometry: this.#maskGeometry,
      cropLeft: 0,
      cropTop: 0,
      cropRight: 0,
      cropBottom: 0,
      adjustmentList: this.#resolveMaskAdjustmentList() ?? []
    };
    return mask;
  }
  #resolveMaskAdjustmentList() {
    if (this.#maskGeometry !== "roundRect" || this.#maskBorderRadius === undefined) {
      return;
    }
    const radiusPx = borderRadiusPxFromConfig(this.#maskBorderRadius);
    if (radiusPx <= 0) {
      return;
    }
    return buildRoundRectAdjustmentListForCornerRadiusPx({
      widthPx: this.position.width,
      heightPx: this.position.height,
      radiusPx
    });
  }
  #recordImageSet(props) {
    if (this.#suppressPatchRecording) {
      return;
    }
    this.#queueCollaborativePublish();
    if (!Object.values(props).some((value) => value !== undefined)) {
      return;
    }
    const anchor = this.elementAnchor();
    if (!anchor || !anchor.startsWith("im/")) {
      return;
    }
    const target = this.recordTargetRef(anchor);
    if (!target) {
      return;
    }
    this.recordPatchOp({
      op: "image.set",
      target,
      props
    });
  }
  #recordImageReplace(options) {
    if (this.#suppressPatchRecording) {
      return;
    }
    const anchor = this.elementAnchor();
    if (!anchor || !anchor.startsWith("im/")) {
      return;
    }
    const target = this.recordTargetRef(anchor);
    if (!target) {
      return;
    }
    this.recordPatchOp({
      op: "image.replace",
      target,
      props: toRecordableImageReplaceOptions(options)
    });
  }
  #queueCollaborativePublish() {
    this.context.getPresentation?.()?.queuePresentationCollabPublish();
  }
  #withPatchRecordingSuppressed(fn) {
    const wasSuppressed = this.#suppressPatchRecording;
    this.#suppressPatchRecording = true;
    try {
      fn();
    } finally {
      this.#suppressPatchRecording = wasSuppressed;
    }
  }
}
function buildSlideChildAid2(prefix, slideId, localId) {
  return buildElementAid(prefix, slideId, localId);
}

// node_modules/@oai/granola/dist/models/presentation/image-element-collection.js
var hasPrompt = (options) => ("prompt" in options) && typeof options.prompt === "string";
var hasConcreteSource2 = (options) => {
  return "path" in options || "blob" in options || "dataUrl" in options || "uri" in options;
};

class ImageElementCollection {
  #context;
  #items;
  constructor(context, proto) {
    this.#context = context;
    this.#items = [];
    proto.forEach((element) => {
      this.add({ proto: element });
    });
  }
  get items() {
    return [...this.#items];
  }
  add(options) {
    if ("proto" in options) {
      const imageElement2 = new ImageElement2(this.#context, options.proto);
      this.#items.push(imageElement2);
      this.#context._register(imageElement2);
      return imageElement2;
    }
    const element = {
      id: "",
      name: "",
      imageReference: undefined,
      paragraphs: [],
      type: 0 /* ELEMENT_TYPE_UNSPECIFIED */,
      effects: [],
      children: [],
      levelsStyles: [],
      citations: []
    };
    const assetPayload = resolveImageAssetPayload(options);
    const imageAsset = this.#context.createImageAsset(assetPayload);
    const imageElement = new ImageElement2(this.#context, element);
    imageElement.setImageReference(imageAsset.id);
    imageElement.applyAssetPayload(assetPayload);
    this.#items.push(imageElement);
    this.#context._register(imageElement);
    const recorder = this.#context.getPresentation?.()?.getRecorder?.();
    const slide = this.#context.getSlide?.();
    if (recorder && slide) {
      const anchor = `im/${slide.id}.${imageElement.id}`;
      const alias = recorder.assignAlias(imageElement, anchor, "image");
      recorder.record({
        op: "image.add",
        slide: recorder.targetRefForElement(slide, `sl/${slide.id}`),
        as: alias,
        props: toRecordableImageAddOptions(options)
      });
    }
    if (options.alt !== undefined) {
      imageElement.alt = options.alt ?? "";
    }
    if (options.fit !== undefined) {
      imageElement.fit = options.fit;
      imageElement.lockAspectRatio = true;
    }
    const position = options.position ?? options.frame;
    if (position) {
      imageElement.position = {
        left: position.left,
        top: position.top,
        width: position.width,
        height: position.height
      };
    }
    if (options.crop) {
      imageElement.crop = options.crop;
    }
    if (options.geometry !== undefined) {
      imageElement.geometry = options.geometry;
    }
    if (options.borderRadius !== undefined) {
      imageElement.borderRadius = options.borderRadius;
    }
    if (hasPrompt(options)) {
      imageElement.prompt = options.prompt;
      imageElement.isPlaceholder = !hasConcreteSource2(options);
      if (imageElement.isPlaceholder) {
        imageElement.lockAspectRatio = true;
      }
    }
    return imageElement;
  }
  deleteById(id) {
    const image = this.#items.find((item) => item.id === id);
    if (!image) {
      return;
    }
    const index = this.#items.indexOf(image);
    if (index !== -1) {
      this.#items.splice(index, 1);
    }
    this.#context._unregister(id);
  }
  toProto() {
    return this.#items.map((image) => image.toProto());
  }
}

// node_modules/@oai/granola/dist/models/presentation/shape-placeholder.js
class ShapePlaceholder {
  #type;
  #index;
  constructor(config = {}) {
    this.#type = config.placeholderType;
    this.#index = config.placeholderIndex;
  }
  get type() {
    return this.#type;
  }
  set type(value) {
    this.#type = value;
  }
  get index() {
    return this.#index;
  }
  set index(value) {
    this.#index = value;
  }
  isSet() {
    return this.#type !== undefined || this.#index !== undefined;
  }
}

// node_modules/@oai/granola/dist/models/presentation/shape.js
class Shape2 extends Element2 {
  type = "shape";
  static #frontSeed = 1;
  static #backSeed = -1;
  #fill;
  #line;
  #placeholder;
  #className;
  #connectorRouteInvalidation;
  constructor(context, config) {
    if (config === null || typeof config !== "object" || Array.isArray(config)) {
      throw new Error("Shape config must be an object.");
    }
    if ("proto" in config) {
      super(context, config.proto);
      this.#fill = new Fill2({ type: "proto", proto: config.proto.shape?.fill });
      this.#line = this.#createLine({
        type: "proto",
        proto: config.proto.shape?.line
      });
      this.#placeholder = new ShapePlaceholder({
        placeholderType: config.proto.placeholderType ? PLACEHOLDER_TYPE_FROM_PROTO[config.proto.placeholderType] : undefined,
        placeholderIndex: config.proto.placeholderIndex
      });
    } else if ("geometry" in config) {
      const className = normalizeShapeClassName(config.className);
      const classStyle = mergeShapeClassNameStyle(className);
      const fillConfig = config.fill ?? classStyle?.fill;
      const borderRadiusConfig = config.borderRadius ?? classStyle?.borderRadius;
      const shadowConfig = config.shadow ?? classStyle?.shadow;
      if (config.geometry === "connector") {
        if (borderRadiusConfig !== undefined) {
          throw new Error('Shape borderRadius is not supported for geometry "connector".');
        }
        if (shadowConfig !== undefined) {
          throw new Error('Shape shadow is not supported for geometry "connector".');
        }
        const connectorInit = buildConnectorElement(config);
        super(context, {
          ...connectorInit.element,
          name: config.name ?? ""
        });
        this.#fill = new Fill2(fillConfig);
        this.#line = this.#createLine(config.line);
        this.#placeholder = new ShapePlaceholder;
        this.#className = className;
      } else {
        const customPaths = buildCustomPaths(config);
        const widthPx = config.position?.width;
        const heightPx = config.position?.height;
        if (borderRadiusConfig !== undefined && config.adjustmentList !== undefined) {
          throw new Error('Shape config cannot set both "borderRadius" and "adjustmentList".');
        }
        const borderRadiusPx = borderRadiusConfig === undefined ? undefined : borderRadiusPxFromConfig(borderRadiusConfig);
        let geometryName = config.geometry;
        if (borderRadiusPx !== undefined) {
          if (config.geometry !== "rect" && config.geometry !== "textbox" && config.geometry !== "roundRect") {
            throw new Error('Shape borderRadius is only supported for geometry "rect", "textbox", or "roundRect".');
          }
          if (widthPx === undefined || heightPx === undefined) {
            throw new Error("Shape borderRadius requires position.width and position.height (px).");
          }
          if (borderRadiusPx > 0) {
            geometryName = "roundRect";
          }
        }
        const roundRectAdjustmentList = geometryName === "roundRect" && widthPx !== undefined && heightPx !== undefined ? buildRoundRectAdjustmentListForCornerRadiusPx({
          widthPx,
          heightPx,
          radiusPx: borderRadiusPx ?? 8
        }) : undefined;
        const adjustmentList = config.adjustmentList ?? roundRectAdjustmentList ?? [];
        super(context, {
          type: 5 /* ELEMENT_TYPE_SHAPE */,
          name: config.name ?? "",
          bbox: config.position ? new Position(config.position, true).toProto() : undefined,
          effectReference: resolveEffectReferenceForShadow(shadowConfig, context.getPresentation?.()?.theme),
          shape: {
            geometry: SHAPE_GEOMETRY_NAME_TO_PROTO[geometryName],
            fill: undefined,
            adjustmentList,
            rectFormula: undefined,
            customPaths
          }
        });
        this.#fill = new Fill2(fillConfig);
        this.#line = this.#createLine(config.line);
        this.#placeholder = new ShapePlaceholder;
        this.#className = className;
      }
    } else {
      super(context, {
        type: 5 /* ELEMENT_TYPE_SHAPE */,
        bbox: undefined,
        shape: {
          geometry: 5 /* SHAPE_GEOMETRY_RECT */,
          fill: undefined,
          adjustmentList: [],
          rectFormula: undefined,
          customPaths: []
        }
      });
      this.#fill = new Fill2;
      this.#line = this.#createLine();
      this.#placeholder = new ShapePlaceholder;
    }
    this.#bindPositionChangeHandler();
  }
  get placeholder() {
    return this.#placeholder;
  }
  get id() {
    return this.data.id;
  }
  toSnapshot() {
    const slideId = this.slideId;
    const localId = this.id;
    const fill = this.#fill.toConfig();
    const line = this.#linePatchFromLine(this.#line);
    return {
      aid: buildSlideChildAid3("sh", slideId, localId),
      kind: "shape",
      id: localId,
      slideId,
      name: this.name,
      text: this.text.toString(),
      className: this.className,
      textClassName: this.text.className,
      frame: this.frame,
      placeholderType: this.placeholderType,
      fill,
      line,
      effectReference: this.data.effectReference,
      adjustmentList: this.data.shape?.adjustmentList
    };
  }
  get fill() {
    return this.#fill;
  }
  set fill(value) {
    this.#fill = new Fill2(value);
    const patchFill = this.#fill.toConfig();
    if (patchFill && isPatchFillConfig2(patchFill)) {
      this.recordShapeSet({ fill: patchFill });
    }
  }
  get line() {
    return this.#line;
  }
  set line(value) {
    const line = value instanceof Line4 ? this.#bindLine(value) : this.#createLine(value);
    this.#line = line;
    this.recordShapeSet({ line: this.#linePatchFromLine(line) });
  }
  set borderRadius(value) {
    if (value === undefined) {
      return;
    }
    if (!this.data.shape) {
      throw new Error("borderRadius is only available on shape elements.");
    }
    if (this.connector) {
      throw new Error("borderRadius is not supported on connector shapes.");
    }
    const radiusPx = borderRadiusPxFromConfig(value);
    const frame = this.frame;
    const widthPx = frame?.width;
    const heightPx = frame?.height;
    if (widthPx === undefined || heightPx === undefined) {
      throw new Error("borderRadius requires shape.position width and height (px) before it can be applied.");
    }
    const geometry = this.data.shape.geometry;
    const isRectLike = geometry === 5 /* SHAPE_GEOMETRY_RECT */ || geometry === 26 /* SHAPE_GEOMETRY_ROUND_RECT */;
    if (!isRectLike) {
      throw new Error("borderRadius is only supported for rect-like shapes.");
    }
    if (radiusPx > 0) {
      this.data.shape.geometry = 26 /* SHAPE_GEOMETRY_ROUND_RECT */;
    }
    if (this.data.shape.geometry === 26 /* SHAPE_GEOMETRY_ROUND_RECT */) {
      const adjustmentList = buildRoundRectAdjustmentListForCornerRadiusPx({
        widthPx,
        heightPx,
        radiusPx
      });
      if (!adjustmentList) {
        throw new Error("Failed to apply borderRadius; shape frame is invalid.");
      }
      this.data.shape.adjustmentList = adjustmentList;
    } else {
      this.data.shape.adjustmentList = [];
    }
    this.recordShapeSet({ borderRadius: value });
  }
  set shadow(value) {
    if (value === undefined) {
      return;
    }
    const reference = resolveEffectReferenceForShadow(value, this.context.getPresentation?.()?.theme);
    this.data.effectReference = reference;
    this.recordShapeSet({ shadow: value });
  }
  get className() {
    return this.#className;
  }
  set className(value) {
    this.#className = normalizeShapeClassName(value);
    if (!this.#className) {
      return;
    }
    const parsed = mergeShapeClassNameStyle(this.#className);
    if (parsed) {
      if (parsed.fill !== undefined) {
        this.fill = parsed.fill;
      }
      if (parsed.borderRadius !== undefined) {
        this.borderRadius = parsed.borderRadius;
      }
      if (parsed.shadow !== undefined) {
        this.shadow = parsed.shadow;
      }
    }
    this.recordShapeSet({ className: this.#className });
  }
  get placeholderType() {
    return this.#placeholder.type;
  }
  set placeholderType(value) {
    this.#placeholder.type = value;
    this.data.placeholderType = value;
    this.recordShapeSet({ placeholderType: value });
  }
  get placeholderIndex() {
    return this.#placeholder.index;
  }
  set placeholderIndex(value) {
    this.#placeholder.index = value;
    this.data.placeholderIndex = value;
    this.recordShapeSet({ placeholderIndex: value });
  }
  isPlaceholder() {
    return this.#placeholder.isSet();
  }
  placeholderKey() {
    return derivePlaceholderKey({
      rawType: this.data.placeholderType,
      name: this.data.name
    });
  }
  get pixelRect() {
    const { left, top, width, height } = this.frame ?? {};
    return {
      x: left ?? 0,
      y: top ?? 0,
      width: width ?? 0,
      height: height ?? 0
    };
  }
  bringToFront() {
    this.zIndex = Shape2.#frontSeed++;
  }
  sendToBack() {
    this.zIndex = Shape2.#backSeed--;
  }
  delete() {
    const anchor = this.elementAnchor();
    const recorder = this.context.getPresentation?.()?.getRecorder?.();
    if (anchor && recorder) {
      recorder.record({
        op: "shape.remove",
        target: recorder.targetRefForElement(this, anchor)
      });
    }
    const deleteElement = this.context.deleteElement;
    if (!deleteElement) {
      throw new Error("Shape deletion is not available in this context.");
    }
    deleteElement(this.id);
  }
  get connector() {
    return this.data.connector;
  }
  get connectorLineStyle() {
    return this.data.connector?.lineStyle;
  }
  get connectorHead() {
    return this.data.connector?.lineStyle?.head;
  }
  get connectorTail() {
    return this.data.connector?.lineStyle?.tail;
  }
  setConnectorFrom(target, fromIdx) {
    this.#setConnectorEndpoint("from", target, fromIdx);
  }
  setConnectorTo(target, toIdx) {
    this.#setConnectorEndpoint("to", target, toIdx);
  }
  get position() {
    return super.position;
  }
  set position(value) {
    super.position = value;
    if (!this.connector) {
      this.#invalidateAttachedConnectorRoutes("committed");
    }
  }
  get frame() {
    return super.frame;
  }
  set frame(value) {
    super.frame = value;
    if (!this.connector) {
      this.#invalidateAttachedConnectorRoutes("committed");
    }
  }
  get previewFrame() {
    return super.previewFrame;
  }
  set previewFrame(value) {
    super.previewFrame = value;
    if (!this.connector) {
      this.#invalidateAttachedConnectorRoutes("preview");
    }
  }
  clearPreviewFrame() {
    super.clearPreviewFrame();
    if (!this.connector) {
      this.#invalidateAttachedConnectorRoutes("committed");
    }
  }
  invalidateConnectorRoute(scope = "committed") {
    if (!this.data.connector || !this.data.shape) {
      return;
    }
    this.#connectorRouteInvalidation = scope;
    if (scope === "committed") {
      super.clearPreviewFrame();
    }
  }
  toProto() {
    this.#applyConnectorRouteLayout();
    const proto = super.toProto();
    if (!proto.shape) {
      return proto;
    }
    const fillProto = this.#fill.toProto();
    proto.shape.fill = fillProto ?? undefined;
    const lineProto = this.#line.toProto();
    proto.shape.line = lineProto ?? undefined;
    return proto;
  }
  #applyConnectorRouteLayout() {
    if (!this.data.connector || !this.data.shape) {
      return;
    }
    if (!this.#connectorRouteInvalidation && this.position.toProto()) {
      return;
    }
    const presentation = this.context.getPresentation?.();
    const slide = this.context.getSlide?.();
    if (!presentation || !slide) {
      return;
    }
    const sourceGeometry = this.data.shape.geometry;
    const connectorEl = super.toProto();
    if (connectorEl.shape && sourceGeometry !== undefined) {
      connectorEl.shape.geometry = sourceGeometry;
    }
    const elements = slide.elements.items.filter((element) => !(element instanceof Shape2 && element.connector)).map((element) => element.toProto());
    let commands = [];
    try {
      const routed = autoRouteConnectorPx({
        connectorEl,
        elements,
        pres: presentation,
        slide
      });
      commands = routed.commands;
    } catch (error) {
      console.warn("autoRouteConnectorPx failed; using fallback line", error);
      commands = [];
    }
    let points = commandsToPoints(commands);
    if (points.length < 2) {
      points = buildFallbackConnectorPoints(connectorEl.connector, elements, presentation, slide);
    }
    if (points.length < 2) {
      return;
    }
    let layout = isCurvedConnectorGeometry(sourceGeometry) ? buildCurvedConnectorPresetLayout(points) : undefined;
    if (!layout) {
      layout = buildConnectorPresetLayout(points);
    }
    if (!layout) {
      layout = buildConnectorFallbackPresetLayout(points, sourceGeometry);
    }
    if (!layout && points.length >= 2) {
      const fallbackPoints = buildOrthogonalFallbackPoints(points[0], points[points.length - 1]);
      layout = buildConnectorPresetLayout(fallbackPoints);
    }
    if (!layout) {
      return;
    }
    const nextFrame = {
      left: layout.bounds.minX,
      top: layout.bounds.minY,
      width: layout.width,
      height: layout.height,
      horizontalFlip: layout.flipH || undefined,
      verticalFlip: layout.flipV || undefined
    };
    if (this.#connectorRouteInvalidation === "preview") {
      super.previewFrame = nextFrame;
    } else {
      this.position.merge(nextFrame);
      super.clearPreviewFrame();
    }
    this.#connectorRouteInvalidation = undefined;
    this.data.shape.geometry = layout.geometry;
    this.data.shape.adjustmentList = layout.adjustments;
    this.data.shape.customPaths = [];
  }
  #bindPositionChangeHandler() {
    this.position.setChangeHandler((patch) => {
      this.recordPositionSet(patch);
      if (!this.connector) {
        this.#invalidateAttachedConnectorRoutes("committed");
      }
    });
  }
  #invalidateAttachedConnectorRoutes(scope) {
    if (this.connector || !this.id) {
      return;
    }
    const slide = this.context.getSlide?.();
    if (!slide) {
      return;
    }
    for (const shape of slide.shapes.items) {
      const connector = shape.connector;
      if (!connector) {
        continue;
      }
      if (connector.fromElementId === this.id || connector.toElementId === this.id) {
        shape.invalidateConnectorRoute(scope);
      }
    }
  }
  #setConnectorEndpoint(endpoint, target, siteIndex) {
    const connector = this.data.connector;
    if (!connector) {
      throw new Error("Connector endpoint updates are only available on connector shapes.");
    }
    if (target === undefined && siteIndex === undefined) {
      return;
    }
    const resolvedTarget = this.#resolveConnectorEndpointUpdateTarget(endpoint, target);
    const indexLabel = endpoint === "from" ? "fromIdx" : "toIdx";
    const normalizedIndex = siteIndex === undefined ? undefined : normalizeConnectorIndex(siteIndex, indexLabel);
    if (endpoint === "from") {
      if (resolvedTarget) {
        connector.fromElementId = resolvedTarget.localId;
      }
      if (normalizedIndex !== undefined) {
        connector.fromIdx = normalizedIndex;
      }
      this.invalidateConnectorRoute("committed");
      this.recordShapeSet({
        from: resolvedTarget?.targetRef,
        fromIdx: normalizedIndex
      });
      return;
    }
    if (resolvedTarget) {
      connector.toElementId = resolvedTarget.localId;
    }
    if (normalizedIndex !== undefined) {
      connector.toIdx = normalizedIndex;
    }
    this.invalidateConnectorRoute("committed");
    this.recordShapeSet({
      to: resolvedTarget?.targetRef,
      toIdx: normalizedIndex
    });
  }
  #resolveConnectorEndpointUpdateTarget(endpoint, target) {
    if (target === undefined) {
      return;
    }
    const slide = this.context.getSlide?.();
    if (!slide) {
      throw new Error(`Connector ${endpoint} updates require a slide context.`);
    }
    const localId = typeof target === "string" ? resolveElementLocalId(target, {
      prefix: "sh",
      aliases: ["shape"],
      slideId: slide.id,
      localIds: slide.shapes.items.map((shape) => shape.id)
    }) : target.id;
    if (!localId) {
      throw new Error(`Connector ${endpoint} endpoint id must be non-empty.`);
    }
    const endpointShape = typeof target === "string" ? slide.shapes.getById(localId) : target;
    if (!endpointShape) {
      throw new Error(`Connector ${endpoint} shape not found for id: ${localId}`);
    }
    if (endpointShape.connector) {
      throw new Error(`Connector ${endpoint} endpoint cannot be another connector.`);
    }
    if (endpointShape.slideId && endpointShape.slideId !== slide.id) {
      throw new Error(`Connector ${endpoint} endpoint must belong to slide ${slide.id}.`);
    }
    const anchor = endpointShape.elementAnchor();
    if (!anchor) {
      throw new Error(`Connector ${endpoint} endpoint shape is missing an anchor id.`);
    }
    return {
      localId,
      targetRef: endpointShape.recordTargetRef(anchor)
    };
  }
  #bindLine(value) {
    value.setChangeHandler((line) => {
      this.recordShapeSet({ line: this.#linePatchFromLine(line) });
    });
    return value;
  }
  #createLine(config) {
    return this.#bindLine(new Line4(config));
  }
  #linePatchFromLine(value) {
    const patch = {};
    if (value.style !== undefined) {
      patch.style = value.style;
    }
    if (value.width !== undefined) {
      patch.width = value.width;
    }
    const fillConfig = value.fill?.toConfig();
    if (fillConfig && isPatchFillConfig2(fillConfig)) {
      patch.fill = fillConfig;
    }
    return Object.keys(patch).length > 0 ? patch : undefined;
  }
}
var isPatchFillConfig2 = (value) => {
  if (!value || typeof value !== "object") {
    return true;
  }
  if ("type" in value && value.type === "proto") {
    return false;
  }
  return true;
};
function buildConnectorElement(config) {
  const bbox = config.position ? new Position(config.position, true).toProto() : undefined;
  const geometry = resolveConnectorGeometry(config.kind);
  const connector = {
    fromElementId: resolveConnectorEndpoint(config.from, "from"),
    fromIdx: normalizeConnectorIndex(config.fromIdx, "fromIdx"),
    toElementId: resolveConnectorEndpoint(config.to, "to"),
    toIdx: normalizeConnectorIndex(config.toIdx, "toIdx"),
    lineStyle: buildConnectorLineStyle(config)
  };
  return {
    element: {
      type: 5 /* ELEMENT_TYPE_SHAPE */,
      bbox,
      connector,
      shape: {
        geometry,
        fill: undefined,
        adjustmentList: config.adjustmentList ?? [],
        rectFormula: undefined,
        customPaths: []
      }
    }
  };
}
function resolveConnectorGeometry(kind) {
  const normalized = kind ?? "elbow";
  switch (normalized) {
    case "straight":
      return 96 /* SHAPE_GEOMETRY_STRAIGHT_CONNECTOR1 */;
    case "curved":
      return 103 /* SHAPE_GEOMETRY_CURVED_CONNECTOR4 */;
    case "elbow2":
      return 97 /* SHAPE_GEOMETRY_BENT_CONNECTOR2 */;
    case "elbow3":
      return 98 /* SHAPE_GEOMETRY_BENT_CONNECTOR3 */;
    case "elbow5":
      return 100 /* SHAPE_GEOMETRY_BENT_CONNECTOR5 */;
    case "elbow":
    case "elbow4":
    default:
      return 99 /* SHAPE_GEOMETRY_BENT_CONNECTOR4 */;
  }
}
function resolveConnectorEndpoint(target, label) {
  if (typeof target === "string") {
    if (!target) {
      throw new Error(`Connector ${label} endpoint id must be non-empty.`);
    }
    return target;
  }
  const id = target.id;
  if (!id) {
    throw new Error(`Connector ${label} endpoint shape must have an id.`);
  }
  return id;
}
function normalizeConnectorIndex(value, label) {
  if (!Number.isFinite(value)) {
    throw new Error(`Connector ${label} must be a finite number.`);
  }
  return value;
}
function buildConnectorLineStyle(config) {
  const head = buildConnectorLineEnd(config.head);
  const tail = buildConnectorLineEnd(config.tail);
  const cap = config.cap ? CONNECTOR_LINE_CAPS[config.cap] : undefined;
  const join = config.join ? CONNECTOR_LINE_JOINS[config.join] : undefined;
  if (!head && !tail && !cap && !join) {
    return;
  }
  return {
    head,
    tail,
    cap,
    join
  };
}
function buildConnectorLineEnd(config) {
  if (!config) {
    return;
  }
  const typeKey = config.type ?? "none";
  const widthKey = config.width ?? "med";
  const lengthKey = config.length ?? "med";
  const type = CONNECTOR_LINE_END_TYPES[typeKey] ?? 0 /* LINE_END_TYPE_UNSPECIFIED */;
  const width = CONNECTOR_LINE_END_WIDTHS[widthKey] ?? 2 /* LINE_END_WIDTH_MEDIUM */;
  const length = CONNECTOR_LINE_END_LENGTHS[lengthKey] ?? 2 /* LINE_END_LENGTH_MEDIUM */;
  return { type, width, length };
}
var CONNECTOR_LINE_CAPS = {
  flat: 1 /* LINE_CAP_FLAT */,
  round: 2 /* LINE_CAP_ROUND */,
  square: 3 /* LINE_CAP_SQUARE */
};
var CONNECTOR_LINE_JOINS = {
  round: 1 /* LINE_JOIN_ROUND */,
  bevel: 2 /* LINE_JOIN_BEVEL */,
  miter: 3 /* LINE_JOIN_MITER */
};
var CONNECTOR_LINE_END_TYPES = {
  none: 1 /* LINE_END_TYPE_NONE */,
  triangle: 2 /* LINE_END_TYPE_TRIANGLE */,
  stealth: 3 /* LINE_END_TYPE_STEALTH */,
  diamond: 4 /* LINE_END_TYPE_DIAMOND */,
  oval: 5 /* LINE_END_TYPE_OVAL */,
  arrow: 6 /* LINE_END_TYPE_ARROW */
};
var CONNECTOR_LINE_END_WIDTHS = {
  sm: 1 /* LINE_END_WIDTH_SMALL */,
  med: 2 /* LINE_END_WIDTH_MEDIUM */,
  lg: 3 /* LINE_END_WIDTH_LARGE */
};
var CONNECTOR_LINE_END_LENGTHS = {
  sm: 1 /* LINE_END_LENGTH_SMALL */,
  med: 2 /* LINE_END_LENGTH_MEDIUM */,
  lg: 3 /* LINE_END_LENGTH_LARGE */
};
var CONNECTOR_FALLBACK_STUB_PX = 24;
function buildFallbackConnectorPoints(connector, elements, pres, slide) {
  if (!connector) {
    return [];
  }
  const fromEl = elements.find((candidate) => candidate.id === connector.fromElementId);
  const toEl = elements.find((candidate) => candidate.id === connector.toElementId);
  if (!fromEl || !toEl) {
    return [];
  }
  const fromRect = getBBox(fromEl, pres, slide);
  const toRect = getBBox(toEl, pres, slide);
  const fromCenter = bboxCenter2(fromRect);
  const toCenter = bboxCenter2(toRect);
  const fromAnchor = resolveFallbackConnectorAnchor(fromRect, connector.fromIdx, toCenter);
  const toAnchor = resolveFallbackConnectorAnchor(toRect, connector.toIdx, fromCenter);
  const fromStub = offsetRoutePoint(fromAnchor.point, fromAnchor.normal, CONNECTOR_FALLBACK_STUB_PX);
  const toStub = offsetRoutePoint(toAnchor.point, toAnchor.normal, CONNECTOR_FALLBACK_STUB_PX);
  const middle = buildOrthogonalFallbackPoints(fromStub, toStub);
  return simplifyRoutePoints([fromAnchor.point, ...middle, toAnchor.point]);
}
function buildConnectorPresetLayout(points) {
  const normalized = simplifyRoutePoints(points);
  if (normalized.length < 2) {
    return;
  }
  const bounds = routeBounds(normalized);
  const width = bounds.maxX - bounds.minX;
  const height = bounds.maxY - bounds.minY;
  if (width === 0 && height === 0) {
    return;
  }
  const start = normalized[0];
  const end = normalized[normalized.length - 1];
  const flipH = width !== 0 && start.x > end.x;
  const flipV = height !== 0 && start.y > end.y;
  const segments = normalized.length - 1;
  if (segments <= 1) {
    return {
      bounds,
      width,
      height,
      flipH,
      flipV,
      geometry: 96 /* SHAPE_GEOMETRY_STRAIGHT_CONNECTOR1 */,
      adjustments: []
    };
  }
  const canonical = normalized.map((point3) => {
    const localX = point3.x - bounds.minX;
    const localY = point3.y - bounds.minY;
    return {
      x: flipH ? width - localX : localX,
      y: flipV ? height - localY : localY
    };
  });
  if (!isMonotoneRoute(canonical)) {
    return;
  }
  const firstSegmentVertical = segments > 0 && almostEqual(canonical[0]?.x ?? 0, canonical[1]?.x ?? 0);
  if (segments === 2) {
    if (firstSegmentVertical) {
      return {
        bounds,
        width,
        height,
        flipH,
        flipV,
        geometry: 98 /* SHAPE_GEOMETRY_BENT_CONNECTOR3 */,
        adjustments: [{ name: "adj1", formula: "val 0" }]
      };
    }
    return {
      bounds,
      width,
      height,
      flipH,
      flipV,
      geometry: 97 /* SHAPE_GEOMETRY_BENT_CONNECTOR2 */,
      adjustments: []
    };
  }
  if (segments === 3) {
    if (firstSegmentVertical) {
      const adj22 = computeAdj(canonical[1]?.y, height);
      if (adj22 === undefined)
        return;
      return {
        bounds,
        width,
        height,
        flipH,
        flipV,
        geometry: 99 /* SHAPE_GEOMETRY_BENT_CONNECTOR4 */,
        adjustments: [
          { name: "adj1", formula: "val 0" },
          { name: "adj2", formula: `val ${adj22}` }
        ]
      };
    }
    const adj12 = computeAdj(canonical[1]?.x, width);
    if (adj12 === undefined)
      return;
    return {
      bounds,
      width,
      height,
      flipH,
      flipV,
      geometry: 98 /* SHAPE_GEOMETRY_BENT_CONNECTOR3 */,
      adjustments: [{ name: "adj1", formula: `val ${adj12}` }]
    };
  }
  if (segments === 4) {
    if (firstSegmentVertical) {
      const adj23 = computeAdj(canonical[1]?.y, height);
      const adj32 = computeAdj(canonical[2]?.x, width);
      if (adj23 === undefined || adj32 === undefined)
        return;
      return {
        bounds,
        width,
        height,
        flipH,
        flipV,
        geometry: 100 /* SHAPE_GEOMETRY_BENT_CONNECTOR5 */,
        adjustments: [
          { name: "adj1", formula: "val 0" },
          { name: "adj2", formula: `val ${adj23}` },
          { name: "adj3", formula: `val ${adj32}` }
        ]
      };
    }
    const adj12 = computeAdj(canonical[1]?.x, width);
    const adj22 = computeAdj(canonical[2]?.y, height);
    if (adj12 === undefined || adj22 === undefined)
      return;
    return {
      bounds,
      width,
      height,
      flipH,
      flipV,
      geometry: 99 /* SHAPE_GEOMETRY_BENT_CONNECTOR4 */,
      adjustments: [
        { name: "adj1", formula: `val ${adj12}` },
        { name: "adj2", formula: `val ${adj22}` }
      ]
    };
  }
  if (firstSegmentVertical) {
    return;
  }
  const adj1 = computeAdj(canonical[1]?.x, width);
  const adj2 = computeAdj(canonical[2]?.y, height);
  const adj3 = computeAdj(canonical[3]?.x, width);
  if (adj1 === undefined || adj2 === undefined || adj3 === undefined) {
    return;
  }
  return {
    bounds,
    width,
    height,
    flipH,
    flipV,
    geometry: 100 /* SHAPE_GEOMETRY_BENT_CONNECTOR5 */,
    adjustments: [
      { name: "adj1", formula: `val ${adj1}` },
      { name: "adj2", formula: `val ${adj2}` },
      { name: "adj3", formula: `val ${adj3}` }
    ]
  };
}
function buildCurvedConnectorPresetLayout(points) {
  const normalized = simplifyRoutePoints(points);
  if (normalized.length < 2) {
    return;
  }
  const bounds = routeBounds(normalized);
  const width = bounds.maxX - bounds.minX;
  const height = bounds.maxY - bounds.minY;
  if (width === 0 && height === 0) {
    return;
  }
  const start = normalized[0];
  const end = normalized[normalized.length - 1];
  const flipH = width !== 0 && start.x > end.x;
  const flipV = height !== 0 && start.y > end.y;
  const canonical = normalized.map((point3) => {
    const localX = point3.x - bounds.minX;
    const localY = point3.y - bounds.minY;
    return {
      x: flipH ? width - localX : localX,
      y: flipV ? height - localY : localY
    };
  });
  const segments = normalized.length - 1;
  if (segments <= 1) {
    if (width > 0 && height > 0) {
      return {
        bounds,
        width,
        height,
        flipH,
        flipV,
        geometry: 102 /* SHAPE_GEOMETRY_CURVED_CONNECTOR3 */,
        adjustments: [{ name: "adj1", formula: "val 50000" }]
      };
    }
    return {
      bounds,
      width,
      height,
      flipH,
      flipV,
      geometry: 101 /* SHAPE_GEOMETRY_CURVED_CONNECTOR2 */,
      adjustments: []
    };
  }
  if (!isMonotoneCurveRoute(canonical)) {
    return;
  }
  if (segments === 2) {
    const adj12 = computeAdj(canonical[1]?.x, width);
    if (adj12 === undefined)
      return;
    return {
      bounds,
      width,
      height,
      flipH,
      flipV,
      geometry: 102 /* SHAPE_GEOMETRY_CURVED_CONNECTOR3 */,
      adjustments: [{ name: "adj1", formula: `val ${adj12}` }]
    };
  }
  if (segments === 3) {
    const adj12 = computeAdj(canonical[1]?.x, width);
    const adj22 = computeAdj(canonical[2]?.y, height);
    if (adj12 === undefined || adj22 === undefined)
      return;
    return {
      bounds,
      width,
      height,
      flipH,
      flipV,
      geometry: 103 /* SHAPE_GEOMETRY_CURVED_CONNECTOR4 */,
      adjustments: [
        { name: "adj1", formula: `val ${adj12}` },
        { name: "adj2", formula: `val ${adj22}` }
      ]
    };
  }
  const adj1 = computeAdj(canonical[1]?.x, width);
  const adj2 = computeAdj(canonical[2]?.y, height);
  const adj3 = computeAdj(canonical[3]?.x, width);
  if (adj1 === undefined || adj2 === undefined || adj3 === undefined) {
    return;
  }
  return {
    bounds,
    width,
    height,
    flipH,
    flipV,
    geometry: 104 /* SHAPE_GEOMETRY_CURVED_CONNECTOR5 */,
    adjustments: [
      { name: "adj1", formula: `val ${adj1}` },
      { name: "adj2", formula: `val ${adj2}` },
      { name: "adj3", formula: `val ${adj3}` }
    ]
  };
}
function isMonotoneCurveRoute(points) {
  for (let i = 0;i < points.length - 1; i += 1) {
    const a = points[i];
    const b = points[i + 1];
    if (b.x < a.x - 0.001 || b.y < a.y - 0.001) {
      return false;
    }
  }
  return true;
}
function buildConnectorFallbackPresetLayout(points, sourceGeometry) {
  const normalized = simplifyRoutePoints(points);
  if (normalized.length < 2) {
    return;
  }
  const bounds = routeBounds(normalized);
  const width = bounds.maxX - bounds.minX;
  const height = bounds.maxY - bounds.minY;
  if (width === 0 && height === 0) {
    return;
  }
  const start = normalized[0];
  const end = normalized[normalized.length - 1];
  const flipH = width !== 0 && start.x > end.x;
  const flipV = height !== 0 && start.y > end.y;
  return {
    bounds,
    width,
    height,
    flipH,
    flipV,
    geometry: resolveFallbackConnectorGeometry(sourceGeometry, normalized.length - 1),
    adjustments: []
  };
}
function resolveFallbackConnectorGeometry(sourceGeometry, segments) {
  if (sourceGeometry !== undefined && isConnectorPresetGeometry(sourceGeometry)) {
    return sourceGeometry;
  }
  if (segments <= 1) {
    return 96 /* SHAPE_GEOMETRY_STRAIGHT_CONNECTOR1 */;
  }
  return resolveBentConnectorGeometry(segments);
}
function resolveBentConnectorGeometry(segments) {
  if (segments <= 2) {
    return 97 /* SHAPE_GEOMETRY_BENT_CONNECTOR2 */;
  }
  if (segments === 3) {
    return 98 /* SHAPE_GEOMETRY_BENT_CONNECTOR3 */;
  }
  if (segments === 4) {
    return 99 /* SHAPE_GEOMETRY_BENT_CONNECTOR4 */;
  }
  return 100 /* SHAPE_GEOMETRY_BENT_CONNECTOR5 */;
}
function isConnectorPresetGeometry(geometry) {
  return geometry === 96 /* SHAPE_GEOMETRY_STRAIGHT_CONNECTOR1 */ || isBentConnectorGeometry(geometry) || isCurvedConnectorGeometry(geometry);
}
function isBentConnectorGeometry(geometry) {
  switch (geometry) {
    case 97 /* SHAPE_GEOMETRY_BENT_CONNECTOR2 */:
    case 98 /* SHAPE_GEOMETRY_BENT_CONNECTOR3 */:
    case 99 /* SHAPE_GEOMETRY_BENT_CONNECTOR4 */:
    case 100 /* SHAPE_GEOMETRY_BENT_CONNECTOR5 */:
      return true;
    default:
      return false;
  }
}
function isCurvedConnectorGeometry(geometry) {
  switch (geometry) {
    case 101 /* SHAPE_GEOMETRY_CURVED_CONNECTOR2 */:
    case 102 /* SHAPE_GEOMETRY_CURVED_CONNECTOR3 */:
    case 103 /* SHAPE_GEOMETRY_CURVED_CONNECTOR4 */:
    case 104 /* SHAPE_GEOMETRY_CURVED_CONNECTOR5 */:
      return true;
    default:
      return false;
  }
}
function buildCustomPaths(config) {
  if (config.geometry !== "custom") {
    return [];
  }
  const provided = config.customPaths ?? [];
  if (provided.length === 0) {
    throw new Error('geometry "custom" requires at least one custom path.');
  }
  return provided.map((path3, index) => {
    if (!path3?.commands?.length) {
      throw new Error(`Custom path ${index + 1} must declare at least one command.`);
    }
    const widthPx = Number(path3.width);
    const heightPx = Number(path3.height);
    if (!Number.isFinite(widthPx) || widthPx <= 0) {
      throw new Error(`Custom path ${index + 1} must specify a positive width (pixels).`);
    }
    if (!Number.isFinite(heightPx) || heightPx <= 0) {
      throw new Error(`Custom path ${index + 1} must specify a positive height (pixels).`);
    }
    return {
      id: path3.id,
      widthEmu: emuFromPixels(widthPx),
      heightEmu: emuFromPixels(heightPx),
      commands: path3.commands.map(convertCustomPathCommand)
    };
  });
}
function pxToEmu(value) {
  if (!Number.isFinite(value)) {
    throw new Error("Custom path coordinates must be finite numbers.");
  }
  return emuFromPixels(value);
}
function convertCustomPathCommand(command) {
  if ("moveTo" in command) {
    return {
      moveTo: {
        x: pxToEmu(command.moveTo.x),
        y: pxToEmu(command.moveTo.y)
      }
    };
  }
  if ("lineTo" in command) {
    return {
      lineTo: {
        x: pxToEmu(command.lineTo.x),
        y: pxToEmu(command.lineTo.y)
      }
    };
  }
  return { close: {} };
}
function buildSlideChildAid3(prefix, slideId, localId) {
  return buildElementAid(prefix, slideId, localId);
}

// node_modules/uuid/dist-node/stringify.js
var byteToHex = [];
for (let i = 0;i < 256; ++i) {
  byteToHex.push((i + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 0) {
  return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
}

// node_modules/uuid/dist-node/rng.js
import { randomFillSync } from "node:crypto";
var rnds8Pool = new Uint8Array(256);
var poolPtr = rnds8Pool.length;
function rng() {
  if (poolPtr > rnds8Pool.length - 16) {
    randomFillSync(rnds8Pool);
    poolPtr = 0;
  }
  return rnds8Pool.slice(poolPtr, poolPtr += 16);
}

// node_modules/uuid/dist-node/native.js
import { randomUUID } from "node:crypto";
var native_default = { randomUUID };

// node_modules/uuid/dist-node/v4.js
function _v4(options, buf, offset) {
  options = options || {};
  const rnds = options.random ?? options.rng?.() ?? rng();
  if (rnds.length < 16) {
    throw new Error("Random bytes length must be >= 16");
  }
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  if (buf) {
    offset = offset || 0;
    if (offset < 0 || offset + 16 > buf.length) {
      throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
    }
    for (let i = 0;i < 16; ++i) {
      buf[offset + i] = rnds[i];
    }
    return buf;
  }
  return unsafeStringify(rnds);
}
function v4(options, buf, offset) {
  if (native_default.randomUUID && !buf && !options) {
    return native_default.randomUUID();
  }
  return _v4(options, buf, offset);
}
var v4_default = v4;
// node_modules/lib0/map.js
var create = () => new Map;
var copy2 = (m) => {
  const r = create();
  m.forEach((v, k) => {
    r.set(k, v);
  });
  return r;
};
var setIfUndefined = (map3, key, createT) => {
  let set = map3.get(key);
  if (set === undefined) {
    map3.set(key, set = createT());
  }
  return set;
};
var any = (m, f) => {
  for (const [key, value] of m) {
    if (f(value, key)) {
      return true;
    }
  }
  return false;
};

// node_modules/lib0/set.js
var create2 = () => new Set;

// node_modules/lib0/array.js
var last = (arr) => arr[arr.length - 1];
var appendTo = (dest, src) => {
  for (let i = 0;i < src.length; i++) {
    dest.push(src[i]);
  }
};
var from = Array.from;
var some = (arr, f) => {
  for (let i = 0;i < arr.length; i++) {
    if (f(arr[i], i, arr)) {
      return true;
    }
  }
  return false;
};
var isArray = Array.isArray;

// node_modules/lib0/observable.js
class ObservableV2 {
  constructor() {
    this._observers = create();
  }
  on(name, f) {
    setIfUndefined(this._observers, name, create2).add(f);
    return f;
  }
  once(name, f) {
    const _f = (...args) => {
      this.off(name, _f);
      f(...args);
    };
    this.on(name, _f);
  }
  off(name, f) {
    const observers = this._observers.get(name);
    if (observers !== undefined) {
      observers.delete(f);
      if (observers.size === 0) {
        this._observers.delete(name);
      }
    }
  }
  emit(name, args) {
    return from((this._observers.get(name) || create()).values()).forEach((f) => f(...args));
  }
  destroy() {
    this._observers = create();
  }
}

// node_modules/lib0/math.js
var floor = Math.floor;
var abs2 = Math.abs;
var min2 = (a, b) => a < b ? a : b;
var max3 = (a, b) => a > b ? a : b;
var isNegativeZero = (n) => n !== 0 ? n < 0 : 1 / n < 0;

// node_modules/lib0/binary.js
var BIT1 = 1;
var BIT2 = 2;
var BIT3 = 4;
var BIT4 = 8;
var BIT6 = 32;
var BIT7 = 64;
var BIT8 = 128;
var BIT18 = 1 << 17;
var BIT19 = 1 << 18;
var BIT20 = 1 << 19;
var BIT21 = 1 << 20;
var BIT22 = 1 << 21;
var BIT23 = 1 << 22;
var BIT24 = 1 << 23;
var BIT25 = 1 << 24;
var BIT26 = 1 << 25;
var BIT27 = 1 << 26;
var BIT28 = 1 << 27;
var BIT29 = 1 << 28;
var BIT30 = 1 << 29;
var BIT31 = 1 << 30;
var BIT32 = 1 << 31;
var BITS5 = 31;
var BITS6 = 63;
var BITS7 = 127;
var BITS17 = BIT18 - 1;
var BITS18 = BIT19 - 1;
var BITS19 = BIT20 - 1;
var BITS20 = BIT21 - 1;
var BITS21 = BIT22 - 1;
var BITS22 = BIT23 - 1;
var BITS23 = BIT24 - 1;
var BITS24 = BIT25 - 1;
var BITS25 = BIT26 - 1;
var BITS26 = BIT27 - 1;
var BITS27 = BIT28 - 1;
var BITS28 = BIT29 - 1;
var BITS29 = BIT30 - 1;
var BITS30 = BIT31 - 1;
var BITS31 = 2147483647;

// node_modules/lib0/number.js
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER;
var LOWEST_INT32 = 1 << 31;
var isInteger = Number.isInteger || ((num) => typeof num === "number" && isFinite(num) && floor(num) === num);

// node_modules/lib0/string.js
var fromCharCode = String.fromCharCode;
var fromCodePoint = String.fromCodePoint;
var MAX_UTF16_CHARACTER = fromCharCode(65535);
var toLowerCase = (s) => s.toLowerCase();
var trimLeftRegex = /^\s*/g;
var trimLeft = (s) => s.replace(trimLeftRegex, "");
var fromCamelCaseRegex = /([A-Z])/g;
var fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, (match) => `${separator}${toLowerCase(match)}`));
var _encodeUtf8Polyfill = (str) => {
  const encodedString = unescape(encodeURIComponent(str));
  const len = encodedString.length;
  const buf = new Uint8Array(len);
  for (let i = 0;i < len; i++) {
    buf[i] = encodedString.codePointAt(i);
  }
  return buf;
};
var utf8TextEncoder = typeof TextEncoder !== "undefined" ? new TextEncoder : null;
var _encodeUtf8Native = (str) => utf8TextEncoder.encode(str);
var encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill;
var utf8TextDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array).length === 1) {
  utf8TextDecoder = null;
}

// node_modules/lib0/encoding.js
class Encoder {
  constructor() {
    this.cpos = 0;
    this.cbuf = new Uint8Array(100);
    this.bufs = [];
  }
}
var createEncoder = () => new Encoder;
var length = (encoder) => {
  let len = encoder.cpos;
  for (let i = 0;i < encoder.bufs.length; i++) {
    len += encoder.bufs[i].length;
  }
  return len;
};
var toUint8Array = (encoder) => {
  const uint8arr = new Uint8Array(length(encoder));
  let curPos = 0;
  for (let i = 0;i < encoder.bufs.length; i++) {
    const d = encoder.bufs[i];
    uint8arr.set(d, curPos);
    curPos += d.length;
  }
  uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos);
  return uint8arr;
};
var verifyLen = (encoder, len) => {
  const bufferLen = encoder.cbuf.length;
  if (bufferLen - encoder.cpos < len) {
    encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos));
    encoder.cbuf = new Uint8Array(max3(bufferLen, len) * 2);
    encoder.cpos = 0;
  }
};
var write = (encoder, num) => {
  const bufferLen = encoder.cbuf.length;
  if (encoder.cpos === bufferLen) {
    encoder.bufs.push(encoder.cbuf);
    encoder.cbuf = new Uint8Array(bufferLen * 2);
    encoder.cpos = 0;
  }
  encoder.cbuf[encoder.cpos++] = num;
};
var writeUint8 = write;
var writeVarUint = (encoder, num) => {
  while (num > BITS7) {
    write(encoder, BIT8 | BITS7 & num);
    num = floor(num / 128);
  }
  write(encoder, BITS7 & num);
};
var writeVarInt = (encoder, num) => {
  const isNegative = isNegativeZero(num);
  if (isNegative) {
    num = -num;
  }
  write(encoder, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | BITS6 & num);
  num = floor(num / 64);
  while (num > 0) {
    write(encoder, (num > BITS7 ? BIT8 : 0) | BITS7 & num);
    num = floor(num / 128);
  }
};
var _strBuffer = new Uint8Array(30000);
var _maxStrBSize = _strBuffer.length / 3;
var _writeVarStringNative = (encoder, str) => {
  if (str.length < _maxStrBSize) {
    const written = utf8TextEncoder.encodeInto(str, _strBuffer).written || 0;
    writeVarUint(encoder, written);
    for (let i = 0;i < written; i++) {
      write(encoder, _strBuffer[i]);
    }
  } else {
    writeVarUint8Array(encoder, encodeUtf8(str));
  }
};
var _writeVarStringPolyfill = (encoder, str) => {
  const encodedString = unescape(encodeURIComponent(str));
  const len = encodedString.length;
  writeVarUint(encoder, len);
  for (let i = 0;i < len; i++) {
    write(encoder, encodedString.codePointAt(i));
  }
};
var writeVarString = utf8TextEncoder && utf8TextEncoder.encodeInto ? _writeVarStringNative : _writeVarStringPolyfill;
var writeUint8Array = (encoder, uint8Array) => {
  const bufferLen = encoder.cbuf.length;
  const cpos = encoder.cpos;
  const leftCopyLen = min2(bufferLen - cpos, uint8Array.length);
  const rightCopyLen = uint8Array.length - leftCopyLen;
  encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
  encoder.cpos += leftCopyLen;
  if (rightCopyLen > 0) {
    encoder.bufs.push(encoder.cbuf);
    encoder.cbuf = new Uint8Array(max3(bufferLen * 2, rightCopyLen));
    encoder.cbuf.set(uint8Array.subarray(leftCopyLen));
    encoder.cpos = rightCopyLen;
  }
};
var writeVarUint8Array = (encoder, uint8Array) => {
  writeVarUint(encoder, uint8Array.byteLength);
  writeUint8Array(encoder, uint8Array);
};
var writeOnDataView = (encoder, len) => {
  verifyLen(encoder, len);
  const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len);
  encoder.cpos += len;
  return dview;
};
var writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false);
var writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false);
var writeBigInt64 = (encoder, num) => writeOnDataView(encoder, 8).setBigInt64(0, num, false);
var floatTestBed = new DataView(new ArrayBuffer(4));
var isFloat32 = (num) => {
  floatTestBed.setFloat32(0, num);
  return floatTestBed.getFloat32(0) === num;
};
var writeAny = (encoder, data) => {
  switch (typeof data) {
    case "string":
      write(encoder, 119);
      writeVarString(encoder, data);
      break;
    case "number":
      if (isInteger(data) && abs2(data) <= BITS31) {
        write(encoder, 125);
        writeVarInt(encoder, data);
      } else if (isFloat32(data)) {
        write(encoder, 124);
        writeFloat32(encoder, data);
      } else {
        write(encoder, 123);
        writeFloat64(encoder, data);
      }
      break;
    case "bigint":
      write(encoder, 122);
      writeBigInt64(encoder, data);
      break;
    case "object":
      if (data === null) {
        write(encoder, 126);
      } else if (isArray(data)) {
        write(encoder, 117);
        writeVarUint(encoder, data.length);
        for (let i = 0;i < data.length; i++) {
          writeAny(encoder, data[i]);
        }
      } else if (data instanceof Uint8Array) {
        write(encoder, 116);
        writeVarUint8Array(encoder, data);
      } else {
        write(encoder, 118);
        const keys = Object.keys(data);
        writeVarUint(encoder, keys.length);
        for (let i = 0;i < keys.length; i++) {
          const key = keys[i];
          writeVarString(encoder, key);
          writeAny(encoder, data[key]);
        }
      }
      break;
    case "boolean":
      write(encoder, data ? 120 : 121);
      break;
    default:
      write(encoder, 127);
  }
};

class RleEncoder extends Encoder {
  constructor(writer) {
    super();
    this.w = writer;
    this.s = null;
    this.count = 0;
  }
  write(v) {
    if (this.s === v) {
      this.count++;
    } else {
      if (this.count > 0) {
        writeVarUint(this, this.count - 1);
      }
      this.count = 1;
      this.w(this, v);
      this.s = v;
    }
  }
}
var flushUintOptRleEncoder = (encoder) => {
  if (encoder.count > 0) {
    writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s);
    if (encoder.count > 1) {
      writeVarUint(encoder.encoder, encoder.count - 2);
    }
  }
};

class UintOptRleEncoder {
  constructor() {
    this.encoder = new Encoder;
    this.s = 0;
    this.count = 0;
  }
  write(v) {
    if (this.s === v) {
      this.count++;
    } else {
      flushUintOptRleEncoder(this);
      this.count = 1;
      this.s = v;
    }
  }
  toUint8Array() {
    flushUintOptRleEncoder(this);
    return toUint8Array(this.encoder);
  }
}
var flushIntDiffOptRleEncoder = (encoder) => {
  if (encoder.count > 0) {
    const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1);
    writeVarInt(encoder.encoder, encodedDiff);
    if (encoder.count > 1) {
      writeVarUint(encoder.encoder, encoder.count - 2);
    }
  }
};

class IntDiffOptRleEncoder {
  constructor() {
    this.encoder = new Encoder;
    this.s = 0;
    this.count = 0;
    this.diff = 0;
  }
  write(v) {
    if (this.diff === v - this.s) {
      this.s = v;
      this.count++;
    } else {
      flushIntDiffOptRleEncoder(this);
      this.count = 1;
      this.diff = v - this.s;
      this.s = v;
    }
  }
  toUint8Array() {
    flushIntDiffOptRleEncoder(this);
    return toUint8Array(this.encoder);
  }
}

class StringEncoder {
  constructor() {
    this.sarr = [];
    this.s = "";
    this.lensE = new UintOptRleEncoder;
  }
  write(string) {
    this.s += string;
    if (this.s.length > 19) {
      this.sarr.push(this.s);
      this.s = "";
    }
    this.lensE.write(string.length);
  }
  toUint8Array() {
    const encoder = new Encoder;
    this.sarr.push(this.s);
    this.s = "";
    writeVarString(encoder, this.sarr.join(""));
    writeUint8Array(encoder, this.lensE.toUint8Array());
    return toUint8Array(encoder);
  }
}

// node_modules/lib0/error.js
var create3 = (s) => new Error(s);
var methodUnimplemented = () => {
  throw create3("Method unimplemented");
};
var unexpectedCase = () => {
  throw create3("Unexpected case");
};

// node_modules/lib0/decoding.js
var errorUnexpectedEndOfArray = create3("Unexpected end of array");
var errorIntegerOutOfRange = create3("Integer out of Range");

class Decoder {
  constructor(uint8Array) {
    this.arr = uint8Array;
    this.pos = 0;
  }
}
var createDecoder = (uint8Array) => new Decoder(uint8Array);
var hasContent = (decoder) => decoder.pos !== decoder.arr.length;
var readUint8Array = (decoder, len) => {
  const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len);
  decoder.pos += len;
  return view;
};
var readVarUint8Array = (decoder) => readUint8Array(decoder, readVarUint(decoder));
var readUint8 = (decoder) => decoder.arr[decoder.pos++];
var readVarUint = (decoder) => {
  let num = 0;
  let mult = 1;
  const len = decoder.arr.length;
  while (decoder.pos < len) {
    const r = decoder.arr[decoder.pos++];
    num = num + (r & BITS7) * mult;
    mult *= 128;
    if (r < BIT8) {
      return num;
    }
    if (num > MAX_SAFE_INTEGER) {
      throw errorIntegerOutOfRange;
    }
  }
  throw errorUnexpectedEndOfArray;
};
var readVarInt = (decoder) => {
  let r = decoder.arr[decoder.pos++];
  let num = r & BITS6;
  let mult = 64;
  const sign2 = (r & BIT7) > 0 ? -1 : 1;
  if ((r & BIT8) === 0) {
    return sign2 * num;
  }
  const len = decoder.arr.length;
  while (decoder.pos < len) {
    r = decoder.arr[decoder.pos++];
    num = num + (r & BITS7) * mult;
    mult *= 128;
    if (r < BIT8) {
      return sign2 * num;
    }
    if (num > MAX_SAFE_INTEGER) {
      throw errorIntegerOutOfRange;
    }
  }
  throw errorUnexpectedEndOfArray;
};
var _readVarStringPolyfill = (decoder) => {
  let remainingLen = readVarUint(decoder);
  if (remainingLen === 0) {
    return "";
  } else {
    let encodedString = String.fromCodePoint(readUint8(decoder));
    if (--remainingLen < 100) {
      while (remainingLen--) {
        encodedString += String.fromCodePoint(readUint8(decoder));
      }
    } else {
      while (remainingLen > 0) {
        const nextLen = remainingLen < 1e4 ? remainingLen : 1e4;
        const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen);
        decoder.pos += nextLen;
        encodedString += String.fromCodePoint.apply(null, bytes);
        remainingLen -= nextLen;
      }
    }
    return decodeURIComponent(escape(encodedString));
  }
};
var _readVarStringNative = (decoder) => utf8TextDecoder.decode(readVarUint8Array(decoder));
var readVarString = utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill;
var readFromDataView = (decoder, len) => {
  const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len);
  decoder.pos += len;
  return dv;
};
var readFloat32 = (decoder) => readFromDataView(decoder, 4).getFloat32(0, false);
var readFloat64 = (decoder) => readFromDataView(decoder, 8).getFloat64(0, false);
var readBigInt64 = (decoder) => readFromDataView(decoder, 8).getBigInt64(0, false);
var readAnyLookupTable = [
  (decoder) => {
    return;
  },
  (decoder) => null,
  readVarInt,
  readFloat32,
  readFloat64,
  readBigInt64,
  (decoder) => false,
  (decoder) => true,
  readVarString,
  (decoder) => {
    const len = readVarUint(decoder);
    const obj = {};
    for (let i = 0;i < len; i++) {
      const key = readVarString(decoder);
      obj[key] = readAny(decoder);
    }
    return obj;
  },
  (decoder) => {
    const len = readVarUint(decoder);
    const arr = [];
    for (let i = 0;i < len; i++) {
      arr.push(readAny(decoder));
    }
    return arr;
  },
  readVarUint8Array
];
var readAny = (decoder) => readAnyLookupTable[127 - readUint8(decoder)](decoder);

class RleDecoder extends Decoder {
  constructor(uint8Array, reader) {
    super(uint8Array);
    this.reader = reader;
    this.s = null;
    this.count = 0;
  }
  read() {
    if (this.count === 0) {
      this.s = this.reader(this);
      if (hasContent(this)) {
        this.count = readVarUint(this) + 1;
      } else {
        this.count = -1;
      }
    }
    this.count--;
    return this.s;
  }
}
class UintOptRleDecoder extends Decoder {
  constructor(uint8Array) {
    super(uint8Array);
    this.s = 0;
    this.count = 0;
  }
  read() {
    if (this.count === 0) {
      this.s = readVarInt(this);
      const isNegative = isNegativeZero(this.s);
      this.count = 1;
      if (isNegative) {
        this.s = -this.s;
        this.count = readVarUint(this) + 2;
      }
    }
    this.count--;
    return this.s;
  }
}
class IntDiffOptRleDecoder extends Decoder {
  constructor(uint8Array) {
    super(uint8Array);
    this.s = 0;
    this.count = 0;
    this.diff = 0;
  }
  read() {
    if (this.count === 0) {
      const diff = readVarInt(this);
      const hasCount = diff & 1;
      this.diff = floor(diff / 2);
      this.count = 1;
      if (hasCount) {
        this.count = readVarUint(this) + 2;
      }
    }
    this.s += this.diff;
    this.count--;
    return this.s;
  }
}

class StringDecoder {
  constructor(uint8Array) {
    this.decoder = new UintOptRleDecoder(uint8Array);
    this.str = readVarString(this.decoder);
    this.spos = 0;
  }
  read() {
    const end = this.spos + this.decoder.read();
    const res = this.str.slice(this.spos, end);
    this.spos = end;
    return res;
  }
}

// node_modules/lib0/webcrypto.node.js
import { webcrypto } from "node:crypto";
var subtle = webcrypto.subtle;
var getRandomValues = webcrypto.getRandomValues.bind(webcrypto);

// node_modules/lib0/random.js
var uint32 = () => getRandomValues(new Uint32Array(1))[0];
var uuidv4Template = [1e7] + -1000 + -4000 + -8000 + -100000000000;
var uuidv4 = () => uuidv4Template.replace(/[018]/g, (c) => (c ^ uint32() & 15 >> c / 4).toString(16));

// node_modules/lib0/time.js
var getUnixTime = Date.now;

// node_modules/lib0/promise.js
var create4 = (f) => new Promise(f);
var all = Promise.all.bind(Promise);

// node_modules/lib0/conditions.js
var undefinedToNull = (v) => v === undefined ? null : v;

// node_modules/lib0/storage.js
class VarStoragePolyfill {
  constructor() {
    this.map = new Map;
  }
  setItem(key, newValue) {
    this.map.set(key, newValue);
  }
  getItem(key) {
    return this.map.get(key);
  }
}
var _localStorage = new VarStoragePolyfill;
var usePolyfill = true;
try {
  if (typeof localStorage !== "undefined" && localStorage) {
    _localStorage = localStorage;
    usePolyfill = false;
  }
} catch (e) {}
var varStorage = _localStorage;

// node_modules/lib0/trait/equality.js
var EqualityTraitSymbol = Symbol("Equality");
var equals = (a, b) => a === b || !!a?.[EqualityTraitSymbol]?.(b) || false;

// node_modules/lib0/object.js
var assign = Object.assign;
var keys = Object.keys;
var forEach = (obj, f) => {
  for (const key in obj) {
    f(obj[key], key);
  }
};
var size = (obj) => keys(obj).length;
var isEmpty = (obj) => {
  for (const _k in obj) {
    return false;
  }
  return true;
};
var every = (obj, f) => {
  for (const key in obj) {
    if (!f(obj[key], key)) {
      return false;
    }
  }
  return true;
};
var hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
var equalFlat = (a, b) => a === b || size(a) === size(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && equals(b[key], val));
var freeze = Object.freeze;
var deepFreeze = (o) => {
  for (const key in o) {
    const c = o[key];
    if (typeof c === "object" || typeof c === "function") {
      deepFreeze(o[key]);
    }
  }
  return freeze(o);
};

// node_modules/lib0/function.js
var callAll = (fs2, args, i = 0) => {
  try {
    for (;i < fs2.length; i++) {
      fs2[i](...args);
    }
  } finally {
    if (i < fs2.length) {
      callAll(fs2, args, i + 1);
    }
  }
};
var id = (a) => a;
var isOneOf = (value, options) => options.includes(value);

// node_modules/lib0/environment.js
var isNode = typeof process !== "undefined" && process.release && /node|io\.js/.test(process.release.name) && Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]";
var isMac = typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false;
var params;
var args = [];
var computeParams = () => {
  if (params === undefined) {
    if (isNode) {
      params = create();
      const pargs = process.argv;
      let currParamName = null;
      for (let i = 0;i < pargs.length; i++) {
        const parg = pargs[i];
        if (parg[0] === "-") {
          if (currParamName !== null) {
            params.set(currParamName, "");
          }
          currParamName = parg;
        } else {
          if (currParamName !== null) {
            params.set(currParamName, parg);
            currParamName = null;
          } else {
            args.push(parg);
          }
        }
      }
      if (currParamName !== null) {
        params.set(currParamName, "");
      }
    } else if (typeof location === "object") {
      params = create();
      (location.search || "?").slice(1).split("&").forEach((kv) => {
        if (kv.length !== 0) {
          const [key, value] = kv.split("=");
          params.set(`--${fromCamelCase(key, "-")}`, value);
          params.set(`-${fromCamelCase(key, "-")}`, value);
        }
      });
    } else {
      params = create();
    }
  }
  return params;
};
var hasParam = (name) => computeParams().has(name);
var getVariable = (name) => isNode ? undefinedToNull(process.env[name.toUpperCase().replaceAll("-", "_")]) : undefinedToNull(varStorage.getItem(name));
var hasConf = (name) => hasParam("--" + name) || getVariable(name) !== null;
var production = hasConf("production");
var forceColor = isNode && isOneOf(process.env.FORCE_COLOR, ["true", "1", "2"]);
var supportsColor = forceColor || !hasParam("--no-colors") && !hasConf("no-color") && (!isNode || process.stdout.isTTY) && (!isNode || hasParam("--color") || getVariable("COLORTERM") !== null || (getVariable("TERM") || "").includes("color"));

// node_modules/lib0/buffer.js
var createUint8ArrayFromLen = (len) => new Uint8Array(len);
var copyUint8Array = (uint8Array) => {
  const newBuf = createUint8ArrayFromLen(uint8Array.byteLength);
  newBuf.set(uint8Array);
  return newBuf;
};

// node_modules/lib0/symbol.js
var create5 = Symbol;

// node_modules/lib0/logging.common.js
var BOLD = create5();
var UNBOLD = create5();
var BLUE2 = create5();
var GREY = create5();
var GREEN2 = create5();
var RED2 = create5();
var PURPLE = create5();
var ORANGE2 = create5();
var UNCOLOR = create5();
var computeNoColorLoggingArgs = (args2) => {
  if (args2.length === 1 && args2[0]?.constructor === Function) {
    args2 = args2[0]();
  }
  const strBuilder = [];
  const logArgs = [];
  let i = 0;
  for (;i < args2.length; i++) {
    const arg = args2[i];
    if (arg === undefined) {
      break;
    } else if (arg.constructor === String || arg.constructor === Number) {
      strBuilder.push(arg);
    } else if (arg.constructor === Object) {
      break;
    }
  }
  if (i > 0) {
    logArgs.push(strBuilder.join(""));
  }
  for (;i < args2.length; i++) {
    const arg = args2[i];
    if (!(arg instanceof Symbol)) {
      logArgs.push(arg);
    }
  }
  return logArgs;
};
var lastLoggingTime = getUnixTime();

// node_modules/lib0/logging.node.js
var _nodeStyleMap = {
  [BOLD]: "\x1B[1m",
  [UNBOLD]: "\x1B[2m",
  [BLUE2]: "\x1B[34m",
  [GREEN2]: "\x1B[32m",
  [GREY]: "\x1B[37m",
  [RED2]: "\x1B[31m",
  [PURPLE]: "\x1B[35m",
  [ORANGE2]: "\x1B[38;5;208m",
  [UNCOLOR]: "\x1B[0m"
};
var computeNodeLoggingArgs = (args2) => {
  if (args2.length === 1 && args2[0]?.constructor === Function) {
    args2 = args2[0]();
  }
  const strBuilder = [];
  const logArgs = [];
  let i = 0;
  for (;i < args2.length; i++) {
    const arg = args2[i];
    const style = _nodeStyleMap[arg];
    if (style !== undefined) {
      strBuilder.push(style);
    } else {
      if (arg === undefined) {
        break;
      } else if (arg.constructor === String || arg.constructor === Number) {
        strBuilder.push(arg);
      } else {
        break;
      }
    }
  }
  if (i > 0) {
    strBuilder.push("\x1B[0m");
    logArgs.push(strBuilder.join(""));
  }
  for (;i < args2.length; i++) {
    const arg = args2[i];
    if (!(arg instanceof Symbol)) {
      logArgs.push(arg);
    }
  }
  return logArgs;
};
var computeLoggingArgs = supportsColor ? computeNodeLoggingArgs : computeNoColorLoggingArgs;
var print = (...args2) => {
  console.log(...computeLoggingArgs(args2));
};
var warn2 = (...args2) => {
  console.warn(...computeLoggingArgs(args2));
};

// node_modules/lib0/iterator.js
var createIterator = (next) => ({
  [Symbol.iterator]() {
    return this;
  },
  next
});
var iteratorFilter = (iterator, filter) => createIterator(() => {
  let res;
  do {
    res = iterator.next();
  } while (!res.done && !filter(res.value));
  return res;
});
var iteratorMap = (iterator, fmap) => createIterator(() => {
  const { done, value } = iterator.next();
  return { done, value: done ? undefined : fmap(value) };
});

// node_modules/yjs/dist/yjs.mjs
class DeleteItem {
  constructor(clock, len) {
    this.clock = clock;
    this.len = len;
  }
}

class DeleteSet {
  constructor() {
    this.clients = new Map;
  }
}
var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes, clientid) => {
  const structs = transaction.doc.store.clients.get(clientid);
  if (structs != null) {
    const lastStruct = structs[structs.length - 1];
    const clockState = lastStruct.id.clock + lastStruct.length;
    for (let i = 0, del = deletes[i];i < deletes.length && del.clock < clockState; del = deletes[++i]) {
      iterateStructs(transaction, structs, del.clock, del.len, f);
    }
  }
});
var findIndexDS = (dis, clock) => {
  let left = 0;
  let right = dis.length - 1;
  while (left <= right) {
    const midindex = floor((left + right) / 2);
    const mid = dis[midindex];
    const midclock = mid.clock;
    if (midclock <= clock) {
      if (clock < midclock + mid.len) {
        return midindex;
      }
      left = midindex + 1;
    } else {
      right = midindex - 1;
    }
  }
  return null;
};
var isDeleted = (ds, id2) => {
  const dis = ds.clients.get(id2.client);
  return dis !== undefined && findIndexDS(dis, id2.clock) !== null;
};
var sortAndMergeDeleteSet = (ds) => {
  ds.clients.forEach((dels) => {
    dels.sort((a, b) => a.clock - b.clock);
    let i, j;
    for (i = 1, j = 1;i < dels.length; i++) {
      const left = dels[j - 1];
      const right = dels[i];
      if (left.clock + left.len >= right.clock) {
        dels[j - 1] = new DeleteItem(left.clock, max3(left.len, right.clock + right.len - left.clock));
      } else {
        if (j < i) {
          dels[j] = right;
        }
        j++;
      }
    }
    dels.length = j;
  });
};
var mergeDeleteSets = (dss) => {
  const merged = new DeleteSet;
  for (let dssI = 0;dssI < dss.length; dssI++) {
    dss[dssI].clients.forEach((delsLeft, client) => {
      if (!merged.clients.has(client)) {
        const dels = delsLeft.slice();
        for (let i = dssI + 1;i < dss.length; i++) {
          appendTo(dels, dss[i].clients.get(client) || []);
        }
        merged.clients.set(client, dels);
      }
    });
  }
  sortAndMergeDeleteSet(merged);
  return merged;
};
var addToDeleteSet = (ds, client, clock, length2) => {
  setIfUndefined(ds.clients, client, () => []).push(new DeleteItem(clock, length2));
};
var createDeleteSet = () => new DeleteSet;
var createDeleteSetFromStructStore = (ss) => {
  const ds = createDeleteSet();
  ss.clients.forEach((structs, client) => {
    const dsitems = [];
    for (let i = 0;i < structs.length; i++) {
      const struct = structs[i];
      if (struct.deleted) {
        const clock = struct.id.clock;
        let len = struct.length;
        if (i + 1 < structs.length) {
          for (let next = structs[i + 1];i + 1 < structs.length && next.deleted; next = structs[++i + 1]) {
            len += next.length;
          }
        }
        dsitems.push(new DeleteItem(clock, len));
      }
    }
    if (dsitems.length > 0) {
      ds.clients.set(client, dsitems);
    }
  });
  return ds;
};
var writeDeleteSet = (encoder, ds) => {
  writeVarUint(encoder.restEncoder, ds.clients.size);
  from(ds.clients.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, dsitems]) => {
    encoder.resetDsCurVal();
    writeVarUint(encoder.restEncoder, client);
    const len = dsitems.length;
    writeVarUint(encoder.restEncoder, len);
    for (let i = 0;i < len; i++) {
      const item = dsitems[i];
      encoder.writeDsClock(item.clock);
      encoder.writeDsLen(item.len);
    }
  });
};
var readDeleteSet = (decoder) => {
  const ds = new DeleteSet;
  const numClients = readVarUint(decoder.restDecoder);
  for (let i = 0;i < numClients; i++) {
    decoder.resetDsCurVal();
    const client = readVarUint(decoder.restDecoder);
    const numberOfDeletes = readVarUint(decoder.restDecoder);
    if (numberOfDeletes > 0) {
      const dsField = setIfUndefined(ds.clients, client, () => []);
      for (let i2 = 0;i2 < numberOfDeletes; i2++) {
        dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen()));
      }
    }
  }
  return ds;
};
var readAndApplyDeleteSet = (decoder, transaction, store) => {
  const unappliedDS = new DeleteSet;
  const numClients = readVarUint(decoder.restDecoder);
  for (let i = 0;i < numClients; i++) {
    decoder.resetDsCurVal();
    const client = readVarUint(decoder.restDecoder);
    const numberOfDeletes = readVarUint(decoder.restDecoder);
    const structs = store.clients.get(client) || [];
    const state = getState(store, client);
    for (let i2 = 0;i2 < numberOfDeletes; i2++) {
      const clock = decoder.readDsClock();
      const clockEnd = clock + decoder.readDsLen();
      if (clock < state) {
        if (state < clockEnd) {
          addToDeleteSet(unappliedDS, client, state, clockEnd - state);
        }
        let index = findIndexSS(structs, clock);
        let struct = structs[index];
        if (!struct.deleted && struct.id.clock < clock) {
          structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock));
          index++;
        }
        while (index < structs.length) {
          struct = structs[index++];
          if (struct.id.clock < clockEnd) {
            if (!struct.deleted) {
              if (clockEnd < struct.id.clock + struct.length) {
                structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock));
              }
              struct.delete(transaction);
            }
          } else {
            break;
          }
        }
      } else {
        addToDeleteSet(unappliedDS, client, clock, clockEnd - clock);
      }
    }
  }
  if (unappliedDS.clients.size > 0) {
    const ds = new UpdateEncoderV2;
    writeVarUint(ds.restEncoder, 0);
    writeDeleteSet(ds, unappliedDS);
    return ds.toUint8Array();
  }
  return null;
};
var generateNewClientId = uint32;

class Doc extends ObservableV2 {
  constructor({ guid = uuidv4(), collectionid = null, gc = true, gcFilter = () => true, meta = null, autoLoad = false, shouldLoad = true } = {}) {
    super();
    this.gc = gc;
    this.gcFilter = gcFilter;
    this.clientID = generateNewClientId();
    this.guid = guid;
    this.collectionid = collectionid;
    this.share = new Map;
    this.store = new StructStore;
    this._transaction = null;
    this._transactionCleanups = [];
    this.subdocs = new Set;
    this._item = null;
    this.shouldLoad = shouldLoad;
    this.autoLoad = autoLoad;
    this.meta = meta;
    this.isLoaded = false;
    this.isSynced = false;
    this.isDestroyed = false;
    this.whenLoaded = create4((resolve2) => {
      this.on("load", () => {
        this.isLoaded = true;
        resolve2(this);
      });
    });
    const provideSyncedPromise = () => create4((resolve2) => {
      const eventHandler = (isSynced) => {
        if (isSynced === undefined || isSynced === true) {
          this.off("sync", eventHandler);
          resolve2();
        }
      };
      this.on("sync", eventHandler);
    });
    this.on("sync", (isSynced) => {
      if (isSynced === false && this.isSynced) {
        this.whenSynced = provideSyncedPromise();
      }
      this.isSynced = isSynced === undefined || isSynced === true;
      if (this.isSynced && !this.isLoaded) {
        this.emit("load", [this]);
      }
    });
    this.whenSynced = provideSyncedPromise();
  }
  load() {
    const item = this._item;
    if (item !== null && !this.shouldLoad) {
      transact(item.parent.doc, (transaction) => {
        transaction.subdocsLoaded.add(this);
      }, null, true);
    }
    this.shouldLoad = true;
  }
  getSubdocs() {
    return this.subdocs;
  }
  getSubdocGuids() {
    return new Set(from(this.subdocs).map((doc) => doc.guid));
  }
  transact(f, origin = null) {
    return transact(this, f, origin);
  }
  get(name, TypeConstructor = AbstractType) {
    const type = setIfUndefined(this.share, name, () => {
      const t = new TypeConstructor;
      t._integrate(this, null);
      return t;
    });
    const Constr = type.constructor;
    if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) {
      if (Constr === AbstractType) {
        const t = new TypeConstructor;
        t._map = type._map;
        type._map.forEach((n) => {
          for (;n !== null; n = n.left) {
            n.parent = t;
          }
        });
        t._start = type._start;
        for (let n = t._start;n !== null; n = n.right) {
          n.parent = t;
        }
        t._length = type._length;
        this.share.set(name, t);
        t._integrate(this, null);
        return t;
      } else {
        throw new Error(`Type with the name ${name} has already been defined with a different constructor`);
      }
    }
    return type;
  }
  getArray(name = "") {
    return this.get(name, YArray);
  }
  getText(name = "") {
    return this.get(name, YText);
  }
  getMap(name = "") {
    return this.get(name, YMap);
  }
  getXmlElement(name = "") {
    return this.get(name, YXmlElement);
  }
  getXmlFragment(name = "") {
    return this.get(name, YXmlFragment);
  }
  toJSON() {
    const doc = {};
    this.share.forEach((value, key) => {
      doc[key] = value.toJSON();
    });
    return doc;
  }
  destroy() {
    this.isDestroyed = true;
    from(this.subdocs).forEach((subdoc) => subdoc.destroy());
    const item = this._item;
    if (item !== null) {
      this._item = null;
      const content = item.content;
      content.doc = new Doc({ guid: this.guid, ...content.opts, shouldLoad: false });
      content.doc._item = item;
      transact(item.parent.doc, (transaction) => {
        const doc = content.doc;
        if (!item.deleted) {
          transaction.subdocsAdded.add(doc);
        }
        transaction.subdocsRemoved.add(this);
      }, null, true);
    }
    this.emit("destroyed", [true]);
    this.emit("destroy", [this]);
    super.destroy();
  }
}

class DSDecoderV1 {
  constructor(decoder) {
    this.restDecoder = decoder;
  }
  resetDsCurVal() {}
  readDsClock() {
    return readVarUint(this.restDecoder);
  }
  readDsLen() {
    return readVarUint(this.restDecoder);
  }
}

class UpdateDecoderV1 extends DSDecoderV1 {
  readLeftID() {
    return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder));
  }
  readRightID() {
    return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder));
  }
  readClient() {
    return readVarUint(this.restDecoder);
  }
  readInfo() {
    return readUint8(this.restDecoder);
  }
  readString() {
    return readVarString(this.restDecoder);
  }
  readParentInfo() {
    return readVarUint(this.restDecoder) === 1;
  }
  readTypeRef() {
    return readVarUint(this.restDecoder);
  }
  readLen() {
    return readVarUint(this.restDecoder);
  }
  readAny() {
    return readAny(this.restDecoder);
  }
  readBuf() {
    return copyUint8Array(readVarUint8Array(this.restDecoder));
  }
  readJSON() {
    return JSON.parse(readVarString(this.restDecoder));
  }
  readKey() {
    return readVarString(this.restDecoder);
  }
}

class DSDecoderV2 {
  constructor(decoder) {
    this.dsCurrVal = 0;
    this.restDecoder = decoder;
  }
  resetDsCurVal() {
    this.dsCurrVal = 0;
  }
  readDsClock() {
    this.dsCurrVal += readVarUint(this.restDecoder);
    return this.dsCurrVal;
  }
  readDsLen() {
    const diff = readVarUint(this.restDecoder) + 1;
    this.dsCurrVal += diff;
    return diff;
  }
}

class UpdateDecoderV2 extends DSDecoderV2 {
  constructor(decoder) {
    super(decoder);
    this.keys = [];
    readVarUint(decoder);
    this.keyClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));
    this.clientDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));
    this.leftClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));
    this.rightClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));
    this.infoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8);
    this.stringDecoder = new StringDecoder(readVarUint8Array(decoder));
    this.parentInfoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8);
    this.typeRefDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));
    this.lenDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));
  }
  readLeftID() {
    return new ID(this.clientDecoder.read(), this.leftClockDecoder.read());
  }
  readRightID() {
    return new ID(this.clientDecoder.read(), this.rightClockDecoder.read());
  }
  readClient() {
    return this.clientDecoder.read();
  }
  readInfo() {
    return this.infoDecoder.read();
  }
  readString() {
    return this.stringDecoder.read();
  }
  readParentInfo() {
    return this.parentInfoDecoder.read() === 1;
  }
  readTypeRef() {
    return this.typeRefDecoder.read();
  }
  readLen() {
    return this.lenDecoder.read();
  }
  readAny() {
    return readAny(this.restDecoder);
  }
  readBuf() {
    return readVarUint8Array(this.restDecoder);
  }
  readJSON() {
    return readAny(this.restDecoder);
  }
  readKey() {
    const keyClock = this.keyClockDecoder.read();
    if (keyClock < this.keys.length) {
      return this.keys[keyClock];
    } else {
      const key = this.stringDecoder.read();
      this.keys.push(key);
      return key;
    }
  }
}

class DSEncoderV1 {
  constructor() {
    this.restEncoder = createEncoder();
  }
  toUint8Array() {
    return toUint8Array(this.restEncoder);
  }
  resetDsCurVal() {}
  writeDsClock(clock) {
    writeVarUint(this.restEncoder, clock);
  }
  writeDsLen(len) {
    writeVarUint(this.restEncoder, len);
  }
}

class UpdateEncoderV1 extends DSEncoderV1 {
  writeLeftID(id2) {
    writeVarUint(this.restEncoder, id2.client);
    writeVarUint(this.restEncoder, id2.clock);
  }
  writeRightID(id2) {
    writeVarUint(this.restEncoder, id2.client);
    writeVarUint(this.restEncoder, id2.clock);
  }
  writeClient(client) {
    writeVarUint(this.restEncoder, client);
  }
  writeInfo(info) {
    writeUint8(this.restEncoder, info);
  }
  writeString(s) {
    writeVarString(this.restEncoder, s);
  }
  writeParentInfo(isYKey) {
    writeVarUint(this.restEncoder, isYKey ? 1 : 0);
  }
  writeTypeRef(info) {
    writeVarUint(this.restEncoder, info);
  }
  writeLen(len) {
    writeVarUint(this.restEncoder, len);
  }
  writeAny(any2) {
    writeAny(this.restEncoder, any2);
  }
  writeBuf(buf) {
    writeVarUint8Array(this.restEncoder, buf);
  }
  writeJSON(embed) {
    writeVarString(this.restEncoder, JSON.stringify(embed));
  }
  writeKey(key) {
    writeVarString(this.restEncoder, key);
  }
}

class DSEncoderV2 {
  constructor() {
    this.restEncoder = createEncoder();
    this.dsCurrVal = 0;
  }
  toUint8Array() {
    return toUint8Array(this.restEncoder);
  }
  resetDsCurVal() {
    this.dsCurrVal = 0;
  }
  writeDsClock(clock) {
    const diff = clock - this.dsCurrVal;
    this.dsCurrVal = clock;
    writeVarUint(this.restEncoder, diff);
  }
  writeDsLen(len) {
    if (len === 0) {
      unexpectedCase();
    }
    writeVarUint(this.restEncoder, len - 1);
    this.dsCurrVal += len;
  }
}

class UpdateEncoderV2 extends DSEncoderV2 {
  constructor() {
    super();
    this.keyMap = new Map;
    this.keyClock = 0;
    this.keyClockEncoder = new IntDiffOptRleEncoder;
    this.clientEncoder = new UintOptRleEncoder;
    this.leftClockEncoder = new IntDiffOptRleEncoder;
    this.rightClockEncoder = new IntDiffOptRleEncoder;
    this.infoEncoder = new RleEncoder(writeUint8);
    this.stringEncoder = new StringEncoder;
    this.parentInfoEncoder = new RleEncoder(writeUint8);
    this.typeRefEncoder = new UintOptRleEncoder;
    this.lenEncoder = new UintOptRleEncoder;
  }
  toUint8Array() {
    const encoder = createEncoder();
    writeVarUint(encoder, 0);
    writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array());
    writeVarUint8Array(encoder, this.clientEncoder.toUint8Array());
    writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array());
    writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array());
    writeVarUint8Array(encoder, toUint8Array(this.infoEncoder));
    writeVarUint8Array(encoder, this.stringEncoder.toUint8Array());
    writeVarUint8Array(encoder, toUint8Array(this.parentInfoEncoder));
    writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array());
    writeVarUint8Array(encoder, this.lenEncoder.toUint8Array());
    writeUint8Array(encoder, toUint8Array(this.restEncoder));
    return toUint8Array(encoder);
  }
  writeLeftID(id2) {
    this.clientEncoder.write(id2.client);
    this.leftClockEncoder.write(id2.clock);
  }
  writeRightID(id2) {
    this.clientEncoder.write(id2.client);
    this.rightClockEncoder.write(id2.clock);
  }
  writeClient(client) {
    this.clientEncoder.write(client);
  }
  writeInfo(info) {
    this.infoEncoder.write(info);
  }
  writeString(s) {
    this.stringEncoder.write(s);
  }
  writeParentInfo(isYKey) {
    this.parentInfoEncoder.write(isYKey ? 1 : 0);
  }
  writeTypeRef(info) {
    this.typeRefEncoder.write(info);
  }
  writeLen(len) {
    this.lenEncoder.write(len);
  }
  writeAny(any2) {
    writeAny(this.restEncoder, any2);
  }
  writeBuf(buf) {
    writeVarUint8Array(this.restEncoder, buf);
  }
  writeJSON(embed) {
    writeAny(this.restEncoder, embed);
  }
  writeKey(key) {
    const clock = this.keyMap.get(key);
    if (clock === undefined) {
      this.keyClockEncoder.write(this.keyClock++);
      this.stringEncoder.write(key);
    } else {
      this.keyClockEncoder.write(clock);
    }
  }
}
var writeStructs = (encoder, structs, client, clock) => {
  clock = max3(clock, structs[0].id.clock);
  const startNewStructs = findIndexSS(structs, clock);
  writeVarUint(encoder.restEncoder, structs.length - startNewStructs);
  encoder.writeClient(client);
  writeVarUint(encoder.restEncoder, clock);
  const firstStruct = structs[startNewStructs];
  firstStruct.write(encoder, clock - firstStruct.id.clock);
  for (let i = startNewStructs + 1;i < structs.length; i++) {
    structs[i].write(encoder, 0);
  }
};
var writeClientsStructs = (encoder, store, _sm) => {
  const sm = new Map;
  _sm.forEach((clock, client) => {
    if (getState(store, client) > clock) {
      sm.set(client, clock);
    }
  });
  getStateVector(store).forEach((_clock, client) => {
    if (!_sm.has(client)) {
      sm.set(client, 0);
    }
  });
  writeVarUint(encoder.restEncoder, sm.size);
  from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {
    writeStructs(encoder, store.clients.get(client), client, clock);
  });
};
var readClientsStructRefs = (decoder, doc) => {
  const clientRefs = create();
  const numOfStateUpdates = readVarUint(decoder.restDecoder);
  for (let i = 0;i < numOfStateUpdates; i++) {
    const numberOfStructs = readVarUint(decoder.restDecoder);
    const refs = new Array(numberOfStructs);
    const client = decoder.readClient();
    let clock = readVarUint(decoder.restDecoder);
    clientRefs.set(client, { i: 0, refs });
    for (let i2 = 0;i2 < numberOfStructs; i2++) {
      const info = decoder.readInfo();
      switch (BITS5 & info) {
        case 0: {
          const len = decoder.readLen();
          refs[i2] = new GC(createID(client, clock), len);
          clock += len;
          break;
        }
        case 10: {
          const len = readVarUint(decoder.restDecoder);
          refs[i2] = new Skip(createID(client, clock), len);
          clock += len;
          break;
        }
        default: {
          const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0;
          const struct = new Item(createID(client, clock), null, (info & BIT8) === BIT8 ? decoder.readLeftID() : null, null, (info & BIT7) === BIT7 ? decoder.readRightID() : null, cantCopyParentInfo ? decoder.readParentInfo() ? doc.get(decoder.readString()) : decoder.readLeftID() : null, cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null, readItemContent(decoder, info));
          refs[i2] = struct;
          clock += struct.length;
        }
      }
    }
  }
  return clientRefs;
};
var integrateStructs = (transaction, store, clientsStructRefs) => {
  const stack = [];
  let clientsStructRefsIds = from(clientsStructRefs.keys()).sort((a, b) => a - b);
  if (clientsStructRefsIds.length === 0) {
    return null;
  }
  const getNextStructTarget = () => {
    if (clientsStructRefsIds.length === 0) {
      return null;
    }
    let nextStructsTarget = clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]);
    while (nextStructsTarget.refs.length === nextStructsTarget.i) {
      clientsStructRefsIds.pop();
      if (clientsStructRefsIds.length > 0) {
        nextStructsTarget = clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]);
      } else {
        return null;
      }
    }
    return nextStructsTarget;
  };
  let curStructsTarget = getNextStructTarget();
  if (curStructsTarget === null) {
    return null;
  }
  const restStructs = new StructStore;
  const missingSV = new Map;
  const updateMissingSv = (client, clock) => {
    const mclock = missingSV.get(client);
    if (mclock == null || mclock > clock) {
      missingSV.set(client, clock);
    }
  };
  let stackHead = curStructsTarget.refs[curStructsTarget.i++];
  const state = new Map;
  const addStackToRestSS = () => {
    for (const item of stack) {
      const client = item.id.client;
      const inapplicableItems = clientsStructRefs.get(client);
      if (inapplicableItems) {
        inapplicableItems.i--;
        restStructs.clients.set(client, inapplicableItems.refs.slice(inapplicableItems.i));
        clientsStructRefs.delete(client);
        inapplicableItems.i = 0;
        inapplicableItems.refs = [];
      } else {
        restStructs.clients.set(client, [item]);
      }
      clientsStructRefsIds = clientsStructRefsIds.filter((c) => c !== client);
    }
    stack.length = 0;
  };
  while (true) {
    if (stackHead.constructor !== Skip) {
      const localClock = setIfUndefined(state, stackHead.id.client, () => getState(store, stackHead.id.client));
      const offset = localClock - stackHead.id.clock;
      if (offset < 0) {
        stack.push(stackHead);
        updateMissingSv(stackHead.id.client, stackHead.id.clock - 1);
        addStackToRestSS();
      } else {
        const missing = stackHead.getMissing(transaction, store);
        if (missing !== null) {
          stack.push(stackHead);
          const structRefs = clientsStructRefs.get(missing) || { refs: [], i: 0 };
          if (structRefs.refs.length === structRefs.i) {
            updateMissingSv(missing, getState(store, missing));
            addStackToRestSS();
          } else {
            stackHead = structRefs.refs[structRefs.i++];
            continue;
          }
        } else if (offset === 0 || offset < stackHead.length) {
          stackHead.integrate(transaction, offset);
          state.set(stackHead.id.client, stackHead.id.clock + stackHead.length);
        }
      }
    }
    if (stack.length > 0) {
      stackHead = stack.pop();
    } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) {
      stackHead = curStructsTarget.refs[curStructsTarget.i++];
    } else {
      curStructsTarget = getNextStructTarget();
      if (curStructsTarget === null) {
        break;
      } else {
        stackHead = curStructsTarget.refs[curStructsTarget.i++];
      }
    }
  }
  if (restStructs.clients.size > 0) {
    const encoder = new UpdateEncoderV2;
    writeClientsStructs(encoder, restStructs, new Map);
    writeVarUint(encoder.restEncoder, 0);
    return { missing: missingSV, update: encoder.toUint8Array() };
  }
  return null;
};
var writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState);
var readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) => transact(ydoc, (transaction) => {
  transaction.local = false;
  let retry = false;
  const doc = transaction.doc;
  const store = doc.store;
  const ss = readClientsStructRefs(structDecoder, doc);
  const restStructs = integrateStructs(transaction, store, ss);
  const pending = store.pendingStructs;
  if (pending) {
    for (const [client, clock] of pending.missing) {
      if (clock < getState(store, client)) {
        retry = true;
        break;
      }
    }
    if (restStructs) {
      for (const [client, clock] of restStructs.missing) {
        const mclock = pending.missing.get(client);
        if (mclock == null || mclock > clock) {
          pending.missing.set(client, clock);
        }
      }
      pending.update = mergeUpdatesV2([pending.update, restStructs.update]);
    }
  } else {
    store.pendingStructs = restStructs;
  }
  const dsRest = readAndApplyDeleteSet(structDecoder, transaction, store);
  if (store.pendingDs) {
    const pendingDSUpdate = new UpdateDecoderV2(createDecoder(store.pendingDs));
    readVarUint(pendingDSUpdate.restDecoder);
    const dsRest2 = readAndApplyDeleteSet(pendingDSUpdate, transaction, store);
    if (dsRest && dsRest2) {
      store.pendingDs = mergeUpdatesV2([dsRest, dsRest2]);
    } else {
      store.pendingDs = dsRest || dsRest2;
    }
  } else {
    store.pendingDs = dsRest;
  }
  if (retry) {
    const update = store.pendingStructs.update;
    store.pendingStructs = null;
    applyUpdateV2(transaction.doc, update);
  }
}, transactionOrigin, false);
var applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => {
  const decoder = createDecoder(update);
  readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder));
};
var writeStateAsUpdate = (encoder, doc, targetStateVector = new Map) => {
  writeClientsStructs(encoder, doc.store, targetStateVector);
  writeDeleteSet(encoder, createDeleteSetFromStructStore(doc.store));
};
var encodeStateAsUpdateV2 = (doc, encodedTargetStateVector = new Uint8Array([0]), encoder = new UpdateEncoderV2) => {
  const targetStateVector = decodeStateVector(encodedTargetStateVector);
  writeStateAsUpdate(encoder, doc, targetStateVector);
  const updates = [encoder.toUint8Array()];
  if (doc.store.pendingDs) {
    updates.push(doc.store.pendingDs);
  }
  if (doc.store.pendingStructs) {
    updates.push(diffUpdateV2(doc.store.pendingStructs.update, encodedTargetStateVector));
  }
  if (updates.length > 1) {
    if (encoder.constructor === UpdateEncoderV1) {
      return mergeUpdates(updates.map((update, i) => i === 0 ? update : convertUpdateFormatV2ToV1(update)));
    } else if (encoder.constructor === UpdateEncoderV2) {
      return mergeUpdatesV2(updates);
    }
  }
  return updates[0];
};
var readStateVector = (decoder) => {
  const ss = new Map;
  const ssLength = readVarUint(decoder.restDecoder);
  for (let i = 0;i < ssLength; i++) {
    const client = readVarUint(decoder.restDecoder);
    const clock = readVarUint(decoder.restDecoder);
    ss.set(client, clock);
  }
  return ss;
};
var decodeStateVector = (decodedState) => readStateVector(new DSDecoderV1(createDecoder(decodedState)));
class EventHandler {
  constructor() {
    this.l = [];
  }
}
var createEventHandler = () => new EventHandler;
var addEventHandlerListener = (eventHandler, f) => eventHandler.l.push(f);
var removeEventHandlerListener = (eventHandler, f) => {
  const l = eventHandler.l;
  const len = l.length;
  eventHandler.l = l.filter((g) => f !== g);
  if (len === eventHandler.l.length) {
    console.error("[yjs] Tried to remove event handler that doesn't exist.");
  }
};
var callEventHandlerListeners = (eventHandler, arg0, arg1) => callAll(eventHandler.l, [arg0, arg1]);

class ID {
  constructor(client, clock) {
    this.client = client;
    this.clock = clock;
  }
}
var compareIDs = (a, b) => a === b || a !== null && b !== null && a.client === b.client && a.clock === b.clock;
var createID = (client, clock) => new ID(client, clock);
var findRootTypeKey = (type) => {
  for (const [key, value] of type.doc.share.entries()) {
    if (value === type) {
      return key;
    }
  }
  throw unexpectedCase();
};
var isParentOf = (parent, child) => {
  while (child !== null) {
    if (child.parent === parent) {
      return true;
    }
    child = child.parent._item;
  }
  return false;
};
class Snapshot {
  constructor(ds, sv) {
    this.ds = ds;
    this.sv = sv;
  }
}
var createSnapshot = (ds, sm) => new Snapshot(ds, sm);
var emptySnapshot = createSnapshot(createDeleteSet(), new Map);
var isVisible = (item, snapshot) => snapshot === undefined ? !item.deleted : snapshot.sv.has(item.id.client) && (snapshot.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot.ds, item.id);
var splitSnapshotAffectedStructs = (transaction, snapshot) => {
  const meta = setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, create2);
  const store = transaction.doc.store;
  if (!meta.has(snapshot)) {
    snapshot.sv.forEach((clock, client) => {
      if (clock < getState(store, client)) {
        getItemCleanStart(transaction, createID(client, clock));
      }
    });
    iterateDeletedStructs(transaction, snapshot.ds, (_item) => {});
    meta.add(snapshot);
  }
};
class StructStore {
  constructor() {
    this.clients = new Map;
    this.pendingStructs = null;
    this.pendingDs = null;
  }
}
var getStateVector = (store) => {
  const sm = new Map;
  store.clients.forEach((structs, client) => {
    const struct = structs[structs.length - 1];
    sm.set(client, struct.id.clock + struct.length);
  });
  return sm;
};
var getState = (store, client) => {
  const structs = store.clients.get(client);
  if (structs === undefined) {
    return 0;
  }
  const lastStruct = structs[structs.length - 1];
  return lastStruct.id.clock + lastStruct.length;
};
var addStruct = (store, struct) => {
  let structs = store.clients.get(struct.id.client);
  if (structs === undefined) {
    structs = [];
    store.clients.set(struct.id.client, structs);
  } else {
    const lastStruct = structs[structs.length - 1];
    if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) {
      throw unexpectedCase();
    }
  }
  structs.push(struct);
};
var findIndexSS = (structs, clock) => {
  let left = 0;
  let right = structs.length - 1;
  let mid = structs[right];
  let midclock = mid.id.clock;
  if (midclock === clock) {
    return right;
  }
  let midindex = floor(clock / (midclock + mid.length - 1) * right);
  while (left <= right) {
    mid = structs[midindex];
    midclock = mid.id.clock;
    if (midclock <= clock) {
      if (clock < midclock + mid.length) {
        return midindex;
      }
      left = midindex + 1;
    } else {
      right = midindex - 1;
    }
    midindex = floor((left + right) / 2);
  }
  throw unexpectedCase();
};
var find = (store, id2) => {
  const structs = store.clients.get(id2.client);
  return structs[findIndexSS(structs, id2.clock)];
};
var getItem = find;
var findIndexCleanStart = (transaction, structs, clock) => {
  const index = findIndexSS(structs, clock);
  const struct = structs[index];
  if (struct.id.clock < clock && struct instanceof Item) {
    structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock));
    return index + 1;
  }
  return index;
};
var getItemCleanStart = (transaction, id2) => {
  const structs = transaction.doc.store.clients.get(id2.client);
  return structs[findIndexCleanStart(transaction, structs, id2.clock)];
};
var getItemCleanEnd = (transaction, store, id2) => {
  const structs = store.clients.get(id2.client);
  const index = findIndexSS(structs, id2.clock);
  const struct = structs[index];
  if (id2.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) {
    structs.splice(index + 1, 0, splitItem(transaction, struct, id2.clock - struct.id.clock + 1));
  }
  return struct;
};
var replaceStruct = (store, struct, newStruct) => {
  const structs = store.clients.get(struct.id.client);
  structs[findIndexSS(structs, struct.id.clock)] = newStruct;
};
var iterateStructs = (transaction, structs, clockStart, len, f) => {
  if (len === 0) {
    return;
  }
  const clockEnd = clockStart + len;
  let index = findIndexCleanStart(transaction, structs, clockStart);
  let struct;
  do {
    struct = structs[index++];
    if (clockEnd < struct.id.clock + struct.length) {
      findIndexCleanStart(transaction, structs, clockEnd);
    }
    f(struct);
  } while (index < structs.length && structs[index].id.clock < clockEnd);
};

class Transaction {
  constructor(doc, origin, local) {
    this.doc = doc;
    this.deleteSet = new DeleteSet;
    this.beforeState = getStateVector(doc.store);
    this.afterState = new Map;
    this.changed = new Map;
    this.changedParentTypes = new Map;
    this._mergeStructs = [];
    this.origin = origin;
    this.meta = new Map;
    this.local = local;
    this.subdocsAdded = new Set;
    this.subdocsRemoved = new Set;
    this.subdocsLoaded = new Set;
    this._needFormattingCleanup = false;
  }
}
var writeUpdateMessageFromTransaction = (encoder, transaction) => {
  if (transaction.deleteSet.clients.size === 0 && !any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) {
    return false;
  }
  sortAndMergeDeleteSet(transaction.deleteSet);
  writeStructsFromTransaction(encoder, transaction);
  writeDeleteSet(encoder, transaction.deleteSet);
  return true;
};
var addChangedTypeToTransaction = (transaction, type, parentSub) => {
  const item = type._item;
  if (item === null || item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted) {
    setIfUndefined(transaction.changed, type, create2).add(parentSub);
  }
};
var tryToMergeWithLefts = (structs, pos) => {
  let right = structs[pos];
  let left = structs[pos - 1];
  let i = pos;
  for (;i > 0; right = left, left = structs[--i - 1]) {
    if (left.deleted === right.deleted && left.constructor === right.constructor) {
      if (left.mergeWith(right)) {
        if (right instanceof Item && right.parentSub !== null && right.parent._map.get(right.parentSub) === right) {
          right.parent._map.set(right.parentSub, left);
        }
        continue;
      }
    }
    break;
  }
  const merged = pos - i;
  if (merged) {
    structs.splice(pos + 1 - merged, merged);
  }
  return merged;
};
var tryGcDeleteSet = (ds, store, gcFilter) => {
  for (const [client, deleteItems] of ds.clients.entries()) {
    const structs = store.clients.get(client);
    for (let di = deleteItems.length - 1;di >= 0; di--) {
      const deleteItem = deleteItems[di];
      const endDeleteItemClock = deleteItem.clock + deleteItem.len;
      for (let si = findIndexSS(structs, deleteItem.clock), struct = structs[si];si < structs.length && struct.id.clock < endDeleteItemClock; struct = structs[++si]) {
        const struct2 = structs[si];
        if (deleteItem.clock + deleteItem.len <= struct2.id.clock) {
          break;
        }
        if (struct2 instanceof Item && struct2.deleted && !struct2.keep && gcFilter(struct2)) {
          struct2.gc(store, false);
        }
      }
    }
  }
};
var tryMergeDeleteSet = (ds, store) => {
  ds.clients.forEach((deleteItems, client) => {
    const structs = store.clients.get(client);
    for (let di = deleteItems.length - 1;di >= 0; di--) {
      const deleteItem = deleteItems[di];
      const mostRightIndexToCheck = min2(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1));
      for (let si = mostRightIndexToCheck, struct = structs[si];si > 0 && struct.id.clock >= deleteItem.clock; struct = structs[si]) {
        si -= 1 + tryToMergeWithLefts(structs, si);
      }
    }
  });
};
var cleanupTransactions = (transactionCleanups, i) => {
  if (i < transactionCleanups.length) {
    const transaction = transactionCleanups[i];
    const doc = transaction.doc;
    const store = doc.store;
    const ds = transaction.deleteSet;
    const mergeStructs = transaction._mergeStructs;
    try {
      sortAndMergeDeleteSet(ds);
      transaction.afterState = getStateVector(transaction.doc.store);
      doc.emit("beforeObserverCalls", [transaction, doc]);
      const fs2 = [];
      transaction.changed.forEach((subs, itemtype) => fs2.push(() => {
        if (itemtype._item === null || !itemtype._item.deleted) {
          itemtype._callObserver(transaction, subs);
        }
      }));
      fs2.push(() => {
        transaction.changedParentTypes.forEach((events, type) => {
          if (type._dEH.l.length > 0 && (type._item === null || !type._item.deleted)) {
            events = events.filter((event) => event.target._item === null || !event.target._item.deleted);
            events.forEach((event) => {
              event.currentTarget = type;
              event._path = null;
            });
            events.sort((event1, event2) => event1.path.length - event2.path.length);
            fs2.push(() => {
              callEventHandlerListeners(type._dEH, events, transaction);
            });
          }
        });
        fs2.push(() => doc.emit("afterTransaction", [transaction, doc]));
        fs2.push(() => {
          if (transaction._needFormattingCleanup) {
            cleanupYTextAfterTransaction(transaction);
          }
        });
      });
      callAll(fs2, []);
    } finally {
      if (doc.gc) {
        tryGcDeleteSet(ds, store, doc.gcFilter);
      }
      tryMergeDeleteSet(ds, store);
      transaction.afterState.forEach((clock, client) => {
        const beforeClock = transaction.beforeState.get(client) || 0;
        if (beforeClock !== clock) {
          const structs = store.clients.get(client);
          const firstChangePos = max3(findIndexSS(structs, beforeClock), 1);
          for (let i2 = structs.length - 1;i2 >= firstChangePos; ) {
            i2 -= 1 + tryToMergeWithLefts(structs, i2);
          }
        }
      });
      for (let i2 = mergeStructs.length - 1;i2 >= 0; i2--) {
        const { client, clock } = mergeStructs[i2].id;
        const structs = store.clients.get(client);
        const replacedStructPos = findIndexSS(structs, clock);
        if (replacedStructPos + 1 < structs.length) {
          if (tryToMergeWithLefts(structs, replacedStructPos + 1) > 1) {
            continue;
          }
        }
        if (replacedStructPos > 0) {
          tryToMergeWithLefts(structs, replacedStructPos);
        }
      }
      if (!transaction.local && transaction.afterState.get(doc.clientID) !== transaction.beforeState.get(doc.clientID)) {
        print(ORANGE2, BOLD, "[yjs] ", UNBOLD, RED2, "Changed the client-id because another client seems to be using it.");
        doc.clientID = generateNewClientId();
      }
      doc.emit("afterTransactionCleanup", [transaction, doc]);
      if (doc._observers.has("update")) {
        const encoder = new UpdateEncoderV1;
        const hasContent2 = writeUpdateMessageFromTransaction(encoder, transaction);
        if (hasContent2) {
          doc.emit("update", [encoder.toUint8Array(), transaction.origin, doc, transaction]);
        }
      }
      if (doc._observers.has("updateV2")) {
        const encoder = new UpdateEncoderV2;
        const hasContent2 = writeUpdateMessageFromTransaction(encoder, transaction);
        if (hasContent2) {
          doc.emit("updateV2", [encoder.toUint8Array(), transaction.origin, doc, transaction]);
        }
      }
      const { subdocsAdded, subdocsLoaded, subdocsRemoved } = transaction;
      if (subdocsAdded.size > 0 || subdocsRemoved.size > 0 || subdocsLoaded.size > 0) {
        subdocsAdded.forEach((subdoc) => {
          subdoc.clientID = doc.clientID;
          if (subdoc.collectionid == null) {
            subdoc.collectionid = doc.collectionid;
          }
          doc.subdocs.add(subdoc);
        });
        subdocsRemoved.forEach((subdoc) => doc.subdocs.delete(subdoc));
        doc.emit("subdocs", [{ loaded: subdocsLoaded, added: subdocsAdded, removed: subdocsRemoved }, doc, transaction]);
        subdocsRemoved.forEach((subdoc) => subdoc.destroy());
      }
      if (transactionCleanups.length <= i + 1) {
        doc._transactionCleanups = [];
        doc.emit("afterAllTransactions", [doc, transactionCleanups]);
      } else {
        cleanupTransactions(transactionCleanups, i + 1);
      }
    }
  }
};
var transact = (doc, f, origin = null, local = true) => {
  const transactionCleanups = doc._transactionCleanups;
  let initialCall = false;
  let result = null;
  if (doc._transaction === null) {
    initialCall = true;
    doc._transaction = new Transaction(doc, origin, local);
    transactionCleanups.push(doc._transaction);
    if (transactionCleanups.length === 1) {
      doc.emit("beforeAllTransactions", [doc]);
    }
    doc.emit("beforeTransaction", [doc._transaction, doc]);
  }
  try {
    result = f(doc._transaction);
  } finally {
    if (initialCall) {
      const finishCleanup = doc._transaction === transactionCleanups[0];
      doc._transaction = null;
      if (finishCleanup) {
        cleanupTransactions(transactionCleanups, 0);
      }
    }
  }
  return result;
};

class StackItem {
  constructor(deletions, insertions) {
    this.insertions = insertions;
    this.deletions = deletions;
    this.meta = new Map;
  }
}
var clearUndoManagerStackItem = (tr, um, stackItem) => {
  iterateDeletedStructs(tr, stackItem.deletions, (item) => {
    if (item instanceof Item && um.scope.some((type) => type === tr.doc || isParentOf(type, item))) {
      keepItem(item, false);
    }
  });
};
var popStackItem = (undoManager, stack, eventType) => {
  let _tr = null;
  const doc = undoManager.doc;
  const scope = undoManager.scope;
  transact(doc, (transaction) => {
    while (stack.length > 0 && undoManager.currStackItem === null) {
      const store = doc.store;
      const stackItem = stack.pop();
      const itemsToRedo = new Set;
      const itemsToDelete = [];
      let performedChange = false;
      iterateDeletedStructs(transaction, stackItem.insertions, (struct) => {
        if (struct instanceof Item) {
          if (struct.redone !== null) {
            let { item, diff } = followRedone(store, struct.id);
            if (diff > 0) {
              item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff));
            }
            struct = item;
          }
          if (!struct.deleted && scope.some((type) => type === transaction.doc || isParentOf(type, struct))) {
            itemsToDelete.push(struct);
          }
        }
      });
      iterateDeletedStructs(transaction, stackItem.deletions, (struct) => {
        if (struct instanceof Item && scope.some((type) => type === transaction.doc || isParentOf(type, struct)) && !isDeleted(stackItem.insertions, struct.id)) {
          itemsToRedo.add(struct);
        }
      });
      itemsToRedo.forEach((struct) => {
        performedChange = redoItem(transaction, struct, itemsToRedo, stackItem.insertions, undoManager.ignoreRemoteMapChanges, undoManager) !== null || performedChange;
      });
      for (let i = itemsToDelete.length - 1;i >= 0; i--) {
        const item = itemsToDelete[i];
        if (undoManager.deleteFilter(item)) {
          item.delete(transaction);
          performedChange = true;
        }
      }
      undoManager.currStackItem = performedChange ? stackItem : null;
    }
    transaction.changed.forEach((subProps, type) => {
      if (subProps.has(null) && type._searchMarker) {
        type._searchMarker.length = 0;
      }
    });
    _tr = transaction;
  }, undoManager);
  const res = undoManager.currStackItem;
  if (res != null) {
    const changedParentTypes = _tr.changedParentTypes;
    undoManager.emit("stack-item-popped", [{ stackItem: res, type: eventType, changedParentTypes, origin: undoManager }, undoManager]);
    undoManager.currStackItem = null;
  }
  return res;
};

class UndoManager extends ObservableV2 {
  constructor(typeScope, {
    captureTimeout = 500,
    captureTransaction = (_tr) => true,
    deleteFilter = () => true,
    trackedOrigins = new Set([null]),
    ignoreRemoteMapChanges = false,
    doc = isArray(typeScope) ? typeScope[0].doc : typeScope instanceof Doc ? typeScope : typeScope.doc
  } = {}) {
    super();
    this.scope = [];
    this.doc = doc;
    this.addToScope(typeScope);
    this.deleteFilter = deleteFilter;
    trackedOrigins.add(this);
    this.trackedOrigins = trackedOrigins;
    this.captureTransaction = captureTransaction;
    this.undoStack = [];
    this.redoStack = [];
    this.undoing = false;
    this.redoing = false;
    this.currStackItem = null;
    this.lastChange = 0;
    this.ignoreRemoteMapChanges = ignoreRemoteMapChanges;
    this.captureTimeout = captureTimeout;
    this.afterTransactionHandler = (transaction) => {
      if (!this.captureTransaction(transaction) || !this.scope.some((type) => transaction.changedParentTypes.has(type) || type === this.doc) || !this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor))) {
        return;
      }
      const undoing = this.undoing;
      const redoing = this.redoing;
      const stack = undoing ? this.redoStack : this.undoStack;
      if (undoing) {
        this.stopCapturing();
      } else if (!redoing) {
        this.clear(false, true);
      }
      const insertions = new DeleteSet;
      transaction.afterState.forEach((endClock, client) => {
        const startClock = transaction.beforeState.get(client) || 0;
        const len = endClock - startClock;
        if (len > 0) {
          addToDeleteSet(insertions, client, startClock, len);
        }
      });
      const now = getUnixTime();
      let didAdd = false;
      if (this.lastChange > 0 && now - this.lastChange < this.captureTimeout && stack.length > 0 && !undoing && !redoing) {
        const lastOp = stack[stack.length - 1];
        lastOp.deletions = mergeDeleteSets([lastOp.deletions, transaction.deleteSet]);
        lastOp.insertions = mergeDeleteSets([lastOp.insertions, insertions]);
      } else {
        stack.push(new StackItem(transaction.deleteSet, insertions));
        didAdd = true;
      }
      if (!undoing && !redoing) {
        this.lastChange = now;
      }
      iterateDeletedStructs(transaction, transaction.deleteSet, (item) => {
        if (item instanceof Item && this.scope.some((type) => type === transaction.doc || isParentOf(type, item))) {
          keepItem(item, true);
        }
      });
      const changeEvent = [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? "redo" : "undo", changedParentTypes: transaction.changedParentTypes }, this];
      if (didAdd) {
        this.emit("stack-item-added", changeEvent);
      } else {
        this.emit("stack-item-updated", changeEvent);
      }
    };
    this.doc.on("afterTransaction", this.afterTransactionHandler);
    this.doc.on("destroy", () => {
      this.destroy();
    });
  }
  addToScope(ytypes) {
    const tmpSet = new Set(this.scope);
    ytypes = isArray(ytypes) ? ytypes : [ytypes];
    ytypes.forEach((ytype) => {
      if (!tmpSet.has(ytype)) {
        tmpSet.add(ytype);
        if (ytype instanceof AbstractType ? ytype.doc !== this.doc : ytype !== this.doc)
          warn2("[yjs#509] Not same Y.Doc");
        this.scope.push(ytype);
      }
    });
  }
  addTrackedOrigin(origin) {
    this.trackedOrigins.add(origin);
  }
  removeTrackedOrigin(origin) {
    this.trackedOrigins.delete(origin);
  }
  clear(clearUndoStack = true, clearRedoStack = true) {
    if (clearUndoStack && this.canUndo() || clearRedoStack && this.canRedo()) {
      this.doc.transact((tr) => {
        if (clearUndoStack) {
          this.undoStack.forEach((item) => clearUndoManagerStackItem(tr, this, item));
          this.undoStack = [];
        }
        if (clearRedoStack) {
          this.redoStack.forEach((item) => clearUndoManagerStackItem(tr, this, item));
          this.redoStack = [];
        }
        this.emit("stack-cleared", [{ undoStackCleared: clearUndoStack, redoStackCleared: clearRedoStack }]);
      });
    }
  }
  stopCapturing() {
    this.lastChange = 0;
  }
  undo() {
    this.undoing = true;
    let res;
    try {
      res = popStackItem(this, this.undoStack, "undo");
    } finally {
      this.undoing = false;
    }
    return res;
  }
  redo() {
    this.redoing = true;
    let res;
    try {
      res = popStackItem(this, this.redoStack, "redo");
    } finally {
      this.redoing = false;
    }
    return res;
  }
  canUndo() {
    return this.undoStack.length > 0;
  }
  canRedo() {
    return this.redoStack.length > 0;
  }
  destroy() {
    this.trackedOrigins.delete(this);
    this.doc.off("afterTransaction", this.afterTransactionHandler);
    super.destroy();
  }
}
function* lazyStructReaderGenerator(decoder) {
  const numOfStateUpdates = readVarUint(decoder.restDecoder);
  for (let i = 0;i < numOfStateUpdates; i++) {
    const numberOfStructs = readVarUint(decoder.restDecoder);
    const client = decoder.readClient();
    let clock = readVarUint(decoder.restDecoder);
    for (let i2 = 0;i2 < numberOfStructs; i2++) {
      const info = decoder.readInfo();
      if (info === 10) {
        const len = readVarUint(decoder.restDecoder);
        yield new Skip(createID(client, clock), len);
        clock += len;
      } else if ((BITS5 & info) !== 0) {
        const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0;
        const struct = new Item(createID(client, clock), null, (info & BIT8) === BIT8 ? decoder.readLeftID() : null, null, (info & BIT7) === BIT7 ? decoder.readRightID() : null, cantCopyParentInfo ? decoder.readParentInfo() ? decoder.readString() : decoder.readLeftID() : null, cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null, readItemContent(decoder, info));
        yield struct;
        clock += struct.length;
      } else {
        const len = decoder.readLen();
        yield new GC(createID(client, clock), len);
        clock += len;
      }
    }
  }
}

class LazyStructReader {
  constructor(decoder, filterSkips) {
    this.gen = lazyStructReaderGenerator(decoder);
    this.curr = null;
    this.done = false;
    this.filterSkips = filterSkips;
    this.next();
  }
  next() {
    do {
      this.curr = this.gen.next().value || null;
    } while (this.filterSkips && this.curr !== null && this.curr.constructor === Skip);
    return this.curr;
  }
}
var decodeUpdateV2 = (update, YDecoder = UpdateDecoderV2) => {
  const structs = [];
  const updateDecoder = new YDecoder(createDecoder(update));
  const lazyDecoder = new LazyStructReader(updateDecoder, false);
  for (let curr = lazyDecoder.curr;curr !== null; curr = lazyDecoder.next()) {
    structs.push(curr);
  }
  return {
    structs,
    ds: readDeleteSet(updateDecoder)
  };
};

class LazyStructWriter {
  constructor(encoder) {
    this.currClient = 0;
    this.startClock = 0;
    this.written = 0;
    this.encoder = encoder;
    this.clientStructs = [];
  }
}
var mergeUpdates = (updates) => mergeUpdatesV2(updates, UpdateDecoderV1, UpdateEncoderV1);
var sliceStruct = (left, diff) => {
  if (left.constructor === GC) {
    const { client, clock } = left.id;
    return new GC(createID(client, clock + diff), left.length - diff);
  } else if (left.constructor === Skip) {
    const { client, clock } = left.id;
    return new Skip(createID(client, clock + diff), left.length - diff);
  } else {
    const leftItem = left;
    const { client, clock } = leftItem.id;
    return new Item(createID(client, clock + diff), null, createID(client, clock + diff - 1), null, leftItem.rightOrigin, leftItem.parent, leftItem.parentSub, leftItem.content.splice(diff));
  }
};
var mergeUpdatesV2 = (updates, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {
  if (updates.length === 1) {
    return updates[0];
  }
  const updateDecoders = updates.map((update) => new YDecoder(createDecoder(update)));
  let lazyStructDecoders = updateDecoders.map((decoder) => new LazyStructReader(decoder, true));
  let currWrite = null;
  const updateEncoder = new YEncoder;
  const lazyStructEncoder = new LazyStructWriter(updateEncoder);
  while (true) {
    lazyStructDecoders = lazyStructDecoders.filter((dec) => dec.curr !== null);
    lazyStructDecoders.sort((dec1, dec2) => {
      if (dec1.curr.id.client === dec2.curr.id.client) {
        const clockDiff = dec1.curr.id.clock - dec2.curr.id.clock;
        if (clockDiff === 0) {
          return dec1.curr.constructor === dec2.curr.constructor ? 0 : dec1.curr.constructor === Skip ? 1 : -1;
        } else {
          return clockDiff;
        }
      } else {
        return dec2.curr.id.client - dec1.curr.id.client;
      }
    });
    if (lazyStructDecoders.length === 0) {
      break;
    }
    const currDecoder = lazyStructDecoders[0];
    const firstClient = currDecoder.curr.id.client;
    if (currWrite !== null) {
      let curr = currDecoder.curr;
      let iterated = false;
      while (curr !== null && curr.id.clock + curr.length <= currWrite.struct.id.clock + currWrite.struct.length && curr.id.client >= currWrite.struct.id.client) {
        curr = currDecoder.next();
        iterated = true;
      }
      if (curr === null || curr.id.client !== firstClient || iterated && curr.id.clock > currWrite.struct.id.clock + currWrite.struct.length) {
        continue;
      }
      if (firstClient !== currWrite.struct.id.client) {
        writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
        currWrite = { struct: curr, offset: 0 };
        currDecoder.next();
      } else {
        if (currWrite.struct.id.clock + currWrite.struct.length < curr.id.clock) {
          if (currWrite.struct.constructor === Skip) {
            currWrite.struct.length = curr.id.clock + curr.length - currWrite.struct.id.clock;
          } else {
            writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
            const diff = curr.id.clock - currWrite.struct.id.clock - currWrite.struct.length;
            const struct = new Skip(createID(firstClient, currWrite.struct.id.clock + currWrite.struct.length), diff);
            currWrite = { struct, offset: 0 };
          }
        } else {
          const diff = currWrite.struct.id.clock + currWrite.struct.length - curr.id.clock;
          if (diff > 0) {
            if (currWrite.struct.constructor === Skip) {
              currWrite.struct.length -= diff;
            } else {
              curr = sliceStruct(curr, diff);
            }
          }
          if (!currWrite.struct.mergeWith(curr)) {
            writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
            currWrite = { struct: curr, offset: 0 };
            currDecoder.next();
          }
        }
      }
    } else {
      currWrite = { struct: currDecoder.curr, offset: 0 };
      currDecoder.next();
    }
    for (let next = currDecoder.curr;next !== null && next.id.client === firstClient && next.id.clock === currWrite.struct.id.clock + currWrite.struct.length && next.constructor !== Skip; next = currDecoder.next()) {
      writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
      currWrite = { struct: next, offset: 0 };
    }
  }
  if (currWrite !== null) {
    writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
    currWrite = null;
  }
  finishLazyStructWriting(lazyStructEncoder);
  const dss = updateDecoders.map((decoder) => readDeleteSet(decoder));
  const ds = mergeDeleteSets(dss);
  writeDeleteSet(updateEncoder, ds);
  return updateEncoder.toUint8Array();
};
var diffUpdateV2 = (update, sv, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {
  const state = decodeStateVector(sv);
  const encoder = new YEncoder;
  const lazyStructWriter = new LazyStructWriter(encoder);
  const decoder = new YDecoder(createDecoder(update));
  const reader = new LazyStructReader(decoder, false);
  while (reader.curr) {
    const curr = reader.curr;
    const currClient = curr.id.client;
    const svClock = state.get(currClient) || 0;
    if (reader.curr.constructor === Skip) {
      reader.next();
      continue;
    }
    if (curr.id.clock + curr.length > svClock) {
      writeStructToLazyStructWriter(lazyStructWriter, curr, max3(svClock - curr.id.clock, 0));
      reader.next();
      while (reader.curr && reader.curr.id.client === currClient) {
        writeStructToLazyStructWriter(lazyStructWriter, reader.curr, 0);
        reader.next();
      }
    } else {
      while (reader.curr && reader.curr.id.client === currClient && reader.curr.id.clock + reader.curr.length <= svClock) {
        reader.next();
      }
    }
  }
  finishLazyStructWriting(lazyStructWriter);
  const ds = readDeleteSet(decoder);
  writeDeleteSet(encoder, ds);
  return encoder.toUint8Array();
};
var flushLazyStructWriter = (lazyWriter) => {
  if (lazyWriter.written > 0) {
    lazyWriter.clientStructs.push({ written: lazyWriter.written, restEncoder: toUint8Array(lazyWriter.encoder.restEncoder) });
    lazyWriter.encoder.restEncoder = createEncoder();
    lazyWriter.written = 0;
  }
};
var writeStructToLazyStructWriter = (lazyWriter, struct, offset) => {
  if (lazyWriter.written > 0 && lazyWriter.currClient !== struct.id.client) {
    flushLazyStructWriter(lazyWriter);
  }
  if (lazyWriter.written === 0) {
    lazyWriter.currClient = struct.id.client;
    lazyWriter.encoder.writeClient(struct.id.client);
    writeVarUint(lazyWriter.encoder.restEncoder, struct.id.clock + offset);
  }
  struct.write(lazyWriter.encoder, offset);
  lazyWriter.written++;
};
var finishLazyStructWriting = (lazyWriter) => {
  flushLazyStructWriter(lazyWriter);
  const restEncoder = lazyWriter.encoder.restEncoder;
  writeVarUint(restEncoder, lazyWriter.clientStructs.length);
  for (let i = 0;i < lazyWriter.clientStructs.length; i++) {
    const partStructs = lazyWriter.clientStructs[i];
    writeVarUint(restEncoder, partStructs.written);
    writeUint8Array(restEncoder, partStructs.restEncoder);
  }
};
var convertUpdateFormat = (update, blockTransformer, YDecoder, YEncoder) => {
  const updateDecoder = new YDecoder(createDecoder(update));
  const lazyDecoder = new LazyStructReader(updateDecoder, false);
  const updateEncoder = new YEncoder;
  const lazyWriter = new LazyStructWriter(updateEncoder);
  for (let curr = lazyDecoder.curr;curr !== null; curr = lazyDecoder.next()) {
    writeStructToLazyStructWriter(lazyWriter, blockTransformer(curr), 0);
  }
  finishLazyStructWriting(lazyWriter);
  const ds = readDeleteSet(updateDecoder);
  writeDeleteSet(updateEncoder, ds);
  return updateEncoder.toUint8Array();
};
var convertUpdateFormatV2ToV1 = (update) => convertUpdateFormat(update, id, UpdateDecoderV2, UpdateEncoderV1);
var errorComputeChanges = "You must not compute changes after the event-handler fired.";

class YEvent {
  constructor(target, transaction) {
    this.target = target;
    this.currentTarget = target;
    this.transaction = transaction;
    this._changes = null;
    this._keys = null;
    this._delta = null;
    this._path = null;
  }
  get path() {
    return this._path || (this._path = getPathTo(this.currentTarget, this.target));
  }
  deletes(struct) {
    return isDeleted(this.transaction.deleteSet, struct.id);
  }
  get keys() {
    if (this._keys === null) {
      if (this.transaction.doc._transactionCleanups.length === 0) {
        throw create3(errorComputeChanges);
      }
      const keys2 = new Map;
      const target = this.target;
      const changed = this.transaction.changed.get(target);
      changed.forEach((key) => {
        if (key !== null) {
          const item = target._map.get(key);
          let action;
          let oldValue;
          if (this.adds(item)) {
            let prev = item.left;
            while (prev !== null && this.adds(prev)) {
              prev = prev.left;
            }
            if (this.deletes(item)) {
              if (prev !== null && this.deletes(prev)) {
                action = "delete";
                oldValue = last(prev.content.getContent());
              } else {
                return;
              }
            } else {
              if (prev !== null && this.deletes(prev)) {
                action = "update";
                oldValue = last(prev.content.getContent());
              } else {
                action = "add";
                oldValue = undefined;
              }
            }
          } else {
            if (this.deletes(item)) {
              action = "delete";
              oldValue = last(item.content.getContent());
            } else {
              return;
            }
          }
          keys2.set(key, { action, oldValue });
        }
      });
      this._keys = keys2;
    }
    return this._keys;
  }
  get delta() {
    return this.changes.delta;
  }
  adds(struct) {
    return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0);
  }
  get changes() {
    let changes = this._changes;
    if (changes === null) {
      if (this.transaction.doc._transactionCleanups.length === 0) {
        throw create3(errorComputeChanges);
      }
      const target = this.target;
      const added = create2();
      const deleted = create2();
      const delta = [];
      changes = {
        added,
        deleted,
        delta,
        keys: this.keys
      };
      const changed = this.transaction.changed.get(target);
      if (changed.has(null)) {
        let lastOp = null;
        const packOp = () => {
          if (lastOp) {
            delta.push(lastOp);
          }
        };
        for (let item = target._start;item !== null; item = item.right) {
          if (item.deleted) {
            if (this.deletes(item) && !this.adds(item)) {
              if (lastOp === null || lastOp.delete === undefined) {
                packOp();
                lastOp = { delete: 0 };
              }
              lastOp.delete += item.length;
              deleted.add(item);
            }
          } else {
            if (this.adds(item)) {
              if (lastOp === null || lastOp.insert === undefined) {
                packOp();
                lastOp = { insert: [] };
              }
              lastOp.insert = lastOp.insert.concat(item.content.getContent());
              added.add(item);
            } else {
              if (lastOp === null || lastOp.retain === undefined) {
                packOp();
                lastOp = { retain: 0 };
              }
              lastOp.retain += item.length;
            }
          }
        }
        if (lastOp !== null && lastOp.retain === undefined) {
          packOp();
        }
      }
      this._changes = changes;
    }
    return changes;
  }
}
var getPathTo = (parent, child) => {
  const path3 = [];
  while (child._item !== null && child !== parent) {
    if (child._item.parentSub !== null) {
      path3.unshift(child._item.parentSub);
    } else {
      let i = 0;
      let c = child._item.parent._start;
      while (c !== child._item && c !== null) {
        if (!c.deleted && c.countable) {
          i += c.length;
        }
        c = c.right;
      }
      path3.unshift(i);
    }
    child = child._item.parent;
  }
  return path3;
};
var warnPrematureAccess = () => {
  warn2("Invalid access: Add Yjs type to a document before reading data.");
};
var maxSearchMarker = 80;
var globalSearchMarkerTimestamp = 0;

class ArraySearchMarker {
  constructor(p, index) {
    p.marker = true;
    this.p = p;
    this.index = index;
    this.timestamp = globalSearchMarkerTimestamp++;
  }
}
var refreshMarkerTimestamp = (marker) => {
  marker.timestamp = globalSearchMarkerTimestamp++;
};
var overwriteMarker = (marker, p, index) => {
  marker.p.marker = false;
  marker.p = p;
  p.marker = true;
  marker.index = index;
  marker.timestamp = globalSearchMarkerTimestamp++;
};
var markPosition = (searchMarker, p, index) => {
  if (searchMarker.length >= maxSearchMarker) {
    const marker = searchMarker.reduce((a, b) => a.timestamp < b.timestamp ? a : b);
    overwriteMarker(marker, p, index);
    return marker;
  } else {
    const pm = new ArraySearchMarker(p, index);
    searchMarker.push(pm);
    return pm;
  }
};
var findMarker = (yarray, index) => {
  if (yarray._start === null || index === 0 || yarray._searchMarker === null) {
    return null;
  }
  const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a, b) => abs2(index - a.index) < abs2(index - b.index) ? a : b);
  let p = yarray._start;
  let pindex = 0;
  if (marker !== null) {
    p = marker.p;
    pindex = marker.index;
    refreshMarkerTimestamp(marker);
  }
  while (p.right !== null && pindex < index) {
    if (!p.deleted && p.countable) {
      if (index < pindex + p.length) {
        break;
      }
      pindex += p.length;
    }
    p = p.right;
  }
  while (p.left !== null && pindex > index) {
    p = p.left;
    if (!p.deleted && p.countable) {
      pindex -= p.length;
    }
  }
  while (p.left !== null && p.left.id.client === p.id.client && p.left.id.clock + p.left.length === p.id.clock) {
    p = p.left;
    if (!p.deleted && p.countable) {
      pindex -= p.length;
    }
  }
  if (marker !== null && abs2(marker.index - pindex) < p.parent.length / maxSearchMarker) {
    overwriteMarker(marker, p, pindex);
    return marker;
  } else {
    return markPosition(yarray._searchMarker, p, pindex);
  }
};
var updateMarkerChanges = (searchMarker, index, len) => {
  for (let i = searchMarker.length - 1;i >= 0; i--) {
    const m = searchMarker[i];
    if (len > 0) {
      let p = m.p;
      p.marker = false;
      while (p && (p.deleted || !p.countable)) {
        p = p.left;
        if (p && !p.deleted && p.countable) {
          m.index -= p.length;
        }
      }
      if (p === null || p.marker === true) {
        searchMarker.splice(i, 1);
        continue;
      }
      m.p = p;
      p.marker = true;
    }
    if (index < m.index || len > 0 && index === m.index) {
      m.index = max3(index, m.index + len);
    }
  }
};
var callTypeObservers = (type, transaction, event) => {
  const changedType = type;
  const changedParentTypes = transaction.changedParentTypes;
  while (true) {
    setIfUndefined(changedParentTypes, type, () => []).push(event);
    if (type._item === null) {
      break;
    }
    type = type._item.parent;
  }
  callEventHandlerListeners(changedType._eH, event, transaction);
};

class AbstractType {
  constructor() {
    this._item = null;
    this._map = new Map;
    this._start = null;
    this.doc = null;
    this._length = 0;
    this._eH = createEventHandler();
    this._dEH = createEventHandler();
    this._searchMarker = null;
  }
  get parent() {
    return this._item ? this._item.parent : null;
  }
  _integrate(y2, item) {
    this.doc = y2;
    this._item = item;
  }
  _copy() {
    throw methodUnimplemented();
  }
  clone() {
    throw methodUnimplemented();
  }
  _write(_encoder) {}
  get _first() {
    let n = this._start;
    while (n !== null && n.deleted) {
      n = n.right;
    }
    return n;
  }
  _callObserver(transaction, _parentSubs) {
    if (!transaction.local && this._searchMarker) {
      this._searchMarker.length = 0;
    }
  }
  observe(f) {
    addEventHandlerListener(this._eH, f);
  }
  observeDeep(f) {
    addEventHandlerListener(this._dEH, f);
  }
  unobserve(f) {
    removeEventHandlerListener(this._eH, f);
  }
  unobserveDeep(f) {
    removeEventHandlerListener(this._dEH, f);
  }
  toJSON() {}
}
var typeListSlice = (type, start, end) => {
  type.doc ?? warnPrematureAccess();
  if (start < 0) {
    start = type._length + start;
  }
  if (end < 0) {
    end = type._length + end;
  }
  let len = end - start;
  const cs = [];
  let n = type._start;
  while (n !== null && len > 0) {
    if (n.countable && !n.deleted) {
      const c = n.content.getContent();
      if (c.length <= start) {
        start -= c.length;
      } else {
        for (let i = start;i < c.length && len > 0; i++) {
          cs.push(c[i]);
          len--;
        }
        start = 0;
      }
    }
    n = n.right;
  }
  return cs;
};
var typeListToArray = (type) => {
  type.doc ?? warnPrematureAccess();
  const cs = [];
  let n = type._start;
  while (n !== null) {
    if (n.countable && !n.deleted) {
      const c = n.content.getContent();
      for (let i = 0;i < c.length; i++) {
        cs.push(c[i]);
      }
    }
    n = n.right;
  }
  return cs;
};
var typeListForEach = (type, f) => {
  let index = 0;
  let n = type._start;
  type.doc ?? warnPrematureAccess();
  while (n !== null) {
    if (n.countable && !n.deleted) {
      const c = n.content.getContent();
      for (let i = 0;i < c.length; i++) {
        f(c[i], index++, type);
      }
    }
    n = n.right;
  }
};
var typeListMap = (type, f) => {
  const result = [];
  typeListForEach(type, (c, i) => {
    result.push(f(c, i, type));
  });
  return result;
};
var typeListCreateIterator = (type) => {
  let n = type._start;
  let currentContent = null;
  let currentContentIndex = 0;
  return {
    [Symbol.iterator]() {
      return this;
    },
    next: () => {
      if (currentContent === null) {
        while (n !== null && n.deleted) {
          n = n.right;
        }
        if (n === null) {
          return {
            done: true,
            value: undefined
          };
        }
        currentContent = n.content.getContent();
        currentContentIndex = 0;
        n = n.right;
      }
      const value = currentContent[currentContentIndex++];
      if (currentContent.length <= currentContentIndex) {
        currentContent = null;
      }
      return {
        done: false,
        value
      };
    }
  };
};
var typeListGet = (type, index) => {
  type.doc ?? warnPrematureAccess();
  const marker = findMarker(type, index);
  let n = type._start;
  if (marker !== null) {
    n = marker.p;
    index -= marker.index;
  }
  for (;n !== null; n = n.right) {
    if (!n.deleted && n.countable) {
      if (index < n.length) {
        return n.content.getContent()[index];
      }
      index -= n.length;
    }
  }
};
var typeListInsertGenericsAfter = (transaction, parent, referenceItem, content) => {
  let left = referenceItem;
  const doc = transaction.doc;
  const ownClientId = doc.clientID;
  const store = doc.store;
  const right = referenceItem === null ? parent._start : referenceItem.right;
  let jsonContent = [];
  const packJsonContent = () => {
    if (jsonContent.length > 0) {
      left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent));
      left.integrate(transaction, 0);
      jsonContent = [];
    }
  };
  content.forEach((c) => {
    if (c === null) {
      jsonContent.push(c);
    } else {
      switch (c.constructor) {
        case Number:
        case Object:
        case Boolean:
        case Array:
        case String:
          jsonContent.push(c);
          break;
        default:
          packJsonContent();
          switch (c.constructor) {
            case Uint8Array:
            case ArrayBuffer:
              left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array(c)));
              left.integrate(transaction, 0);
              break;
            case Doc:
              left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc(c));
              left.integrate(transaction, 0);
              break;
            default:
              if (c instanceof AbstractType) {
                left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c));
                left.integrate(transaction, 0);
              } else {
                throw new Error("Unexpected content type in insert operation");
              }
          }
      }
    }
  });
  packJsonContent();
};
var lengthExceeded = () => create3("Length exceeded!");
var typeListInsertGenerics = (transaction, parent, index, content) => {
  if (index > parent._length) {
    throw lengthExceeded();
  }
  if (index === 0) {
    if (parent._searchMarker) {
      updateMarkerChanges(parent._searchMarker, index, content.length);
    }
    return typeListInsertGenericsAfter(transaction, parent, null, content);
  }
  const startIndex = index;
  const marker = findMarker(parent, index);
  let n = parent._start;
  if (marker !== null) {
    n = marker.p;
    index -= marker.index;
    if (index === 0) {
      n = n.prev;
      index += n && n.countable && !n.deleted ? n.length : 0;
    }
  }
  for (;n !== null; n = n.right) {
    if (!n.deleted && n.countable) {
      if (index <= n.length) {
        if (index < n.length) {
          getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index));
        }
        break;
      }
      index -= n.length;
    }
  }
  if (parent._searchMarker) {
    updateMarkerChanges(parent._searchMarker, startIndex, content.length);
  }
  return typeListInsertGenericsAfter(transaction, parent, n, content);
};
var typeListPushGenerics = (transaction, parent, content) => {
  const marker = (parent._searchMarker || []).reduce((maxMarker, currMarker) => currMarker.index > maxMarker.index ? currMarker : maxMarker, { index: 0, p: parent._start });
  let n = marker.p;
  if (n) {
    while (n.right) {
      n = n.right;
    }
  }
  return typeListInsertGenericsAfter(transaction, parent, n, content);
};
var typeListDelete = (transaction, parent, index, length2) => {
  if (length2 === 0) {
    return;
  }
  const startIndex = index;
  const startLength = length2;
  const marker = findMarker(parent, index);
  let n = parent._start;
  if (marker !== null) {
    n = marker.p;
    index -= marker.index;
  }
  for (;n !== null && index > 0; n = n.right) {
    if (!n.deleted && n.countable) {
      if (index < n.length) {
        getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index));
      }
      index -= n.length;
    }
  }
  while (length2 > 0 && n !== null) {
    if (!n.deleted) {
      if (length2 < n.length) {
        getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length2));
      }
      n.delete(transaction);
      length2 -= n.length;
    }
    n = n.right;
  }
  if (length2 > 0) {
    throw lengthExceeded();
  }
  if (parent._searchMarker) {
    updateMarkerChanges(parent._searchMarker, startIndex, -startLength + length2);
  }
};
var typeMapDelete = (transaction, parent, key) => {
  const c = parent._map.get(key);
  if (c !== undefined) {
    c.delete(transaction);
  }
};
var typeMapSet = (transaction, parent, key, value) => {
  const left = parent._map.get(key) || null;
  const doc = transaction.doc;
  const ownClientId = doc.clientID;
  let content;
  if (value == null) {
    content = new ContentAny([value]);
  } else {
    switch (value.constructor) {
      case Number:
      case Object:
      case Boolean:
      case Array:
      case String:
      case Date:
      case BigInt:
        content = new ContentAny([value]);
        break;
      case Uint8Array:
        content = new ContentBinary(value);
        break;
      case Doc:
        content = new ContentDoc(value);
        break;
      default:
        if (value instanceof AbstractType) {
          content = new ContentType(value);
        } else {
          throw new Error("Unexpected content type");
        }
    }
  }
  new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, null, null, parent, key, content).integrate(transaction, 0);
};
var typeMapGet = (parent, key) => {
  parent.doc ?? warnPrematureAccess();
  const val = parent._map.get(key);
  return val !== undefined && !val.deleted ? val.content.getContent()[val.length - 1] : undefined;
};
var typeMapGetAll = (parent) => {
  const res = {};
  parent.doc ?? warnPrematureAccess();
  parent._map.forEach((value, key) => {
    if (!value.deleted) {
      res[key] = value.content.getContent()[value.length - 1];
    }
  });
  return res;
};
var typeMapHas = (parent, key) => {
  parent.doc ?? warnPrematureAccess();
  const val = parent._map.get(key);
  return val !== undefined && !val.deleted;
};
var typeMapGetAllSnapshot = (parent, snapshot) => {
  const res = {};
  parent._map.forEach((value, key) => {
    let v = value;
    while (v !== null && (!snapshot.sv.has(v.id.client) || v.id.clock >= (snapshot.sv.get(v.id.client) || 0))) {
      v = v.left;
    }
    if (v !== null && isVisible(v, snapshot)) {
      res[key] = v.content.getContent()[v.length - 1];
    }
  });
  return res;
};
var createMapIterator = (type) => {
  type.doc ?? warnPrematureAccess();
  return iteratorFilter(type._map.entries(), (entry) => !entry[1].deleted);
};

class YArrayEvent extends YEvent {
}

class YArray extends AbstractType {
  constructor() {
    super();
    this._prelimContent = [];
    this._searchMarker = [];
  }
  static from(items) {
    const a = new YArray;
    a.push(items);
    return a;
  }
  _integrate(y2, item) {
    super._integrate(y2, item);
    this.insert(0, this._prelimContent);
    this._prelimContent = null;
  }
  _copy() {
    return new YArray;
  }
  clone() {
    const arr = new YArray;
    arr.insert(0, this.toArray().map((el) => el instanceof AbstractType ? el.clone() : el));
    return arr;
  }
  get length() {
    this.doc ?? warnPrematureAccess();
    return this._length;
  }
  _callObserver(transaction, parentSubs) {
    super._callObserver(transaction, parentSubs);
    callTypeObservers(this, transaction, new YArrayEvent(this, transaction));
  }
  insert(index, content) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeListInsertGenerics(transaction, this, index, content);
      });
    } else {
      this._prelimContent.splice(index, 0, ...content);
    }
  }
  push(content) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeListPushGenerics(transaction, this, content);
      });
    } else {
      this._prelimContent.push(...content);
    }
  }
  unshift(content) {
    this.insert(0, content);
  }
  delete(index, length2 = 1) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeListDelete(transaction, this, index, length2);
      });
    } else {
      this._prelimContent.splice(index, length2);
    }
  }
  get(index) {
    return typeListGet(this, index);
  }
  toArray() {
    return typeListToArray(this);
  }
  slice(start = 0, end = this.length) {
    return typeListSlice(this, start, end);
  }
  toJSON() {
    return this.map((c) => c instanceof AbstractType ? c.toJSON() : c);
  }
  map(f) {
    return typeListMap(this, f);
  }
  forEach(f) {
    typeListForEach(this, f);
  }
  [Symbol.iterator]() {
    return typeListCreateIterator(this);
  }
  _write(encoder) {
    encoder.writeTypeRef(YArrayRefID);
  }
}
var readYArray = (_decoder) => new YArray;

class YMapEvent extends YEvent {
  constructor(ymap, transaction, subs) {
    super(ymap, transaction);
    this.keysChanged = subs;
  }
}

class YMap extends AbstractType {
  constructor(entries) {
    super();
    this._prelimContent = null;
    if (entries === undefined) {
      this._prelimContent = new Map;
    } else {
      this._prelimContent = new Map(entries);
    }
  }
  _integrate(y2, item) {
    super._integrate(y2, item);
    this._prelimContent.forEach((value, key) => {
      this.set(key, value);
    });
    this._prelimContent = null;
  }
  _copy() {
    return new YMap;
  }
  clone() {
    const map3 = new YMap;
    this.forEach((value, key) => {
      map3.set(key, value instanceof AbstractType ? value.clone() : value);
    });
    return map3;
  }
  _callObserver(transaction, parentSubs) {
    callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs));
  }
  toJSON() {
    this.doc ?? warnPrematureAccess();
    const map3 = {};
    this._map.forEach((item, key) => {
      if (!item.deleted) {
        const v = item.content.getContent()[item.length - 1];
        map3[key] = v instanceof AbstractType ? v.toJSON() : v;
      }
    });
    return map3;
  }
  get size() {
    return [...createMapIterator(this)].length;
  }
  keys() {
    return iteratorMap(createMapIterator(this), (v) => v[0]);
  }
  values() {
    return iteratorMap(createMapIterator(this), (v) => v[1].content.getContent()[v[1].length - 1]);
  }
  entries() {
    return iteratorMap(createMapIterator(this), (v) => [v[0], v[1].content.getContent()[v[1].length - 1]]);
  }
  forEach(f) {
    this.doc ?? warnPrematureAccess();
    this._map.forEach((item, key) => {
      if (!item.deleted) {
        f(item.content.getContent()[item.length - 1], key, this);
      }
    });
  }
  [Symbol.iterator]() {
    return this.entries();
  }
  delete(key) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapDelete(transaction, this, key);
      });
    } else {
      this._prelimContent.delete(key);
    }
  }
  set(key, value) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapSet(transaction, this, key, value);
      });
    } else {
      this._prelimContent.set(key, value);
    }
    return value;
  }
  get(key) {
    return typeMapGet(this, key);
  }
  has(key) {
    return typeMapHas(this, key);
  }
  clear() {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        this.forEach(function(_value, key, map3) {
          typeMapDelete(transaction, map3, key);
        });
      });
    } else {
      this._prelimContent.clear();
    }
  }
  _write(encoder) {
    encoder.writeTypeRef(YMapRefID);
  }
}
var readYMap = (_decoder) => new YMap;
var equalAttrs = (a, b) => a === b || typeof a === "object" && typeof b === "object" && a && b && equalFlat(a, b);

class ItemTextListPosition {
  constructor(left, right, index, currentAttributes) {
    this.left = left;
    this.right = right;
    this.index = index;
    this.currentAttributes = currentAttributes;
  }
  forward() {
    if (this.right === null) {
      unexpectedCase();
    }
    switch (this.right.content.constructor) {
      case ContentFormat:
        if (!this.right.deleted) {
          updateCurrentAttributes(this.currentAttributes, this.right.content);
        }
        break;
      default:
        if (!this.right.deleted) {
          this.index += this.right.length;
        }
        break;
    }
    this.left = this.right;
    this.right = this.right.right;
  }
}
var findNextPosition = (transaction, pos, count3) => {
  while (pos.right !== null && count3 > 0) {
    switch (pos.right.content.constructor) {
      case ContentFormat:
        if (!pos.right.deleted) {
          updateCurrentAttributes(pos.currentAttributes, pos.right.content);
        }
        break;
      default:
        if (!pos.right.deleted) {
          if (count3 < pos.right.length) {
            getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count3));
          }
          pos.index += pos.right.length;
          count3 -= pos.right.length;
        }
        break;
    }
    pos.left = pos.right;
    pos.right = pos.right.right;
  }
  return pos;
};
var findPosition = (transaction, parent, index, useSearchMarker) => {
  const currentAttributes = new Map;
  const marker = useSearchMarker ? findMarker(parent, index) : null;
  if (marker) {
    const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes);
    return findNextPosition(transaction, pos, index - marker.index);
  } else {
    const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes);
    return findNextPosition(transaction, pos, index);
  }
};
var insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => {
  while (currPos.right !== null && (currPos.right.deleted === true || currPos.right.content.constructor === ContentFormat && equalAttrs(negatedAttributes.get(currPos.right.content.key), currPos.right.content.value))) {
    if (!currPos.right.deleted) {
      negatedAttributes.delete(currPos.right.content.key);
    }
    currPos.forward();
  }
  const doc = transaction.doc;
  const ownClientId = doc.clientID;
  negatedAttributes.forEach((val, key) => {
    const left = currPos.left;
    const right = currPos.right;
    const nextFormat = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val));
    nextFormat.integrate(transaction, 0);
    currPos.right = nextFormat;
    currPos.forward();
  });
};
var updateCurrentAttributes = (currentAttributes, format2) => {
  const { key, value } = format2;
  if (value === null) {
    currentAttributes.delete(key);
  } else {
    currentAttributes.set(key, value);
  }
};
var minimizeAttributeChanges = (currPos, attributes) => {
  while (true) {
    if (currPos.right === null) {
      break;
    } else if (currPos.right.deleted || currPos.right.content.constructor === ContentFormat && equalAttrs(attributes[currPos.right.content.key] ?? null, currPos.right.content.value))
      ;
    else {
      break;
    }
    currPos.forward();
  }
};
var insertAttributes = (transaction, parent, currPos, attributes) => {
  const doc = transaction.doc;
  const ownClientId = doc.clientID;
  const negatedAttributes = new Map;
  for (const key in attributes) {
    const val = attributes[key];
    const currentVal = currPos.currentAttributes.get(key) ?? null;
    if (!equalAttrs(currentVal, val)) {
      negatedAttributes.set(key, currentVal);
      const { left, right } = currPos;
      currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val));
      currPos.right.integrate(transaction, 0);
      currPos.forward();
    }
  }
  return negatedAttributes;
};
var insertText = (transaction, parent, currPos, text, attributes) => {
  currPos.currentAttributes.forEach((_val, key) => {
    if (attributes[key] === undefined) {
      attributes[key] = null;
    }
  });
  const doc = transaction.doc;
  const ownClientId = doc.clientID;
  minimizeAttributeChanges(currPos, attributes);
  const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes);
  const content = text.constructor === String ? new ContentString(text) : text instanceof AbstractType ? new ContentType(text) : new ContentEmbed(text);
  let { left, right, index } = currPos;
  if (parent._searchMarker) {
    updateMarkerChanges(parent._searchMarker, currPos.index, content.getLength());
  }
  right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content);
  right.integrate(transaction, 0);
  currPos.right = right;
  currPos.index = index;
  currPos.forward();
  insertNegatedAttributes(transaction, parent, currPos, negatedAttributes);
};
var formatText = (transaction, parent, currPos, length2, attributes) => {
  const doc = transaction.doc;
  const ownClientId = doc.clientID;
  minimizeAttributeChanges(currPos, attributes);
  const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes);
  iterationLoop:
    while (currPos.right !== null && (length2 > 0 || negatedAttributes.size > 0 && (currPos.right.deleted || currPos.right.content.constructor === ContentFormat))) {
      if (!currPos.right.deleted) {
        switch (currPos.right.content.constructor) {
          case ContentFormat: {
            const { key, value } = currPos.right.content;
            const attr = attributes[key];
            if (attr !== undefined) {
              if (equalAttrs(attr, value)) {
                negatedAttributes.delete(key);
              } else {
                if (length2 === 0) {
                  break iterationLoop;
                }
                negatedAttributes.set(key, value);
              }
              currPos.right.delete(transaction);
            } else {
              currPos.currentAttributes.set(key, value);
            }
            break;
          }
          default:
            if (length2 < currPos.right.length) {
              getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length2));
            }
            length2 -= currPos.right.length;
            break;
        }
      }
      currPos.forward();
    }
  if (length2 > 0) {
    let newlines = "";
    for (;length2 > 0; length2--) {
      newlines += `
`;
    }
    currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), currPos.left, currPos.left && currPos.left.lastId, currPos.right, currPos.right && currPos.right.id, parent, null, new ContentString(newlines));
    currPos.right.integrate(transaction, 0);
    currPos.forward();
  }
  insertNegatedAttributes(transaction, parent, currPos, negatedAttributes);
};
var cleanupFormattingGap = (transaction, start, curr, startAttributes, currAttributes) => {
  let end = start;
  const endFormats = create();
  while (end && (!end.countable || end.deleted)) {
    if (!end.deleted && end.content.constructor === ContentFormat) {
      const cf = end.content;
      endFormats.set(cf.key, cf);
    }
    end = end.right;
  }
  let cleanups = 0;
  let reachedCurr = false;
  while (start !== end) {
    if (curr === start) {
      reachedCurr = true;
    }
    if (!start.deleted) {
      const content = start.content;
      switch (content.constructor) {
        case ContentFormat: {
          const { key, value } = content;
          const startAttrValue = startAttributes.get(key) ?? null;
          if (endFormats.get(key) !== content || startAttrValue === value) {
            start.delete(transaction);
            cleanups++;
            if (!reachedCurr && (currAttributes.get(key) ?? null) === value && startAttrValue !== value) {
              if (startAttrValue === null) {
                currAttributes.delete(key);
              } else {
                currAttributes.set(key, startAttrValue);
              }
            }
          }
          if (!reachedCurr && !start.deleted) {
            updateCurrentAttributes(currAttributes, content);
          }
          break;
        }
      }
    }
    start = start.right;
  }
  return cleanups;
};
var cleanupContextlessFormattingGap = (transaction, item) => {
  while (item && item.right && (item.right.deleted || !item.right.countable)) {
    item = item.right;
  }
  const attrs = new Set;
  while (item && (item.deleted || !item.countable)) {
    if (!item.deleted && item.content.constructor === ContentFormat) {
      const key = item.content.key;
      if (attrs.has(key)) {
        item.delete(transaction);
      } else {
        attrs.add(key);
      }
    }
    item = item.left;
  }
};
var cleanupYTextFormatting = (type) => {
  let res = 0;
  transact(type.doc, (transaction) => {
    let start = type._start;
    let end = type._start;
    let startAttributes = create();
    const currentAttributes = copy2(startAttributes);
    while (end) {
      if (end.deleted === false) {
        switch (end.content.constructor) {
          case ContentFormat:
            updateCurrentAttributes(currentAttributes, end.content);
            break;
          default:
            res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes);
            startAttributes = copy2(currentAttributes);
            start = end;
            break;
        }
      }
      end = end.right;
    }
  });
  return res;
};
var cleanupYTextAfterTransaction = (transaction) => {
  const needFullCleanup = new Set;
  const doc = transaction.doc;
  for (const [client, afterClock] of transaction.afterState.entries()) {
    const clock = transaction.beforeState.get(client) || 0;
    if (afterClock === clock) {
      continue;
    }
    iterateStructs(transaction, doc.store.clients.get(client), clock, afterClock, (item) => {
      if (!item.deleted && item.content.constructor === ContentFormat && item.constructor !== GC) {
        needFullCleanup.add(item.parent);
      }
    });
  }
  transact(doc, (t) => {
    iterateDeletedStructs(transaction, transaction.deleteSet, (item) => {
      if (item instanceof GC || !item.parent._hasFormatting || needFullCleanup.has(item.parent)) {
        return;
      }
      const parent = item.parent;
      if (item.content.constructor === ContentFormat) {
        needFullCleanup.add(parent);
      } else {
        cleanupContextlessFormattingGap(t, item);
      }
    });
    for (const yText of needFullCleanup) {
      cleanupYTextFormatting(yText);
    }
  });
};
var deleteText = (transaction, currPos, length2) => {
  const startLength = length2;
  const startAttrs = copy2(currPos.currentAttributes);
  const start = currPos.right;
  while (length2 > 0 && currPos.right !== null) {
    if (currPos.right.deleted === false) {
      switch (currPos.right.content.constructor) {
        case ContentType:
        case ContentEmbed:
        case ContentString:
          if (length2 < currPos.right.length) {
            getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length2));
          }
          length2 -= currPos.right.length;
          currPos.right.delete(transaction);
          break;
      }
    }
    currPos.forward();
  }
  if (start) {
    cleanupFormattingGap(transaction, start, currPos.right, startAttrs, currPos.currentAttributes);
  }
  const parent = (currPos.left || currPos.right).parent;
  if (parent._searchMarker) {
    updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length2);
  }
  return currPos;
};

class YTextEvent extends YEvent {
  constructor(ytext, transaction, subs) {
    super(ytext, transaction);
    this.childListChanged = false;
    this.keysChanged = new Set;
    subs.forEach((sub) => {
      if (sub === null) {
        this.childListChanged = true;
      } else {
        this.keysChanged.add(sub);
      }
    });
  }
  get changes() {
    if (this._changes === null) {
      const changes = {
        keys: this.keys,
        delta: this.delta,
        added: new Set,
        deleted: new Set
      };
      this._changes = changes;
    }
    return this._changes;
  }
  get delta() {
    if (this._delta === null) {
      const y2 = this.target.doc;
      const delta = [];
      transact(y2, (transaction) => {
        const currentAttributes = new Map;
        const oldAttributes = new Map;
        let item = this.target._start;
        let action = null;
        const attributes = {};
        let insert = "";
        let retain = 0;
        let deleteLen = 0;
        const addOp = () => {
          if (action !== null) {
            let op = null;
            switch (action) {
              case "delete":
                if (deleteLen > 0) {
                  op = { delete: deleteLen };
                }
                deleteLen = 0;
                break;
              case "insert":
                if (typeof insert === "object" || insert.length > 0) {
                  op = { insert };
                  if (currentAttributes.size > 0) {
                    op.attributes = {};
                    currentAttributes.forEach((value, key) => {
                      if (value !== null) {
                        op.attributes[key] = value;
                      }
                    });
                  }
                }
                insert = "";
                break;
              case "retain":
                if (retain > 0) {
                  op = { retain };
                  if (!isEmpty(attributes)) {
                    op.attributes = assign({}, attributes);
                  }
                }
                retain = 0;
                break;
            }
            if (op)
              delta.push(op);
            action = null;
          }
        };
        while (item !== null) {
          switch (item.content.constructor) {
            case ContentType:
            case ContentEmbed:
              if (this.adds(item)) {
                if (!this.deletes(item)) {
                  addOp();
                  action = "insert";
                  insert = item.content.getContent()[0];
                  addOp();
                }
              } else if (this.deletes(item)) {
                if (action !== "delete") {
                  addOp();
                  action = "delete";
                }
                deleteLen += 1;
              } else if (!item.deleted) {
                if (action !== "retain") {
                  addOp();
                  action = "retain";
                }
                retain += 1;
              }
              break;
            case ContentString:
              if (this.adds(item)) {
                if (!this.deletes(item)) {
                  if (action !== "insert") {
                    addOp();
                    action = "insert";
                  }
                  insert += item.content.str;
                }
              } else if (this.deletes(item)) {
                if (action !== "delete") {
                  addOp();
                  action = "delete";
                }
                deleteLen += item.length;
              } else if (!item.deleted) {
                if (action !== "retain") {
                  addOp();
                  action = "retain";
                }
                retain += item.length;
              }
              break;
            case ContentFormat: {
              const { key, value } = item.content;
              if (this.adds(item)) {
                if (!this.deletes(item)) {
                  const curVal = currentAttributes.get(key) ?? null;
                  if (!equalAttrs(curVal, value)) {
                    if (action === "retain") {
                      addOp();
                    }
                    if (equalAttrs(value, oldAttributes.get(key) ?? null)) {
                      delete attributes[key];
                    } else {
                      attributes[key] = value;
                    }
                  } else if (value !== null) {
                    item.delete(transaction);
                  }
                }
              } else if (this.deletes(item)) {
                oldAttributes.set(key, value);
                const curVal = currentAttributes.get(key) ?? null;
                if (!equalAttrs(curVal, value)) {
                  if (action === "retain") {
                    addOp();
                  }
                  attributes[key] = curVal;
                }
              } else if (!item.deleted) {
                oldAttributes.set(key, value);
                const attr = attributes[key];
                if (attr !== undefined) {
                  if (!equalAttrs(attr, value)) {
                    if (action === "retain") {
                      addOp();
                    }
                    if (value === null) {
                      delete attributes[key];
                    } else {
                      attributes[key] = value;
                    }
                  } else if (attr !== null) {
                    item.delete(transaction);
                  }
                }
              }
              if (!item.deleted) {
                if (action === "insert") {
                  addOp();
                }
                updateCurrentAttributes(currentAttributes, item.content);
              }
              break;
            }
          }
          item = item.right;
        }
        addOp();
        while (delta.length > 0) {
          const lastOp = delta[delta.length - 1];
          if (lastOp.retain !== undefined && lastOp.attributes === undefined) {
            delta.pop();
          } else {
            break;
          }
        }
      });
      this._delta = delta;
    }
    return this._delta;
  }
}

class YText extends AbstractType {
  constructor(string) {
    super();
    this._pending = string !== undefined ? [() => this.insert(0, string)] : [];
    this._searchMarker = [];
    this._hasFormatting = false;
  }
  get length() {
    this.doc ?? warnPrematureAccess();
    return this._length;
  }
  _integrate(y2, item) {
    super._integrate(y2, item);
    try {
      this._pending.forEach((f) => f());
    } catch (e) {
      console.error(e);
    }
    this._pending = null;
  }
  _copy() {
    return new YText;
  }
  clone() {
    const text = new YText;
    text.applyDelta(this.toDelta());
    return text;
  }
  _callObserver(transaction, parentSubs) {
    super._callObserver(transaction, parentSubs);
    const event = new YTextEvent(this, transaction, parentSubs);
    callTypeObservers(this, transaction, event);
    if (!transaction.local && this._hasFormatting) {
      transaction._needFormattingCleanup = true;
    }
  }
  toString() {
    this.doc ?? warnPrematureAccess();
    let str = "";
    let n = this._start;
    while (n !== null) {
      if (!n.deleted && n.countable && n.content.constructor === ContentString) {
        str += n.content.str;
      }
      n = n.right;
    }
    return str;
  }
  toJSON() {
    return this.toString();
  }
  applyDelta(delta, { sanitize = true } = {}) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        const currPos = new ItemTextListPosition(null, this._start, 0, new Map);
        for (let i = 0;i < delta.length; i++) {
          const op = delta[i];
          if (op.insert !== undefined) {
            const ins = !sanitize && typeof op.insert === "string" && i === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === `
` ? op.insert.slice(0, -1) : op.insert;
            if (typeof ins !== "string" || ins.length > 0) {
              insertText(transaction, this, currPos, ins, op.attributes || {});
            }
          } else if (op.retain !== undefined) {
            formatText(transaction, this, currPos, op.retain, op.attributes || {});
          } else if (op.delete !== undefined) {
            deleteText(transaction, currPos, op.delete);
          }
        }
      });
    } else {
      this._pending.push(() => this.applyDelta(delta));
    }
  }
  toDelta(snapshot, prevSnapshot, computeYChange) {
    this.doc ?? warnPrematureAccess();
    const ops = [];
    const currentAttributes = new Map;
    const doc = this.doc;
    let str = "";
    let n = this._start;
    function packStr() {
      if (str.length > 0) {
        const attributes = {};
        let addAttributes = false;
        currentAttributes.forEach((value, key) => {
          addAttributes = true;
          attributes[key] = value;
        });
        const op = { insert: str };
        if (addAttributes) {
          op.attributes = attributes;
        }
        ops.push(op);
        str = "";
      }
    }
    const computeDelta = () => {
      while (n !== null) {
        if (isVisible(n, snapshot) || prevSnapshot !== undefined && isVisible(n, prevSnapshot)) {
          switch (n.content.constructor) {
            case ContentString: {
              const cur = currentAttributes.get("ychange");
              if (snapshot !== undefined && !isVisible(n, snapshot)) {
                if (cur === undefined || cur.user !== n.id.client || cur.type !== "removed") {
                  packStr();
                  currentAttributes.set("ychange", computeYChange ? computeYChange("removed", n.id) : { type: "removed" });
                }
              } else if (prevSnapshot !== undefined && !isVisible(n, prevSnapshot)) {
                if (cur === undefined || cur.user !== n.id.client || cur.type !== "added") {
                  packStr();
                  currentAttributes.set("ychange", computeYChange ? computeYChange("added", n.id) : { type: "added" });
                }
              } else if (cur !== undefined) {
                packStr();
                currentAttributes.delete("ychange");
              }
              str += n.content.str;
              break;
            }
            case ContentType:
            case ContentEmbed: {
              packStr();
              const op = {
                insert: n.content.getContent()[0]
              };
              if (currentAttributes.size > 0) {
                const attrs = {};
                op.attributes = attrs;
                currentAttributes.forEach((value, key) => {
                  attrs[key] = value;
                });
              }
              ops.push(op);
              break;
            }
            case ContentFormat:
              if (isVisible(n, snapshot)) {
                packStr();
                updateCurrentAttributes(currentAttributes, n.content);
              }
              break;
          }
        }
        n = n.right;
      }
      packStr();
    };
    if (snapshot || prevSnapshot) {
      transact(doc, (transaction) => {
        if (snapshot) {
          splitSnapshotAffectedStructs(transaction, snapshot);
        }
        if (prevSnapshot) {
          splitSnapshotAffectedStructs(transaction, prevSnapshot);
        }
        computeDelta();
      }, "cleanup");
    } else {
      computeDelta();
    }
    return ops;
  }
  insert(index, text, attributes) {
    if (text.length <= 0) {
      return;
    }
    const y2 = this.doc;
    if (y2 !== null) {
      transact(y2, (transaction) => {
        const pos = findPosition(transaction, this, index, !attributes);
        if (!attributes) {
          attributes = {};
          pos.currentAttributes.forEach((v, k) => {
            attributes[k] = v;
          });
        }
        insertText(transaction, this, pos, text, attributes);
      });
    } else {
      this._pending.push(() => this.insert(index, text, attributes));
    }
  }
  insertEmbed(index, embed, attributes) {
    const y2 = this.doc;
    if (y2 !== null) {
      transact(y2, (transaction) => {
        const pos = findPosition(transaction, this, index, !attributes);
        insertText(transaction, this, pos, embed, attributes || {});
      });
    } else {
      this._pending.push(() => this.insertEmbed(index, embed, attributes || {}));
    }
  }
  delete(index, length2) {
    if (length2 === 0) {
      return;
    }
    const y2 = this.doc;
    if (y2 !== null) {
      transact(y2, (transaction) => {
        deleteText(transaction, findPosition(transaction, this, index, true), length2);
      });
    } else {
      this._pending.push(() => this.delete(index, length2));
    }
  }
  format(index, length2, attributes) {
    if (length2 === 0) {
      return;
    }
    const y2 = this.doc;
    if (y2 !== null) {
      transact(y2, (transaction) => {
        const pos = findPosition(transaction, this, index, false);
        if (pos.right === null) {
          return;
        }
        formatText(transaction, this, pos, length2, attributes);
      });
    } else {
      this._pending.push(() => this.format(index, length2, attributes));
    }
  }
  removeAttribute(attributeName) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapDelete(transaction, this, attributeName);
      });
    } else {
      this._pending.push(() => this.removeAttribute(attributeName));
    }
  }
  setAttribute(attributeName, attributeValue) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapSet(transaction, this, attributeName, attributeValue);
      });
    } else {
      this._pending.push(() => this.setAttribute(attributeName, attributeValue));
    }
  }
  getAttribute(attributeName) {
    return typeMapGet(this, attributeName);
  }
  getAttributes() {
    return typeMapGetAll(this);
  }
  _write(encoder) {
    encoder.writeTypeRef(YTextRefID);
  }
}
var readYText = (_decoder) => new YText;

class YXmlTreeWalker {
  constructor(root, f = () => true) {
    this._filter = f;
    this._root = root;
    this._currentNode = root._start;
    this._firstCall = true;
    root.doc ?? warnPrematureAccess();
  }
  [Symbol.iterator]() {
    return this;
  }
  next() {
    let n = this._currentNode;
    let type = n && n.content && n.content.type;
    if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) {
      do {
        type = n.content.type;
        if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) {
          n = type._start;
        } else {
          while (n !== null) {
            const nxt = n.next;
            if (nxt !== null) {
              n = nxt;
              break;
            } else if (n.parent === this._root) {
              n = null;
            } else {
              n = n.parent._item;
            }
          }
        }
      } while (n !== null && (n.deleted || !this._filter(n.content.type)));
    }
    this._firstCall = false;
    if (n === null) {
      return { value: undefined, done: true };
    }
    this._currentNode = n;
    return { value: n.content.type, done: false };
  }
}

class YXmlFragment extends AbstractType {
  constructor() {
    super();
    this._prelimContent = [];
  }
  get firstChild() {
    const first = this._first;
    return first ? first.content.getContent()[0] : null;
  }
  _integrate(y2, item) {
    super._integrate(y2, item);
    this.insert(0, this._prelimContent);
    this._prelimContent = null;
  }
  _copy() {
    return new YXmlFragment;
  }
  clone() {
    const el = new YXmlFragment;
    el.insert(0, this.toArray().map((item) => item instanceof AbstractType ? item.clone() : item));
    return el;
  }
  get length() {
    this.doc ?? warnPrematureAccess();
    return this._prelimContent === null ? this._length : this._prelimContent.length;
  }
  createTreeWalker(filter) {
    return new YXmlTreeWalker(this, filter);
  }
  querySelector(query) {
    query = query.toUpperCase();
    const iterator = new YXmlTreeWalker(this, (element) => element.nodeName && element.nodeName.toUpperCase() === query);
    const next = iterator.next();
    if (next.done) {
      return null;
    } else {
      return next.value;
    }
  }
  querySelectorAll(query) {
    query = query.toUpperCase();
    return from(new YXmlTreeWalker(this, (element) => element.nodeName && element.nodeName.toUpperCase() === query));
  }
  _callObserver(transaction, parentSubs) {
    callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction));
  }
  toString() {
    return typeListMap(this, (xml) => xml.toString()).join("");
  }
  toJSON() {
    return this.toString();
  }
  toDOM(_document = document, hooks = {}, binding) {
    const fragment = _document.createDocumentFragment();
    if (binding !== undefined) {
      binding._createAssociation(fragment, this);
    }
    typeListForEach(this, (xmlType) => {
      fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null);
    });
    return fragment;
  }
  insert(index, content) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeListInsertGenerics(transaction, this, index, content);
      });
    } else {
      this._prelimContent.splice(index, 0, ...content);
    }
  }
  insertAfter(ref, content) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        const refItem = ref && ref instanceof AbstractType ? ref._item : ref;
        typeListInsertGenericsAfter(transaction, this, refItem, content);
      });
    } else {
      const pc = this._prelimContent;
      const index = ref === null ? 0 : pc.findIndex((el) => el === ref) + 1;
      if (index === 0 && ref !== null) {
        throw create3("Reference item not found");
      }
      pc.splice(index, 0, ...content);
    }
  }
  delete(index, length2 = 1) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeListDelete(transaction, this, index, length2);
      });
    } else {
      this._prelimContent.splice(index, length2);
    }
  }
  toArray() {
    return typeListToArray(this);
  }
  push(content) {
    this.insert(this.length, content);
  }
  unshift(content) {
    this.insert(0, content);
  }
  get(index) {
    return typeListGet(this, index);
  }
  slice(start = 0, end = this.length) {
    return typeListSlice(this, start, end);
  }
  forEach(f) {
    typeListForEach(this, f);
  }
  _write(encoder) {
    encoder.writeTypeRef(YXmlFragmentRefID);
  }
}
var readYXmlFragment = (_decoder) => new YXmlFragment;

class YXmlElement extends YXmlFragment {
  constructor(nodeName = "UNDEFINED") {
    super();
    this.nodeName = nodeName;
    this._prelimAttrs = new Map;
  }
  get nextSibling() {
    const n = this._item ? this._item.next : null;
    return n ? n.content.type : null;
  }
  get prevSibling() {
    const n = this._item ? this._item.prev : null;
    return n ? n.content.type : null;
  }
  _integrate(y2, item) {
    super._integrate(y2, item);
    this._prelimAttrs.forEach((value, key) => {
      this.setAttribute(key, value);
    });
    this._prelimAttrs = null;
  }
  _copy() {
    return new YXmlElement(this.nodeName);
  }
  clone() {
    const el = new YXmlElement(this.nodeName);
    const attrs = this.getAttributes();
    forEach(attrs, (value, key) => {
      el.setAttribute(key, value);
    });
    el.insert(0, this.toArray().map((v) => v instanceof AbstractType ? v.clone() : v));
    return el;
  }
  toString() {
    const attrs = this.getAttributes();
    const stringBuilder = [];
    const keys2 = [];
    for (const key in attrs) {
      keys2.push(key);
    }
    keys2.sort();
    const keysLen = keys2.length;
    for (let i = 0;i < keysLen; i++) {
      const key = keys2[i];
      stringBuilder.push(key + '="' + attrs[key] + '"');
    }
    const nodeName = this.nodeName.toLocaleLowerCase();
    const attrsString = stringBuilder.length > 0 ? " " + stringBuilder.join(" ") : "";
    return `<${nodeName}${attrsString}>${super.toString()}</${nodeName}>`;
  }
  removeAttribute(attributeName) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapDelete(transaction, this, attributeName);
      });
    } else {
      this._prelimAttrs.delete(attributeName);
    }
  }
  setAttribute(attributeName, attributeValue) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapSet(transaction, this, attributeName, attributeValue);
      });
    } else {
      this._prelimAttrs.set(attributeName, attributeValue);
    }
  }
  getAttribute(attributeName) {
    return typeMapGet(this, attributeName);
  }
  hasAttribute(attributeName) {
    return typeMapHas(this, attributeName);
  }
  getAttributes(snapshot) {
    return snapshot ? typeMapGetAllSnapshot(this, snapshot) : typeMapGetAll(this);
  }
  toDOM(_document = document, hooks = {}, binding) {
    const dom = _document.createElement(this.nodeName);
    const attrs = this.getAttributes();
    for (const key in attrs) {
      const value = attrs[key];
      if (typeof value === "string") {
        dom.setAttribute(key, value);
      }
    }
    typeListForEach(this, (yxml) => {
      dom.appendChild(yxml.toDOM(_document, hooks, binding));
    });
    if (binding !== undefined) {
      binding._createAssociation(dom, this);
    }
    return dom;
  }
  _write(encoder) {
    encoder.writeTypeRef(YXmlElementRefID);
    encoder.writeKey(this.nodeName);
  }
}
var readYXmlElement = (decoder) => new YXmlElement(decoder.readKey());

class YXmlEvent extends YEvent {
  constructor(target, subs, transaction) {
    super(target, transaction);
    this.childListChanged = false;
    this.attributesChanged = new Set;
    subs.forEach((sub) => {
      if (sub === null) {
        this.childListChanged = true;
      } else {
        this.attributesChanged.add(sub);
      }
    });
  }
}

class YXmlHook extends YMap {
  constructor(hookName) {
    super();
    this.hookName = hookName;
  }
  _copy() {
    return new YXmlHook(this.hookName);
  }
  clone() {
    const el = new YXmlHook(this.hookName);
    this.forEach((value, key) => {
      el.set(key, value);
    });
    return el;
  }
  toDOM(_document = document, hooks = {}, binding) {
    const hook = hooks[this.hookName];
    let dom;
    if (hook !== undefined) {
      dom = hook.createDom(this);
    } else {
      dom = document.createElement(this.hookName);
    }
    dom.setAttribute("data-yjs-hook", this.hookName);
    if (binding !== undefined) {
      binding._createAssociation(dom, this);
    }
    return dom;
  }
  _write(encoder) {
    encoder.writeTypeRef(YXmlHookRefID);
    encoder.writeKey(this.hookName);
  }
}
var readYXmlHook = (decoder) => new YXmlHook(decoder.readKey());

class YXmlText extends YText {
  get nextSibling() {
    const n = this._item ? this._item.next : null;
    return n ? n.content.type : null;
  }
  get prevSibling() {
    const n = this._item ? this._item.prev : null;
    return n ? n.content.type : null;
  }
  _copy() {
    return new YXmlText;
  }
  clone() {
    const text = new YXmlText;
    text.applyDelta(this.toDelta());
    return text;
  }
  toDOM(_document = document, hooks, binding) {
    const dom = _document.createTextNode(this.toString());
    if (binding !== undefined) {
      binding._createAssociation(dom, this);
    }
    return dom;
  }
  toString() {
    return this.toDelta().map((delta) => {
      const nestedNodes = [];
      for (const nodeName in delta.attributes) {
        const attrs = [];
        for (const key in delta.attributes[nodeName]) {
          attrs.push({ key, value: delta.attributes[nodeName][key] });
        }
        attrs.sort((a, b) => a.key < b.key ? -1 : 1);
        nestedNodes.push({ nodeName, attrs });
      }
      nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1);
      let str = "";
      for (let i = 0;i < nestedNodes.length; i++) {
        const node = nestedNodes[i];
        str += `<${node.nodeName}`;
        for (let j = 0;j < node.attrs.length; j++) {
          const attr = node.attrs[j];
          str += ` ${attr.key}="${attr.value}"`;
        }
        str += ">";
      }
      str += delta.insert;
      for (let i = nestedNodes.length - 1;i >= 0; i--) {
        str += `</${nestedNodes[i].nodeName}>`;
      }
      return str;
    }).join("");
  }
  toJSON() {
    return this.toString();
  }
  _write(encoder) {
    encoder.writeTypeRef(YXmlTextRefID);
  }
}
var readYXmlText = (decoder) => new YXmlText;

class AbstractStruct {
  constructor(id2, length2) {
    this.id = id2;
    this.length = length2;
  }
  get deleted() {
    throw methodUnimplemented();
  }
  mergeWith(right) {
    return false;
  }
  write(encoder, offset, encodingRef) {
    throw methodUnimplemented();
  }
  integrate(transaction, offset) {
    throw methodUnimplemented();
  }
}
var structGCRefNumber = 0;

class GC extends AbstractStruct {
  get deleted() {
    return true;
  }
  delete() {}
  mergeWith(right) {
    if (this.constructor !== right.constructor) {
      return false;
    }
    this.length += right.length;
    return true;
  }
  integrate(transaction, offset) {
    if (offset > 0) {
      this.id.clock += offset;
      this.length -= offset;
    }
    addStruct(transaction.doc.store, this);
  }
  write(encoder, offset) {
    encoder.writeInfo(structGCRefNumber);
    encoder.writeLen(this.length - offset);
  }
  getMissing(transaction, store) {
    return null;
  }
}

class ContentBinary {
  constructor(content) {
    this.content = content;
  }
  getLength() {
    return 1;
  }
  getContent() {
    return [this.content];
  }
  isCountable() {
    return true;
  }
  copy() {
    return new ContentBinary(this.content);
  }
  splice(offset) {
    throw methodUnimplemented();
  }
  mergeWith(right) {
    return false;
  }
  integrate(transaction, item) {}
  delete(transaction) {}
  gc(store) {}
  write(encoder, offset) {
    encoder.writeBuf(this.content);
  }
  getRef() {
    return 3;
  }
}
var readContentBinary = (decoder) => new ContentBinary(decoder.readBuf());

class ContentDeleted {
  constructor(len) {
    this.len = len;
  }
  getLength() {
    return this.len;
  }
  getContent() {
    return [];
  }
  isCountable() {
    return false;
  }
  copy() {
    return new ContentDeleted(this.len);
  }
  splice(offset) {
    const right = new ContentDeleted(this.len - offset);
    this.len = offset;
    return right;
  }
  mergeWith(right) {
    this.len += right.len;
    return true;
  }
  integrate(transaction, item) {
    addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len);
    item.markDeleted();
  }
  delete(transaction) {}
  gc(store) {}
  write(encoder, offset) {
    encoder.writeLen(this.len - offset);
  }
  getRef() {
    return 1;
  }
}
var readContentDeleted = (decoder) => new ContentDeleted(decoder.readLen());
var createDocFromOpts = (guid, opts) => new Doc({ guid, ...opts, shouldLoad: opts.shouldLoad || opts.autoLoad || false });

class ContentDoc {
  constructor(doc) {
    if (doc._item) {
      console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid.");
    }
    this.doc = doc;
    const opts = {};
    this.opts = opts;
    if (!doc.gc) {
      opts.gc = false;
    }
    if (doc.autoLoad) {
      opts.autoLoad = true;
    }
    if (doc.meta !== null) {
      opts.meta = doc.meta;
    }
  }
  getLength() {
    return 1;
  }
  getContent() {
    return [this.doc];
  }
  isCountable() {
    return true;
  }
  copy() {
    return new ContentDoc(createDocFromOpts(this.doc.guid, this.opts));
  }
  splice(offset) {
    throw methodUnimplemented();
  }
  mergeWith(right) {
    return false;
  }
  integrate(transaction, item) {
    this.doc._item = item;
    transaction.subdocsAdded.add(this.doc);
    if (this.doc.shouldLoad) {
      transaction.subdocsLoaded.add(this.doc);
    }
  }
  delete(transaction) {
    if (transaction.subdocsAdded.has(this.doc)) {
      transaction.subdocsAdded.delete(this.doc);
    } else {
      transaction.subdocsRemoved.add(this.doc);
    }
  }
  gc(store) {}
  write(encoder, offset) {
    encoder.writeString(this.doc.guid);
    encoder.writeAny(this.opts);
  }
  getRef() {
    return 9;
  }
}
var readContentDoc = (decoder) => new ContentDoc(createDocFromOpts(decoder.readString(), decoder.readAny()));

class ContentEmbed {
  constructor(embed) {
    this.embed = embed;
  }
  getLength() {
    return 1;
  }
  getContent() {
    return [this.embed];
  }
  isCountable() {
    return true;
  }
  copy() {
    return new ContentEmbed(this.embed);
  }
  splice(offset) {
    throw methodUnimplemented();
  }
  mergeWith(right) {
    return false;
  }
  integrate(transaction, item) {}
  delete(transaction) {}
  gc(store) {}
  write(encoder, offset) {
    encoder.writeJSON(this.embed);
  }
  getRef() {
    return 5;
  }
}
var readContentEmbed = (decoder) => new ContentEmbed(decoder.readJSON());

class ContentFormat {
  constructor(key, value) {
    this.key = key;
    this.value = value;
  }
  getLength() {
    return 1;
  }
  getContent() {
    return [];
  }
  isCountable() {
    return false;
  }
  copy() {
    return new ContentFormat(this.key, this.value);
  }
  splice(_offset2) {
    throw methodUnimplemented();
  }
  mergeWith(_right) {
    return false;
  }
  integrate(_transaction, item) {
    const p = item.parent;
    p._searchMarker = null;
    p._hasFormatting = true;
  }
  delete(transaction) {}
  gc(store) {}
  write(encoder, offset) {
    encoder.writeKey(this.key);
    encoder.writeJSON(this.value);
  }
  getRef() {
    return 6;
  }
}
var readContentFormat = (decoder) => new ContentFormat(decoder.readKey(), decoder.readJSON());

class ContentJSON {
  constructor(arr) {
    this.arr = arr;
  }
  getLength() {
    return this.arr.length;
  }
  getContent() {
    return this.arr;
  }
  isCountable() {
    return true;
  }
  copy() {
    return new ContentJSON(this.arr);
  }
  splice(offset) {
    const right = new ContentJSON(this.arr.slice(offset));
    this.arr = this.arr.slice(0, offset);
    return right;
  }
  mergeWith(right) {
    this.arr = this.arr.concat(right.arr);
    return true;
  }
  integrate(transaction, item) {}
  delete(transaction) {}
  gc(store) {}
  write(encoder, offset) {
    const len = this.arr.length;
    encoder.writeLen(len - offset);
    for (let i = offset;i < len; i++) {
      const c = this.arr[i];
      encoder.writeString(c === undefined ? "undefined" : JSON.stringify(c));
    }
  }
  getRef() {
    return 2;
  }
}
var readContentJSON = (decoder) => {
  const len = decoder.readLen();
  const cs = [];
  for (let i = 0;i < len; i++) {
    const c = decoder.readString();
    if (c === "undefined") {
      cs.push(undefined);
    } else {
      cs.push(JSON.parse(c));
    }
  }
  return new ContentJSON(cs);
};
var isDevMode = getVariable("node_env") === "development";

class ContentAny {
  constructor(arr) {
    this.arr = arr;
    isDevMode && deepFreeze(arr);
  }
  getLength() {
    return this.arr.length;
  }
  getContent() {
    return this.arr;
  }
  isCountable() {
    return true;
  }
  copy() {
    return new ContentAny(this.arr);
  }
  splice(offset) {
    const right = new ContentAny(this.arr.slice(offset));
    this.arr = this.arr.slice(0, offset);
    return right;
  }
  mergeWith(right) {
    this.arr = this.arr.concat(right.arr);
    return true;
  }
  integrate(transaction, item) {}
  delete(transaction) {}
  gc(store) {}
  write(encoder, offset) {
    const len = this.arr.length;
    encoder.writeLen(len - offset);
    for (let i = offset;i < len; i++) {
      const c = this.arr[i];
      encoder.writeAny(c);
    }
  }
  getRef() {
    return 8;
  }
}
var readContentAny = (decoder) => {
  const len = decoder.readLen();
  const cs = [];
  for (let i = 0;i < len; i++) {
    cs.push(decoder.readAny());
  }
  return new ContentAny(cs);
};

class ContentString {
  constructor(str) {
    this.str = str;
  }
  getLength() {
    return this.str.length;
  }
  getContent() {
    return this.str.split("");
  }
  isCountable() {
    return true;
  }
  copy() {
    return new ContentString(this.str);
  }
  splice(offset) {
    const right = new ContentString(this.str.slice(offset));
    this.str = this.str.slice(0, offset);
    const firstCharCode = this.str.charCodeAt(offset - 1);
    if (firstCharCode >= 55296 && firstCharCode <= 56319) {
      this.str = this.str.slice(0, offset - 1) + "�";
      right.str = "�" + right.str.slice(1);
    }
    return right;
  }
  mergeWith(right) {
    this.str += right.str;
    return true;
  }
  integrate(transaction, item) {}
  delete(transaction) {}
  gc(store) {}
  write(encoder, offset) {
    encoder.writeString(offset === 0 ? this.str : this.str.slice(offset));
  }
  getRef() {
    return 4;
  }
}
var readContentString = (decoder) => new ContentString(decoder.readString());
var typeRefs = [
  readYArray,
  readYMap,
  readYText,
  readYXmlElement,
  readYXmlFragment,
  readYXmlHook,
  readYXmlText
];
var YArrayRefID = 0;
var YMapRefID = 1;
var YTextRefID = 2;
var YXmlElementRefID = 3;
var YXmlFragmentRefID = 4;
var YXmlHookRefID = 5;
var YXmlTextRefID = 6;

class ContentType {
  constructor(type) {
    this.type = type;
  }
  getLength() {
    return 1;
  }
  getContent() {
    return [this.type];
  }
  isCountable() {
    return true;
  }
  copy() {
    return new ContentType(this.type._copy());
  }
  splice(offset) {
    throw methodUnimplemented();
  }
  mergeWith(right) {
    return false;
  }
  integrate(transaction, item) {
    this.type._integrate(transaction.doc, item);
  }
  delete(transaction) {
    let item = this.type._start;
    while (item !== null) {
      if (!item.deleted) {
        item.delete(transaction);
      } else if (item.id.clock < (transaction.beforeState.get(item.id.client) || 0)) {
        transaction._mergeStructs.push(item);
      }
      item = item.right;
    }
    this.type._map.forEach((item2) => {
      if (!item2.deleted) {
        item2.delete(transaction);
      } else if (item2.id.clock < (transaction.beforeState.get(item2.id.client) || 0)) {
        transaction._mergeStructs.push(item2);
      }
    });
    transaction.changed.delete(this.type);
  }
  gc(store) {
    let item = this.type._start;
    while (item !== null) {
      item.gc(store, true);
      item = item.right;
    }
    this.type._start = null;
    this.type._map.forEach((item2) => {
      while (item2 !== null) {
        item2.gc(store, true);
        item2 = item2.left;
      }
    });
    this.type._map = new Map;
  }
  write(encoder, offset) {
    this.type._write(encoder);
  }
  getRef() {
    return 7;
  }
}
var readContentType = (decoder) => new ContentType(typeRefs[decoder.readTypeRef()](decoder));
var followRedone = (store, id2) => {
  let nextID = id2;
  let diff = 0;
  let item;
  do {
    if (diff > 0) {
      nextID = createID(nextID.client, nextID.clock + diff);
    }
    item = getItem(store, nextID);
    diff = nextID.clock - item.id.clock;
    nextID = item.redone;
  } while (nextID !== null && item instanceof Item);
  return {
    item,
    diff
  };
};
var keepItem = (item, keep) => {
  while (item !== null && item.keep !== keep) {
    item.keep = keep;
    item = item.parent._item;
  }
};
var splitItem = (transaction, leftItem, diff) => {
  const { client, clock } = leftItem.id;
  const rightItem = new Item(createID(client, clock + diff), leftItem, createID(client, clock + diff - 1), leftItem.right, leftItem.rightOrigin, leftItem.parent, leftItem.parentSub, leftItem.content.splice(diff));
  if (leftItem.deleted) {
    rightItem.markDeleted();
  }
  if (leftItem.keep) {
    rightItem.keep = true;
  }
  if (leftItem.redone !== null) {
    rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff);
  }
  leftItem.right = rightItem;
  if (rightItem.right !== null) {
    rightItem.right.left = rightItem;
  }
  transaction._mergeStructs.push(rightItem);
  if (rightItem.parentSub !== null && rightItem.right === null) {
    rightItem.parent._map.set(rightItem.parentSub, rightItem);
  }
  leftItem.length = diff;
  return rightItem;
};
var isDeletedByUndoStack = (stack, id2) => some(stack, (s) => isDeleted(s.deletions, id2));
var redoItem = (transaction, item, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) => {
  const doc = transaction.doc;
  const store = doc.store;
  const ownClientID = doc.clientID;
  const redone = item.redone;
  if (redone !== null) {
    return getItemCleanStart(transaction, redone);
  }
  let parentItem = item.parent._item;
  let left = null;
  let right;
  if (parentItem !== null && parentItem.deleted === true) {
    if (parentItem.redone === null && (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) === null)) {
      return null;
    }
    while (parentItem.redone !== null) {
      parentItem = getItemCleanStart(transaction, parentItem.redone);
    }
  }
  const parentType = parentItem === null ? item.parent : parentItem.content.type;
  if (item.parentSub === null) {
    left = item.left;
    right = item;
    while (left !== null) {
      let leftTrace = left;
      while (leftTrace !== null && leftTrace.parent._item !== parentItem) {
        leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone);
      }
      if (leftTrace !== null && leftTrace.parent._item === parentItem) {
        left = leftTrace;
        break;
      }
      left = left.left;
    }
    while (right !== null) {
      let rightTrace = right;
      while (rightTrace !== null && rightTrace.parent._item !== parentItem) {
        rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone);
      }
      if (rightTrace !== null && rightTrace.parent._item === parentItem) {
        right = rightTrace;
        break;
      }
      right = right.right;
    }
  } else {
    right = null;
    if (item.right && !ignoreRemoteMapChanges) {
      left = item;
      while (left !== null && left.right !== null && (left.right.redone || isDeleted(itemsToDelete, left.right.id) || isDeletedByUndoStack(um.undoStack, left.right.id) || isDeletedByUndoStack(um.redoStack, left.right.id))) {
        left = left.right;
        while (left.redone)
          left = getItemCleanStart(transaction, left.redone);
      }
      if (left && left.right !== null) {
        return null;
      }
    } else {
      left = parentType._map.get(item.parentSub) || null;
    }
  }
  const nextClock = getState(store, ownClientID);
  const nextId = createID(ownClientID, nextClock);
  const redoneItem = new Item(nextId, left, left && left.lastId, right, right && right.id, parentType, item.parentSub, item.content.copy());
  item.redone = nextId;
  keepItem(redoneItem, true);
  redoneItem.integrate(transaction, 0);
  return redoneItem;
};

class Item extends AbstractStruct {
  constructor(id2, left, origin, right, rightOrigin, parent, parentSub, content) {
    super(id2, content.getLength());
    this.origin = origin;
    this.left = left;
    this.right = right;
    this.rightOrigin = rightOrigin;
    this.parent = parent;
    this.parentSub = parentSub;
    this.redone = null;
    this.content = content;
    this.info = this.content.isCountable() ? BIT2 : 0;
  }
  set marker(isMarked) {
    if ((this.info & BIT4) > 0 !== isMarked) {
      this.info ^= BIT4;
    }
  }
  get marker() {
    return (this.info & BIT4) > 0;
  }
  get keep() {
    return (this.info & BIT1) > 0;
  }
  set keep(doKeep) {
    if (this.keep !== doKeep) {
      this.info ^= BIT1;
    }
  }
  get countable() {
    return (this.info & BIT2) > 0;
  }
  get deleted() {
    return (this.info & BIT3) > 0;
  }
  set deleted(doDelete) {
    if (this.deleted !== doDelete) {
      this.info ^= BIT3;
    }
  }
  markDeleted() {
    this.info |= BIT3;
  }
  getMissing(transaction, store) {
    if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store, this.origin.client)) {
      return this.origin.client;
    }
    if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store, this.rightOrigin.client)) {
      return this.rightOrigin.client;
    }
    if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store, this.parent.client)) {
      return this.parent.client;
    }
    if (this.origin) {
      this.left = getItemCleanEnd(transaction, store, this.origin);
      this.origin = this.left.lastId;
    }
    if (this.rightOrigin) {
      this.right = getItemCleanStart(transaction, this.rightOrigin);
      this.rightOrigin = this.right.id;
    }
    if (this.left && this.left.constructor === GC || this.right && this.right.constructor === GC) {
      this.parent = null;
    } else if (!this.parent) {
      if (this.left && this.left.constructor === Item) {
        this.parent = this.left.parent;
        this.parentSub = this.left.parentSub;
      } else if (this.right && this.right.constructor === Item) {
        this.parent = this.right.parent;
        this.parentSub = this.right.parentSub;
      }
    } else if (this.parent.constructor === ID) {
      const parentItem = getItem(store, this.parent);
      if (parentItem.constructor === GC) {
        this.parent = null;
      } else {
        this.parent = parentItem.content.type;
      }
    }
    return null;
  }
  integrate(transaction, offset) {
    if (offset > 0) {
      this.id.clock += offset;
      this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1));
      this.origin = this.left.lastId;
      this.content = this.content.splice(offset);
      this.length -= offset;
    }
    if (this.parent) {
      if (!this.left && (!this.right || this.right.left !== null) || this.left && this.left.right !== this.right) {
        let left = this.left;
        let o;
        if (left !== null) {
          o = left.right;
        } else if (this.parentSub !== null) {
          o = this.parent._map.get(this.parentSub) || null;
          while (o !== null && o.left !== null) {
            o = o.left;
          }
        } else {
          o = this.parent._start;
        }
        const conflictingItems = new Set;
        const itemsBeforeOrigin = new Set;
        while (o !== null && o !== this.right) {
          itemsBeforeOrigin.add(o);
          conflictingItems.add(o);
          if (compareIDs(this.origin, o.origin)) {
            if (o.id.client < this.id.client) {
              left = o;
              conflictingItems.clear();
            } else if (compareIDs(this.rightOrigin, o.rightOrigin)) {
              break;
            }
          } else if (o.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o.origin))) {
            if (!conflictingItems.has(getItem(transaction.doc.store, o.origin))) {
              left = o;
              conflictingItems.clear();
            }
          } else {
            break;
          }
          o = o.right;
        }
        this.left = left;
      }
      if (this.left !== null) {
        const right = this.left.right;
        this.right = right;
        this.left.right = this;
      } else {
        let r;
        if (this.parentSub !== null) {
          r = this.parent._map.get(this.parentSub) || null;
          while (r !== null && r.left !== null) {
            r = r.left;
          }
        } else {
          r = this.parent._start;
          this.parent._start = this;
        }
        this.right = r;
      }
      if (this.right !== null) {
        this.right.left = this;
      } else if (this.parentSub !== null) {
        this.parent._map.set(this.parentSub, this);
        if (this.left !== null) {
          this.left.delete(transaction);
        }
      }
      if (this.parentSub === null && this.countable && !this.deleted) {
        this.parent._length += this.length;
      }
      addStruct(transaction.doc.store, this);
      this.content.integrate(transaction, this);
      addChangedTypeToTransaction(transaction, this.parent, this.parentSub);
      if (this.parent._item !== null && this.parent._item.deleted || this.parentSub !== null && this.right !== null) {
        this.delete(transaction);
      }
    } else {
      new GC(this.id, this.length).integrate(transaction, 0);
    }
  }
  get next() {
    let n = this.right;
    while (n !== null && n.deleted) {
      n = n.right;
    }
    return n;
  }
  get prev() {
    let n = this.left;
    while (n !== null && n.deleted) {
      n = n.left;
    }
    return n;
  }
  get lastId() {
    return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1);
  }
  mergeWith(right) {
    if (this.constructor === right.constructor && compareIDs(right.origin, this.lastId) && this.right === right && compareIDs(this.rightOrigin, right.rightOrigin) && this.id.client === right.id.client && this.id.clock + this.length === right.id.clock && this.deleted === right.deleted && this.redone === null && right.redone === null && this.content.constructor === right.content.constructor && this.content.mergeWith(right.content)) {
      const searchMarker = this.parent._searchMarker;
      if (searchMarker) {
        searchMarker.forEach((marker) => {
          if (marker.p === right) {
            marker.p = this;
            if (!this.deleted && this.countable) {
              marker.index -= this.length;
            }
          }
        });
      }
      if (right.keep) {
        this.keep = true;
      }
      this.right = right.right;
      if (this.right !== null) {
        this.right.left = this;
      }
      this.length += right.length;
      return true;
    }
    return false;
  }
  delete(transaction) {
    if (!this.deleted) {
      const parent = this.parent;
      if (this.countable && this.parentSub === null) {
        parent._length -= this.length;
      }
      this.markDeleted();
      addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length);
      addChangedTypeToTransaction(transaction, parent, this.parentSub);
      this.content.delete(transaction);
    }
  }
  gc(store, parentGCd) {
    if (!this.deleted) {
      throw unexpectedCase();
    }
    this.content.gc(store);
    if (parentGCd) {
      replaceStruct(store, this, new GC(this.id, this.length));
    } else {
      this.content = new ContentDeleted(this.length);
    }
  }
  write(encoder, offset) {
    const origin = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin;
    const rightOrigin = this.rightOrigin;
    const parentSub = this.parentSub;
    const info = this.content.getRef() & BITS5 | (origin === null ? 0 : BIT8) | (rightOrigin === null ? 0 : BIT7) | (parentSub === null ? 0 : BIT6);
    encoder.writeInfo(info);
    if (origin !== null) {
      encoder.writeLeftID(origin);
    }
    if (rightOrigin !== null) {
      encoder.writeRightID(rightOrigin);
    }
    if (origin === null && rightOrigin === null) {
      const parent = this.parent;
      if (parent._item !== undefined) {
        const parentItem = parent._item;
        if (parentItem === null) {
          const ykey = findRootTypeKey(parent);
          encoder.writeParentInfo(true);
          encoder.writeString(ykey);
        } else {
          encoder.writeParentInfo(false);
          encoder.writeLeftID(parentItem.id);
        }
      } else if (parent.constructor === String) {
        encoder.writeParentInfo(true);
        encoder.writeString(parent);
      } else if (parent.constructor === ID) {
        encoder.writeParentInfo(false);
        encoder.writeLeftID(parent);
      } else {
        unexpectedCase();
      }
      if (parentSub !== null) {
        encoder.writeString(parentSub);
      }
    }
    this.content.write(encoder, offset);
  }
}
var readItemContent = (decoder, info) => contentRefs[info & BITS5](decoder);
var contentRefs = [
  () => {
    unexpectedCase();
  },
  readContentDeleted,
  readContentJSON,
  readContentBinary,
  readContentString,
  readContentEmbed,
  readContentFormat,
  readContentType,
  readContentAny,
  readContentDoc,
  () => {
    unexpectedCase();
  }
];
var structSkipRefNumber = 10;

class Skip extends AbstractStruct {
  get deleted() {
    return true;
  }
  delete() {}
  mergeWith(right) {
    if (this.constructor !== right.constructor) {
      return false;
    }
    this.length += right.length;
    return true;
  }
  integrate(transaction, offset) {
    unexpectedCase();
  }
  write(encoder, offset) {
    encoder.writeInfo(structSkipRefNumber);
    writeVarUint(encoder.restEncoder, this.length - offset);
  }
  getMissing(transaction, store) {
    return null;
  }
}
var glo = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {};
var importIdentifier = "__ $YJS$ __";
if (glo[importIdentifier] === true) {
  console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");
}
glo[importIdentifier] = true;

// node_modules/@oai/granola/dist/models/presentation/shape-collection.js
class ShapeCollection {
  #context;
  #items;
  #itemsById;
  #yShapes;
  constructor(context, proto = []) {
    this.#context = context;
    this.#items = [];
    this.#itemsById = new Map;
    const slideState = this.#context.getSlideCollabState?.();
    if (slideState) {
      this.#yShapes = this.#getOrCreateShapesState(slideState);
    }
    proto.forEach((element) => {
      this.add({ proto: element });
    });
  }
  get items() {
    return [...this.#items];
  }
  getItem(selector) {
    if (typeof selector === "number") {
      return this.getItemAt(selector);
    }
    if (typeof selector === "string") {
      const byId = this.getById(selector);
      if (byId) {
        return byId;
      }
      return this.#items.find((shape) => shape.name === selector);
    }
    return this.getById(selector?.id ?? "");
  }
  getItemAt(index) {
    if (!Number.isFinite(index)) {
      return;
    }
    const normalizedIndex = Math.trunc(index);
    if (normalizedIndex < 0 || normalizedIndex >= this.#items.length) {
      return;
    }
    return this.#items[normalizedIndex];
  }
  getById(id2) {
    const localId = this.#normalizeShapeLookupId(id2);
    if (!localId) {
      return;
    }
    return this.#itemsById.get(localId);
  }
  add(config) {
    const shape = new Shape2(this.#shapeContext(), config);
    const isNewConnectorShape = !("proto" in config) && config.geometry === "connector";
    const attached = this.#attachShape(shape);
    const seed = "proto" in config ? config.proto.bbox : attached.position.toProto();
    this.#bindShapeBbox(attached, seed);
    if (!("proto" in config)) {
      const recorder = this.#context.getPresentation?.()?.getRecorder?.();
      const slide = this.#context.getSlide?.();
      if (recorder && slide) {
        const anchor = buildElementAid("sh", slide.id, shape.id);
        const alias = recorder.assignAlias(shape, anchor, "shape");
        recorder.record({
          op: "shape.add",
          slide: recorder.targetRefForElement(slide, `sl/${slide.id}`),
          as: alias,
          props: buildShapeAddProps(config, slide, recorder)
        });
      }
    }
    if (isNewConnectorShape) {
      attached.sendToBack();
    }
    return attached;
  }
  connect(from2, to, options = {}) {
    const fromShape = this.#resolveConnectorShape(from2, "from");
    const toShape = this.#resolveConnectorShape(to, "to");
    const kind = options.kind ?? "elbow";
    const autoIndices = this.#shouldResolveAutoConnectorPair(options) ? this.#resolveAutoConnectorPair(fromShape, toShape, kind) : null;
    const [autoFromSide, autoToSide] = this.#resolveAutoConnectorSides(fromShape, toShape);
    const fromIdx = this.#resolveConnectorIndex(autoIndices?.fromIdx ?? options.fromIdx, options.fromSide, autoFromSide, fromShape, "from");
    const toIdx = this.#resolveConnectorIndex(autoIndices?.toIdx ?? options.toIdx, options.toSide, autoToSide, toShape, "to");
    const connectorConfig = { ...options };
    delete connectorConfig.fromIdx;
    delete connectorConfig.toIdx;
    delete connectorConfig.fromSide;
    delete connectorConfig.toSide;
    delete connectorConfig.kind;
    return this.add({
      ...connectorConfig,
      geometry: "connector",
      from: fromShape,
      to: toShape,
      fromIdx,
      toIdx,
      kind
    });
  }
  getConnectionSiteIndex(shape, side) {
    const resolvedShape = shape instanceof Shape2 ? shape : this.getById(shape);
    if (!resolvedShape) {
      throw new Error(`Connector shape not found for id: ${shape}`);
    }
    return this.#resolveConnectionSiteIndexForSide(resolvedShape, side);
  }
  addPlaceholder(name) {
    const element = {
      id: v4_default(),
      name,
      placeholderIndex: this.#nextPlaceholderIndex(),
      paragraphs: [],
      type: 1 /* ELEMENT_TYPE_TEXT */,
      effects: [],
      children: [],
      levelsStyles: [],
      citations: []
    };
    const shape = new Shape2(this.#shapeContext(), {
      proto: element
    });
    shape.placeholderIndex = element.placeholderIndex;
    shape.text = "";
    const attached = this.#attachShape(shape);
    this.#bindShapeBbox(attached, element.bbox);
    return attached;
  }
  deleteById(id2) {
    const shape = this.#itemsById.get(id2);
    if (!shape) {
      return;
    }
    const index = this.#items.indexOf(shape);
    if (index !== -1) {
      this.#items.splice(index, 1);
    }
    this.#itemsById.delete(id2);
    this.#yShapes?.delete(id2);
    this.#context._unregister(id2);
  }
  deleteAll() {
    const shapes = this.#items;
    this.#items = [];
    this.#itemsById.clear();
    shapes.forEach((shape) => {
      if (!shape.id) {
        return;
      }
      this.#yShapes?.delete(shape.id);
      this.#context._unregister(shape.id);
    });
  }
  toProto() {
    return this.items.map((shape) => shape.toProto());
  }
  setPlaceholdersFromProtos(protos) {
    const placeholderShapes = protos.map((proto) => new Shape2(this.#shapeContext(), { proto }));
    this.#items.slice().forEach((shape) => {
      if (shape.isPlaceholder()) {
        this.#detachShape(shape);
      }
    });
    placeholderShapes.forEach((shape) => {
      const attached = this.#attachShape(shape);
      this.#bindShapeBbox(attached, shape.position.toProto());
    });
  }
  hydrateCollaborativeRefsFromProto() {
    const slideState = this.#context.getSlideCollabState?.();
    if (!slideState) {
      return;
    }
    this.#yShapes = this.#getOrCreateShapesState(slideState);
    for (const shape of this.#items) {
      this.#bindShapeBbox(shape, shape.position.toProto());
    }
  }
  #shapeContext() {
    return this.#context;
  }
  #normalizeShapeLookupId(id2) {
    const trimmed = id2.trim();
    if (!trimmed) {
      return "";
    }
    const slideId = this.#context.getSlide?.()?.id;
    const localId = resolveLocalShapeId(trimmed, slideId, this.#itemsById.keys());
    if (!localId) {
      return "";
    }
    return localId;
  }
  #attachShape(shape) {
    return this.#attachShapeInternal(shape, { register: true });
  }
  #attachShapeInternal(shape, options = {}) {
    this.#items.push(shape);
    const id2 = shape.id;
    if (id2) {
      this.#itemsById.set(id2, shape);
      if (options.register !== false) {
        this.#context._register(shape, { index: options.index });
      }
    }
    return shape;
  }
  #detachShape(shape) {
    const index = this.#items.indexOf(shape);
    if (index !== -1) {
      this.#items.splice(index, 1);
    }
    const id2 = shape.id;
    if (id2) {
      const entry = this.#itemsById.get(id2);
      if (entry === shape) {
        this.#itemsById.delete(id2);
        this.#context._unregister(id2);
      }
    }
  }
  #nextPlaceholderIndex() {
    const indices = this.#items.map((shape) => shape.placeholderIndex).filter((value) => value !== undefined);
    if (indices.length === 0) {
      return 0;
    }
    return Math.max(...indices) + 1;
  }
  #getOrCreateShapesState(slideState) {
    const existing = slideState.get("shapes");
    if (existing instanceof YMap) {
      return existing;
    }
    const created = new YMap;
    slideState.set("shapes", created);
    return created;
  }
  #getOrCreateShapeState(shapeId) {
    if (!this.#yShapes) {
      return;
    }
    const existing = this.#yShapes.get(shapeId);
    if (existing instanceof YMap) {
      return existing;
    }
    const created = new YMap;
    this.#yShapes.set(shapeId, created);
    return created;
  }
  #getOrCreateShapeBbox(shapeId, seed) {
    const shapeState = this.#getOrCreateShapeState(shapeId);
    if (!shapeState) {
      return;
    }
    const existing = shapeState.get("bbox");
    const bbox = existing instanceof YMap ? existing : new YMap;
    if (!(existing instanceof YMap)) {
      shapeState.set("bbox", bbox);
    }
    if (seed && bbox.size === 0) {
      this.#seedBboxStruct(bbox, seed);
    }
    return bbox;
  }
  #seedBboxStruct(bbox, seed) {
    if (!seed) {
      return;
    }
    if (seed.xEmu !== undefined)
      bbox.set("xEmu", seed.xEmu);
    if (seed.yEmu !== undefined)
      bbox.set("yEmu", seed.yEmu);
    if (seed.widthEmu !== undefined)
      bbox.set("widthEmu", seed.widthEmu);
    if (seed.heightEmu !== undefined)
      bbox.set("heightEmu", seed.heightEmu);
    if (seed.rotation !== undefined)
      bbox.set("rotation", seed.rotation);
    if (seed.horizontalFlip !== undefined) {
      bbox.set("horizontalFlip", seed.horizontalFlip);
    }
    if (seed.verticalFlip !== undefined) {
      bbox.set("verticalFlip", seed.verticalFlip);
    }
  }
  #bindShapeBbox(shape, seed) {
    const bbox = this.#getOrCreateShapeBbox(shape.id, seed);
    if (!bbox) {
      return;
    }
    shape.position.bindToBboxStruct(bbox, seed);
  }
  #resolveConnectorShape(shape, label) {
    if (shape instanceof Shape2) {
      return shape;
    }
    const resolved = this.getById(shape);
    if (!resolved) {
      throw new Error(`Connector ${label} shape not found for id: ${shape}`);
    }
    return resolved;
  }
  #resolveAutoConnectorSides(from2, to) {
    const fromCenter = this.#resolveConnectorFrameCenter(from2, "from");
    const toCenter = this.#resolveConnectorFrameCenter(to, "to");
    const deltaX = toCenter.x - fromCenter.x;
    const deltaY = toCenter.y - fromCenter.y;
    if (Math.abs(deltaX) >= Math.abs(deltaY)) {
      return deltaX >= 0 ? ["right", "left"] : ["left", "right"];
    }
    return deltaY >= 0 ? ["bottom", "top"] : ["top", "bottom"];
  }
  #shouldResolveAutoConnectorPair(options) {
    return options.fromIdx === undefined && options.toIdx === undefined && options.fromSide === undefined && options.toSide === undefined;
  }
  #resolveAutoConnectorPair(from2, to, kind) {
    const fromCandidates = this.#listAutoConnectorSiteCandidates(from2);
    const toCandidates = this.#listAutoConnectorSiteCandidates(to);
    if (fromCandidates.length === 0 || toCandidates.length === 0) {
      return null;
    }
    let best;
    for (const fromCandidate of fromCandidates) {
      for (const toCandidate of toCandidates) {
        const score = this.#scoreAutoConnectorSitePair(fromCandidate, toCandidate, kind);
        if (!best || score < best.score) {
          best = {
            fromIdx: fromCandidate.index,
            toIdx: toCandidate.index,
            score
          };
        }
      }
    }
    return best ? { fromIdx: best.fromIdx, toIdx: best.toIdx } : null;
  }
  #listAutoConnectorSiteCandidates(shape) {
    const presentation = this.#context.getPresentation?.();
    const slide = this.#context.getSlide?.();
    if (!presentation || !slide) {
      return this.#listFallbackConnectorSiteCandidates(shape);
    }
    const proto = shape.toProto();
    const geometry = proto.shape?.geometry;
    const preset = geometry !== undefined && geometry !== -1 /* UNRECOGNIZED */ ? getPresetShapeDefinition(geometry) : undefined;
    const connectionSiteCount = preset?.cxnLst?.length ?? 0;
    const siteCount = connectionSiteCount > 0 ? connectionSiteCount : 4;
    const candidates = [];
    for (let index = 0;index < siteCount; index += 1) {
      try {
        const anchor = resolveConnectorAnchorPx({
          element: proto,
          siteIndex: index,
          pres: presentation,
          slide
        });
        candidates.push({
          index,
          point: anchor.point,
          normal: anchor.normal
        });
      } catch {
        continue;
      }
    }
    return candidates.length > 0 ? candidates : this.#listFallbackConnectorSiteCandidates(shape);
  }
  #listFallbackConnectorSiteCandidates(shape) {
    const fallbackCandidates = [0, 1, 2, 3].map((index) => this.#buildFallbackConnectorSiteCandidate(shape, index)).filter((candidate) => candidate !== null);
    return fallbackCandidates;
  }
  #buildFallbackConnectorSiteCandidate(shape, index) {
    const frame = shape.frame;
    if (!frame || frame.left === undefined || frame.top === undefined || frame.width === undefined || frame.height === undefined) {
      return null;
    }
    const centerX = frame.left + frame.width / 2;
    const centerY = frame.top + frame.height / 2;
    switch (index) {
      case 0:
        return {
          index,
          point: { x: centerX, y: frame.top },
          normal: { x: 0, y: -1 }
        };
      case 1:
        return {
          index,
          point: { x: frame.left, y: centerY },
          normal: { x: -1, y: 0 }
        };
      case 2:
        return {
          index,
          point: { x: centerX, y: frame.top + frame.height },
          normal: { x: 0, y: 1 }
        };
      case 3:
        return {
          index,
          point: { x: frame.left + frame.width, y: centerY },
          normal: { x: 1, y: 0 }
        };
      default:
        return null;
    }
  }
  #scoreAutoConnectorSitePair(from2, to, kind) {
    const dx = to.point.x - from2.point.x;
    const dy = to.point.y - from2.point.y;
    const euclideanDistance = Math.hypot(dx, dy);
    const orthogonalDistance = Math.abs(dx) + Math.abs(dy);
    const routeDistance = kind === "straight" ? euclideanDistance : orthogonalDistance;
    const startForward = dotProduct({ x: dx, y: dy }, from2.normal);
    const endApproach = dotProduct({ x: -dx, y: -dy }, to.normal);
    let score = routeDistance;
    score += this.#estimateAutoConnectorBendCount(from2, to, kind) * 96;
    if (startForward < 0) {
      score += 220 + Math.abs(startForward) * 2;
    }
    if (endApproach < 0) {
      score += 220 + Math.abs(endApproach) * 2;
    }
    return score;
  }
  #estimateAutoConnectorBendCount(from2, to, kind) {
    if (kind === "straight") {
      return 0;
    }
    const startDir = directionFromVector(from2.normal);
    const endDir = oppositeDirection2(directionFromVector(to.normal));
    const startAxis = directionAxis2(startDir);
    const endAxis = directionAxis2(endDir);
    if (startAxis === "none" || endAxis === "none") {
      return 2;
    }
    let bends = 0;
    if (startAxis !== endAxis) {
      bends = 1;
    } else if (startDir === endDir) {
      bends = sharePerpendicularAxis(from2.point, to.point, startAxis) ? 0 : 1;
    } else {
      bends = 2;
    }
    if (!isDirectionForward(from2.point, to.point, startDir)) {
      bends += 2;
    }
    if (!isDirectionForward(to.point, from2.point, directionFromVector(to.normal))) {
      bends += 2;
    }
    return bends;
  }
  #resolveConnectorFrameCenter(shape, label) {
    const frame = shape.frame;
    const left = frame?.left;
    const top = frame?.top;
    const width = frame?.width;
    const height = frame?.height;
    if (left === undefined || top === undefined || width === undefined || height === undefined) {
      throw new Error(`Connector ${label} shape is missing frame data.`);
    }
    return {
      x: left + width / 2,
      y: top + height / 2
    };
  }
  #resolveConnectorIndex(explicitIndex, side, fallbackSide, shape, label) {
    if (explicitIndex !== undefined) {
      return explicitIndex;
    }
    const resolvedSide = side ?? fallbackSide;
    const resolvedIndex = this.#resolveConnectionSiteIndexForSide(shape, resolvedSide);
    if (Number.isFinite(resolvedIndex)) {
      return resolvedIndex;
    }
    const fallbackIndex = CONNECTOR_SIDE_INDEX[resolvedSide];
    if (!Number.isFinite(fallbackIndex)) {
      throw new Error(`Failed to resolve connector ${label} index.`);
    }
    return fallbackIndex;
  }
  #resolveConnectionSiteIndexForSide(shape, side) {
    if (shape.connector) {
      return CONNECTOR_SIDE_INDEX[side];
    }
    const frame = shape.frame;
    const width = frame?.width;
    const height = frame?.height;
    if (width === undefined || height === undefined || width <= 0 || height <= 0) {
      return CONNECTOR_SIDE_INDEX[side];
    }
    const proto = shape.toProto();
    const geometry = proto.shape?.geometry;
    if (geometry === undefined || geometry === -1 /* UNRECOGNIZED */) {
      return CONNECTOR_SIDE_INDEX[side];
    }
    const preset = getPresetShapeDefinition(geometry);
    if (!preset) {
      return CONNECTOR_SIDE_INDEX[side];
    }
    const connectionSites = preset.cxnLst ?? [];
    if (connectionSites.length === 0) {
      return CONNECTOR_SIDE_INDEX[side];
    }
    const adjustmentMap = {};
    for (const adjustment of proto.shape?.adjustmentList ?? []) {
      if (adjustment.name && adjustment.formula) {
        adjustmentMap[adjustment.name] = adjustment.formula;
      }
    }
    const env = buildEnv(preset, width, height, adjustmentMap);
    let bestIndex;
    let bestPrimary = Number.POSITIVE_INFINITY;
    let bestSecondary = Number.POSITIVE_INFINITY;
    const centerX = width / 2;
    const centerY = height / 2;
    for (const [index, connectionSite] of connectionSites.entries()) {
      const x2 = resolve(connectionSite.pos?.x, env);
      const y2 = resolve(connectionSite.pos?.y, env);
      if (!Number.isFinite(x2) || !Number.isFinite(y2)) {
        continue;
      }
      let primary;
      let secondary;
      switch (side) {
        case "left":
          primary = x2;
          secondary = Math.abs(y2 - centerY);
          break;
        case "right":
          primary = Math.abs(x2 - width);
          secondary = Math.abs(y2 - centerY);
          break;
        case "top":
          primary = y2;
          secondary = Math.abs(x2 - centerX);
          break;
        case "bottom":
          primary = Math.abs(y2 - height);
          secondary = Math.abs(x2 - centerX);
          break;
      }
      if (primary < bestPrimary || primary === bestPrimary && secondary < bestSecondary) {
        bestPrimary = primary;
        bestSecondary = secondary;
        bestIndex = index;
      }
    }
    return bestIndex ?? CONNECTOR_SIDE_INDEX[side];
  }
}
var CONNECTOR_SIDE_INDEX = {
  top: 0,
  left: 1,
  bottom: 2,
  right: 3
};
function dotProduct(a, b) {
  return a.x * b.x + a.y * b.y;
}
function directionFromVector(vector) {
  const absX = Math.abs(vector.x);
  const absY = Math.abs(vector.y);
  if (absX < 0.000001 && absY < 0.000001) {
    return "none";
  }
  if (absX >= absY) {
    return vector.x >= 0 ? "right" : "left";
  }
  return vector.y >= 0 ? "down" : "up";
}
function oppositeDirection2(direction) {
  switch (direction) {
    case "up":
      return "down";
    case "down":
      return "up";
    case "left":
      return "right";
    case "right":
      return "left";
    default:
      return "none";
  }
}
function directionAxis2(direction) {
  if (direction === "left" || direction === "right") {
    return "horizontal";
  }
  if (direction === "up" || direction === "down") {
    return "vertical";
  }
  return "none";
}
function sharePerpendicularAxis(from2, to, axis) {
  if (axis === "horizontal") {
    return Math.abs(from2.y - to.y) < 0.000001;
  }
  return Math.abs(from2.x - to.x) < 0.000001;
}
function isDirectionForward(from2, to, direction) {
  switch (direction) {
    case "left":
      return to.x <= from2.x;
    case "right":
      return to.x >= from2.x;
    case "up":
      return to.y <= from2.y;
    case "down":
      return to.y >= from2.y;
    default:
      return false;
  }
}
function buildShapeAddProps(config, slide, recorder) {
  if ("proto" in config) {
    throw new Error("Cannot build shape props from proto config.");
  }
  if (config.geometry === "custom") {
    return {
      geometry: "custom",
      position: config.position,
      fill: config.fill,
      line: config.line,
      adjustmentList: config.adjustmentList,
      borderRadius: config.borderRadius,
      shadow: config.shadow,
      className: config.className,
      name: config.name,
      customPaths: config.customPaths
    };
  }
  if (config.geometry === "connector") {
    return {
      geometry: "connector",
      position: config.position,
      fill: config.fill,
      line: config.line,
      adjustmentList: config.adjustmentList,
      className: config.className,
      name: config.name,
      from: resolveConnectorTarget(config.from, slide, recorder),
      to: resolveConnectorTarget(config.to, slide, recorder),
      fromIdx: config.fromIdx,
      toIdx: config.toIdx,
      kind: config.kind,
      head: config.head,
      tail: config.tail,
      cap: config.cap,
      join: config.join
    };
  }
  return {
    geometry: config.geometry,
    position: config.position,
    fill: config.fill,
    line: config.line,
    adjustmentList: config.adjustmentList,
    borderRadius: config.borderRadius,
    shadow: config.shadow,
    className: config.className,
    name: config.name
  };
}
function resolveConnectorTarget(target, slide, recorder) {
  if (typeof target === "string") {
    const localId = resolveLocalShapeId(target, slide.id, slide.shapes.items.map((shape) => shape.id));
    if (!localId) {
      throw new Error("Connector target id must be non-empty.");
    }
    return buildElementAid("sh", slide.id, localId);
  }
  const anchor = buildElementAid("sh", slide.id, target.id);
  if (!recorder) {
    return anchor;
  }
  return recorder.targetRefForElement(target, anchor);
}
function resolveLocalShapeId(value, expectedSlideId, localIds) {
  return resolveElementLocalId(value, {
    prefix: "sh",
    aliases: ["shape"],
    slideId: expectedSlideId,
    localIds
  });
}

// node_modules/@oai/granola/dist/models/presentation/table-borders.js
function buildBorderLine(config) {
  if (!config) {
    return;
  }
  const line = new Line4;
  if (config.width !== undefined) {
    line.width = config.width;
  }
  if (config.style !== undefined) {
    line.style = config.style;
  }
  if (config.fill !== undefined) {
    line.fill = config.fill;
  }
  if (config.color !== undefined) {
    line.fill.color = config.color;
  }
  return line.toProto() ? line : undefined;
}

// node_modules/@oai/granola/dist/models/presentation/cell.js
var DEFAULT_TABLE_CELL_MARGIN_PX = {
  left: 0.1 * 96,
  right: 0.1 * 96,
  top: 0.05 * 96,
  bottom: 0.05 * 96
};

class Cell2 {
  #id;
  #paragraphs;
  #text;
  #textStyle;
  #levelsStyles;
  #fill;
  #lines;
  #gridSpan;
  #rowSpan;
  #horizontalMerge;
  #verticalMerge;
  #textDirection;
  #marginLeft;
  #marginRight;
  #marginTop;
  #marginBottom;
  #anchor;
  #anchorCenter;
  #horizontalOverflow;
  constructor(proto, context) {
    this.#id = proto?.id ?? v4_default();
    this.#paragraphs = new ParagraphCollection(context, proto?.paragraphs ?? []);
    this.#textStyle = proto?.textStyle ? new TextStyle2(proto.textStyle) : undefined;
    this.#text = new Text(this.#paragraphs, {
      getDefaultTextStyle: () => this.#textStyle,
      setDefaultTextStyle: (style) => {
        this.#textStyle = style ?? undefined;
      },
      resolveTextStyle: (name) => context.getTextStyleByName(name)
    });
    this.#levelsStyles = proto?.levelsStyles ?? [];
    this.#fill = new Fill2({ type: "proto", proto: proto?.fill });
    this.#lines = {
      top: new Line4({ type: "proto", proto: proto?.lines?.top }),
      right: new Line4({ type: "proto", proto: proto?.lines?.right }),
      bottom: new Line4({ type: "proto", proto: proto?.lines?.bottom }),
      left: new Line4({ type: "proto", proto: proto?.lines?.left }),
      diagonalDown: new Line4({ type: "proto", proto: proto?.lines?.diagonalDown }),
      diagonalUp: new Line4({ type: "proto", proto: proto?.lines?.diagonalUp })
    };
    this.#gridSpan = proto?.gridSpan;
    this.#rowSpan = proto?.rowSpan;
    this.#horizontalMerge = proto?.horizontalMerge;
    this.#verticalMerge = proto?.verticalMerge;
    this.#textDirection = proto?.textDirection;
    this.#marginLeft = proto?.marginLeft !== undefined ? pixelsFromEmu(proto.marginLeft) : undefined;
    this.#marginRight = proto?.marginRight !== undefined ? pixelsFromEmu(proto.marginRight) : undefined;
    this.#marginTop = proto?.marginTop !== undefined ? pixelsFromEmu(proto.marginTop) : undefined;
    this.#marginBottom = proto?.marginBottom !== undefined ? pixelsFromEmu(proto.marginBottom) : undefined;
    this.#anchor = proto?.anchor;
    this.#anchorCenter = proto?.anchorCenter;
    this.#horizontalOverflow = proto?.horizontalOverflow;
  }
  get id() {
    return this.#id;
  }
  get paragraphs() {
    return this.#paragraphs;
  }
  get text() {
    return this.#text;
  }
  get value() {
    return this.#text.toString();
  }
  set value(input) {
    if (input === undefined || input === null) {
      this.#text.set("");
      return;
    }
    this.#text.set(this.#normalizeInput(input));
  }
  get levelsStyles() {
    return this.#levelsStyles;
  }
  get textStyle() {
    if (!this.#textStyle) {
      this.#textStyle = new TextStyle2;
    }
    return this.#textStyle;
  }
  set textStyle(value) {
    this.#textStyle = value;
  }
  get fill() {
    return this.#fill;
  }
  set fill(value) {
    if (value instanceof Fill2) {
      const proto = value.toProto();
      this.#fill = proto ? new Fill2({ type: "proto", proto }) : new Fill2;
      return;
    }
    this.#fill = new Fill2(value);
  }
  get lines() {
    return this.#lines;
  }
  set lines(config) {
    if (config.top) {
      this.#lines.top = new Line4(config.top);
    }
    if (config.right) {
      this.#lines.right = new Line4(config.right);
    }
    if (config.bottom) {
      this.#lines.bottom = new Line4(config.bottom);
    }
    if (config.left) {
      this.#lines.left = new Line4(config.left);
    }
    if (config.diagonalDown) {
      this.#lines.diagonalDown = new Line4(config.diagonalDown);
    }
    if (config.diagonalUp) {
      this.#lines.diagonalUp = new Line4(config.diagonalUp);
    }
  }
  get borders() {
    return this.#lines;
  }
  set borders(config) {
    this.#applyBorderConfig(config);
  }
  get gridSpan() {
    return this.#gridSpan;
  }
  set gridSpan(value) {
    this.#gridSpan = value;
  }
  get rowSpan() {
    return this.#rowSpan;
  }
  set rowSpan(value) {
    this.#rowSpan = value;
  }
  get horizontalMerge() {
    return this.#horizontalMerge;
  }
  set horizontalMerge(value) {
    this.#horizontalMerge = value;
  }
  get verticalMerge() {
    return this.#verticalMerge;
  }
  set verticalMerge(value) {
    this.#verticalMerge = value;
  }
  get textDirection() {
    return this.#textDirection;
  }
  set textDirection(value) {
    this.#textDirection = value;
  }
  get margins() {
    if (this.#marginLeft === undefined && this.#marginRight === undefined && this.#marginTop === undefined && this.#marginBottom === undefined) {
      return;
    }
    return {
      left: this.#marginLeft,
      right: this.#marginRight,
      top: this.#marginTop,
      bottom: this.#marginBottom
    };
  }
  set margins(value) {
    this.#marginLeft = value?.left;
    this.#marginRight = value?.right;
    this.#marginTop = value?.top;
    this.#marginBottom = value?.bottom;
  }
  get anchor() {
    return this.#anchor;
  }
  set anchor(value) {
    this.#anchor = value;
  }
  get anchorCenter() {
    return this.#anchorCenter;
  }
  set anchorCenter(value) {
    this.#anchorCenter = value;
  }
  get horizontalOverflow() {
    return this.#horizontalOverflow;
  }
  set horizontalOverflow(value) {
    this.#horizontalOverflow = value;
  }
  #normalizeInput(input) {
    if (input instanceof Text) {
      return input;
    }
    if (typeof input === "number") {
      return String(input);
    }
    if (Array.isArray(input)) {
      const isPlainStringArray = input.every((entry) => typeof entry === "string");
      if (isPlainStringArray) {
        return input;
      }
      return input;
    }
    return input;
  }
  toProto() {
    return {
      id: this.#id,
      paragraphs: this.#paragraphs.toProto(),
      levelsStyles: this.#levelsStyles,
      fill: this.#fill.toProto(),
      text: this.value,
      textStyle: this.#textStyle?.toProto(),
      lines: {
        left: this.#lines.left?.toProto(),
        right: this.#lines.right?.toProto(),
        top: this.#lines.top?.toProto(),
        bottom: this.#lines.bottom?.toProto(),
        diagonalDown: this.#lines.diagonalDown?.toProto(),
        diagonalUp: this.#lines.diagonalUp?.toProto()
      },
      gridSpan: this.#gridSpan,
      rowSpan: this.#rowSpan,
      horizontalMerge: this.#horizontalMerge,
      verticalMerge: this.#verticalMerge,
      textDirection: this.#textDirection,
      marginLeft: emuFromPixels(this.#marginLeft ?? DEFAULT_TABLE_CELL_MARGIN_PX.left),
      marginRight: emuFromPixels(this.#marginRight ?? DEFAULT_TABLE_CELL_MARGIN_PX.right),
      marginTop: emuFromPixels(this.#marginTop ?? DEFAULT_TABLE_CELL_MARGIN_PX.top),
      marginBottom: emuFromPixels(this.#marginBottom ?? DEFAULT_TABLE_CELL_MARGIN_PX.bottom),
      anchor: this.#anchor,
      anchorCenter: this.#anchorCenter,
      horizontalOverflow: this.#horizontalOverflow
    };
  }
  #applyBorderConfig(config) {
    if (config.top) {
      const line = buildBorderLine(config.top);
      if (line) {
        this.#lines.top = line;
      }
    }
    if (config.right) {
      const line = buildBorderLine(config.right);
      if (line) {
        this.#lines.right = line;
      }
    }
    if (config.bottom) {
      const line = buildBorderLine(config.bottom);
      if (line) {
        this.#lines.bottom = line;
      }
    }
    if (config.left) {
      const line = buildBorderLine(config.left);
      if (line) {
        this.#lines.left = line;
      }
    }
    if (config.diagonalDown) {
      const line = buildBorderLine(config.diagonalDown);
      if (line) {
        this.#lines.diagonalDown = line;
      }
    }
    if (config.diagonalUp) {
      const line = buildBorderLine(config.diagonalUp);
      if (line) {
        this.#lines.diagonalUp = line;
      }
    }
  }
}

// node_modules/@oai/granola/dist/models/row.js
class Row2 {
  #cells;
  #id;
  #height;
  #context;
  constructor(proto, context) {
    this.#context = context;
    this.#cells = proto?.cells?.map((c) => new Cell2(c, context)) ?? [];
    this.#id = proto?.id ?? v4_default();
    this.#height = proto?.heightEmu ? proto.heightEmu * EMU_TO_PX : 0;
  }
  get cells() {
    return this.#cells;
  }
  getCell(index) {
    if (index < 0 || index >= this.#cells.length) {
      return;
    }
    return this.#cells[index];
  }
  get id() {
    return this.#id;
  }
  get height() {
    return this.#height;
  }
  ensureCellCount(count3) {
    if (count3 <= 0) {
      this.#cells = [];
      return;
    }
    while (this.#cells.length < count3) {
      this.#cells.push(new Cell2(undefined, this.#context));
    }
    if (this.#cells.length > count3) {
      this.#cells.splice(count3);
    }
  }
  toProto() {
    return {
      id: this.#id,
      heightEmu: emuFromPixels(this.#height),
      cells: this.#cells.map((c) => c.toProto())
    };
  }
}

// node_modules/@oai/granola/dist/models/presentation/table-cell-range.js
class TableCellRange {
  #table;
  #row;
  #column;
  #rowCount;
  #columnCount;
  #textStyle;
  #borders;
  #fillProxy;
  constructor(table, config) {
    if (config.row < 0 || config.column < 0) {
      throw new Error("Table range indices must be non-negative.");
    }
    if (config.rowCount <= 0 || config.columnCount <= 0) {
      throw new Error("Table range dimensions must be positive.");
    }
    if (config.row + config.rowCount > table.rowCount) {
      throw new Error("Table range rows exceed table bounds.");
    }
    if (config.column + config.columnCount > table.columnCount) {
      throw new Error("Table range columns exceed table bounds.");
    }
    this.#table = table;
    this.#row = config.row;
    this.#column = config.column;
    this.#rowCount = config.rowCount;
    this.#columnCount = config.columnCount;
  }
  get rowCount() {
    return this.#rowCount;
  }
  get columnCount() {
    return this.#columnCount;
  }
  get fill() {
    if (!this.#fillProxy) {
      this.#fillProxy = new TableRangeFill(this);
    }
    return this.#fillProxy;
  }
  set fill(value) {
    this.applyFill(value);
  }
  get textStyle() {
    if (!this.#textStyle) {
      this.#textStyle = new TableRangeTextStyle(this);
    }
    return this.#textStyle;
  }
  get borders() {
    if (!this.#borders) {
      this.#borders = new TableRangeBorders(this);
    }
    return this.#borders;
  }
  set borders(config) {
    this.applyBorders(config);
  }
  applyFill(value) {
    this.#forEachCell((cell) => {
      if (value instanceof Fill2) {
        const proto = value.toProto();
        cell.fill = proto ? new Fill2({ type: "proto", proto }) : new Fill2;
        return;
      }
      cell.fill = value;
    });
  }
  applyBorders(config) {
    const plan = {};
    if (config.outside) {
      plan.top ??= config.outside;
      plan.bottom ??= config.outside;
      plan.left ??= config.outside;
      plan.right ??= config.outside;
    }
    if (config.inside) {
      plan.insideHorizontal ??= config.inside;
      plan.insideVertical ??= config.inside;
    }
    if (config.top)
      plan.top = config.top;
    if (config.bottom)
      plan.bottom = config.bottom;
    if (config.left)
      plan.left = config.left;
    if (config.right)
      plan.right = config.right;
    if (config.insideHorizontal)
      plan.insideHorizontal = config.insideHorizontal;
    if (config.insideVertical)
      plan.insideVertical = config.insideVertical;
    if (config.diagonalDown)
      plan.diagonalDown = config.diagonalDown;
    if (config.diagonalUp)
      plan.diagonalUp = config.diagonalUp;
    this.#forEachCell((cell, rowIndex2, colIndex) => {
      if (plan.top && rowIndex2 === 0) {
        this.#applyCellLine(cell, "top", plan.top);
      }
      if (plan.bottom && rowIndex2 === this.#rowCount - 1) {
        this.#applyCellLine(cell, "bottom", plan.bottom);
      }
      if (plan.left && colIndex === 0) {
        this.#applyCellLine(cell, "left", plan.left);
      }
      if (plan.right && colIndex === this.#columnCount - 1) {
        this.#applyCellLine(cell, "right", plan.right);
      }
      if (plan.insideHorizontal && rowIndex2 < this.#rowCount - 1) {
        this.#applyCellLine(cell, "bottom", plan.insideHorizontal);
      }
      if (plan.insideVertical && colIndex < this.#columnCount - 1) {
        this.#applyCellLine(cell, "right", plan.insideVertical);
      }
      if (plan.diagonalDown) {
        this.#applyCellLine(cell, "diagonalDown", plan.diagonalDown);
      }
      if (plan.diagonalUp) {
        this.#applyCellLine(cell, "diagonalUp", plan.diagonalUp);
      }
    });
  }
  forEachCell(visitor) {
    this.#forEachCell(visitor);
  }
  #applyCellLine(cell, edge, config) {
    const line = buildBorderLine(config);
    if (!line) {
      return;
    }
    cell.lines[edge] = line;
  }
  #forEachCell(visitor) {
    for (let rowOffset = 0;rowOffset < this.#rowCount; rowOffset += 1) {
      for (let colOffset = 0;colOffset < this.#columnCount; colOffset += 1) {
        const cell = this.#table.getCell(this.#row + rowOffset, this.#column + colOffset);
        visitor(cell, rowOffset, colOffset);
      }
    }
  }
}

class TableRangeFill {
  #range;
  constructor(range2) {
    this.#range = range2;
  }
  get color() {
    return;
  }
  set color(value) {
    if (value === undefined) {
      this.#range.applyFill(undefined);
      return;
    }
    this.#range.applyFill({ type: "solid", color: value });
  }
}

class TableRangeTextStyle {
  #range;
  constructor(range2) {
    this.#range = range2;
  }
  get bold() {
    return this.#uniformValue((style) => style.bold);
  }
  set bold(value) {
    this.#applyStyle((style) => {
      style.bold = value;
    });
  }
  get italic() {
    return this.#uniformValue((style) => style.italic);
  }
  set italic(value) {
    this.#applyStyle((style) => {
      style.italic = value;
    });
  }
  get fontSize() {
    return this.#uniformValue((style) => style.fontSize);
  }
  set fontSize(value) {
    this.#applyStyle((style) => {
      style.fontSize = value;
    });
  }
  get underline() {
    return this.#uniformValue((style) => style.underline);
  }
  set underline(value) {
    this.#applyStyle((style) => {
      style.underline = value;
    });
  }
  get color() {
    return this.#uniformValue((style) => style.color, colorsEqual);
  }
  set color(value) {
    this.#applyStyle((style) => {
      style.color = value;
    });
  }
  #applyStyle(handler) {
    this.#range.forEachCell((cell) => {
      handler(cell.textStyle);
    });
  }
  #uniformValue(getter, equals2 = Object.is) {
    let initialized = false;
    let current;
    let mismatch = false;
    this.#range.forEachCell((cell) => {
      if (mismatch) {
        return;
      }
      const value = getter(cell.textStyle);
      if (!initialized) {
        initialized = true;
        current = value;
        return;
      }
      if (!equals2(current, value)) {
        current = undefined;
        mismatch = true;
      }
    });
    return mismatch ? undefined : current;
  }
}

class TableRangeBorders {
  #range;
  constructor(range2) {
    this.#range = range2;
  }
  assign(config) {
    this.#range.applyBorders(config);
  }
  set top(value) {
    if (!value) {
      return;
    }
    this.#range.applyBorders({ top: value });
  }
  set bottom(value) {
    if (!value) {
      return;
    }
    this.#range.applyBorders({ bottom: value });
  }
  set left(value) {
    if (!value) {
      return;
    }
    this.#range.applyBorders({ left: value });
  }
  set right(value) {
    if (!value) {
      return;
    }
    this.#range.applyBorders({ right: value });
  }
  set inside(value) {
    if (!value) {
      return;
    }
    this.#range.applyBorders({ inside: value });
  }
  set outside(value) {
    if (!value) {
      return;
    }
    this.#range.applyBorders({ outside: value });
  }
  set insideHorizontal(value) {
    if (!value) {
      return;
    }
    this.#range.applyBorders({ insideHorizontal: value });
  }
  set insideVertical(value) {
    if (!value) {
      return;
    }
    this.#range.applyBorders({ insideVertical: value });
  }
  set diagonalDown(value) {
    if (!value) {
      return;
    }
    this.#range.applyBorders({ diagonalDown: value });
  }
  set diagonalUp(value) {
    if (!value) {
      return;
    }
    this.#range.applyBorders({ diagonalUp: value });
  }
}
function colorsEqual(left, right) {
  if (!left && !right) {
    return true;
  }
  if (!left || !right) {
    return false;
  }
  const leftProto = left.toProto();
  const rightProto = right.toProto();
  if (!leftProto && !rightProto) {
    return true;
  }
  if (!leftProto || !rightProto) {
    return false;
  }
  return JSON.stringify(leftProto) === JSON.stringify(rightProto);
}

// node_modules/@oai/granola/dist/models/presentation/table-columns.js
class TableColumn2 {
  #table;
  #index;
  constructor(table, index) {
    this.#table = table;
    this.#index = index;
  }
  get width() {
    const widths = this.#table.columnWidths;
    if (widths.length > 0) {
      return widths[this.#index] ?? 0;
    }
    const columnCount = this.#table.columnCount;
    const frameWidth = this.#table.frame?.width;
    if (frameWidth && columnCount > 0) {
      return frameWidth / columnCount;
    }
    return 0;
  }
  set width(value) {
    if (!Number.isFinite(value) || value <= 0) {
      throw new Error("Column width must be a positive number.");
    }
    const columnCount = this.#table.columnCount;
    const widths = this.#table.columnWidths;
    let next = [];
    if (widths.length > 0) {
      next = widths.slice(0, columnCount);
    } else {
      const frameWidth = this.#table.frame?.width;
      const fallback = frameWidth && columnCount > 0 ? frameWidth / columnCount : 1;
      next = new Array(columnCount).fill(fallback);
    }
    while (next.length < columnCount) {
      next.push(next[next.length - 1] ?? 1);
    }
    next[this.#index] = value;
    this.#table.columnWidths = next;
  }
}

class TableColumns {
  #table;
  constructor(table) {
    this.#table = table;
  }
  get(index) {
    if (index < 0 || index >= this.#table.columnCount) {
      throw new Error("Column index is outside the table bounds.");
    }
    return new TableColumn2(this.#table, index);
  }
  get items() {
    const columns = [];
    for (let index = 0;index < this.#table.columnCount; index += 1) {
      columns.push(new TableColumn2(this.#table, index));
    }
    return columns;
  }
}

// node_modules/@oai/granola/dist/models/presentation/table-border-collection.js
class TableBorders {
  #table;
  constructor(table) {
    this.#table = table;
  }
  assign(config) {
    this.#apply(config);
  }
  set outside(value) {
    if (!value) {
      return;
    }
    this.#apply({ outside: value });
  }
  set inside(value) {
    if (!value) {
      return;
    }
    this.#apply({ inside: value });
  }
  set insideHorizontal(value) {
    if (!value) {
      return;
    }
    this.#apply({ insideHorizontal: value });
  }
  set insideVertical(value) {
    if (!value) {
      return;
    }
    this.#apply({ insideVertical: value });
  }
  #apply(config) {
    if (this.#table.rowCount === 0 || this.#table.columnCount === 0) {
      return;
    }
    const range2 = new TableCellRange(this.#table, {
      row: 0,
      column: 0,
      rowCount: this.#table.rowCount,
      columnCount: this.#table.columnCount
    });
    range2.applyBorders(config);
  }
}

// node_modules/@oai/granola/dist/models/presentation/table.js
class TableCellGrid {
  #table;
  constructor(table) {
    this.#table = table;
  }
  get(row, column) {
    return this.#table.getCell(row, column);
  }
  set(row, column, value) {
    this.#table.setCellValue(row, column, value);
  }
  block(config) {
    return new TableCellRange(this.#table, config);
  }
}

class Table2 extends Element2 {
  type = "table";
  #columnWidths;
  #columnWidthsExplicit;
  #rows;
  #cellsAccessor;
  #columnsAccessor;
  #bordersAccessor;
  #style;
  #propertiesFill;
  #propertiesRightToLeft;
  #propertiesEffects;
  #propertiesStyleXml;
  #firstRow;
  #lastRow;
  #firstColumn;
  #lastColumn;
  #bandedRows;
  #bandedColumns;
  constructor(context, proto) {
    const tableProto = proto?.table;
    super(context, proto ?? {});
    const rawColumnWidths = tableProto?.columnWidths ?? [];
    const normalizedColumnWidths = rawColumnWidths.map((width) => Number.isFinite(width) && width > 0 ? pixelsFromEmu(width) : 0);
    this.#columnWidthsExplicit = normalizedColumnWidths.some((width) => width > 0);
    this.#columnWidths = this.#columnWidthsExplicit ? normalizedColumnWidths : [];
    this.#rows = (tableProto?.rows ?? []).map((row) => new Row2(row, context));
    const properties = tableProto?.properties;
    this.#style = properties?.styleId;
    this.#propertiesFill = new Fill2({ type: "proto", proto: properties?.fill });
    this.#propertiesRightToLeft = properties?.rightToLeft;
    this.#firstRow = properties?.firstRow;
    this.#lastRow = properties?.lastRow;
    this.#firstColumn = properties?.firstColumn;
    this.#lastColumn = properties?.lastColumn;
    this.#bandedRows = properties?.bandedRows;
    this.#bandedColumns = properties?.bandedColumns;
    this.#propertiesEffects = properties?.effects?.map((effect) => ({ ...effect })) ?? [];
    this.#propertiesStyleXml = properties?.styleXml;
    this.data.type = 9 /* ELEMENT_TYPE_TABLE */;
  }
  get id() {
    return this.data.id;
  }
  toSnapshot() {
    const slideId = this.slideId;
    const localId = this.id;
    return {
      aid: buildSlideChildAid4("tb", slideId, localId),
      kind: "table",
      id: localId,
      slideId,
      name: this.name,
      rows: this.rowCount,
      cols: this.columnCount,
      preview: buildTablePreview(this.#rows),
      frame: this.frame
    };
  }
  get cells() {
    if (!this.#cellsAccessor) {
      this.#cellsAccessor = new TableCellGrid(this);
    }
    return this.#cellsAccessor;
  }
  get columns() {
    if (!this.#columnsAccessor) {
      this.#columnsAccessor = new TableColumns(this);
    }
    return this.#columnsAccessor;
  }
  get borders() {
    if (!this.#bordersAccessor) {
      this.#bordersAccessor = new TableBorders(this);
    }
    return this.#bordersAccessor;
  }
  set borders(config) {
    this.borders.assign(config);
  }
  get rows() {
    return [...this.#rows];
  }
  get rowCount() {
    return this.#rows.length;
  }
  get columnCount() {
    if (this.#columnWidths.length > 0) {
      return this.#columnWidths.length;
    }
    return this.#rows.reduce((max4, row) => Math.max(max4, row.cells.length), 0);
  }
  get columnWidths() {
    return [...this.#columnWidths];
  }
  get hasExplicitColumnWidths() {
    return this.#columnWidthsExplicit;
  }
  set columnWidths(widths) {
    if (!Array.isArray(widths) || widths.length === 0) {
      this.#columnWidths = [];
      this.#columnWidthsExplicit = false;
      return;
    }
    this.#columnWidths = widths.map((width) => Number.isFinite(width) && width > 0 ? width : 1);
    this.#columnWidthsExplicit = true;
  }
  get style() {
    return this.#style;
  }
  set style(value) {
    const normalized = value?.trim();
    this.#style = normalized && normalized.length > 0 ? normalized : undefined;
  }
  get styleOptions() {
    return {
      headerRow: this.#firstRow,
      totalRow: this.#lastRow,
      firstColumn: this.#firstColumn,
      lastColumn: this.#lastColumn,
      bandedRows: this.#bandedRows,
      bandedColumns: this.#bandedColumns
    };
  }
  set styleOptions(value) {
    if (!value) {
      this.#firstRow = undefined;
      this.#lastRow = undefined;
      this.#firstColumn = undefined;
      this.#lastColumn = undefined;
      this.#bandedRows = undefined;
      this.#bandedColumns = undefined;
      return;
    }
    if (value.headerRow !== undefined) {
      this.#firstRow = value.headerRow;
    }
    if (value.totalRow !== undefined) {
      this.#lastRow = value.totalRow;
    }
    if (value.firstColumn !== undefined) {
      this.#firstColumn = value.firstColumn;
    }
    if (value.lastColumn !== undefined) {
      this.#lastColumn = value.lastColumn;
    }
    if (value.bandedRows !== undefined) {
      this.#bandedRows = value.bandedRows;
    }
    if (value.bandedColumns !== undefined) {
      this.#bandedColumns = value.bandedColumns;
    }
  }
  get fill() {
    return this.#propertiesFill;
  }
  set fill(value) {
    if (value instanceof Fill2) {
      const proto = value.toProto();
      this.#propertiesFill = proto ? new Fill2({ type: "proto", proto }) : new Fill2;
      return;
    }
    this.#propertiesFill = new Fill2(value);
  }
  get rightToLeft() {
    return this.#propertiesRightToLeft;
  }
  set rightToLeft(value) {
    this.#propertiesRightToLeft = value;
  }
  setColumnWidths(widths) {
    if (widths.length !== this.columnCount) {
      throw new Error(`Expected ${this.columnCount} column widths, received ${widths.length}.`);
    }
    this.columnWidths = widths;
  }
  setValues(values) {
    const rowCount = values.length;
    const columnCount = values.reduce((max4, row) => Math.max(max4, row.length), 0);
    this.#ensureSize(rowCount, columnCount);
    values.forEach((rowValues, rowIndex2) => {
      rowValues.forEach((cellValue, columnIndex2) => {
        const cell = this.#rows[rowIndex2]?.getCell(columnIndex2);
        if (!cell) {
          return;
        }
        cell.value = cellValue;
      });
    });
  }
  setCellValue(row, column, value) {
    const cell = this.getCell(row, column);
    cell.value = value;
  }
  getCell(row, column) {
    if (row < 0 || column < 0) {
      throw new Error("Table addresses must be non-negative.");
    }
    const rowModel = this.#rows[row];
    if (!rowModel) {
      throw new Error(`Row ${row} is outside the current table bounds.`);
    }
    const cell = rowModel.getCell(column);
    if (!cell) {
      throw new Error(`Column ${column} is outside the current table bounds.`);
    }
    return cell;
  }
  merge(range2) {
    const { startRow, endRow, startColumn, endColumn } = range2;
    if (startRow < 0 || startColumn < 0 || endRow < startRow || endColumn < startColumn) {
      throw new Error("Invalid merge coordinates supplied.");
    }
    const maxRowIndex = this.rowCount - 1;
    const maxColumnIndex = this.columnCount - 1;
    if (startRow > maxRowIndex || endRow > maxRowIndex || startColumn > maxColumnIndex || endColumn > maxColumnIndex) {
      throw new Error("Merge range exceeds current table bounds.");
    }
    const rowSpan = endRow - startRow + 1;
    const columnSpan = endColumn - startColumn + 1;
    for (let row = startRow;row <= endRow; row += 1) {
      for (let column = startColumn;column <= endColumn; column += 1) {
        const cell = this.#rows[row]?.getCell(column);
        if (!cell) {
          continue;
        }
        const isStartRow = row === startRow;
        const isStartColumn = column === startColumn;
        if (isStartRow && isStartColumn) {
          cell.gridSpan = columnSpan > 1 ? columnSpan : undefined;
          cell.rowSpan = rowSpan > 1 ? rowSpan : undefined;
          cell.horizontalMerge = undefined;
          cell.verticalMerge = undefined;
        } else {
          cell.gridSpan = undefined;
          cell.rowSpan = undefined;
          cell.horizontalMerge = columnSpan > 1 ? !isStartColumn : undefined;
          cell.verticalMerge = rowSpan > 1 ? !isStartRow : undefined;
        }
      }
    }
  }
  toProto() {
    const proto = super.toProto();
    proto.type = this.data.type;
    const columnWidths = this.#resolveColumnWidths();
    const rowHeights = this.#resolveRowHeights();
    const properties = this.#buildTableProperties();
    proto.table = {
      columnWidths: columnWidths.map((width) => emuFromPixels(width)),
      rows: this.#rows.map((row, index) => {
        const rowProto = row.toProto();
        if (rowHeights) {
          rowProto.heightEmu = emuFromPixels(rowHeights[index] ?? 0);
        }
        return rowProto;
      }),
      properties
    };
    return proto;
  }
  #buildTableProperties() {
    const fill = this.#propertiesFill?.toProto();
    const styleId = resolveTableStyleId(this.#style);
    const hasOptions = this.#firstRow !== undefined || this.#lastRow !== undefined || this.#firstColumn !== undefined || this.#lastColumn !== undefined || this.#bandedRows !== undefined || this.#bandedColumns !== undefined;
    const hasEffects = this.#propertiesEffects.length > 0;
    const hasStyleXml = this.#propertiesStyleXml !== undefined;
    const hasRtl = this.#propertiesRightToLeft !== undefined;
    if (!fill && !styleId && !hasOptions && !hasEffects && !hasStyleXml && !hasRtl) {
      return;
    }
    return {
      fill,
      rightToLeft: this.#propertiesRightToLeft,
      firstRow: this.#firstRow,
      lastRow: this.#lastRow,
      firstColumn: this.#firstColumn,
      lastColumn: this.#lastColumn,
      bandedRows: this.#bandedRows,
      bandedColumns: this.#bandedColumns,
      styleId,
      effects: this.#propertiesEffects ?? [],
      styleXml: this.#propertiesStyleXml
    };
  }
  #resolveColumnWidths() {
    const columnCount = this.columnCount;
    if (columnCount <= 0) {
      return [];
    }
    if (this.#columnWidthsExplicit) {
      const widths = this.#columnWidths.map((width) => Number.isFinite(width) && width > 0 ? width : 1);
      if (widths.length >= columnCount) {
        return widths.slice(0, columnCount);
      }
      const padWidth = widths[widths.length - 1] ?? 1;
      return widths.concat(new Array(columnCount - widths.length).fill(padWidth));
    }
    const bbox = this.position.toProto();
    const frameWidth = this.frame?.width ?? (bbox?.widthEmu !== undefined ? pixelsFromEmu(bbox.widthEmu) : undefined);
    if (frameWidth && Number.isFinite(frameWidth) && frameWidth > 0) {
      const width = frameWidth / columnCount;
      return new Array(columnCount).fill(width);
    }
    return new Array(columnCount).fill(1);
  }
  #resolveRowHeights() {
    const rowCount = this.rowCount;
    if (rowCount <= 0) {
      return;
    }
    if (this.#rows.some((row) => row.height > 0)) {
      return;
    }
    const bbox = this.position.toProto();
    const frameHeight = this.frame?.height ?? (bbox?.heightEmu !== undefined ? pixelsFromEmu(bbox.heightEmu) : undefined);
    if (!frameHeight || !Number.isFinite(frameHeight) || frameHeight <= 0) {
      return;
    }
    const height = frameHeight / rowCount;
    if (!Number.isFinite(height) || height <= 0) {
      return;
    }
    return new Array(rowCount).fill(height);
  }
  #ensureSize(rowCount, columnCount) {
    if (rowCount < 0 || columnCount < 0) {
      throw new Error("Table dimensions must be non-negative.");
    }
    const safeRows = Math.floor(rowCount);
    const safeColumns = Math.floor(columnCount);
    while (this.#rows.length < safeRows) {
      const row = new Row2(undefined, this.context);
      row.ensureCellCount(safeColumns);
      this.#rows.push(row);
    }
    if (this.#rows.length > safeRows) {
      this.#rows.splice(safeRows);
    }
    for (const row of this.#rows) {
      row.ensureCellCount(safeColumns);
    }
    if (safeColumns <= 0) {
      this.#columnWidths = [];
    } else if (this.#columnWidths.length < safeColumns) {
      this.#columnWidths.push(...new Array(safeColumns - this.#columnWidths.length).fill(1));
    } else if (this.#columnWidths.length > safeColumns) {
      this.#columnWidths = this.#columnWidths.slice(0, safeColumns);
    }
  }
}
var TABLE_STYLE_IDS = {
  tablestylemedium2: "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}",
  "medium style 2 - accent 1": "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"
};
var TABLE_STYLE_GUID_PATTERN = /^\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}$/i;
function resolveTableStyleId(value) {
  if (!value) {
    return;
  }
  const trimmed = value.trim();
  if (!trimmed) {
    return;
  }
  if (TABLE_STYLE_GUID_PATTERN.test(trimmed)) {
    return trimmed;
  }
  const normalized = normalizeStyleKey2(trimmed);
  return TABLE_STYLE_IDS[normalized];
}
function normalizeStyleKey2(value) {
  return value.trim().toLowerCase().replace(/\s+/g, " ").replace(/\s*-\s*/g, " - ");
}
function buildSlideChildAid4(prefix, slideId, localId) {
  return buildElementAid(prefix, slideId, localId);
}
function buildTablePreview(rows, maxLength = 140) {
  if (!rows.length) {
    return;
  }
  const row = rows.find((candidate) => candidate.cells.some((cell) => cell.value.trim().length > 0)) ?? rows[0];
  if (!row) {
    return;
  }
  const values = row.cells.map((cell) => cell.value).map((value) => value.replace(/\r?\n/g, " ").trim()).filter((value) => value.length > 0);
  if (values.length === 0) {
    return;
  }
  const joined = values.join(" | ");
  if (joined.length <= maxLength) {
    return joined;
  }
  const sliceLength = Math.max(1, maxLength - 3);
  return `${joined.slice(0, sliceLength)}...`;
}

// node_modules/@oai/granola/dist/models/presentation/tables.js
class Tables {
  #context;
  #items;
  constructor(context, proto) {
    this.#context = context;
    this.#items = [];
    proto.forEach((element) => {
      this.add({ proto: element });
    });
  }
  get items() {
    return [...this.#items];
  }
  add(input) {
    if (input && typeof input === "object" && "proto" in input) {
      if (!input.proto?.table) {
        throw new Error("Cannot add a table element without table data.");
      }
      const table2 = new Table2(this.#tableContext(), input.proto);
      this.#items.push(table2);
      this.#context._register(table2);
      return table2;
    }
    const normalized = this.#normalizeAddInput(input);
    const table = new Table2(this.#tableContext(), undefined);
    this.#items.push(table);
    this.#context._register(table);
    if (normalized.position) {
      table.frame = normalized.position;
    }
    const baseMatrix = this.#buildBlankMatrix(normalized.rows, normalized.columns);
    if (normalized.values && normalized.values.length > 0) {
      normalized.values.forEach((rowValues, rowIndex2) => {
        const targetRow = baseMatrix[rowIndex2];
        if (!targetRow) {
          return;
        }
        rowValues.forEach((cellValue, columnIndex2) => {
          if (columnIndex2 >= targetRow.length) {
            return;
          }
          targetRow[columnIndex2] = cellValue;
        });
      });
    }
    table.setValues(baseMatrix);
    return table;
  }
  toProto() {
    return this.#items.map((table) => table.toProto());
  }
  #normalizeAddInput(input) {
    if (!input) {
      return { rows: 1, columns: 1 };
    }
    if (Array.isArray(input)) {
      const rowCount = input.length;
      const columnCount = input.reduce((max4, row) => Math.max(max4, row.length), 0);
      return {
        rows: Math.max(rowCount, 1),
        columns: Math.max(columnCount, 1),
        values: input
      };
    }
    let rows = Math.floor(input.rows);
    let columns = Math.floor(input.columns);
    if (!Number.isFinite(rows) || rows <= 0) {
      throw new Error("Table rows must be a positive integer.");
    }
    if (!Number.isFinite(columns) || columns <= 0) {
      throw new Error("Table columns must be a positive integer.");
    }
    if (input.values) {
      const valueRows = input.values.length;
      const valueColumns = input.values.reduce((max4, row) => Math.max(max4, row.length), 0);
      rows = Math.max(rows, valueRows);
      columns = Math.max(columns, valueColumns);
    }
    const hasPosition = input.left !== undefined || input.top !== undefined || input.width !== undefined || input.height !== undefined;
    return {
      rows,
      columns,
      values: input.values,
      position: hasPosition ? {
        left: input.left,
        top: input.top,
        width: input.width,
        height: input.height
      } : undefined
    };
  }
  #buildBlankMatrix(rows, columns) {
    const safeRows = Math.max(0, rows);
    const safeColumns = Math.max(0, columns);
    if (safeRows === 0 || safeColumns === 0) {
      return [];
    }
    return Array.from({ length: safeRows }, () => Array.from({ length: safeColumns }, () => ""));
  }
  #tableContext() {
    return this.#context;
  }
}

// node_modules/@oai/granola/dist/models/presentation/elements-collection.js
var toValidElementIdNumber = (id2) => {
  if (!id2) {
    return;
  }
  const parsed = Number(id2);
  if (!Number.isInteger(parsed) || parsed <= 0) {
    return;
  }
  return parsed;
};
var hydrateElementIds = (elements) => {
  if (elements.length === 0) {
    return elements;
  }
  let nextNumericId = 0;
  for (const element of elements) {
    const parsed = toValidElementIdNumber(element.id);
    if (parsed !== undefined) {
      nextNumericId = Math.max(nextNumericId, parsed);
    }
  }
  const assignedIds = new Set;
  return elements.map((element) => {
    const candidate = element.id;
    if (candidate && toValidElementIdNumber(candidate) !== undefined && !assignedIds.has(candidate)) {
      assignedIds.add(candidate);
      return element;
    }
    nextNumericId += 1;
    const generated = String(nextNumericId);
    assignedIds.add(generated);
    return {
      ...element,
      id: generated
    };
  });
};

class ElementsCollection {
  #shapes;
  #images;
  #tables;
  #charts;
  #order;
  #byId;
  #hydrating;
  #context;
  constructor(hostContext, elements) {
    const mutationContext = Object.create(hostContext);
    mutationContext._register = (element, options) => this._register(element, options);
    mutationContext._unregister = (id2) => this._unregister(id2);
    mutationContext.deleteElement = (id2) => this.#deleteElement(id2);
    this.#context = mutationContext;
    this.#order = [];
    this.#byId = new Map;
    this.#hydrating = true;
    this.#shapes = new ShapeCollection(this.#context, []);
    this.#images = new ImageElementCollection(this.#context, []);
    this.#tables = new Tables(this.#context, []);
    this.#charts = new ChartElementCollection(this.#context, []);
    const hydratedElements = hydrateElementIds(elements ?? []);
    for (const proto of hydratedElements) {
      const element = this.#createElementFromProto(proto);
      if (!element) {
        continue;
      }
      this.#order.push(element.id);
    }
    this.#hydrating = false;
  }
  get shapes() {
    return this.#shapes;
  }
  get images() {
    return this.#images;
  }
  get tables() {
    return this.#tables;
  }
  get charts() {
    return this.#charts;
  }
  get items() {
    const ordered = [];
    for (const id2 of this.#order) {
      const element = this.#byId.get(id2);
      if (element) {
        ordered.push(element);
      }
    }
    return ordered;
  }
  getById(id2) {
    return this.#byId.get(id2);
  }
  toProto() {
    return this.items.map((element) => element.toProto());
  }
  hydrateCollaborativeRefsFromProto() {
    this.#shapes.hydrateCollaborativeRefsFromProto();
  }
  _register(element, options) {
    this.#byId.set(element.id, element);
    if (this.#hydrating) {
      return;
    }
    const existingIndex = this.#order.indexOf(element.id);
    if (existingIndex >= 0) {
      this.#order.splice(existingIndex, 1);
    }
    const targetIndex = options?.index ?? this.#order.length;
    this.#order.splice(targetIndex, 0, element.id);
    this.#queueCollaborativePublish();
  }
  _unregister(id2) {
    this.#byId.delete(id2);
    const index = this.#order.indexOf(id2);
    if (index >= 0) {
      this.#order.splice(index, 1);
    }
    this.#queueCollaborativePublish();
  }
  #deleteElement(id2) {
    const element = this.#byId.get(id2);
    if (!element) {
      return;
    }
    if (element instanceof Shape2) {
      this.#shapes.deleteById(id2);
      return;
    }
    if (element instanceof ImageElement2) {
      this.#images.deleteById(id2);
      return;
    }
    throw new Error("deleteElement currently supports shapes and images only.");
  }
  #createElementFromProto(proto) {
    return this.#instantiateSlideElement(proto);
  }
  #instantiateSlideElement(proto) {
    switch (proto.type) {
      case 5 /* ELEMENT_TYPE_SHAPE */:
      case 1 /* ELEMENT_TYPE_TEXT */:
      case 2 /* ELEMENT_TYPE_TEXT_GROUP */:
        return this.#shapes.add({ proto });
      case 3 /* ELEMENT_TYPE_IMAGE */:
      case 7 /* ELEMENT_TYPE_IMAGE_REFERENCE */:
        return this.#images.add({ proto });
      case 9 /* ELEMENT_TYPE_TABLE */:
        return this.#tables.add({ proto });
      case 4 /* ELEMENT_TYPE_CHART */:
      case 6 /* ELEMENT_TYPE_CHART_REFERENCE */:
        return this.#charts.add({ proto });
      default:
        return;
    }
  }
  #queueCollaborativePublish() {
    this.#context.getPresentation?.()?.queuePresentationCollabPublish();
  }
}

// node_modules/@oai/granola/dist/models/presentation/placeholders.js
class PlaceholderCollection {
  #shapes;
  #hostLabel;
  constructor(shapes, hostLabel = "slide") {
    this.#shapes = shapes;
    this.#hostLabel = hostLabel;
  }
  summary() {
    return this.#placeholderShapes().map((shape) => ({
      name: this.#placeholderKey(shape) ?? shape.name,
      type: shape.placeholderType,
      text: shape.text?.toString() ?? ""
    }));
  }
  getItem(name) {
    const key = normalizePlaceholderKey(name);
    const match = this.#placeholderShapes().find((shape) => {
      const placeholderKey = this.#placeholderKey(shape);
      return placeholderKey !== undefined && placeholderKey === key;
    });
    if (!match) {
      throw new Error(`Placeholder "${name}" not found on ${this.#hostLabel}.`);
    }
    return match;
  }
  getAll() {
    return this.#placeholderShapes();
  }
  add(nameOrConfig, type) {
    if (typeof nameOrConfig === "string") {
      const shape2 = this.#shapes.addPlaceholder(nameOrConfig);
      if (type) {
        shape2.placeholderType = type;
      }
      return shape2;
    }
    const config = nameOrConfig;
    const placeholderName = config.name ?? `placeholder_${this.#placeholderShapes().length + 1}`;
    const shape = config.geometry !== undefined && config.geometry !== "custom" && config.geometry !== "connector" ? this.#shapes.add({
      geometry: config.geometry === "textbox" ? "rect" : config.geometry,
      fill: config.fill,
      line: config.line,
      position: config.position
    }) : this.#shapes.addPlaceholder(placeholderName);
    shape.name = placeholderName;
    const nextIndex = config.index ?? shape.placeholderIndex ?? this.#nextPlaceholderIndex();
    shape.placeholderIndex = nextIndex;
    if (config.type) {
      shape.placeholderType = config.type;
    }
    if (config.text !== undefined) {
      shape.text = config.text;
    }
    return shape;
  }
  #placeholderShapes() {
    return this.#shapes.items.filter((shape) => shape.isPlaceholder());
  }
  #nextPlaceholderIndex() {
    const indices = this.#placeholderShapes().map((shape) => shape.placeholderIndex).filter((value) => value !== undefined);
    if (indices.length === 0) {
      return 0;
    }
    return Math.max(...indices) + 1;
  }
  #placeholderKey(shape) {
    return shape.placeholderKey() ?? derivePlaceholderKey({ name: shape.name }) ?? undefined;
  }
}

// node_modules/@oai/granola/dist/models/presentation/layout.js
class Layout2 {
  #context;
  #data;
  #elements;
  #background;
  #placeholders;
  constructor(config, context) {
    this.#context = context;
    if ("proto" in config) {
      const proto = config.proto;
      this.#data = proto;
      this.#elements = new ElementsCollection(this.#context, proto.elements ?? []);
      this.#background = new SlideBackground(this.#backgroundContext(), proto.background ?? undefined);
    } else {
      this.#data = {
        id: generateUuid(),
        name: config.name,
        type: config.type ?? "",
        bodyLevelStyles: [],
        titleLevelStyles: [],
        otherLevelStyles: [],
        parentLayoutId: "",
        colorMap: undefined
      };
      this.#elements = new ElementsCollection(this.#context, []);
      this.#background = new SlideBackground(this.#backgroundContext(), undefined);
    }
  }
  get id() {
    return this.#data.id;
  }
  get name() {
    return this.#data.name;
  }
  rename(name) {
    this.#data.name = name;
  }
  get background() {
    return this.#background;
  }
  get titleLevelStyles() {
    return this.#data.titleLevelStyles;
  }
  get bodyLevelStyles() {
    return this.#data.bodyLevelStyles;
  }
  get otherLevelStyles() {
    return this.#data.otherLevelStyles;
  }
  get shapes() {
    return this.#elements.shapes;
  }
  get images() {
    return this.#elements.images;
  }
  get tables() {
    return this.#elements.tables;
  }
  get charts() {
    return this.#elements.charts;
  }
  get parentLayoutId() {
    return this.#data.parentLayoutId;
  }
  setParentLayoutId(parentLayoutId) {
    this.#data.parentLayoutId = parentLayoutId;
  }
  setColorMap(colorMap) {
    this.#data.colorMap = colorMap;
  }
  get elements() {
    return this.#elements.items;
  }
  get type() {
    return this.#data.type;
  }
  get colorMap() {
    return this.#data.colorMap;
  }
  get placeholders() {
    if (!this.#placeholders) {
      this.#placeholders = new PlaceholderCollection(this.#elements.shapes, "layout");
    }
    return this.#placeholders;
  }
  findPlaceholder(types, index) {
    if (!Array.isArray(types) || types.length === 0) {
      return;
    }
    const elements = this.#elements.items;
    if (!elements.length) {
      return;
    }
    const matchesType = (placeholderType) => placeholderType !== undefined && types.includes(placeholderType);
    return elements.find((element) => matchesType(element.placeholderType) && (element.placeholderIndex ?? 0) === index) ?? elements.find((element) => matchesType(element.placeholderType));
  }
  toProto() {
    return {
      id: this.#data.id,
      name: this.#data.name,
      elements: this.#elements.toProto(),
      background: this.#background.toProto(),
      type: this.#data.type,
      bodyLevelStyles: this.#data.bodyLevelStyles,
      titleLevelStyles: this.#data.titleLevelStyles,
      otherLevelStyles: this.#data.otherLevelStyles,
      parentLayoutId: this.#data.parentLayoutId,
      colorMap: this.#data.colorMap
    };
  }
  #backgroundContext() {
    return {
      stub: () => {}
    };
  }
}

// node_modules/@oai/granola/dist/models/presentation/layout-collection.js
class LayoutCollection {
  #context;
  #items;
  #itemsById;
  constructor(context, proto) {
    this.#context = context;
    this.#items = (proto ?? []).map((layout) => new Layout2({ proto: layout }, this.#layoutContext()));
    this.#itemsById = new Map(this.#items.filter((layout) => Boolean(layout.id)).map((layout) => [layout.id, layout]));
  }
  get items() {
    return [...this.#items];
  }
  getById(id2) {
    if (!id2) {
      return;
    }
    return this.#itemsById.get(id2);
  }
  add(name, init) {
    if (!name || name.length === 0) {
      throw new Error("Layout name is required.");
    }
    const layout = new Layout2({ name, ...init }, this.#layoutContext());
    this.#items.push(layout);
    if (layout.id) {
      this.#itemsById.set(layout.id, layout);
    }
    return layout;
  }
  replace(proto) {
    this.#items = (proto ?? []).map((layout) => new Layout2({ proto: layout }, this.#layoutContext()));
    this.#itemsById = new Map(this.#items.filter((layout) => Boolean(layout.id)).map((layout) => [layout.id, layout]));
  }
  getByName(name) {
    return this.#items.find((layout) => layout.name === name);
  }
  getItem(name) {
    const layout = this.getByName(name);
    if (!layout) {
      throw new Error(`Layout "${name}" not found.`);
    }
    return layout;
  }
  removeByName(name) {
    const index = this.#items.findIndex((layout) => layout.name === name);
    if (index >= 0) {
      const [removed] = this.#items.splice(index, 1);
      if (removed?.id) {
        this.#itemsById.delete(removed.id);
      }
    }
  }
  toProto() {
    return this.#items.map((layout) => layout.toProto());
  }
  #layoutContext() {
    return this.#context;
  }
}

// node_modules/@oai/granola/dist/models/presentation/master.js
class Masters {
  #layouts;
  constructor(layouts) {
    this.#layouts = layouts;
  }
  get items() {
    return this.#layouts.items.filter((layout) => layout.type === "master");
  }
  getDefault() {
    return this.items[0];
  }
  add(name) {
    return this.#layouts.add(name, { type: "master" });
  }
  toProto() {
    return this.items.map((layout) => layout.toProto());
  }
}

// node_modules/@oai/granola/dist/models/presentation/style.js
class Style {
  #textStyle;
  #name;
  #kind = "text";
  #isBuiltIn;
  #description;
  #usageHint;
  constructor(options) {
    this.#name = options.name;
    this.#isBuiltIn = options.isBuiltIn ?? false;
    this.#description = options.description;
    this.#usageHint = options.usageHint;
    this.#textStyle = new TextStyle2(options.textStyle);
  }
  get name() {
    return this.#name;
  }
  get kind() {
    return this.#kind;
  }
  get isBuiltIn() {
    return this.#isBuiltIn;
  }
  get description() {
    return this.#description;
  }
  set description(value) {
    this.#description = value;
  }
  get usageHint() {
    return this.#usageHint;
  }
  set usageHint(value) {
    this.#usageHint = value;
  }
  get bold() {
    return this.#textStyle.bold;
  }
  set bold(value) {
    this.#textStyle.bold = value;
  }
  get italic() {
    return this.#textStyle.italic;
  }
  set italic(value) {
    this.#textStyle.italic = value;
  }
  get fontSize() {
    return this.#textStyle.fontSize;
  }
  set fontSize(value) {
    this.#textStyle.fontSize = value;
  }
  get underline() {
    return this.#textStyle.underline;
  }
  set underline(value) {
    this.#textStyle.underline = value;
  }
  get alignment() {
    return mapProtoTextHorizontalAlignment(this.#textStyle.alignment);
  }
  set alignment(value) {
    this.#textStyle.alignment = value ? mapTextHorizontalAlignment(value) : undefined;
  }
  get color() {
    return this.#colorFromFill(this.#textStyle.fill);
  }
  set color(value) {
    this.#textStyle.fill = value;
  }
  get textStyle() {
    return this.#textStyle;
  }
  describe() {
    return {
      name: this.#name,
      kind: this.#kind,
      description: this.#description,
      usageHint: this.#usageHint,
      isBuiltIn: this.#isBuiltIn
    };
  }
  #colorFromFill(fill) {
    if (!fill) {
      return;
    }
    const proto = fill.color.toProto();
    if (!proto) {
      return;
    }
    const color2 = new Color4({ type: "proto", proto });
    return color2;
  }
}

// node_modules/@oai/granola/dist/models/presentation/styles-collection.js
var BUILT_IN_PRESETS = [
  {
    options: {
      name: "title",
      isBuiltIn: true,
      description: "Primary slide title",
      usageHint: "Use 'title' for the main slide heading, usually once per slide."
    },
    configure: (style) => {
      style.bold = true;
      style.fontSize = 36;
      style.alignment = "center";
    }
  },
  {
    options: {
      name: "heading1",
      isBuiltIn: true,
      description: "Section heading inside slides",
      usageHint: "Use 'heading1' for major sections or standout headings."
    },
    configure: (style) => {
      style.bold = true;
      style.fontSize = 28;
      style.alignment = "left";
    }
  },
  {
    options: {
      name: "heading2",
      isBuiltIn: true,
      description: "Sub-heading within content blocks",
      usageHint: "Use 'heading2' for secondary headings beneath a heading1."
    },
    configure: (style) => {
      style.bold = true;
      style.fontSize = 22;
      style.alignment = "left";
    }
  },
  {
    options: {
      name: "body",
      isBuiltIn: true,
      description: "Default body copy",
      usageHint: "Use 'body' for standard paragraphs and descriptive text."
    },
    configure: (style) => {
      style.fontSize = 18;
      style.alignment = "left";
    }
  },
  {
    options: {
      name: "list",
      isBuiltIn: true,
      description: "Bulleted list formatting",
      usageHint: "Use 'list' for bulleted bodies when enumerating items."
    },
    configure: (style) => {
      style.fontSize = 18;
      style.alignment = "left";
    }
  },
  {
    options: {
      name: "numberedList",
      isBuiltIn: true,
      description: "Numbered list formatting",
      usageHint: "Use 'numberedList' for ordered lists or step-wise instructions."
    },
    configure: (style) => {
      style.fontSize = 18;
      style.alignment = "left";
    }
  }
];

class StylesCollection {
  #styles;
  constructor() {
    this.#styles = new Map;
    this.#seedBuiltIns();
  }
  get(name) {
    const style = this.#styles.get(name);
    if (!style) {
      throw new Error(`Style '${name}' does not exist.`);
    }
    return style;
  }
  add(name) {
    const existing = this.#styles.get(name);
    if (existing) {
      return existing;
    }
    const style = new Style({ name, isBuiltIn: false });
    this.#styles.set(name, style);
    return style;
  }
  describe(name) {
    if (typeof name === "string") {
      return this.get(name).describe();
    }
    return Array.from(this.#styles.values()).map((style) => style.describe());
  }
  resolveTextStyle(name) {
    return this.#styles.get(name)?.textStyle;
  }
  #seedBuiltIns() {
    for (const preset of BUILT_IN_PRESETS) {
      const style = new Style(preset.options);
      preset.configure?.(style);
      this.#styles.set(style.name, style);
    }
  }
}

// node_modules/@lume/kiwi/dist/maptype.js
function createMap() {
  return new IndexedMap;
}

class IndexedMap {
  index = {};
  array = [];
  size() {
    return this.array.length;
  }
  empty() {
    return this.array.length === 0;
  }
  itemAt(index) {
    return this.array[index];
  }
  contains(key) {
    return this.index[key.id()] !== undefined;
  }
  find(key) {
    const i = this.index[key.id()];
    return i === undefined ? undefined : this.array[i];
  }
  setDefault(key, factory) {
    const i = this.index[key.id()];
    if (i === undefined) {
      const pair = new Pair(key, factory());
      this.index[key.id()] = this.array.length;
      this.array.push(pair);
      return pair;
    } else {
      return this.array[i];
    }
  }
  insert(key, value) {
    const pair = new Pair(key, value);
    const i = this.index[key.id()];
    if (i === undefined) {
      this.index[key.id()] = this.array.length;
      this.array.push(pair);
    } else {
      this.array[i] = pair;
    }
    return pair;
  }
  erase(key) {
    const i = this.index[key.id()];
    if (i === undefined) {
      return;
    }
    this.index[key.id()] = undefined;
    const pair = this.array[i];
    const last2 = this.array.pop();
    if (pair !== last2) {
      this.array[i] = last2;
      this.index[last2.first.id()] = i;
    }
    return pair;
  }
  copy() {
    const copy3 = new IndexedMap;
    for (let i = 0;i < this.array.length; i++) {
      const pair = this.array[i].copy();
      copy3.array[i] = pair;
      copy3.index[pair.first.id()] = i;
    }
    return copy3;
  }
}

class Pair {
  first;
  second;
  constructor(first, second) {
    this.first = first;
    this.second = second;
  }
  copy() {
    return new Pair(this.first, this.second);
  }
}

// node_modules/@lume/kiwi/dist/variable.js
class Variable {
  constructor(name = "") {
    this._name = name;
  }
  id() {
    return this._id;
  }
  name() {
    return this._name;
  }
  setName(name) {
    this._name = name;
  }
  context() {
    return this._context;
  }
  setContext(context) {
    this._context = context;
  }
  value() {
    return this._value;
  }
  setValue(value) {
    this._value = value;
  }
  plus(value) {
    return new Expression(this, value);
  }
  minus(value) {
    return new Expression(this, typeof value === "number" ? -value : [-1, value]);
  }
  multiply(coefficient) {
    return new Expression([coefficient, this]);
  }
  divide(coefficient) {
    return new Expression([1 / coefficient, this]);
  }
  toJSON() {
    return {
      name: this._name,
      value: this._value
    };
  }
  toString() {
    return this._context + "[" + this._name + ":" + this._value + "]";
  }
  _name;
  _value = 0;
  _context = null;
  _id = VarId++;
}
var VarId = 0;

// node_modules/@lume/kiwi/dist/expression.js
class Expression {
  constructor() {
    let parsed = parseArgs(arguments);
    this._terms = parsed.terms;
    this._constant = parsed.constant;
  }
  terms() {
    return this._terms;
  }
  constant() {
    return this._constant;
  }
  value() {
    let result = this._constant;
    for (let i = 0, n = this._terms.size();i < n; i++) {
      let pair = this._terms.itemAt(i);
      result += pair.first.value() * pair.second;
    }
    return result;
  }
  plus(value) {
    return new Expression(this, value);
  }
  minus(value) {
    return new Expression(this, typeof value === "number" ? -value : [-1, value]);
  }
  multiply(coefficient) {
    return new Expression([coefficient, this]);
  }
  divide(coefficient) {
    return new Expression([1 / coefficient, this]);
  }
  isConstant() {
    return this._terms.size() == 0;
  }
  toString() {
    let result = this._terms.array.map(function(pair) {
      return pair.second + "*" + pair.first.toString();
    }).join(" + ");
    if (!this.isConstant() && this._constant !== 0) {
      result += " + ";
    }
    result += this._constant;
    return result;
  }
  _terms;
  _constant;
}
function parseArgs(args2) {
  let constant2 = 0;
  let factory = () => 0;
  let terms = createMap();
  for (let i = 0, n = args2.length;i < n; ++i) {
    let item = args2[i];
    if (typeof item === "number") {
      constant2 += item;
    } else if (item instanceof Variable) {
      terms.setDefault(item, factory).second += 1;
    } else if (item instanceof Expression) {
      constant2 += item.constant();
      let terms2 = item.terms();
      for (let j = 0, k = terms2.size();j < k; j++) {
        let termPair = terms2.itemAt(j);
        terms.setDefault(termPair.first, factory).second += termPair.second;
      }
    } else if (item instanceof Array) {
      if (item.length !== 2) {
        throw new Error("array must have length 2");
      }
      let value = item[0];
      let value2 = item[1];
      if (typeof value !== "number") {
        throw new Error("array item 0 must be a number");
      }
      if (value2 instanceof Variable) {
        terms.setDefault(value2, factory).second += value;
      } else if (value2 instanceof Expression) {
        constant2 += value2.constant() * value;
        let terms2 = value2.terms();
        for (let j = 0, k = terms2.size();j < k; j++) {
          let termPair = terms2.itemAt(j);
          terms.setDefault(termPair.first, factory).second += termPair.second * value;
        }
      } else {
        throw new Error("array item 1 must be a variable or expression");
      }
    } else {
      throw new Error("invalid Expression argument: " + item);
    }
  }
  return { terms, constant: constant2 };
}

// node_modules/@lume/kiwi/dist/strength.js
class Strength {
  static create(a, b, c, w = 1) {
    let result = 0;
    result += Math.max(0, Math.min(1000, a * w)) * 1e6;
    result += Math.max(0, Math.min(1000, b * w)) * 1000;
    result += Math.max(0, Math.min(1000, c * w));
    return result;
  }
  static required = Strength.create(1000, 1000, 1000);
  static strong = Strength.create(1, 0, 0);
  static medium = Strength.create(0, 1, 0);
  static weak = Strength.create(0, 0, 1);
  static clip(value) {
    return Math.max(0, Math.min(Strength.required, value));
  }
}

// node_modules/@lume/kiwi/dist/constraint.js
var Operator;
(function(Operator2) {
  Operator2[Operator2["Le"] = 0] = "Le";
  Operator2[Operator2["Ge"] = 1] = "Ge";
  Operator2[Operator2["Eq"] = 2] = "Eq";
})(Operator || (Operator = {}));

class Constraint {
  constructor(expression, operator, rhs, strength = Strength.required) {
    this._operator = operator;
    this._strength = Strength.clip(strength);
    if (rhs === undefined && expression instanceof Expression) {
      this._expression = expression;
    } else {
      this._expression = expression.minus(rhs);
    }
  }
  id() {
    return this._id;
  }
  expression() {
    return this._expression;
  }
  op() {
    return this._operator;
  }
  strength() {
    return this._strength;
  }
  toString() {
    return this._expression.toString() + " " + ["<=", ">=", "="][this._operator] + " 0 (" + this._strength.toString() + ")";
  }
  _expression;
  _operator;
  _strength;
  _id = CnId++;
}
var CnId = 0;
// node_modules/@lume/kiwi/dist/solver.js
class Solver {
  maxIterations = 1000;
  constructor() {}
  createConstraint(lhs, operator, rhs, strength = Strength.required) {
    let cn = new Constraint(lhs, operator, rhs, strength);
    this.addConstraint(cn);
    return cn;
  }
  addConstraint(constraint) {
    let cnPair = this._cnMap.find(constraint);
    if (cnPair !== undefined) {
      throw new Error("duplicate constraint");
    }
    let data = this._createRow(constraint);
    let row = data.row;
    let tag = data.tag;
    let subject = this._chooseSubject(row, tag);
    if (subject.type() === SymbolType.Invalid && row.allDummies()) {
      if (!nearZero(row.constant())) {
        throw new Error("unsatisfiable constraint");
      } else {
        subject = tag.marker;
      }
    }
    if (subject.type() === SymbolType.Invalid) {
      if (!this._addWithArtificialVariable(row)) {
        throw new Error("unsatisfiable constraint");
      }
    } else {
      row.solveFor(subject);
      this._substitute(subject, row);
      this._rowMap.insert(subject, row);
    }
    this._cnMap.insert(constraint, tag);
    this._optimize(this._objective);
  }
  removeConstraint(constraint) {
    let cnPair = this._cnMap.erase(constraint);
    if (cnPair === undefined) {
      throw new Error("unknown constraint");
    }
    this._removeConstraintEffects(constraint, cnPair.second);
    let marker = cnPair.second.marker;
    let rowPair = this._rowMap.erase(marker);
    if (rowPair === undefined) {
      let leaving = this._getMarkerLeavingSymbol(marker);
      if (leaving.type() === SymbolType.Invalid) {
        throw new Error("failed to find leaving row");
      }
      rowPair = this._rowMap.erase(leaving);
      rowPair.second.solveForEx(leaving, marker);
      this._substitute(marker, rowPair.second);
    }
    this._optimize(this._objective);
  }
  hasConstraint(constraint) {
    return this._cnMap.contains(constraint);
  }
  getConstraints() {
    return this._cnMap.array.map(({ first }) => first);
  }
  addEditVariable(variable, strength) {
    let editPair = this._editMap.find(variable);
    if (editPair !== undefined) {
      throw new Error("duplicate edit variable");
    }
    strength = Strength.clip(strength);
    if (strength === Strength.required) {
      throw new Error("bad required strength");
    }
    let expr = new Expression(variable);
    let cn = new Constraint(expr, Operator.Eq, undefined, strength);
    this.addConstraint(cn);
    let tag = this._cnMap.find(cn).second;
    let info = { tag, constraint: cn, constant: 0 };
    this._editMap.insert(variable, info);
  }
  removeEditVariable(variable) {
    let editPair = this._editMap.erase(variable);
    if (editPair === undefined) {
      throw new Error("unknown edit variable");
    }
    this.removeConstraint(editPair.second.constraint);
  }
  hasEditVariable(variable) {
    return this._editMap.contains(variable);
  }
  suggestValue(variable, value) {
    let editPair = this._editMap.find(variable);
    if (editPair === undefined) {
      throw new Error("unknown edit variable");
    }
    let rows = this._rowMap;
    let info = editPair.second;
    let delta = value - info.constant;
    info.constant = value;
    let marker = info.tag.marker;
    let rowPair = rows.find(marker);
    if (rowPair !== undefined) {
      if (rowPair.second.add(-delta) < 0) {
        this._infeasibleRows.push(marker);
      }
      this._dualOptimize();
      return;
    }
    let other = info.tag.other;
    rowPair = rows.find(other);
    if (rowPair !== undefined) {
      if (rowPair.second.add(delta) < 0) {
        this._infeasibleRows.push(other);
      }
      this._dualOptimize();
      return;
    }
    for (let i = 0, n = rows.size();i < n; ++i) {
      let rowPair2 = rows.itemAt(i);
      let row = rowPair2.second;
      let coeff = row.coefficientFor(marker);
      if (coeff !== 0 && row.add(delta * coeff) < 0 && rowPair2.first.type() !== SymbolType.External) {
        this._infeasibleRows.push(rowPair2.first);
      }
    }
    this._dualOptimize();
  }
  updateVariables() {
    let vars = this._varMap;
    let rows = this._rowMap;
    for (let i = 0, n = vars.size();i < n; ++i) {
      let pair = vars.itemAt(i);
      let rowPair = rows.find(pair.second);
      if (rowPair !== undefined) {
        pair.first.setValue(rowPair.second.constant());
      } else {
        pair.first.setValue(0);
      }
    }
  }
  _getVarSymbol(variable) {
    let factory = () => this._makeSymbol(SymbolType.External);
    return this._varMap.setDefault(variable, factory).second;
  }
  _createRow(constraint) {
    let expr = constraint.expression();
    let row = new Row3(expr.constant());
    let terms = expr.terms();
    for (let i = 0, n = terms.size();i < n; ++i) {
      let termPair = terms.itemAt(i);
      if (!nearZero(termPair.second)) {
        let symbol2 = this._getVarSymbol(termPair.first);
        let basicPair = this._rowMap.find(symbol2);
        if (basicPair !== undefined) {
          row.insertRow(basicPair.second, termPair.second);
        } else {
          row.insertSymbol(symbol2, termPair.second);
        }
      }
    }
    let objective = this._objective;
    let strength = constraint.strength();
    let tag = { marker: INVALID_SYMBOL, other: INVALID_SYMBOL };
    switch (constraint.op()) {
      case Operator.Le:
      case Operator.Ge: {
        let coeff = constraint.op() === Operator.Le ? 1 : -1;
        let slack = this._makeSymbol(SymbolType.Slack);
        tag.marker = slack;
        row.insertSymbol(slack, coeff);
        if (strength < Strength.required) {
          let error = this._makeSymbol(SymbolType.Error);
          tag.other = error;
          row.insertSymbol(error, -coeff);
          objective.insertSymbol(error, strength);
        }
        break;
      }
      case Operator.Eq: {
        if (strength < Strength.required) {
          let errplus = this._makeSymbol(SymbolType.Error);
          let errminus = this._makeSymbol(SymbolType.Error);
          tag.marker = errplus;
          tag.other = errminus;
          row.insertSymbol(errplus, -1);
          row.insertSymbol(errminus, 1);
          objective.insertSymbol(errplus, strength);
          objective.insertSymbol(errminus, strength);
        } else {
          let dummy = this._makeSymbol(SymbolType.Dummy);
          tag.marker = dummy;
          row.insertSymbol(dummy);
        }
        break;
      }
    }
    if (row.constant() < 0) {
      row.reverseSign();
    }
    return { row, tag };
  }
  _chooseSubject(row, tag) {
    let cells = row.cells();
    for (let i = 0, n = cells.size();i < n; ++i) {
      let pair = cells.itemAt(i);
      if (pair.first.type() === SymbolType.External) {
        return pair.first;
      }
    }
    let type = tag.marker.type();
    if (type === SymbolType.Slack || type === SymbolType.Error) {
      if (row.coefficientFor(tag.marker) < 0) {
        return tag.marker;
      }
    }
    type = tag.other.type();
    if (type === SymbolType.Slack || type === SymbolType.Error) {
      if (row.coefficientFor(tag.other) < 0) {
        return tag.other;
      }
    }
    return INVALID_SYMBOL;
  }
  _addWithArtificialVariable(row) {
    let art = this._makeSymbol(SymbolType.Slack);
    this._rowMap.insert(art, row.copy());
    this._artificial = row.copy();
    this._optimize(this._artificial);
    let success = nearZero(this._artificial.constant());
    this._artificial = null;
    let pair = this._rowMap.erase(art);
    if (pair !== undefined) {
      let basicRow = pair.second;
      if (basicRow.isConstant()) {
        return success;
      }
      let entering = this._anyPivotableSymbol(basicRow);
      if (entering.type() === SymbolType.Invalid) {
        return false;
      }
      basicRow.solveForEx(art, entering);
      this._substitute(entering, basicRow);
      this._rowMap.insert(entering, basicRow);
    }
    let rows = this._rowMap;
    for (let i = 0, n = rows.size();i < n; ++i) {
      rows.itemAt(i).second.removeSymbol(art);
    }
    this._objective.removeSymbol(art);
    return success;
  }
  _substitute(symbol2, row) {
    let rows = this._rowMap;
    for (let i = 0, n = rows.size();i < n; ++i) {
      let pair = rows.itemAt(i);
      pair.second.substitute(symbol2, row);
      if (pair.second.constant() < 0 && pair.first.type() !== SymbolType.External) {
        this._infeasibleRows.push(pair.first);
      }
    }
    this._objective.substitute(symbol2, row);
    if (this._artificial) {
      this._artificial.substitute(symbol2, row);
    }
  }
  _optimize(objective) {
    let iterations = 0;
    while (iterations < this.maxIterations) {
      let entering = this._getEnteringSymbol(objective);
      if (entering.type() === SymbolType.Invalid) {
        return;
      }
      let leaving = this._getLeavingSymbol(entering);
      if (leaving.type() === SymbolType.Invalid) {
        throw new Error("the objective is unbounded");
      }
      let row = this._rowMap.erase(leaving).second;
      row.solveForEx(leaving, entering);
      this._substitute(entering, row);
      this._rowMap.insert(entering, row);
      iterations++;
    }
    throw new Error("solver iterations exceeded");
  }
  _dualOptimize() {
    let rows = this._rowMap;
    let infeasible = this._infeasibleRows;
    while (infeasible.length !== 0) {
      let leaving = infeasible.pop();
      let pair = rows.find(leaving);
      if (pair !== undefined && pair.second.constant() < 0) {
        let entering = this._getDualEnteringSymbol(pair.second);
        if (entering.type() === SymbolType.Invalid) {
          throw new Error("dual optimize failed");
        }
        let row = pair.second;
        rows.erase(leaving);
        row.solveForEx(leaving, entering);
        this._substitute(entering, row);
        rows.insert(entering, row);
      }
    }
  }
  _getEnteringSymbol(objective) {
    let cells = objective.cells();
    for (let i = 0, n = cells.size();i < n; ++i) {
      let pair = cells.itemAt(i);
      let symbol2 = pair.first;
      if (pair.second < 0 && symbol2.type() !== SymbolType.Dummy) {
        return symbol2;
      }
    }
    return INVALID_SYMBOL;
  }
  _getDualEnteringSymbol(row) {
    let ratio = Number.MAX_VALUE;
    let entering = INVALID_SYMBOL;
    let cells = row.cells();
    for (let i = 0, n = cells.size();i < n; ++i) {
      let pair = cells.itemAt(i);
      let symbol2 = pair.first;
      let c = pair.second;
      if (c > 0 && symbol2.type() !== SymbolType.Dummy) {
        let coeff = this._objective.coefficientFor(symbol2);
        let r = coeff / c;
        if (r < ratio) {
          ratio = r;
          entering = symbol2;
        }
      }
    }
    return entering;
  }
  _getLeavingSymbol(entering) {
    let ratio = Number.MAX_VALUE;
    let found = INVALID_SYMBOL;
    let rows = this._rowMap;
    for (let i = 0, n = rows.size();i < n; ++i) {
      let pair = rows.itemAt(i);
      let symbol2 = pair.first;
      if (symbol2.type() !== SymbolType.External) {
        let row = pair.second;
        let temp = row.coefficientFor(entering);
        if (temp < 0) {
          let temp_ratio = -row.constant() / temp;
          if (temp_ratio < ratio) {
            ratio = temp_ratio;
            found = symbol2;
          }
        }
      }
    }
    return found;
  }
  _getMarkerLeavingSymbol(marker) {
    let dmax = Number.MAX_VALUE;
    let r1 = dmax;
    let r2 = dmax;
    let invalid = INVALID_SYMBOL;
    let first = invalid;
    let second = invalid;
    let third = invalid;
    let rows = this._rowMap;
    for (let i = 0, n = rows.size();i < n; ++i) {
      let pair = rows.itemAt(i);
      let row = pair.second;
      let c = row.coefficientFor(marker);
      if (c === 0) {
        continue;
      }
      let symbol2 = pair.first;
      if (symbol2.type() === SymbolType.External) {
        third = symbol2;
      } else if (c < 0) {
        let r = -row.constant() / c;
        if (r < r1) {
          r1 = r;
          first = symbol2;
        }
      } else {
        let r = row.constant() / c;
        if (r < r2) {
          r2 = r;
          second = symbol2;
        }
      }
    }
    if (first !== invalid) {
      return first;
    }
    if (second !== invalid) {
      return second;
    }
    return third;
  }
  _removeConstraintEffects(cn, tag) {
    if (tag.marker.type() === SymbolType.Error) {
      this._removeMarkerEffects(tag.marker, cn.strength());
    }
    if (tag.other.type() === SymbolType.Error) {
      this._removeMarkerEffects(tag.other, cn.strength());
    }
  }
  _removeMarkerEffects(marker, strength) {
    let pair = this._rowMap.find(marker);
    if (pair !== undefined) {
      this._objective.insertRow(pair.second, -strength);
    } else {
      this._objective.insertSymbol(marker, -strength);
    }
  }
  _anyPivotableSymbol(row) {
    let cells = row.cells();
    for (let i = 0, n = cells.size();i < n; ++i) {
      let pair = cells.itemAt(i);
      let type = pair.first.type();
      if (type === SymbolType.Slack || type === SymbolType.Error) {
        return pair.first;
      }
    }
    return INVALID_SYMBOL;
  }
  _makeSymbol(type) {
    return new Symbol2(type, this._idTick++);
  }
  _cnMap = createCnMap();
  _rowMap = createRowMap();
  _varMap = createVarMap();
  _editMap = createEditMap();
  _infeasibleRows = [];
  _objective = new Row3;
  _artificial = null;
  _idTick = 0;
}
function nearZero(value) {
  let eps = 0.00000001;
  return value < 0 ? -value < eps : value < eps;
}
function createCnMap() {
  return createMap();
}
function createRowMap() {
  return createMap();
}
function createVarMap() {
  return createMap();
}
function createEditMap() {
  return createMap();
}
var SymbolType;
(function(SymbolType2) {
  SymbolType2[SymbolType2["Invalid"] = 0] = "Invalid";
  SymbolType2[SymbolType2["External"] = 1] = "External";
  SymbolType2[SymbolType2["Slack"] = 2] = "Slack";
  SymbolType2[SymbolType2["Error"] = 3] = "Error";
  SymbolType2[SymbolType2["Dummy"] = 4] = "Dummy";
})(SymbolType || (SymbolType = {}));

class Symbol2 {
  constructor(type, id2) {
    this._id = id2;
    this._type = type;
  }
  id() {
    return this._id;
  }
  type() {
    return this._type;
  }
  _id;
  _type;
}
var INVALID_SYMBOL = new Symbol2(SymbolType.Invalid, -1);

class Row3 {
  constructor(constant2 = 0) {
    this._constant = constant2;
  }
  cells() {
    return this._cellMap;
  }
  constant() {
    return this._constant;
  }
  isConstant() {
    return this._cellMap.empty();
  }
  allDummies() {
    let cells = this._cellMap;
    for (let i = 0, n = cells.size();i < n; ++i) {
      let pair = cells.itemAt(i);
      if (pair.first.type() !== SymbolType.Dummy) {
        return false;
      }
    }
    return true;
  }
  copy() {
    let theCopy = new Row3(this._constant);
    theCopy._cellMap = this._cellMap.copy();
    return theCopy;
  }
  add(value) {
    return this._constant += value;
  }
  insertSymbol(symbol2, coefficient = 1) {
    let pair = this._cellMap.setDefault(symbol2, () => 0);
    if (nearZero(pair.second += coefficient)) {
      this._cellMap.erase(symbol2);
    }
  }
  insertRow(other, coefficient = 1) {
    this._constant += other._constant * coefficient;
    let cells = other._cellMap;
    for (let i = 0, n = cells.size();i < n; ++i) {
      let pair = cells.itemAt(i);
      this.insertSymbol(pair.first, pair.second * coefficient);
    }
  }
  removeSymbol(symbol2) {
    this._cellMap.erase(symbol2);
  }
  reverseSign() {
    this._constant = -this._constant;
    let cells = this._cellMap;
    for (let i = 0, n = cells.size();i < n; ++i) {
      let pair = cells.itemAt(i);
      pair.second = -pair.second;
    }
  }
  solveFor(symbol2) {
    let cells = this._cellMap;
    let pair = cells.erase(symbol2);
    let coeff = -1 / pair.second;
    this._constant *= coeff;
    for (let i = 0, n = cells.size();i < n; ++i) {
      cells.itemAt(i).second *= coeff;
    }
  }
  solveForEx(lhs, rhs) {
    this.insertSymbol(lhs, -1);
    this.solveFor(rhs);
  }
  coefficientFor(symbol2) {
    let pair = this._cellMap.find(symbol2);
    return pair !== undefined ? pair.second : 0;
  }
  substitute(symbol2, row) {
    let pair = this._cellMap.erase(symbol2);
    if (pair !== undefined) {
      this.insertRow(row, pair.second);
    }
  }
  _cellMap = createMap();
  _constant;
}
// node_modules/@oai/granola/dist/models/auto-layout/types.js
var AutoLayoutAlign;
(function(AutoLayoutAlign2) {
  AutoLayoutAlign2["center"] = "center";
  AutoLayoutAlign2["topLeft"] = "topLeft";
  AutoLayoutAlign2["topCenter"] = "topCenter";
  AutoLayoutAlign2["topRight"] = "topRight";
  AutoLayoutAlign2["left"] = "left";
  AutoLayoutAlign2["right"] = "right";
  AutoLayoutAlign2["bottomLeft"] = "bottomLeft";
  AutoLayoutAlign2["bottomCenter"] = "bottomCenter";
  AutoLayoutAlign2["bottomRight"] = "bottomRight";
})(AutoLayoutAlign || (AutoLayoutAlign = {}));
var AutoLayoutDirection;
(function(AutoLayoutDirection2) {
  AutoLayoutDirection2["horizontal"] = "horizontal";
  AutoLayoutDirection2["vertical"] = "vertical";
})(AutoLayoutDirection || (AutoLayoutDirection = {}));

// node_modules/@oai/granola/dist/models/auto-layout/auto-layout.js
class AutoLayout {
  static apply(slide, shapes, options = {}) {
    if (!shapes.length)
      return;
    const frame = resolveFrame(slide, options.frame);
    const direction = options.direction ?? inferDirection(shapes, options);
    const align = options.align ?? AutoLayoutAlign.center;
    const horizontalPadding = options.horizontalPadding ?? 0;
    const verticalPadding = options.verticalPadding ?? 0;
    const horizontalGapOption = options.horizontalGap ?? 0;
    const verticalGapOption = options.verticalGap ?? 0;
    const solver2 = new Solver;
    const shapeVars = shapes.map((shape, index) => createShapeVariables(solver2, shape, index));
    const horizontalGap = resolveGapOption({
      option: horizontalGapOption,
      axis: "horizontal",
      frame,
      padding: horizontalPadding,
      shapeVars
    });
    const verticalGap = resolveGapOption({
      option: verticalGapOption,
      axis: "vertical",
      frame,
      padding: verticalPadding,
      shapeVars
    });
    solver2.maxIterations = 20000;
    addAlignmentConstraints(solver2, shapeVars, frame, align, {
      horizontalPadding,
      verticalPadding
    }, direction);
    if (shapes.length > 1) {
      addStackingConstraints(solver2, shapeVars, frame, direction, horizontalGap, verticalGap, align, { horizontalPadding, verticalPadding });
    } else {
      addSingleShapeConstraints(solver2, shapeVars[0], frame, align, horizontalPadding, verticalPadding);
    }
    solver2.updateVariables();
    for (const { shape, left, top } of shapeVars) {
      const pos = shape.position ?? {};
      pos.left = left.value();
      pos.top = top.value();
      shape.position = pos;
    }
  }
}
function resolveFrame(slide, frame) {
  if (!frame || frame === "slide") {
    return {
      left: slide.frame.left,
      top: slide.frame.top,
      width: slide.frame.width,
      height: slide.frame.height
    };
  }
  if (isShape(frame)) {
    const pos = frame.position ?? {};
    if (pos.left == null || pos.top == null || pos.width == null || pos.height == null) {
      throw new Error("Container shape must have left/top/width/height.");
    }
    return {
      left: pos.left,
      top: pos.top,
      width: pos.width,
      height: pos.height
    };
  }
  return {
    left: frame.left,
    top: frame.top,
    width: frame.width,
    height: frame.height
  };
}
function isShape(value) {
  return typeof value === "object" && value !== null && "position" in value;
}
function inferDirection(_shapes, _options) {
  return AutoLayoutDirection.vertical;
}
function createShapeVariables(solver2, shape, index) {
  const pos = shape.position ?? {};
  if (pos.width == null || pos.height == null) {
    throw new Error("Auto-layout requires position.width and position.height.");
  }
  const left = new Variable(`shape_${index}_left`);
  const top = new Variable(`shape_${index}_top`);
  if (pos.left != null) {
    solver2.addEditVariable(left, Strength.weak);
    solver2.suggestValue(left, pos.left);
  }
  if (pos.top != null) {
    solver2.addEditVariable(top, Strength.weak);
    solver2.suggestValue(top, pos.top);
  }
  return {
    shape,
    index,
    left,
    top,
    width: pos.width,
    height: pos.height
  };
}
function addAlignmentConstraints(solver2, shapes, frame, align, padding, direction) {
  if (shapes.length <= 1) {
    return;
  }
  const { horizontalPadding, verticalPadding } = padding;
  const frameLeft = frame.left + horizontalPadding;
  const frameRight = frame.left + frame.width - horizontalPadding;
  const frameTop = frame.top + verticalPadding;
  const frameBottom = frame.top + frame.height - verticalPadding;
  const frameCenterX = frame.left + frame.width / 2;
  const frameCenterY = frame.top + frame.height / 2;
  const { horizontal, vertical } = parseAlignAnchors(align);
  if (direction === AutoLayoutDirection.vertical) {
    for (const shape of shapes) {
      const rightExpr = new Expression(shape.left).plus(shape.width);
      const centerXExpr = new Expression(shape.left).plus(shape.width / 2);
      switch (horizontal) {
        case "left":
          solver2.addConstraint(new Constraint(shape.left, Operator.Eq, frameLeft, Strength.strong));
          break;
        case "center":
          solver2.addConstraint(new Constraint(centerXExpr, Operator.Eq, frameCenterX, Strength.strong));
          break;
        case "right":
          solver2.addConstraint(new Constraint(rightExpr, Operator.Eq, frameRight, Strength.strong));
          break;
      }
    }
    if (vertical === "top") {
      const first = shapes[0];
      solver2.addConstraint(new Constraint(first.top, Operator.Eq, frameTop, Strength.strong));
    } else if (vertical === "bottom") {
      const last2 = shapes[shapes.length - 1];
      const lastBottomExpr = new Expression(last2.top).plus(last2.height);
      solver2.addConstraint(new Constraint(lastBottomExpr, Operator.Eq, frameBottom, Strength.strong));
    }
  } else {
    for (const shape of shapes) {
      const bottomExpr = new Expression(shape.top).plus(shape.height);
      const centerYExpr = new Expression(shape.top).plus(shape.height / 2);
      switch (vertical) {
        case "top":
          solver2.addConstraint(new Constraint(shape.top, Operator.Eq, frameTop, Strength.strong));
          break;
        case "center":
          solver2.addConstraint(new Constraint(centerYExpr, Operator.Eq, frameCenterY, Strength.strong));
          break;
        case "bottom":
          solver2.addConstraint(new Constraint(bottomExpr, Operator.Eq, frameBottom, Strength.strong));
          break;
      }
    }
    if (horizontal === "left") {
      const first = shapes[0];
      solver2.addConstraint(new Constraint(first.left, Operator.Eq, frameLeft, Strength.strong));
    } else if (horizontal === "right") {
      const last2 = shapes[shapes.length - 1];
      const lastRightExpr = new Expression(last2.left).plus(last2.width);
      solver2.addConstraint(new Constraint(lastRightExpr, Operator.Eq, frameRight, Strength.strong));
    }
  }
}
function parseAlignAnchors(align) {
  switch (align) {
    case AutoLayoutAlign.topLeft:
      return { vertical: "top", horizontal: "left" };
    case AutoLayoutAlign.topCenter:
      return { vertical: "top", horizontal: "center" };
    case AutoLayoutAlign.topRight:
      return { vertical: "top", horizontal: "right" };
    case AutoLayoutAlign.left:
      return { horizontal: "left" };
    case AutoLayoutAlign.center:
      return { vertical: "center", horizontal: "center" };
    case AutoLayoutAlign.right:
      return { horizontal: "right" };
    case AutoLayoutAlign.bottomLeft:
      return { vertical: "bottom", horizontal: "left" };
    case AutoLayoutAlign.bottomCenter:
      return { vertical: "bottom", horizontal: "center" };
    case AutoLayoutAlign.bottomRight:
      return { vertical: "bottom", horizontal: "right" };
    default:
      return {};
  }
}
function addStackingConstraints(solver2, shapes, frame, direction, horizontalGap, verticalGap, align, padding) {
  const { horizontalPadding, verticalPadding } = padding;
  const anchors = parseAlignAnchors(align);
  if (direction === AutoLayoutDirection.vertical) {
    const first = shapes[0];
    const frameTop = frame.top + verticalPadding;
    if (anchors.vertical !== "bottom") {
      solver2.addConstraint(new Constraint(first.top, Operator.Eq, frameTop, Strength.strong));
    }
    for (let i = 1;i < shapes.length; i++) {
      const prev = shapes[i - 1];
      const curr = shapes[i];
      const prevBottomExpr = new Expression(prev.top).plus(prev.height);
      const currTopExpr = new Expression(curr.top);
      solver2.addConstraint(new Constraint(currTopExpr, Operator.Eq, prevBottomExpr.plus(verticalGap), Strength.strong));
    }
  } else {
    const first = shapes[0];
    const frameLeft = frame.left + horizontalPadding;
    if (anchors.horizontal !== "right") {
      solver2.addConstraint(new Constraint(first.left, Operator.Eq, frameLeft, Strength.strong));
    }
    for (let i = 1;i < shapes.length; i++) {
      const prev = shapes[i - 1];
      const curr = shapes[i];
      const prevRightExpr = new Expression(prev.left).plus(prev.width);
      const currLeftExpr = new Expression(curr.left);
      solver2.addConstraint(new Constraint(currLeftExpr, Operator.Eq, prevRightExpr.plus(horizontalGap), Strength.strong));
    }
  }
}
function addSingleShapeConstraints(solver2, s, frame, align, horizontalPadding, verticalPadding) {
  const frameLeft = frame.left + horizontalPadding;
  const frameRight = frame.left + frame.width - horizontalPadding;
  const frameTop = frame.top + verticalPadding;
  const frameBottom = frame.top + frame.height - verticalPadding;
  const frameCenterX = frame.left + frame.width / 2;
  const frameCenterY = frame.top + frame.height / 2;
  const rightExpr = new Expression(s.left).plus(s.width);
  const bottomExpr = new Expression(s.top).plus(s.height);
  switch (align) {
    case AutoLayoutAlign.center: {
      const centerXExpr = new Expression(s.left).plus(s.width / 2);
      solver2.addConstraint(new Constraint(centerXExpr, Operator.Eq, frameCenterX, Strength.strong));
      const centerYExpr = new Expression(s.top).plus(s.height / 2);
      solver2.addConstraint(new Constraint(centerYExpr, Operator.Eq, frameCenterY, Strength.strong));
      break;
    }
    case AutoLayoutAlign.topLeft:
      solver2.addConstraint(new Constraint(s.left, Operator.Eq, frameLeft, Strength.strong));
      solver2.addConstraint(new Constraint(s.top, Operator.Eq, frameTop, Strength.strong));
      break;
    case AutoLayoutAlign.topCenter: {
      const cxExpr = new Expression(s.left).plus(s.width / 2);
      solver2.addConstraint(new Constraint(cxExpr, Operator.Eq, frameCenterX, Strength.strong));
      solver2.addConstraint(new Constraint(s.top, Operator.Eq, frameTop, Strength.strong));
      break;
    }
    case AutoLayoutAlign.topRight:
      solver2.addConstraint(new Constraint(rightExpr, Operator.Eq, frameRight, Strength.strong));
      solver2.addConstraint(new Constraint(s.top, Operator.Eq, frameTop, Strength.strong));
      break;
    case AutoLayoutAlign.left: {
      solver2.addConstraint(new Constraint(s.left, Operator.Eq, frameLeft, Strength.strong));
      const cy1 = new Expression(s.top).plus(s.height / 2);
      solver2.addConstraint(new Constraint(cy1, Operator.Eq, frameCenterY, Strength.strong));
      break;
    }
    case AutoLayoutAlign.right: {
      solver2.addConstraint(new Constraint(rightExpr, Operator.Eq, frameRight, Strength.strong));
      const cy2 = new Expression(s.top).plus(s.height / 2);
      solver2.addConstraint(new Constraint(cy2, Operator.Eq, frameCenterY, Strength.strong));
      break;
    }
    case AutoLayoutAlign.bottomLeft:
      solver2.addConstraint(new Constraint(s.left, Operator.Eq, frameLeft, Strength.strong));
      solver2.addConstraint(new Constraint(bottomExpr, Operator.Eq, frameBottom, Strength.strong));
      break;
    case AutoLayoutAlign.bottomCenter: {
      const cx3 = new Expression(s.left).plus(s.width / 2);
      solver2.addConstraint(new Constraint(cx3, Operator.Eq, frameCenterX, Strength.strong));
      solver2.addConstraint(new Constraint(bottomExpr, Operator.Eq, frameBottom, Strength.strong));
      break;
    }
    case AutoLayoutAlign.bottomRight:
      solver2.addConstraint(new Constraint(rightExpr, Operator.Eq, frameRight, Strength.strong));
      solver2.addConstraint(new Constraint(bottomExpr, Operator.Eq, frameBottom, Strength.strong));
      break;
  }
}
function resolveGapOption({ option, axis, frame, padding, shapeVars }) {
  if (option === "auto") {
    if (shapeVars.length <= 1) {
      return 0;
    }
    const totalSpan = shapeVars.reduce((sum2, shapeVar) => {
      return sum2 + (axis === "horizontal" ? shapeVar.width : shapeVar.height);
    }, 0);
    const frameSpan = axis === "horizontal" ? frame.width : frame.height;
    const innerSpan = frameSpan - padding * 2;
    return (innerSpan - totalSpan) / (shapeVars.length - 1);
  }
  if (typeof option === "number") {
    return option;
  }
  return 0;
}

// node_modules/@oai/granola/dist/models/presentation/grid-layout.js
var DEFAULT_COLUMNS = 12;
var DEFAULT_GUTTER_PX = 24;
var DEFAULT_MARGIN_X_PX = 80;
var DEFAULT_MARGIN_Y_PX = 64;
var DEFAULT_ROW_HEIGHT_PX2 = 72;
var DEFAULT_ROW_GAP_PX = 16;
var DEFAULT_BASE_UNIT_PX = 8;
function getSlideGridFrame(slideFrame, area, options = {}) {
  const columns = readPositiveInt(options.columns, DEFAULT_COLUMNS, "columns");
  const gutter = readNonNegative(options.gutter, DEFAULT_GUTTER_PX, "gutter");
  const marginX = readNonNegative(options.marginX, DEFAULT_MARGIN_X_PX, "marginX");
  const marginY = readNonNegative(options.marginY, DEFAULT_MARGIN_Y_PX, "marginY");
  const rowHeight = readPositive(options.rowHeight, DEFAULT_ROW_HEIGHT_PX2, "rowHeight");
  const rowGap = readNonNegative(options.rowGap, DEFAULT_ROW_GAP_PX, "rowGap");
  const baseUnit = readPositive(options.baseUnit, DEFAULT_BASE_UNIT_PX, "baseUnit");
  const colStart = readPositiveInt(area.colStart, 1, "colStart");
  const colSpan = readPositiveInt(area.colSpan, 1, "colSpan");
  if (colStart + colSpan - 1 > columns) {
    throw new Error(`Grid area exceeds column count: colStart=${colStart}, colSpan=${colSpan}, columns=${columns}.`);
  }
  const usableWidth = slideFrame.width - marginX * 2 - gutter * Math.max(0, columns - 1);
  if (usableWidth <= 0) {
    throw new Error(`Grid width is not positive. Check marginX/gutter/columns for frame width ${slideFrame.width}.`);
  }
  const colWidth = usableWidth / columns;
  const leftRaw = slideFrame.left + marginX + (colStart - 1) * (colWidth + gutter);
  const widthRaw = colSpan * colWidth + Math.max(0, colSpan - 1) * gutter;
  const rowStart = area.rowStart === undefined ? 1 : readPositiveInt(area.rowStart, 1, "rowStart");
  const rowSpan = area.rowSpan === undefined ? 1 : readPositiveInt(area.rowSpan, 1, "rowSpan");
  const topRaw = area.top ?? slideFrame.top + marginY + (rowStart - 1) * (rowHeight + rowGap);
  const heightRaw = area.height ?? rowSpan * rowHeight + Math.max(0, rowSpan - 1) * rowGap;
  return {
    left: snapToBaseUnit(leftRaw, baseUnit),
    top: snapToBaseUnit(topRaw, baseUnit),
    width: Math.max(1, snapToBaseUnit(widthRaw, baseUnit)),
    height: Math.max(1, snapToBaseUnit(heightRaw, baseUnit))
  };
}
function computeSlideGridLayoutPlacements(slideFrame, items, options = {}) {
  if (items.length === 0) {
    return [];
  }
  const baseUnit = readPositive(options.baseUnit, DEFAULT_BASE_UNIT_PX, "baseUnit");
  const defaultAlignX = options.defaultAlignX ?? "stretch";
  const defaultAlignY = options.defaultAlignY ?? "stretch";
  return items.map((item) => {
    const area = resolveGridArea(item.area, options.areas);
    const areaFrame = getSlideGridFrame(slideFrame, area, options);
    const insets = resolveInsets(item);
    const insetFrame = insetGridFrame(areaFrame, insets);
    const alignX = item.alignX ?? defaultAlignX;
    const alignY = item.alignY ?? defaultAlignY;
    const shapeWidth = alignX === "stretch" ? insetFrame.width : readShapeDimension(item.shape.position.width, "shape.position.width", "alignX");
    const shapeHeight = alignY === "stretch" ? insetFrame.height : readShapeDimension(item.shape.position.height, "shape.position.height", "alignY");
    const left = alignStart(insetFrame.left, insetFrame.width, shapeWidth, alignX);
    const top = alignStart(insetFrame.top, insetFrame.height, shapeHeight, alignY);
    return {
      shape: item.shape,
      frame: {
        left: snapToBaseUnit(left, baseUnit),
        top: snapToBaseUnit(top, baseUnit),
        width: Math.max(1, snapToBaseUnit(shapeWidth, baseUnit)),
        height: Math.max(1, snapToBaseUnit(shapeHeight, baseUnit))
      }
    };
  });
}
var readPositiveInt = (value, fallback, name) => {
  if (value === undefined) {
    return fallback;
  }
  if (!Number.isFinite(value) || value <= 0 || !Number.isInteger(value)) {
    throw new Error(`${name} must be a positive integer.`);
  }
  return value;
};
var readPositive = (value, fallback, name) => {
  if (value === undefined) {
    return fallback;
  }
  if (!Number.isFinite(value) || value <= 0) {
    throw new Error(`${name} must be a positive number.`);
  }
  return value;
};
var readNonNegative = (value, fallback, name) => {
  if (value === undefined) {
    return fallback;
  }
  if (!Number.isFinite(value) || value < 0) {
    throw new Error(`${name} must be a non-negative number.`);
  }
  return value;
};
var snapToBaseUnit = (value, baseUnit) => Math.round(value / baseUnit) * baseUnit;
var resolveGridArea = (areaRef, areas) => {
  if (typeof areaRef !== "string") {
    return areaRef;
  }
  if (!areas) {
    throw new Error(`Named grid area "${areaRef}" was provided, but options.areas is empty.`);
  }
  const area = areas[areaRef];
  if (!area) {
    throw new Error(`Named grid area "${areaRef}" was not found in options.areas.`);
  }
  return area;
};
var readShapeDimension = (value, fieldName, alignField) => {
  if (!Number.isFinite(value) || value === undefined || value <= 0) {
    throw new Error(`${fieldName} must be a positive number when ${alignField} is not "stretch".`);
  }
  return value;
};
var alignStart = (start, available, size2, align) => {
  if (align === "start" || align === "stretch") {
    return start;
  }
  if (align === "center") {
    return start + (available - size2) / 2;
  }
  return start + (available - size2);
};
var resolveInsets = (item) => {
  const inset = readNonNegative(item.inset, 0, "inset");
  const insetX = readNonNegative(item.insetX, inset, "insetX");
  const insetY = readNonNegative(item.insetY, inset, "insetY");
  return {
    left: readNonNegative(item.insetLeft, insetX, "insetLeft"),
    right: readNonNegative(item.insetRight, insetX, "insetRight"),
    top: readNonNegative(item.insetTop, insetY, "insetTop"),
    bottom: readNonNegative(item.insetBottom, insetY, "insetBottom")
  };
};
var insetGridFrame = (frame, insets) => {
  const width = frame.width - insets.left - insets.right;
  const height = frame.height - insets.top - insets.bottom;
  if (width <= 0 || height <= 0) {
    throw new Error("Grid item insets collapse the area below zero width/height.");
  }
  return {
    left: frame.left + insets.left,
    top: frame.top + insets.top,
    width,
    height
  };
};

// node_modules/@oai/granola/dist/models/presentation/speaker-notes.js
class SpeakerNotesTextFrame {
  #paragraphs;
  #text;
  constructor(paragraphs, text) {
    this.#paragraphs = paragraphs;
    this.#text = text;
  }
  get paragraphs() {
    return this.#paragraphs;
  }
  setText(value) {
    this.#text.set(value);
  }
  append(value) {
    this.#text.add(value);
  }
  clear() {
    this.#text.set("");
  }
}

class SpeakerNotes {
  #context;
  #paragraphs;
  #visible;
  #textFrame;
  #text;
  #slideId;
  constructor(context, proto) {
    this.#context = context;
    this.#context;
    this.#slideId = context.getSlideId?.();
    const element = proto?.elements?.find((candidate) => candidate?.placeholderType === "body" || candidate?.placeholderType === "notes");
    const paragraphs = element?.paragraphs ?? [];
    this.#paragraphs = new ParagraphCollection(this.#paragraphContext(), paragraphs);
    this.#text = new Text(this.#paragraphs);
    this.#textFrame = new SpeakerNotesTextFrame(this.#paragraphs, this.#text);
    this.#visible = true;
  }
  get paragraphs() {
    return this.#paragraphs;
  }
  get textFrame() {
    return this.#textFrame;
  }
  get text() {
    return this.#text.toString();
  }
  set text(value) {
    this.#text.set(value);
    this.#recordNotesSet(value);
  }
  get slideId() {
    return this.#slideId;
  }
  toSnapshot(slideId) {
    return {
      aid: `nt/${slideId}`,
      kind: "notes",
      slideId,
      text: this.text
    };
  }
  setText(value) {
    this.#textFrame.setText(value);
    this.#recordNotesSet(value);
  }
  append(value) {
    this.#textFrame.append(value);
  }
  setVisible(value) {
    this.#visible = value;
  }
  isVisible() {
    return this.#visible;
  }
  clear() {
    this.#textFrame.clear();
    this.#recordNotesSet("");
  }
  toProto() {
    const text = this.text;
    if (!this.#visible && text.length === 0) {
      return;
    }
    return {
      id: "",
      elements: [
        this.#createSlideImagePlaceholder(),
        this.#createNotesPlaceholder(),
        this.#createSlideNumberPlaceholder()
      ],
      index: 0,
      useLayoutId: "",
      widthEmu: 0,
      heightEmu: 0
    };
  }
  #createSlideImagePlaceholder() {
    return {
      id: "",
      name: "Slide Image Placeholder 1",
      type: 0 /* ELEMENT_TYPE_UNSPECIFIED */,
      placeholderIndex: 0,
      placeholderType: "sldImg",
      zIndex: 0,
      paragraphs: [],
      effects: [],
      children: [],
      levelsStyles: [],
      citations: []
    };
  }
  #createNotesPlaceholder() {
    const paragraphs = this.#paragraphs.toProto();
    return {
      id: "",
      name: "Notes Placeholder 2",
      type: 1 /* ELEMENT_TYPE_TEXT */,
      placeholderIndex: 1,
      placeholderType: "body",
      zIndex: 0,
      textStyle: {},
      paragraphs: paragraphs.length > 0 ? paragraphs : [{ id: "", runs: [], textStyle: {} }],
      effects: [],
      children: [],
      levelsStyles: [],
      citations: []
    };
  }
  #createSlideNumberPlaceholder() {
    return {
      id: "",
      name: "Slide Number Placeholder 3",
      type: 1 /* ELEMENT_TYPE_TEXT */,
      placeholderIndex: 5,
      placeholderType: "sldNum",
      zIndex: 0,
      textStyle: {},
      paragraphs: [{ id: "", runs: [], textStyle: {} }],
      effects: [],
      children: [],
      levelsStyles: [],
      citations: []
    };
  }
  #paragraphContext() {
    return {
      stub: () => {},
      attachChartAsset: (_chart) => {
        throw new Error("attachChartAsset is not available in speaker notes context.");
      },
      getImageById: () => {
        return;
      },
      createImageAsset: () => {
        throw new Error("createImageAsset is not available in speaker notes context.");
      },
      getChartById: () => {
        return;
      },
      createChartAsset: () => {
        throw new Error("createChartAsset is not available in speaker notes context.");
      },
      getTextStyleByName: () => {
        return;
      }
    };
  }
  #recordNotesSet(value) {
    const recordOp = this.#context.recordOp;
    if (!recordOp) {
      return;
    }
    const slideId = this.#slideId;
    if (!slideId) {
      return;
    }
    const normalized = value instanceof Text ? value.toString() : value;
    recordOp({
      op: "notes.set",
      target: `nt/${slideId}`,
      value: normalized
    });
  }
}

// node_modules/@oai/granola/dist/models/presentation/compose/text-content.js
var transformComposeTextValue = (value, transform) => {
  if (transform === "none") {
    return value;
  }
  if (typeof value === "string") {
    return transformText(value, transform);
  }
  if (Array.isArray(value)) {
    if (value.length === 0) {
      return [];
    }
    if (isParagraphRunsInput(value)) {
      return transformParagraphRuns(value, transform);
    }
    if (isParagraphValueList(value)) {
      return value.map((entry) => transformParagraphValue(entry, transform));
    }
  }
  return transformParagraphInput(value, transform);
};
var composeTextParagraphProtos = (value, transform) => {
  const transformed = transformComposeTextValue(value, transform);
  if (typeof transformed === "string") {
    const lines = transformed.length > 0 ? transformed.split(/\r?\n/) : [""];
    return lines.map((line) => ({
      id: "",
      runs: [
        {
          id: "",
          text: line,
          citations: [],
          reviewMarkIds: []
        }
      ]
    }));
  }
  return buildParagraphProtosFromInput(transformed);
};
var composeTextPreview = (value, transform) => {
  const paragraphs = composeTextParagraphProtos(value, transform);
  return paragraphs.map((paragraph) => (paragraph.runs ?? []).map((run) => run.text ?? "").join("")).join(`
`);
};
function transformParagraphValue(value, transform) {
  if (Array.isArray(value)) {
    return transformParagraphRuns(value, transform);
  }
  return transformParagraphInput(value, transform);
}
function transformParagraphRuns(runs, transform) {
  return (runs ?? []).map((entry) => {
    if (typeof entry === "string" || typeof entry === "number") {
      return transformText(String(entry), transform);
    }
    return {
      ...entry,
      run: transformText(entry.run, transform)
    };
  });
}
function transformParagraphInput(input, transform) {
  return {
    ...input,
    runs: transformParagraphRuns(input.runs, transform),
    paragraphStyle: input.paragraphStyle ? { ...input.paragraphStyle } : undefined
  };
}
function transformText(value, transform) {
  if (transform === "uppercase") {
    return value.toUpperCase();
  }
  if (transform === "lowercase") {
    return value.toLowerCase();
  }
  return value;
}
function isParagraphValueList(value) {
  return value.every((entry) => isParagraphRunsInput(entry) || isStructuredTextParagraphInput(entry));
}

// node_modules/@oai/granola/dist/models/presentation/compose/engine.js
var HUGE_MEASURE = 1e5;
var layoutComposeTreeDetailed = (slide, root, options = {}) => {
  const frame = readFrame(options.frame ?? slide.frame, "slide.compose frame");
  const baseUnit = readOptionalBaseUnit(options.baseUnit);
  const presentation = getSlidePresentation(slide);
  const context = {
    slide,
    presentation
  };
  const measured = measureNode(context, root);
  const rootWidth = resolveRootAxisSize(root.width, measured.intrinsicWidth, frame.width);
  const rootFrame = {
    left: frame.left,
    top: frame.top,
    width: rootWidth,
    height: resolveRootHeight(context, measured, rootWidth, frame.height)
  };
  const placements = [];
  layoutNode(context, measured, rootFrame, placements, baseUnit);
  const materializedPaths = [];
  const rootSnapshot = buildLayoutSnapshot(context, measured, rootFrame, baseUnit, "0", materializedPaths);
  return {
    placements,
    materializedPaths,
    run: {
      frame: snapshotFrame(frame),
      baseUnit,
      root: rootSnapshot
    }
  };
};
var measureNode = (context, node) => {
  if (node.kind === "text") {
    const metrics = measureTextNode(context, node);
    return {
      node,
      intrinsicWidth: metrics.width,
      intrinsicHeight: metrics.height,
      children: []
    };
  }
  if (node.kind === "rule") {
    return {
      node,
      intrinsicWidth: intrinsicSizeForSpec(node.width, 0),
      intrinsicHeight: intrinsicSizeForSpec(node.height, node.weight),
      children: []
    };
  }
  if (node.kind === "shape") {
    return measureSimpleLeafNode(node, 24, 24);
  }
  if (node.kind === "image") {
    return measureSimpleLeafNode(node, 320, 180);
  }
  if (node.kind === "table") {
    return measureSimpleLeafNode(node, 360, 200);
  }
  if (node.kind === "chart") {
    return measureSimpleLeafNode(node, 640, 360);
  }
  if (node.kind === "panel") {
    return measurePanelNode(context, node);
  }
  if (node.kind === "layers") {
    return measureLayersNode(context, node);
  }
  if (node.kind === "row") {
    return measureRowNode(context, node);
  }
  if (node.kind === "column") {
    return measureColumnNode(context, node);
  }
  return measureGridNode(context, node);
};
var measureSimpleLeafNode = (node, fallbackWidth, fallbackHeight) => ({
  node,
  intrinsicWidth: intrinsicSizeForSpec(node.width, fallbackWidth),
  intrinsicHeight: intrinsicSizeForSpec(node.height, fallbackHeight),
  children: []
});
var measurePanelNode = (context, node) => {
  const child = node.child ? measureNode(context, node.child) : undefined;
  if (node.width.mode === "hug" && child && child.node.width.mode === "fill") {
    throw new Error(`Panel "${node.name ?? "(unnamed)"}" cannot use width: "hug" when its child uses width: "fill".`);
  }
  return {
    node,
    intrinsicWidth: (child ? intrinsicNodeAxisSize(child, "x") : 0) + node.padding.left + node.padding.right,
    intrinsicHeight: (child ? intrinsicNodeAxisSize(child, "y") : 0) + node.padding.top + node.padding.bottom,
    children: child ? [child] : []
  };
};
var measureLayersNode = (context, node) => {
  const children = node.children.map((child) => measureNode(context, child));
  if (node.width.mode === "hug" && hasFillChild(children, "x")) {
    throw new Error(`Layers "${node.name ?? "(unnamed)"}" cannot use width: "hug" when a child uses width: "fill".`);
  }
  if (node.height.mode === "hug" && hasFillChild(children, "y")) {
    throw new Error(`Layers "${node.name ?? "(unnamed)"}" cannot use height: "hug" when a child uses height: "fill".`);
  }
  const intrinsicWidth = Math.max(0, ...children.map((child) => intrinsicNodeAxisSize(child, "x"))) + node.padding.left + node.padding.right;
  const intrinsicHeight = Math.max(0, ...children.map((child) => intrinsicNodeAxisSize(child, "y"))) + node.padding.top + node.padding.bottom;
  return {
    node,
    intrinsicWidth,
    intrinsicHeight,
    children
  };
};
var measureRowNode = (context, node) => {
  const children = node.children.map((child) => measureNode(context, child));
  if (node.width.mode === "hug" && hasFillChild(children, "x")) {
    throw new Error(`Row "${node.name ?? "(unnamed)"}" cannot use width: "hug" when a child uses width: "fill".`);
  }
  const main = sumValues(children.map((child) => intrinsicNodeAxisSize(child, "x")));
  const totalGap = Math.max(0, children.length - 1) * node.gap;
  const cross = Math.max(0, ...children.map((child) => intrinsicNodeAxisSize(child, "y")));
  return {
    node,
    intrinsicWidth: main + totalGap + node.padding.left + node.padding.right,
    intrinsicHeight: cross + node.padding.top + node.padding.bottom,
    children
  };
};
var measureColumnNode = (context, node) => {
  const children = node.children.map((child) => measureNode(context, child));
  if (node.height.mode === "hug" && hasFillChild(children, "y")) {
    throw new Error(`Column "${node.name ?? "(unnamed)"}" cannot use height: "hug" when a child uses height: "fill".`);
  }
  const main = sumValues(children.map((child) => intrinsicNodeAxisSize(child, "y")));
  const totalGap = Math.max(0, children.length - 1) * node.gap;
  const cross = Math.max(0, ...children.map((child) => intrinsicNodeAxisSize(child, "x")));
  return {
    node,
    intrinsicWidth: cross + node.padding.left + node.padding.right,
    intrinsicHeight: main + totalGap + node.padding.top + node.padding.bottom,
    children
  };
};
var measureGridNode = (context, node) => {
  const children = node.children.map((child) => measureNode(context, child));
  const items = placeGridChildren(node, children);
  const rows = resolveGridRows(node, resolveGridRowCount(node, items));
  if (node.width.mode === "hug" && node.columns.some((track) => isFrTrack(track))) {
    throw new Error(`Grid "${node.name ?? "(unnamed)"}" cannot use width: "hug" with fr columns.`);
  }
  if (node.height.mode === "hug" && rows.some((track) => isFrTrack(track))) {
    throw new Error(`Grid "${node.name ?? "(unnamed)"}" cannot use height: "hug" with fr rows.`);
  }
  const autoColumnSizes = resolveAutoTrackSizesForIntrinsicAxis(node.columns, node.columnGap, items, "x");
  const autoRowSizes = resolveAutoTrackSizesForIntrinsicAxis(rows, node.rowGap, items, "y");
  const intrinsicColumns = node.columns.map((track, index) => track === "auto" ? autoColumnSizes[index] ?? 0 : intrinsicTrackSize(track));
  const intrinsicRows = rows.map((track, index) => track === "auto" ? autoRowSizes[index] ?? 0 : intrinsicTrackSize(track));
  const intrinsicWidth = sumValues(intrinsicColumns) + Math.max(0, node.columns.length - 1) * node.columnGap + node.padding.left + node.padding.right;
  const intrinsicHeight = sumValues(intrinsicRows) + Math.max(0, rows.length - 1) * node.rowGap + node.padding.top + node.padding.bottom;
  return {
    node,
    intrinsicWidth,
    intrinsicHeight,
    children
  };
};
var layoutNode = (context, measured, frame, placements, baseUnit) => {
  if (frame.width <= 0 || frame.height <= 0) {
    return;
  }
  const placementBaseUnit = resolveNodeSnapUnit(measured, frame, baseUnit);
  if (measured.node.kind === "text") {
    placements.push({
      kind: "text",
      frame: snapMeasuredFrame(measured, frame, placementBaseUnit),
      name: measured.node.name,
      value: transformComposeTextValue(measured.node.value, measured.node.transform),
      style: measured.node.style
    });
    return;
  }
  if (measured.node.kind === "rule") {
    placements.push({
      kind: "rule",
      frame: snapMeasuredFrame(measured, frame, placementBaseUnit),
      name: measured.node.name,
      stroke: measured.node.stroke,
      opacity: measured.node.opacity,
      weight: measured.node.weight
    });
    return;
  }
  if (measured.node.kind === "shape") {
    placements.push({
      kind: "shape",
      frame: snapMeasuredFrame(measured, frame, placementBaseUnit),
      name: measured.node.name,
      geometry: measured.node.geometry,
      fill: measured.node.fill,
      line: measured.node.line,
      borderRadius: measured.node.borderRadius,
      shadow: measured.node.shadow
    });
    return;
  }
  if (measured.node.kind === "image") {
    placements.push({
      kind: "image",
      frame: snapMeasuredFrame(measured, frame, placementBaseUnit),
      name: measured.node.name,
      source: measured.node.source,
      contentType: measured.node.contentType,
      fit: measured.node.fit,
      alt: measured.node.alt,
      geometry: measured.node.geometry,
      borderRadius: measured.node.borderRadius,
      crop: measured.node.crop,
      rotation: measured.node.rotation,
      flipHorizontal: measured.node.flipHorizontal,
      flipVertical: measured.node.flipVertical,
      lockAspectRatio: measured.node.lockAspectRatio
    });
    return;
  }
  if (measured.node.kind === "table") {
    placements.push({
      kind: "table",
      frame: snapMeasuredFrame(measured, frame, placementBaseUnit),
      name: measured.node.name,
      rows: measured.node.rows,
      columns: measured.node.columns,
      values: measured.node.values,
      style: measured.node.style,
      styleOptions: measured.node.styleOptions
    });
    return;
  }
  if (measured.node.kind === "chart") {
    placements.push({
      kind: "chart",
      frame: snapMeasuredFrame(measured, frame, placementBaseUnit),
      name: measured.node.name,
      chartType: measured.node.chartType,
      config: measured.node.config
    });
    return;
  }
  if (measured.node.kind === "panel") {
    layoutPanel(context, measured, frame, placements, baseUnit);
    return;
  }
  if (measured.node.kind === "layers") {
    layoutLayers(context, measured, frame, placements, baseUnit);
    return;
  }
  if (measured.node.kind === "row") {
    layoutStackRow(context, measured, frame, placements, baseUnit);
    return;
  }
  if (measured.node.kind === "column") {
    layoutStackColumn(context, measured, frame, placements, baseUnit);
    return;
  }
  layoutGrid(context, measured, frame, placements, baseUnit);
};
var layoutPanel = (context, measured, frame, placements, baseUnit) => {
  const node = measured.node;
  const containerFrame = resolveContainerLayoutFrame(measured, frame, baseUnit);
  placements.push({
    kind: "shape",
    frame: containerFrame,
    name: node.name,
    geometry: "rect",
    fill: node.fill,
    line: node.line,
    borderRadius: node.borderRadius,
    shadow: node.shadow
  });
  const child = measured.children[0];
  if (!child) {
    return;
  }
  const content = insetFrame(containerFrame, node.padding);
  if (content.width <= 0 || content.height <= 0) {
    return;
  }
  const childWidth = resolveNodeWidthForAvailable(child, content.width, node.align === "stretch");
  const childHeight = resolveNodeHeightForFrame(context, child, childWidth, content.height, node.justify === "stretch");
  const alignedX = resolveAlignedAxisFrame(content.left, content.width, childWidth, node.align, baseUnit, preserveRequestedAxisSize(child, "x"));
  const alignedY = resolveAlignedAxisFrame(content.top, content.height, childHeight, node.justify, baseUnit, preserveRequestedAxisSize(child, "y"));
  layoutNode(context, child, {
    left: alignedX.start,
    top: alignedY.start,
    width: alignedX.size,
    height: alignedY.size
  }, placements, baseUnit);
};
var layoutStackRow = (context, measured, frame, placements, baseUnit) => {
  const node = measured.node;
  const containerFrame = resolveContainerLayoutFrame(measured, frame, baseUnit);
  const content = insetFrame(containerFrame, node.padding);
  if (content.width <= 0 || content.height <= 0 || measured.children.length === 0) {
    return;
  }
  const baseWidths = measured.children.map((child) => intrinsicNodeAxisSize(child, "x"));
  const fillWeights = measured.children.map((child) => child.node.width.mode === "fill" ? child.node.width.value : 0);
  const widths = resolveStackItemSizes({
    available: content.width,
    baseSizes: baseWidths,
    gap: node.gap,
    fillWeights,
    kind: node.kind,
    name: node.name,
    axis: "x",
    warnOverflow: true
  });
  const layout = resolveStackLayoutPositioning(content.width, widths, node.gap, node.justify);
  let cursor = content.left + layout.offset;
  measured.children.forEach((child, index) => {
    const width = widths[index] ?? 0;
    const height = resolveNodeHeightForFrame(context, child, width, content.height, node.align === "stretch");
    const alignedY = resolveAlignedAxisFrame(content.top, content.height, height, node.align, baseUnit, preserveRequestedAxisSize(child, "y"));
    layoutNode(context, child, {
      left: cursor,
      top: alignedY.start,
      width,
      height: alignedY.size
    }, placements, baseUnit);
    cursor += width + layout.gap;
  });
};
var layoutLayers = (context, measured, frame, placements, baseUnit) => {
  const node = measured.node;
  const containerFrame = resolveContainerLayoutFrame(measured, frame, baseUnit);
  const content = insetFrame(containerFrame, node.padding);
  if (content.width <= 0 || content.height <= 0 || measured.children.length === 0) {
    return;
  }
  measured.children.forEach((child) => {
    const width = resolveNodeWidthForAvailable(child, content.width, node.justifyItems === "stretch");
    const height = resolveNodeHeightForFrame(context, child, width, content.height, node.alignItems === "stretch");
    const alignedX = resolveAlignedAxisFrame(content.left, content.width, width, node.justifyItems, baseUnit, preserveRequestedAxisSize(child, "x"));
    const alignedY = resolveAlignedAxisFrame(content.top, content.height, height, node.alignItems, baseUnit, preserveRequestedAxisSize(child, "y"));
    layoutNode(context, child, {
      left: alignedX.start,
      top: alignedY.start,
      width: alignedX.size,
      height: alignedY.size
    }, placements, baseUnit);
  });
};
var layoutStackColumn = (context, measured, frame, placements, baseUnit) => {
  const node = measured.node;
  const containerFrame = resolveContainerLayoutFrame(measured, frame, baseUnit);
  const content = insetFrame(containerFrame, node.padding);
  if (content.width <= 0 || content.height <= 0 || measured.children.length === 0) {
    return;
  }
  const resolvedWidths = measured.children.map((child) => resolveNodeWidthForAvailable(child, content.width, node.align === "stretch"));
  const baseHeights = measured.children.map((child, index) => resolveNodeBaseHeightForAssignedWidth(context, child, resolvedWidths[index] ?? 0));
  const fillWeights = measured.children.map((child) => child.node.height.mode === "fill" ? child.node.height.value : 0);
  const heights = resolveStackItemSizes({
    available: content.height,
    baseSizes: baseHeights,
    gap: node.gap,
    fillWeights,
    kind: node.kind,
    name: node.name,
    axis: "y",
    warnOverflow: true
  });
  const layout = resolveStackLayoutPositioning(content.height, heights, node.gap, node.justify);
  let cursor = content.top + layout.offset;
  measured.children.forEach((child, index) => {
    const width = resolvedWidths[index] ?? 0;
    const height = heights[index] ?? 0;
    const alignedX = resolveAlignedAxisFrame(content.left, content.width, width, node.align, baseUnit, preserveRequestedAxisSize(child, "x"));
    layoutNode(context, child, {
      left: alignedX.start,
      top: cursor,
      width: alignedX.size,
      height
    }, placements, baseUnit);
    cursor += height + layout.gap;
  });
};
var layoutGrid = (context, measured, frame, placements, baseUnit) => {
  const node = measured.node;
  const containerFrame = resolveContainerLayoutFrame(measured, frame, baseUnit);
  const content = insetFrame(containerFrame, node.padding);
  if (content.width <= 0 || content.height <= 0 || measured.children.length === 0) {
    return;
  }
  const geometry = resolveGridGeometry(context, node, placeGridChildren(node, measured.children), content.width, content.height, true);
  geometry.items.forEach((item) => {
    const cellLeft = content.left + sumValues(geometry.columnSizes.slice(0, item.column)) + item.column * node.columnGap;
    const cellTop = content.top + sumValues(geometry.rowSizes.slice(0, item.row)) + item.row * node.rowGap;
    const cellWidth = sumValues(geometry.columnSizes.slice(item.column, item.column + item.columnSpan)) + Math.max(0, item.columnSpan - 1) * node.columnGap;
    const cellHeight = sumValues(geometry.rowSizes.slice(item.row, item.row + item.rowSpan)) + Math.max(0, item.rowSpan - 1) * node.rowGap;
    const width = resolveNodeWidthForAvailable(item.child, cellWidth, node.justifyItems === "stretch");
    const height = resolveNodeHeightForFrame(context, item.child, width, cellHeight, node.alignItems === "stretch");
    const alignedX = resolveAlignedAxisFrame(cellLeft, cellWidth, width, node.justifyItems, baseUnit, preserveRequestedAxisSize(item.child, "x"));
    const alignedY = resolveAlignedAxisFrame(cellTop, cellHeight, height, node.alignItems, baseUnit, preserveRequestedAxisSize(item.child, "y"));
    layoutNode(context, item.child, {
      left: alignedX.start,
      top: alignedY.start,
      width: alignedX.size,
      height: alignedY.size
    }, placements, baseUnit);
  });
};
var buildLayoutSnapshot = (context, measured, frame, baseUnit, path3, materializedPaths) => {
  if (measured.node.kind === "text") {
    if (canMaterializeFrame(frame)) {
      materializedPaths.push(path3);
    }
    return {
      ...buildCommonSnapshot(measured, frame, baseUnit, path3, true),
      kind: "text",
      text: composeTextPreview(measured.node.value, measured.node.transform),
      transform: measured.node.transform
    };
  }
  if (measured.node.kind === "rule") {
    if (canMaterializeFrame(frame)) {
      materializedPaths.push(path3);
    }
    return {
      ...buildCommonSnapshot(measured, frame, baseUnit, path3, true),
      kind: "rule",
      weight: measured.node.weight,
      opacity: measured.node.opacity
    };
  }
  if (measured.node.kind === "shape") {
    if (canMaterializeFrame(frame)) {
      materializedPaths.push(path3);
    }
    return {
      ...buildCommonSnapshot(measured, frame, baseUnit, path3, true),
      kind: "shape",
      geometry: measured.node.geometry
    };
  }
  if (measured.node.kind === "image") {
    if (canMaterializeFrame(frame)) {
      materializedPaths.push(path3);
    }
    return {
      ...buildCommonSnapshot(measured, frame, baseUnit, path3, true),
      kind: "image",
      source: summarizeImageSource(measured.node.source),
      contentType: measured.node.contentType,
      fit: measured.node.fit,
      alt: measured.node.alt,
      geometry: measured.node.geometry,
      crop: measured.node.crop,
      rotation: measured.node.rotation,
      flipHorizontal: measured.node.flipHorizontal,
      flipVertical: measured.node.flipVertical,
      lockAspectRatio: measured.node.lockAspectRatio
    };
  }
  if (measured.node.kind === "table") {
    if (canMaterializeFrame(frame)) {
      materializedPaths.push(path3);
    }
    return {
      ...buildCommonSnapshot(measured, frame, baseUnit, path3, true),
      kind: "table",
      rows: measured.node.rows,
      columns: measured.node.columns,
      style: measured.node.style
    };
  }
  if (measured.node.kind === "chart") {
    if (canMaterializeFrame(frame)) {
      materializedPaths.push(path3);
    }
    return {
      ...buildCommonSnapshot(measured, frame, baseUnit, path3, true),
      kind: "chart",
      chartType: measured.node.chartType,
      title: typeof measured.node.config?.title === "string" ? measured.node.config.title : undefined
    };
  }
  if (measured.node.kind === "panel") {
    if (canMaterializeFrame(frame)) {
      materializedPaths.push(path3);
    }
    const node2 = measured.node;
    const child = measured.children[0];
    const containerFrame2 = resolveContainerLayoutFrame(measured, frame, baseUnit);
    const content2 = insetFrame(containerFrame2, node2.padding);
    const children2 = [];
    if (child && content2.width > 0 && content2.height > 0) {
      const childWidth = resolveNodeWidthForAvailable(child, content2.width, node2.align === "stretch");
      const childHeight = resolveNodeHeightForFrame(context, child, childWidth, content2.height, node2.justify === "stretch");
      const alignedX = resolveAlignedAxisFrame(content2.left, content2.width, childWidth, node2.align, baseUnit, preserveRequestedAxisSize(child, "x"));
      const alignedY = resolveAlignedAxisFrame(content2.top, content2.height, childHeight, node2.justify, baseUnit, preserveRequestedAxisSize(child, "y"));
      children2.push(buildLayoutSnapshot(context, child, {
        left: alignedX.start,
        top: alignedY.start,
        width: alignedX.size,
        height: alignedY.size
      }, baseUnit, buildChildPath(path3, 0), materializedPaths));
    }
    return {
      ...buildCommonSnapshot(measured, frame, baseUnit, path3, true),
      kind: "panel",
      padding: clonePadding(node2.padding),
      align: node2.align,
      justify: node2.justify,
      contentFrame: snapshotFrame(content2),
      children: children2
    };
  }
  if (measured.node.kind === "layers") {
    const node2 = measured.node;
    const containerFrame2 = resolveContainerLayoutFrame(measured, frame, baseUnit);
    const content2 = insetFrame(containerFrame2, node2.padding);
    const children2 = [];
    const items = [];
    if (content2.width > 0 && content2.height > 0 && measured.children.length > 0) {
      measured.children.forEach((child, index) => {
        const width = resolveNodeWidthForAvailable(child, content2.width, node2.justifyItems === "stretch");
        const height = resolveNodeHeightForFrame(context, child, width, content2.height, node2.alignItems === "stretch");
        const alignedX = resolveAlignedAxisFrame(content2.left, content2.width, width, node2.justifyItems, baseUnit, preserveRequestedAxisSize(child, "x"));
        const alignedY = resolveAlignedAxisFrame(content2.top, content2.height, height, node2.alignItems, baseUnit, preserveRequestedAxisSize(child, "y"));
        const childPath = buildChildPath(path3, index);
        const childFrame = {
          left: alignedX.start,
          top: alignedY.start,
          width: alignedX.size,
          height: alignedY.size
        };
        items.push({ path: childPath, frame: snapshotFrame(childFrame) });
        children2.push(buildLayoutSnapshot(context, child, childFrame, baseUnit, childPath, materializedPaths));
      });
    }
    return {
      ...buildCommonSnapshot(measured, frame, baseUnit, path3, false),
      kind: "layers",
      padding: clonePadding(node2.padding),
      alignItems: node2.alignItems,
      justifyItems: node2.justifyItems,
      contentFrame: snapshotFrame(content2),
      items,
      children: children2
    };
  }
  if (measured.node.kind === "row") {
    const node2 = measured.node;
    const containerFrame2 = resolveContainerLayoutFrame(measured, frame, baseUnit);
    const content2 = insetFrame(containerFrame2, node2.padding);
    const children2 = [];
    const items = [];
    let effectiveGap = node2.gap;
    let justifyOffset = 0;
    if (content2.width > 0 && content2.height > 0 && measured.children.length > 0) {
      const baseWidths = measured.children.map((child) => intrinsicNodeAxisSize(child, "x"));
      const fillWeights = measured.children.map((child) => child.node.width.mode === "fill" ? child.node.width.value : 0);
      const widths = resolveStackItemSizes({
        available: content2.width,
        baseSizes: baseWidths,
        gap: node2.gap,
        fillWeights,
        kind: node2.kind,
        name: node2.name,
        axis: "x",
        warnOverflow: false
      });
      const layout = resolveStackLayoutPositioning(content2.width, widths, node2.gap, node2.justify);
      effectiveGap = layout.gap;
      justifyOffset = layout.offset;
      let cursor = content2.left + layout.offset;
      measured.children.forEach((child, index) => {
        const width = widths[index] ?? 0;
        const height = resolveNodeHeightForFrame(context, child, width, content2.height, node2.align === "stretch");
        const alignedY = resolveAlignedAxisFrame(content2.top, content2.height, height, node2.align, baseUnit, preserveRequestedAxisSize(child, "y"));
        const childFrame = {
          left: cursor,
          top: alignedY.start,
          width,
          height: alignedY.size
        };
        const childPath = buildChildPath(path3, index);
        items.push({ path: childPath, frame: snapshotFrame(childFrame) });
        children2.push(buildLayoutSnapshot(context, child, childFrame, baseUnit, childPath, materializedPaths));
        cursor += width + layout.gap;
      });
    }
    return {
      ...buildCommonSnapshot(measured, frame, baseUnit, path3, false),
      kind: "row",
      padding: clonePadding(node2.padding),
      gap: node2.gap,
      effectiveGap: roundLayoutNumber(effectiveGap),
      justifyOffset: roundLayoutNumber(justifyOffset),
      align: node2.align,
      justify: node2.justify,
      contentFrame: snapshotFrame(content2),
      items,
      children: children2
    };
  }
  if (measured.node.kind === "column") {
    const node2 = measured.node;
    const containerFrame2 = resolveContainerLayoutFrame(measured, frame, baseUnit);
    const content2 = insetFrame(containerFrame2, node2.padding);
    const children2 = [];
    const items = [];
    let effectiveGap = node2.gap;
    let justifyOffset = 0;
    if (content2.width > 0 && content2.height > 0 && measured.children.length > 0) {
      const resolvedWidths = measured.children.map((child) => resolveNodeWidthForAvailable(child, content2.width, node2.align === "stretch"));
      const baseHeights = measured.children.map((child, index) => resolveNodeBaseHeightForAssignedWidth(context, child, resolvedWidths[index] ?? 0));
      const fillWeights = measured.children.map((child) => child.node.height.mode === "fill" ? child.node.height.value : 0);
      const heights = resolveStackItemSizes({
        available: content2.height,
        baseSizes: baseHeights,
        gap: node2.gap,
        fillWeights,
        kind: node2.kind,
        name: node2.name,
        axis: "y",
        warnOverflow: false
      });
      const layout = resolveStackLayoutPositioning(content2.height, heights, node2.gap, node2.justify);
      effectiveGap = layout.gap;
      justifyOffset = layout.offset;
      let cursor = content2.top + layout.offset;
      measured.children.forEach((child, index) => {
        const width = resolvedWidths[index] ?? 0;
        const height = heights[index] ?? 0;
        const alignedX = resolveAlignedAxisFrame(content2.left, content2.width, width, node2.align, baseUnit, preserveRequestedAxisSize(child, "x"));
        const childFrame = {
          left: alignedX.start,
          top: cursor,
          width: alignedX.size,
          height
        };
        const childPath = buildChildPath(path3, index);
        items.push({ path: childPath, frame: snapshotFrame(childFrame) });
        children2.push(buildLayoutSnapshot(context, child, childFrame, baseUnit, childPath, materializedPaths));
        cursor += height + layout.gap;
      });
    }
    return {
      ...buildCommonSnapshot(measured, frame, baseUnit, path3, false),
      kind: "column",
      padding: clonePadding(node2.padding),
      gap: node2.gap,
      effectiveGap: roundLayoutNumber(effectiveGap),
      justifyOffset: roundLayoutNumber(justifyOffset),
      align: node2.align,
      justify: node2.justify,
      contentFrame: snapshotFrame(content2),
      items,
      children: children2
    };
  }
  const node = measured.node;
  const containerFrame = resolveContainerLayoutFrame(measured, frame, baseUnit);
  const content = insetFrame(containerFrame, node.padding);
  const children = [];
  const cells = [];
  let columnSizes = [];
  let rowSizes = [];
  let resolvedRows = node.rows ? cloneTracks(node.rows) : [];
  if (content.width > 0 && content.height > 0 && measured.children.length > 0) {
    const geometry = resolveGridGeometry(context, node, placeGridChildren(node, measured.children), content.width, content.height, true);
    columnSizes = geometry.columnSizes.map(roundLayoutNumber);
    rowSizes = geometry.rowSizes.map(roundLayoutNumber);
    resolvedRows = cloneTracks(geometry.rows);
    geometry.items.forEach((item, index) => {
      const cellLeft = content.left + sumValues(geometry.columnSizes.slice(0, item.column)) + item.column * node.columnGap;
      const cellTop = content.top + sumValues(geometry.rowSizes.slice(0, item.row)) + item.row * node.rowGap;
      const cellWidth = sumValues(geometry.columnSizes.slice(item.column, item.column + item.columnSpan)) + Math.max(0, item.columnSpan - 1) * node.columnGap;
      const cellHeight = sumValues(geometry.rowSizes.slice(item.row, item.row + item.rowSpan)) + Math.max(0, item.rowSpan - 1) * node.rowGap;
      const width = resolveNodeWidthForAvailable(item.child, cellWidth, node.justifyItems === "stretch");
      const height = resolveNodeHeightForFrame(context, item.child, width, cellHeight, node.alignItems === "stretch");
      const alignedX = resolveAlignedAxisFrame(cellLeft, cellWidth, width, node.justifyItems, baseUnit, preserveRequestedAxisSize(item.child, "x"));
      const alignedY = resolveAlignedAxisFrame(cellTop, cellHeight, height, node.alignItems, baseUnit, preserveRequestedAxisSize(item.child, "y"));
      const childPath = buildChildPath(path3, index);
      const childFrame = {
        left: alignedX.start,
        top: alignedY.start,
        width: alignedX.size,
        height: alignedY.size
      };
      cells.push({
        path: childPath,
        column: item.column,
        row: item.row,
        columnSpan: item.columnSpan,
        rowSpan: item.rowSpan,
        cellFrame: snapshotFrame({
          left: cellLeft,
          top: cellTop,
          width: cellWidth,
          height: cellHeight
        })
      });
      children.push(buildLayoutSnapshot(context, item.child, childFrame, baseUnit, childPath, materializedPaths));
    });
  }
  return {
    ...buildCommonSnapshot(measured, frame, baseUnit, path3, false),
    kind: "grid",
    padding: clonePadding(node.padding),
    columnGap: node.columnGap,
    rowGap: node.rowGap,
    alignItems: node.alignItems,
    justifyItems: node.justifyItems,
    contentFrame: snapshotFrame(content),
    columns: cloneTracks(node.columns),
    rows: node.rows ? cloneTracks(node.rows) : undefined,
    autoRows: cloneTrack(node.autoRows),
    resolvedRows,
    columnSizes,
    rowSizes,
    cells,
    children
  };
};
var buildCommonSnapshot = (measured, frame, baseUnit, path3, includeSnappedFrame) => {
  return {
    path: path3,
    kind: measured.node.kind,
    name: measured.node.name,
    requestedSize: {
      width: cloneNormalizedLayoutSize(measured.node.width),
      height: cloneNormalizedLayoutSize(measured.node.height)
    },
    intrinsicSize: {
      width: roundLayoutNumber(measured.intrinsicWidth),
      height: roundLayoutNumber(measured.intrinsicHeight)
    },
    frame: snapshotFrame(frame),
    snappedFrame: includeSnappedFrame && baseUnit !== undefined && canMaterializeFrame(frame) ? snapshotFrame(snapMeasuredFrame(measured, frame, resolveNodeSnapUnit(measured, frame, baseUnit))) : undefined,
    children: []
  };
};
var resolveNodeSnapUnit = (measured, frame, baseUnit) => {
  if (baseUnit === undefined) {
    return;
  }
  if (measured.node.kind === "text") {
    return Math.max(1, baseUnit / 4);
  }
  if (measured.node.kind === "rule") {
    return Math.max(1, baseUnit / 4);
  }
  if (measured.node.kind === "shape" && frame.width <= baseUnit * 2 && frame.height <= baseUnit * 2) {
    return Math.max(1, baseUnit / 4);
  }
  if (measured.node.kind === "shape" && frame.width <= baseUnit * 10 && frame.height <= baseUnit * 10) {
    return Math.max(1, baseUnit / 2);
  }
  return measured.node.kind === "shape" ? baseUnit : undefined;
};
var resolveNodeWidthForAvailable = (measured, available, stretch) => {
  const spec = measured.node.width;
  if (spec.mode === "fill") {
    return Math.max(0, available);
  }
  if (spec.mode === "fixed") {
    return spec.value;
  }
  if (spec.mode === "wrap") {
    return Math.min(measured.intrinsicWidth, spec.max);
  }
  if (stretch) {
    return Math.max(0, available);
  }
  return measured.intrinsicWidth;
};
var resolveNodeHeightForFrame = (context, measured, assignedWidth, availableHeight, stretch) => {
  const spec = measured.node.height;
  if (spec.mode === "fill") {
    return Math.max(0, availableHeight);
  }
  if (spec.mode === "fixed") {
    return spec.value;
  }
  const requiredHeight = resolveNodeRequiredHeightForWidth(context, measured, assignedWidth);
  if (spec.mode === "wrap") {
    return Math.min(requiredHeight, spec.max);
  }
  if (stretch) {
    return Math.max(0, availableHeight);
  }
  return requiredHeight;
};
var resolveNodeBaseHeightForAssignedWidth = (context, measured, assignedWidth, treatFillAsHug = false) => {
  const spec = measured.node.height;
  if (spec.mode === "fill") {
    if (!treatFillAsHug) {
      return 0;
    }
    return resolveNodeRequiredHeightForWidth(context, measured, assignedWidth, true);
  }
  if (spec.mode === "fixed") {
    return spec.value;
  }
  const requiredHeight = resolveNodeRequiredHeightForWidth(context, measured, assignedWidth, treatFillAsHug);
  if (spec.mode === "wrap") {
    return Math.min(requiredHeight, spec.max);
  }
  return requiredHeight;
};
var resolveNodeRequiredHeightForWidth = (context, measured, assignedWidth, treatSelfFillAsHug = false) => {
  if (measured.node.kind === "text") {
    if (treatSelfFillAsHug && measured.node.height.mode === "fill") {
      return measureTextNode(context, {
        ...measured.node,
        height: { mode: "hug" }
      }, assignedWidth).height;
    }
    return measureTextNode(context, measured.node, assignedWidth).height;
  }
  if (measured.node.kind === "rule" || measured.node.kind === "shape" || measured.node.kind === "image" || measured.node.kind === "table" || measured.node.kind === "chart") {
    if (treatSelfFillAsHug && measured.node.height.mode === "fill") {
      return measured.intrinsicHeight;
    }
    return intrinsicSizeForSpec(measured.node.height, measured.intrinsicHeight);
  }
  if (measured.node.kind === "panel") {
    const child = measured.children[0];
    const contentWidth2 = Math.max(0, assignedWidth - measured.node.padding.left - measured.node.padding.right);
    const childWidth = child ? resolveRootAxisSize(child.node.width, child.intrinsicWidth, contentWidth2) : 0;
    const childHeight = child ? resolveNodeBaseHeightForAssignedWidth(context, child, childWidth, true) : 0;
    return childHeight + measured.node.padding.top + measured.node.padding.bottom;
  }
  if (measured.node.kind === "layers") {
    const node = measured.node;
    const contentWidth2 = Math.max(0, assignedWidth - node.padding.left - node.padding.right);
    const heights = measured.children.map((child) => {
      const childWidth = resolveNodeWidthForAvailable(child, contentWidth2, node.justifyItems === "stretch");
      return resolveNodeBaseHeightForAssignedWidth(context, child, childWidth, true);
    });
    return Math.max(0, ...heights) + node.padding.top + node.padding.bottom;
  }
  if (measured.node.kind === "row") {
    const contentWidth2 = Math.max(0, assignedWidth - measured.node.padding.left - measured.node.padding.right);
    const baseWidths = measured.children.map((child) => intrinsicNodeAxisSize(child, "x"));
    const fillWeights = measured.children.map((child) => child.node.width.mode === "fill" ? child.node.width.value : 0);
    const widths = resolveStackItemSizes({
      available: contentWidth2,
      baseSizes: baseWidths,
      gap: measured.node.gap,
      fillWeights,
      kind: measured.node.kind,
      name: measured.node.name,
      axis: "x",
      warnOverflow: false
    });
    const cross = Math.max(0, ...measured.children.map((child, index) => resolveNodeHeightForFrame(context, child, widths[index] ?? 0, 0, false)));
    return cross + measured.node.padding.top + measured.node.padding.bottom;
  }
  if (measured.node.kind === "column") {
    const contentWidth2 = Math.max(0, assignedWidth - measured.node.padding.left - measured.node.padding.right);
    const stretchChildren = measured.node.align === "stretch";
    const widths = measured.children.map((child) => resolveNodeWidthForAvailable(child, contentWidth2, stretchChildren));
    const main = sumValues(measured.children.map((child, index) => resolveNodeBaseHeightForAssignedWidth(context, child, widths[index] ?? 0)));
    const totalGap = Math.max(0, measured.children.length - 1) * measured.node.gap;
    return main + totalGap + measured.node.padding.top + measured.node.padding.bottom;
  }
  const contentWidth = Math.max(0, assignedWidth - measured.node.padding.left - measured.node.padding.right);
  const geometry = resolveGridGeometry(context, measured.node, placeGridChildren(measured.node, measured.children), contentWidth, undefined, false);
  return sumValues(geometry.rowSizes) + Math.max(0, geometry.rowSizes.length - 1) * measured.node.rowGap + measured.node.padding.top + measured.node.padding.bottom;
};
var resolveStackItemSizes = (params2) => {
  const totalGap = Math.max(0, params2.baseSizes.length - 1) * params2.gap;
  const usedWithoutFill = sumValues(params2.baseSizes.filter((_value, index) => (params2.fillWeights[index] ?? 0) <= 0)) + totalGap;
  const overflow = Math.max(0, usedWithoutFill - params2.available);
  if (params2.warnOverflow && overflow > 0.5) {
    console.warn(`Compose ${params2.kind} "${params2.name ?? "(unnamed)"}" overflowed its ${params2.axis === "x" ? "width" : "height"} by ${overflow.toFixed(1)}px.`, {
      kind: params2.kind,
      name: params2.name,
      axis: params2.axis,
      overflowPx: overflow
    });
  }
  const totalFillWeight = sumValues(params2.fillWeights);
  if (totalFillWeight <= 0) {
    return [...params2.baseSizes];
  }
  const remaining = Math.max(0, params2.available - usedWithoutFill);
  const unit2 = remaining / totalFillWeight;
  return params2.baseSizes.map((baseSize, index) => {
    const weight = params2.fillWeights[index] ?? 0;
    return weight > 0 ? unit2 * weight : baseSize;
  });
};
var resolveStackLayoutPositioning = (available, sizes, gapBase, justify) => {
  const used = sumValues(sizes) + Math.max(0, sizes.length - 1) * gapBase;
  const free = Math.max(0, available - used);
  let gap = gapBase;
  let offset = 0;
  if (justify === "center") {
    offset = free / 2;
  } else if (justify === "end") {
    offset = free;
  } else if (justify === "between" && sizes.length > 1 && free > 0) {
    gap = gapBase + free / (sizes.length - 1);
  }
  return { gap, offset };
};
var resolveGridGeometry = (context, node, items, availableWidth, availableHeight, stretchRows) => {
  const rows = resolveGridRows(node, resolveGridRowCount(node, items));
  const autoColumnSizes = Array.from({ length: node.columns.length }, () => 0);
  items.forEach((item) => {
    distributeTrackRequirement({
      tracks: node.columns,
      sizes: autoColumnSizes,
      start: item.column,
      span: item.columnSpan,
      gap: node.columnGap,
      required: intrinsicNodeAxisSize(item.child, "x")
    });
  });
  const columnSizes = resolveTracks(node.columns, autoColumnSizes, availableWidth, node.columnGap, true);
  const autoRowSizes = Array.from({ length: rows.length }, () => 0);
  items.forEach((item) => {
    const cellWidth = sumValues(columnSizes.slice(item.column, item.column + item.columnSpan)) + Math.max(0, item.columnSpan - 1) * node.columnGap;
    const childWidth = resolveNodeWidthForAvailable(item.child, cellWidth, node.justifyItems === "stretch");
    const requiredHeight = resolveNodeBaseHeightForAssignedWidth(context, item.child, childWidth);
    distributeTrackRequirement({
      tracks: rows,
      sizes: autoRowSizes,
      start: item.row,
      span: item.rowSpan,
      gap: node.rowGap,
      required: requiredHeight
    });
  });
  const rowSizes = resolveTracks(rows, autoRowSizes, availableHeight, node.rowGap, stretchRows);
  return {
    items,
    rows,
    columnSizes,
    rowSizes
  };
};
var resolveTracks = (tracks, autoSizes, available, gap, stretchAuto) => {
  const baseSizes = tracks.map((track, index) => {
    if (track === "auto") {
      return autoSizes[index] ?? 0;
    }
    if (track.mode === "fixed") {
      return track.value;
    }
    return 0;
  });
  const totalGap = Math.max(0, tracks.length - 1) * gap;
  const used = sumValues(baseSizes) + totalGap;
  const totalFr = sumValues(tracks.map((track) => track !== "auto" && track.mode === "fr" ? track.value : 0));
  const remaining = available === undefined ? 0 : Math.max(0, available - used);
  const autoIndexes = tracks.map((track, index) => ({ track, index })).filter(({ track }) => track === "auto").map(({ index }) => index);
  const frUnit = totalFr > 0 ? remaining / totalFr : 0;
  const autoGrow = stretchAuto && totalFr === 0 && autoIndexes.length > 0 ? remaining / autoIndexes.length : 0;
  return tracks.map((track, index) => {
    if (track !== "auto" && track.mode === "fr") {
      return frUnit * track.value;
    }
    if (track === "auto" && autoGrow > 0) {
      return (baseSizes[index] ?? 0) + autoGrow;
    }
    return baseSizes[index] ?? 0;
  });
};
var resolveGridRowCount = (node, items) => {
  if (node.rows) {
    return node.rows.length;
  }
  if (items.length === 0) {
    return 0;
  }
  return Math.max(...items.map((item) => item.row + item.rowSpan));
};
var resolveGridRows = (node, rowCount) => {
  if (node.rows) {
    return [...node.rows];
  }
  return Array.from({ length: rowCount }, () => node.autoRows);
};
var placeGridChildren = (node, children) => {
  const columnCount = node.columns.length;
  const explicitRowCount = node.rows?.length;
  const occupied = new Set;
  const items = [];
  children.forEach((child) => {
    const columnSpan = child.node.columnSpan;
    const rowSpan = child.node.rowSpan;
    if (columnSpan > columnCount) {
      throw new Error(`Grid "${node.name ?? "(unnamed)"}" child "${child.node.name ?? "(unnamed)"}" cannot span ${columnSpan} columns when only ${columnCount} exist.`);
    }
    const lastStartColumn = columnCount - columnSpan;
    let placed = false;
    const maxStartRow = explicitRowCount === undefined ? Number.POSITIVE_INFINITY : explicitRowCount - rowSpan;
    for (let row = 0;row <= maxStartRow && !placed; row += 1) {
      for (let column = 0;column <= lastStartColumn; column += 1) {
        if (!canPlaceGridItem(occupied, row, column, rowSpan, columnSpan)) {
          continue;
        }
        markGridItemOccupied(occupied, row, column, rowSpan, columnSpan);
        items.push({
          child,
          column,
          row,
          columnSpan,
          rowSpan
        });
        placed = true;
        break;
      }
    }
    if (!placed) {
      throw new Error(`Grid "${node.name ?? "(unnamed)"}" could not place child "${child.node.name ?? "(unnamed)"}" within the available tracks.`);
    }
  });
  return items;
};
var canPlaceGridItem = (occupied, row, column, rowSpan, columnSpan) => {
  for (let rowOffset = 0;rowOffset < rowSpan; rowOffset += 1) {
    for (let columnOffset = 0;columnOffset < columnSpan; columnOffset += 1) {
      if (occupied.has(gridCellKey(row + rowOffset, column + columnOffset))) {
        return false;
      }
    }
  }
  return true;
};
var markGridItemOccupied = (occupied, row, column, rowSpan, columnSpan) => {
  for (let rowOffset = 0;rowOffset < rowSpan; rowOffset += 1) {
    for (let columnOffset = 0;columnOffset < columnSpan; columnOffset += 1) {
      occupied.add(gridCellKey(row + rowOffset, column + columnOffset));
    }
  }
};
var gridCellKey = (row, column) => `${row}:${column}`;
var resolveAutoTrackSizesForIntrinsicAxis = (tracks, gap, items, axis) => {
  const sizes = Array.from({ length: tracks.length }, () => 0);
  items.forEach((item) => {
    distributeTrackRequirement({
      tracks,
      sizes,
      start: axis === "x" ? item.column : item.row,
      span: axis === "x" ? item.columnSpan : item.rowSpan,
      gap,
      required: intrinsicNodeAxisSize(item.child, axis)
    });
  });
  return sizes;
};
var distributeTrackRequirement = (params2) => {
  const trackSlice = params2.tracks.slice(params2.start, params2.start + params2.span);
  const internalGap = Math.max(0, params2.span - 1) * params2.gap;
  const autoIndexes = trackSlice.map((track, index) => ({ track, index })).filter(({ track }) => track === "auto").map(({ index }) => params2.start + index);
  if (autoIndexes.length === 0) {
    return;
  }
  const used = internalGap + sumValues(trackSlice.map((track, index) => track === "auto" ? params2.sizes[params2.start + index] ?? 0 : intrinsicTrackSize(track)));
  const deficit = Math.max(0, params2.required - used);
  if (deficit <= 0) {
    return;
  }
  const addition = deficit / autoIndexes.length;
  autoIndexes.forEach((index) => {
    params2.sizes[index] = (params2.sizes[index] ?? 0) + addition;
  });
};
var intrinsicNodeAxisSize = (measured, axis) => {
  const spec = axis === "x" ? measured.node.width : measured.node.height;
  const intrinsic = axis === "x" ? measured.intrinsicWidth : measured.intrinsicHeight;
  return intrinsicSizeForSpec(spec, intrinsic);
};
var intrinsicSizeForSpec = (spec, intrinsic) => {
  if (spec.mode === "fill") {
    return 0;
  }
  if (spec.mode === "fixed") {
    return spec.value;
  }
  if (spec.mode === "wrap") {
    return Math.min(intrinsic, spec.max);
  }
  return intrinsic;
};
var hasFillChild = (children, axis) => children.some((child) => (axis === "x" ? child.node.width : child.node.height).mode === "fill");
var measureTextNode = (context, node, widthOverride) => {
  const presentation = context.presentation;
  const text = composeTextPreview(node.value, node.transform);
  const paragraphs = composeTextParagraphProtos(node.value, node.transform);
  const widthSpec = node.width;
  const heightSpec = node.height;
  const measureWidth = widthOverride ?? (widthSpec.mode === "fixed" ? widthSpec.value : widthSpec.mode === "wrap" ? widthSpec.max : widthSpec.mode === "fill" ? HUGE_MEASURE : HUGE_MEASURE);
  if (presentation) {
    const { textStyleProto, paragraphStyle } = resolveTextMeasureStyle(presentation, node.style);
    const explicitNoWrap = textStyleProto?.wrap === 1 /* TEXT_WRAPPING_TYPE_NONE */;
    const wrapMode = !explicitNoWrap && (widthSpec.mode === "wrap" || widthSpec.mode === "fixed" || widthSpec.mode === "fill" || widthOverride !== undefined);
    const styleForMeasure = wrapMode ? {
      ...textStyleProto ?? {},
      wrap: textStyleProto?.wrap ?? 2 /* TEXT_WRAPPING_TYPE_SQUARE */
    } : textStyleProto;
    const element = buildTextMeasureElement(paragraphs, measureWidth, HUGE_MEASURE, styleForMeasure, paragraphStyle);
    const bounds = computeShapeAutoFitBounds({
      element,
      presentation,
      slide: context.slide,
      wrap: wrapMode,
      resolvedStyle: styleForMeasure
    });
    const measuredWidth = widthSpec.mode === "fixed" ? widthSpec.value : widthSpec.mode === "wrap" ? Math.min(bounds.width, widthSpec.max) : widthSpec.mode === "fill" ? 0 : bounds.width;
    const measuredHeight = heightSpec.mode === "fixed" ? heightSpec.value : heightSpec.mode === "fill" ? 0 : bounds.height;
    return {
      width: Math.max(0, measuredWidth),
      height: Math.max(0, measuredHeight)
    };
  }
  return fallbackTextBounds(text, widthSpec, heightSpec, widthOverride);
};
var buildTextMeasureElement = (paragraphs, width, height, textStyleProto, paragraphStyle) => {
  const widthEmu = emuFromPixels(Math.max(1, width));
  const heightEmu = emuFromPixels(Math.max(1, height));
  return {
    id: "compose-text-measure",
    type: 1 /* ELEMENT_TYPE_TEXT */,
    bbox: {
      xEmu: 0,
      yEmu: 0,
      widthEmu: widthEmu ?? 0,
      heightEmu: heightEmu ?? 0
    },
    paragraphs: paragraphs.map((paragraph) => ({
      ...paragraph,
      id: "",
      runs: (paragraph.runs ?? []).map((run) => ({
        ...run,
        id: "",
        citations: [...run.citations ?? []],
        reviewMarkIds: [...run.reviewMarkIds ?? []]
      })),
      textStyle: textStyleProto,
      paragraphStyle: paragraphStyle || paragraph.paragraphStyle ? {
        ...paragraphStyle ?? {},
        ...paragraph.paragraphStyle ?? {}
      } : undefined
    })),
    textStyle: textStyleProto,
    effects: [],
    children: [],
    levelsStyles: [],
    citations: []
  };
};
var resolveTextMeasureStyle = (presentation, style) => {
  const normalizedStyle = normalizeComposeTextStyleRef(style);
  const composeMeasureInsets = {
    topInset: 0,
    rightInset: 0,
    bottomInset: 0,
    leftInset: 0
  };
  const withComposeMeasureInsets = (textStyleProto) => ({
    ...textStyleProto ?? {},
    topInset: textStyleProto?.topInset ?? composeMeasureInsets.topInset,
    rightInset: textStyleProto?.rightInset ?? composeMeasureInsets.rightInset,
    bottomInset: textStyleProto?.bottomInset ?? composeMeasureInsets.bottomInset,
    leftInset: textStyleProto?.leftInset ?? composeMeasureInsets.leftInset
  });
  if (!normalizedStyle) {
    return {
      textStyleProto: { ...composeMeasureInsets },
      paragraphStyle: undefined
    };
  }
  if (typeof normalizedStyle === "string") {
    const resolved2 = presentation.styles.resolveTextStyle(normalizedStyle);
    return {
      textStyleProto: withComposeMeasureInsets(resolved2?.toProto()),
      paragraphStyle: resolved2?.lineSpacing !== undefined ? {
        lineSpacingPercent: Math.round(resolved2.lineSpacing * 1e5)
      } : undefined
    };
  }
  const resolved = new TextStyle2;
  applyTextStyleConfig(resolved, normalizedStyle);
  return {
    textStyleProto: withComposeMeasureInsets(resolved.toProto()),
    paragraphStyle: normalizedStyle.lineSpacing !== undefined ? {
      lineSpacingPercent: Math.round(normalizedStyle.lineSpacing * 1e5)
    } : undefined
  };
};
var fallbackTextBounds = (text, widthSpec, heightSpec, widthOverride) => {
  const approxChar = 8;
  const lineHeight = 20;
  const lines = text.length > 0 ? text.split(/\r?\n/) : [""];
  const widestChars = Math.max(0, ...lines.map((line) => line.length));
  const plainWidth = widestChars * approxChar + 4;
  let width = plainWidth;
  if (widthOverride !== undefined) {
    width = widthOverride;
  } else if (widthSpec.mode === "fixed") {
    width = widthSpec.value;
  } else if (widthSpec.mode === "wrap") {
    width = Math.min(plainWidth, widthSpec.max);
  } else if (widthSpec.mode === "fill") {
    width = 0;
  }
  let lineCount = Math.max(1, lines.length);
  if (width > 0 && (widthOverride !== undefined || widthSpec.mode === "wrap" || widthSpec.mode === "fixed")) {
    lineCount = lines.reduce((count3, line) => {
      const charsPerLine = Math.max(1, Math.floor(width / approxChar));
      return count3 + Math.max(1, Math.ceil(line.length / charsPerLine));
    }, 0);
  }
  let height = lineCount * lineHeight;
  if (heightSpec.mode === "fixed") {
    height = heightSpec.value;
  } else if (heightSpec.mode === "fill") {
    height = 0;
  }
  return { width: Math.max(0, width), height: Math.max(0, height) };
};
var getSlidePresentation = (slide) => {
  const candidate = slide;
  if (typeof candidate.getPresentation === "function") {
    return candidate.getPresentation();
  }
  return candidate.presentation;
};
var isFrTrack = (track) => track !== "auto" && track.mode === "fr";
var intrinsicTrackSize = (track) => {
  if (track === "auto") {
    return 0;
  }
  if (track.mode === "fixed") {
    return track.value;
  }
  return 0;
};
var insetFrame = (frame, padding) => ({
  left: frame.left + padding.left,
  top: frame.top + padding.top,
  width: Math.max(0, frame.width - padding.left - padding.right),
  height: Math.max(0, frame.height - padding.top - padding.bottom)
});
var alignAxis = (origin, available, size2, align) => {
  if (align === "start" || align === "stretch") {
    return origin;
  }
  if (align === "center") {
    return origin + (available - size2) / 2;
  }
  return origin + (available - size2);
};
var resolveAlignedAxisFrame = (origin, available, size2, align, baseUnit, preserveSize = false) => {
  if (baseUnit === undefined || align === "start" || align === "stretch") {
    return {
      start: alignAxis(origin, available, size2, align),
      size: size2
    };
  }
  const positionBaseUnit = Math.max(1, baseUnit / 4);
  const effectiveSize = preserveSize ? size2 : Math.max(1, snapSpan(size2, Math.max(1, baseUnit / 2)));
  const rawStart = alignAxis(origin, available, effectiveSize, align);
  return {
    start: snapValue(rawStart, positionBaseUnit),
    size: effectiveSize
  };
};
var sumValues = (values) => values.reduce((total, value) => total + value, 0);
var resolveContainerLayoutFrame = (measured, frame, baseUnit) => snapMeasuredFrame(measured, frame, resolveNodeSnapUnit(measured, frame, baseUnit));
var snapMeasuredFrame = (measured, frame, baseUnit) => {
  const preserveWidth = preserveRequestedAxisSize(measured, "x");
  const preserveHeight = preserveRequestedAxisSize(measured, "y");
  return snapOriginAndSpanFrame(frame, baseUnit, {
    preserveWidth,
    preserveHeight,
    ceilHeight: measured.node.kind === "text"
  });
};
var snapOriginAndSpanFrame = (frame, baseUnit, options = {}) => {
  if (baseUnit === undefined) {
    return frame;
  }
  return {
    left: snapValue(frame.left, baseUnit),
    top: snapValue(frame.top, baseUnit),
    width: Math.max(1, options.preserveWidth ? frame.width : snapSpan(frame.width, baseUnit)),
    height: Math.max(1, options.preserveHeight ? frame.height : options.ceilHeight ? snapSpanCeil(frame.height, baseUnit) : snapSpan(frame.height, baseUnit))
  };
};
var preserveRequestedAxisSize = (measured, axis) => (axis === "x" ? measured.node.width : measured.node.height).mode === "fixed";
var snapValue = (value, baseUnit) => {
  if (baseUnit === undefined) {
    return value;
  }
  return Math.round(value / baseUnit) * baseUnit;
};
var snapSpan = (value, baseUnit) => {
  if (baseUnit === undefined) {
    return value;
  }
  return Math.round(value / baseUnit) * baseUnit;
};
var snapSpanCeil = (value, baseUnit) => {
  if (baseUnit === undefined) {
    return value;
  }
  return Math.ceil(value / baseUnit) * baseUnit;
};
var readOptionalBaseUnit = (value) => {
  if (value === undefined) {
    return;
  }
  if (!Number.isFinite(value) || value <= 0) {
    throw new Error("slide.compose baseUnit must be a positive number.");
  }
  return value;
};
var readFrame = (frame, name) => {
  if (!Number.isFinite(frame.left) || !Number.isFinite(frame.top) || !Number.isFinite(frame.width) || !Number.isFinite(frame.height)) {
    throw new Error(`${name} must include finite left/top/width/height values.`);
  }
  if (frame.width <= 0 || frame.height <= 0) {
    throw new Error(`${name} width and height must be positive.`);
  }
  return frame;
};
var resolveRootAxisSize = (spec, intrinsic, available) => {
  if (spec.mode === "fill") {
    return available;
  }
  if (spec.mode === "fixed") {
    return spec.value;
  }
  if (spec.mode === "wrap") {
    return Math.min(spec.max, intrinsic);
  }
  return intrinsic;
};
var resolveRootHeight = (context, measured, resolvedWidth, availableHeight) => {
  const spec = measured.node.height;
  if (spec.mode === "fill") {
    return availableHeight;
  }
  if (spec.mode === "fixed") {
    return spec.value;
  }
  const requiredHeight = resolveNodeRequiredHeightForWidth(context, measured, resolvedWidth);
  if (spec.mode === "wrap") {
    return Math.min(requiredHeight, spec.max);
  }
  return requiredHeight;
};
var canMaterializeFrame = (frame) => frame.width > 0 && frame.height > 0;
var buildChildPath = (path3, index) => `${path3}.${index}`;
var clonePadding = (padding) => ({
  top: roundLayoutNumber(padding.top),
  right: roundLayoutNumber(padding.right),
  bottom: roundLayoutNumber(padding.bottom),
  left: roundLayoutNumber(padding.left)
});
var cloneNormalizedLayoutSize = (value) => {
  if (value.mode === "hug") {
    return { mode: "hug" };
  }
  if (value.mode === "fill") {
    return {
      mode: "fill",
      value: roundLayoutNumber(value.value)
    };
  }
  if (value.mode === "fixed") {
    return {
      mode: "fixed",
      value: roundLayoutNumber(value.value)
    };
  }
  return {
    mode: "wrap",
    max: roundLayoutNumber(value.max)
  };
};
var cloneTrack = (track) => {
  if (track === "auto") {
    return "auto";
  }
  if (track.mode === "fixed") {
    return {
      mode: "fixed",
      value: roundLayoutNumber(track.value)
    };
  }
  return {
    mode: "fr",
    value: roundLayoutNumber(track.value)
  };
};
var cloneTracks = (tracks) => tracks.map((track) => cloneTrack(track));
var summarizeImageSource = (source) => {
  if ("path" in source) {
    return { kind: "path", path: source.path };
  }
  if ("dataUrl" in source) {
    return { kind: "dataUrl" };
  }
  if ("blob" in source) {
    return { kind: "blob" };
  }
  if ("uri" in source) {
    return { kind: "uri", uri: source.uri };
  }
  return {
    kind: "prompt",
    prompt: source.prompt
  };
};
var snapshotFrame = (frame) => ({
  left: roundLayoutNumber(frame.left),
  top: roundLayoutNumber(frame.top),
  width: roundLayoutNumber(frame.width),
  height: roundLayoutNumber(frame.height)
});
var roundLayoutNumber = (value) => Math.round(value * 100) / 100;

// node_modules/@oai/granola/dist/models/presentation/compose/materialize.js
var composeSlideDetailed = (slide, root, options = {}) => {
  const { placements, materializedPaths, run } = layoutComposeTreeDetailed(slide, root, options);
  const elements = placements.map((placement) => materializePlacement(slide, placement));
  const elementsByPath = new Map;
  const refsByPath = new Map;
  const count3 = Math.min(materializedPaths.length, elements.length);
  for (let index = 0;index < count3; index += 1) {
    const path3 = materializedPaths[index];
    const element = elements[index];
    if (!path3 || !element) {
      continue;
    }
    elementsByPath.set(path3, element);
    refsByPath.set(path3, buildLayoutElementRef(element));
  }
  attachElementRefs(run.root, refsByPath);
  return {
    elements,
    elementsByPath,
    run
  };
};
var materializePlacement = (slide, placement) => {
  if (placement.kind === "text") {
    const shape = slide.shapes.add({
      geometry: "textbox",
      position: placement.frame
    });
    if (placement.name) {
      shape.name = placement.name;
    }
    shape.text.set(placement.value);
    if (placement.style) {
      if (typeof placement.style === "string") {
        shape.text.style = placement.style;
      } else {
        shape.text.style = {
          ...placement.style,
          insets: placement.style.insets ?? {
            top: 0,
            right: 0,
            bottom: 0,
            left: 0
          }
        };
      }
    }
    if (typeof placement.style === "string") {
      shape.text.insets = { top: 0, right: 0, bottom: 0, left: 0 };
    } else if (!placement.style?.insets) {
      shape.text.insets = { top: 0, right: 0, bottom: 0, left: 0 };
    }
    if (typeof placement.value !== "string") {
      const explicitParagraphs = buildParagraphProtosFromInput(placement.value);
      explicitParagraphs.forEach((paragraphProto, index) => {
        const paragraph = shape.text.paragraphs.items[index];
        if (!paragraph || !paragraphProto.paragraphStyle) {
          return;
        }
        paragraph.paragraphStyle = {
          ...paragraph.paragraphStyle ?? {},
          ...paragraphProto.paragraphStyle
        };
      });
    }
    return shape;
  }
  if (placement.kind === "shape") {
    const shape = slide.shapes.add({
      geometry: placement.geometry,
      position: placement.frame,
      fill: toShapeFillConfig(placement.fill) ?? "none",
      line: toShapeLineConfig(placement.line) ?? {
        style: "solid",
        width: 0,
        fill: toShapeFillConfig(placement.fill) ?? "none"
      }
    });
    if (placement.name) {
      shape.name = placement.name;
    }
    if (placement.borderRadius !== undefined) {
      shape.borderRadius = placement.borderRadius;
    }
    if (placement.shadow !== undefined) {
      shape.shadow = placement.shadow;
    }
    return shape;
  }
  if (placement.kind === "image") {
    const image = slide.images.add({
      ...placement.source,
      contentType: placement.contentType,
      position: placement.frame,
      fit: placement.fit,
      alt: placement.alt,
      geometry: placement.geometry,
      borderRadius: placement.borderRadius,
      crop: placement.crop
    });
    if (placement.name) {
      image.name = placement.name;
    }
    if (placement.lockAspectRatio !== undefined) {
      image.lockAspectRatio = placement.lockAspectRatio;
    }
    if (placement.rotation !== undefined) {
      image.rotation = placement.rotation;
    }
    if (placement.flipHorizontal !== undefined) {
      image.flipHorizontal = placement.flipHorizontal;
    }
    if (placement.flipVertical !== undefined) {
      image.flipVertical = placement.flipVertical;
    }
    return image;
  }
  if (placement.kind === "table") {
    const table = slide.tables.add({
      rows: placement.rows,
      columns: placement.columns,
      left: placement.frame.left,
      top: placement.frame.top,
      width: placement.frame.width,
      height: placement.frame.height,
      values: placement.values
    });
    if (placement.name) {
      table.name = placement.name;
    }
    if (placement.style) {
      table.style = placement.style;
    }
    if (placement.styleOptions) {
      table.styleOptions = placement.styleOptions;
    }
    return table;
  }
  if (placement.kind === "chart") {
    const chart = slide.charts.add(placement.chartType, placement.config);
    chart.position = placement.frame;
    if (placement.name) {
      chart.name = placement.name;
    }
    return chart;
  }
  const stroke = toSolidFillConfig(applyOpacityToColor(placement.stroke, placement.opacity));
  const rule = slide.shapes.add({
    geometry: "rect",
    position: placement.frame,
    fill: stroke,
    line: {
      style: "solid",
      width: 0,
      fill: stroke
    }
  });
  if (placement.name) {
    rule.name = placement.name;
  }
  return rule;
};
var toShapeFillConfig = (fill) => {
  if (fill === undefined) {
    return;
  }
  return new Fill2(fill).toConfig({ preserveProto: false });
};
var toShapeLineConfig = (line) => {
  if (line === undefined) {
    return;
  }
  return new Line4(line).toConfig({ preserveProto: false });
};
var toSolidFillConfig = (color2) => {
  const resolved = new Color4(color2).toConfig();
  if (resolved === undefined) {
    return { type: "none" };
  }
  if (typeof resolved === "string") {
    return resolved;
  }
  return {
    type: "solid",
    color: resolved
  };
};
var attachElementRefs = (node, refsByPath) => {
  const element = refsByPath.get(node.path);
  if (element) {
    node.element = element;
  }
  node.children.forEach((child) => attachElementRefs(child, refsByPath));
};
var buildLayoutElementRef = (element) => {
  const snapshot = element.toSnapshot();
  return {
    aid: snapshot.aid,
    id: snapshot.id,
    kind: snapshot.kind === "image" || snapshot.kind === "table" || snapshot.kind === "chart" ? snapshot.kind : "shape"
  };
};
var applyOpacityToColor = (color2, opacity) => {
  if (opacity === undefined || opacity >= 1) {
    return color2;
  }
  if (opacity <= 0) {
    return "rgba(0, 0, 0, 0)";
  }
  if (typeof color2 === "string") {
    const rgba2 = rgbaStringFromColor(color2, opacity);
    return rgba2 ?? color2;
  }
  if (color2.type === "rgb") {
    const transform = {
      ...color2.transform ?? {},
      opacity
    };
    return {
      ...color2,
      transform
    };
  }
  if (color2.type === "theme") {
    const transform = {
      ...color2.transform ?? {},
      opacity
    };
    return {
      ...color2,
      transform
    };
  }
  return color2;
};
var rgbaStringFromColor = (color2, opacity) => {
  const hexMatch = /^#([0-9a-f]{6}|[0-9a-f]{3})$/i.exec(color2.trim());
  if (hexMatch) {
    const [r, g, b] = rgbFromHex(hexMatch[1] ?? "");
    return `rgba(${r}, ${g}, ${b}, ${opacity})`;
  }
  const rgbMatch = /^rgba?\(\s*(\d{1,3})\s*(?:,\s*|\s+)(\d{1,3})\s*(?:,\s*|\s+)(\d{1,3})(?:\s*(?:\/|,)\s*([\d.]+%?))?\s*\)$/i.exec(color2.trim());
  if (rgbMatch) {
    const r = Number(rgbMatch[1] ?? 0);
    const g = Number(rgbMatch[2] ?? 0);
    const b = Number(rgbMatch[3] ?? 0);
    const alpha = parseAlpha2(rgbMatch[4]) ?? 1;
    return `rgba(${r}, ${g}, ${b}, ${alpha * opacity})`;
  }
  return;
};
var rgbFromHex = (raw) => {
  if (raw.length === 3) {
    const expanded = raw.split("").map((part) => `${part}${part}`).join("");
    return [
      parseInt(expanded.slice(0, 2), 16),
      parseInt(expanded.slice(2, 4), 16),
      parseInt(expanded.slice(4, 6), 16)
    ];
  }
  return [
    parseInt(raw.slice(0, 2), 16),
    parseInt(raw.slice(2, 4), 16),
    parseInt(raw.slice(4, 6), 16)
  ];
};
var parseAlpha2 = (token) => {
  if (!token) {
    return;
  }
  const trimmed = token.trim();
  if (!trimmed) {
    return;
  }
  if (trimmed.endsWith("%")) {
    const percent = Number(trimmed.slice(0, -1));
    if (!Number.isFinite(percent)) {
      return;
    }
    return Math.min(1, Math.max(0, percent / 100));
  }
  const numeric = Number(trimmed);
  if (!Number.isFinite(numeric)) {
    return;
  }
  return Math.min(1, Math.max(0, numeric));
};

// node_modules/@oai/granola/dist/models/presentation/compose/theme.js
class SlideComposeThemeFacade {
  #getPresentation;
  #slideId;
  #callCount = 0;
  constructor(getPresentation, slideId) {
    this.#getPresentation = getPresentation;
    this.#slideId = slideId;
  }
  textStyles(styles) {
    const presentation = this.#getPresentation();
    if (!presentation) {
      throw new Error("slide.theme.textStyles(...) requires a slide that belongs to a presentation.");
    }
    const scope = this.#callCount;
    this.#callCount += 1;
    const scoped = {};
    const result = {};
    for (const [key, config] of Object.entries(styles)) {
      const styleName = [
        "slide",
        normalizeToken(this.#slideId),
        "compose",
        String(scope),
        normalizeToken(key)
      ].join(".");
      scoped[styleName] = config;
      result[key] = styleName;
    }
    presentation.theme.textStyles(scoped);
    return result;
  }
}
var normalizeToken = (value) => {
  const trimmed = value.trim();
  const collapsed = trimmed.replace(/[^a-zA-Z0-9]+/g, "_");
  return collapsed.length > 0 ? collapsed : "token";
};

// node_modules/@oai/granola/dist/models/presentation/presentation-layout-export.js
var PRESENTATION_LAYOUT_EXPORT_SCHEMA = "openai.presentation.layout/v4";
var PRESENTATION_LAYOUT_EXPORT_MIME = "application/vnd.openai.presentation-layout+json";
var SHAPE_GEOMETRY_FROM_PROTO = Object.entries(SHAPE_GEOMETRY_NAME_TO_PROTO).reduce((acc, [name, proto]) => {
  if (acc[proto] === undefined) {
    acc[proto] = name;
  }
  return acc;
}, {});
function buildPresentationLayoutExport(slide, composeRuns) {
  const presentation = slide.getPresentation();
  const composeSourceByAid = new Map;
  const textLayoutById = buildElementTextLayoutSnapshots(slide);
  const protoElementsById = new Map(slide.toProto().elements.map((element) => [element.id ?? "", element]));
  composeRuns.forEach((run, index) => {
    collectComposeSources(run.root, index + 1, composeSourceByAid);
  });
  const elements = slide.elements.items.map((element, index) => buildLayoutElementSnapshot({
    scope: "slide",
    order: index + 1,
    modelElement: element,
    slide,
    presentation,
    protoElement: protoElementsById.get(element.id),
    composeSource: composeSourceByAid.get(resolveLayoutSnapshot(element).aid),
    textLayout: textLayoutById.get(element.id)
  }));
  attachTableCellOwnership(elements);
  const resolvedLayout = presentation && slide.useLayoutId ? presentation.layouts.getById(slide.useLayoutId) : undefined;
  const masterLayout = presentation && resolvedLayout?.parentLayoutId ? presentation.layouts.getById(resolvedLayout.parentLayoutId) : undefined;
  const inheritedLayers = presentation ? buildInheritedLayers(presentation, slide, resolvedLayout, masterLayout) : undefined;
  const theme = buildThemeSnapshot(presentation, elements, inheritedLayers);
  return {
    schema: PRESENTATION_LAYOUT_EXPORT_SCHEMA,
    unit: "px",
    slide: {
      aid: `sl/${slide.id}`,
      id: slide.id,
      slide: slide.index + 1,
      layoutId: resolvedLayout?.id,
      layoutName: normalizeString(resolvedLayout?.name),
      layoutType: normalizeString(resolvedLayout?.type),
      masterLayoutId: masterLayout?.id,
      masterLayoutName: normalizeString(masterLayout?.name),
      backgroundColor: resolveBackgroundColor(slide.toProto().background),
      backgroundImage: resolveBackgroundImage2(slide.toProto().background, presentation),
      frame: snapshotFrame2(slide.frame)
    },
    theme,
    inheritedLayers,
    elements,
    composeRuns: composeRuns.map((run, index) => ({
      index: index + 1,
      frame: snapshotFrame2(run.frame),
      baseUnit: run.baseUnit,
      root: run.root
    }))
  };
}
function createPresentationLayoutExportBlob(slide, composeRuns) {
  const payload = buildPresentationLayoutExport(slide, composeRuns);
  return new Blob([JSON.stringify(payload, null, 2)], {
    type: PRESENTATION_LAYOUT_EXPORT_MIME
  });
}
function collectComposeSources(node, runIndex, sources) {
  if (node.element?.aid) {
    sources.set(node.element.aid, {
      run: runIndex,
      path: node.path
    });
  }
  node.children.forEach((child) => collectComposeSources(child, runIndex, sources));
}
function buildLayoutElementSnapshot(params2) {
  const snapshot = resolveLayoutSnapshot(params2.modelElement);
  const paragraphs = buildParagraphs(params2.modelElement);
  const cells = params2.modelElement instanceof Table2 ? buildTableCellSnapshots(params2.modelElement) : undefined;
  const tableText = cells !== undefined ? buildTableText(cells) : normalizeString(snapshot.preview);
  const text = normalizeString(snapshot.text) ?? tableText;
  const bbox = cells !== undefined ? buildTableBoundsFromCells(cells) ?? buildBbox(snapshot.frame) : buildBbox(snapshot.frame);
  return {
    order: params2.order,
    kind: normalizeElementKind(snapshot.kind),
    scope: params2.scope,
    aid: params2.aid ?? snapshot.aid,
    id: snapshot.id,
    name: normalizeString(snapshot.name),
    bbox,
    composeSource: params2.composeSource,
    geometry: resolveElementGeometry(snapshot, params2.protoElement),
    text,
    textPreview: buildTextPreview(text),
    resolvedFontSize: params2.scope === "slide" ? resolveElementFontSize(params2.modelElement, params2.slide, params2.protoElement) : undefined,
    resolvedTextStyle: params2.scope === "slide" ? resolveElementTextStyle(params2.modelElement, params2.slide, params2.protoElement) : pickPreferredTextStyle(collectResolvedRunStyles(params2.modelElement)) ?? buildResolvedTextStyleSnapshot(params2.modelElement.textStyle),
    textLayout: params2.textLayout,
    paragraphs,
    fillColor: resolveElementFillColor(params2.protoElement),
    lineColor: resolveElementLineColor(params2.protoElement),
    lineWidth: resolveElementLineWidth(params2.protoElement),
    alt: normalizeString(snapshot.alt),
    chartType: normalizeString(snapshot.chartType),
    rows: typeof snapshot.rows === "number" && Number.isFinite(snapshot.rows) ? snapshot.rows : undefined,
    cols: typeof snapshot.cols === "number" && Number.isFinite(snapshot.cols) ? snapshot.cols : undefined,
    contentType: normalizeString(snapshot.contentType),
    prompt: normalizeString(snapshot.prompt),
    isPlaceholder: snapshot.isPlaceholder === true ? true : undefined,
    asset: resolveElementAsset(params2.modelElement),
    fillImage: resolveElementFillImage(params2.protoElement, params2.presentation),
    cells
  };
}
function buildInheritedLayers(presentation, slide, resolvedLayout, masterLayout) {
  const layers = [];
  const pushLayer = (scope, layout) => {
    if (!layout) {
      return;
    }
    const protoElementsById = new Map(layout.toProto().elements.map((element) => [element.id ?? "", element]));
    const elements = layout.elements.map((element, index) => buildLayoutElementSnapshot({
      scope,
      order: index + 1,
      modelElement: element,
      slide,
      presentation,
      protoElement: protoElementsById.get(element.id),
      aid: `template/${scope}/${layout.id}/${element.id}`
    }));
    layers.push({
      scope,
      id: layout.id,
      name: normalizeString(layout.name),
      type: normalizeString(layout.type),
      parentLayoutId: normalizeString(layout.parentLayoutId),
      backgroundColor: resolveBackgroundColor(layout.toProto().background),
      backgroundImage: resolveBackgroundImage2(layout.toProto().background, presentation),
      elements
    });
  };
  pushLayer("layout", resolvedLayout);
  pushLayer("master", masterLayout);
  return layers.length > 0 ? layers : undefined;
}
function buildThemeSnapshot(presentation, elements, inheritedLayers) {
  if (!presentation) {
    return;
  }
  const typefaces = new Set;
  const collectElementTypefaces = (element) => {
    addTypeface(typefaces, element.resolvedTextStyle?.typeface);
    element.paragraphs?.forEach((paragraph) => {
      paragraph.runs.forEach((run) => addTypeface(typefaces, run.typeface));
    });
    element.cells?.forEach((cell) => {
      addTypeface(typefaces, cell.resolvedTextStyle?.typeface);
      cell.paragraphs?.forEach((paragraph) => {
        paragraph.runs.forEach((run) => addTypeface(typefaces, run.typeface));
      });
    });
  };
  elements.forEach(collectElementTypefaces);
  inheritedLayers?.forEach((layer) => {
    layer.elements.forEach(collectElementTypefaces);
  });
  const snapshot = {
    colorSchemeName: normalizeString(presentation.theme.colorScheme.name),
    colors: presentation.theme.hexColorMap,
    typefaces: typefaces.size > 0 ? Array.from(typefaces).sort() : undefined
  };
  return Object.values(snapshot).some((value) => value !== undefined) ? snapshot : undefined;
}
function addTypeface(target, value) {
  const normalized = normalizeString(value);
  if (normalized) {
    target.add(normalized);
  }
}
function resolveLayoutSnapshot(element) {
  return element.toSnapshot();
}
function normalizeElementKind(kind) {
  if (kind === "image" || kind === "table" || kind === "chart") {
    return kind;
  }
  return "shape";
}
function buildBbox(frame) {
  if (!frame) {
    return;
  }
  const left = maybeRound(frame.left);
  const top = maybeRound(frame.top);
  const width = maybeRound(frame.width);
  const height = maybeRound(frame.height);
  if (left === undefined || top === undefined || width === undefined || height === undefined) {
    return;
  }
  return [left, top, width, height];
}
function buildTableBoundsFromCells(cells) {
  const rects = cells.map((cell) => bboxToRect(cell.bbox)).filter((rect) => rect !== undefined);
  if (rects.length === 0) {
    return;
  }
  const left = Math.min(...rects.map((rect) => rect.left));
  const top = Math.min(...rects.map((rect) => rect.top));
  const right = Math.max(...rects.map((rect) => rect.right));
  const bottom = Math.max(...rects.map((rect) => rect.bottom));
  return [
    maybeRound(left) ?? left,
    maybeRound(top) ?? top,
    maybeRound(right - left) ?? right - left,
    maybeRound(bottom - top) ?? bottom - top
  ];
}
function buildTextPreview(value, maxLength = 140) {
  if (!value) {
    return;
  }
  const normalized = value.replace(/\r?\n/g, " | ").trim();
  if (!normalized) {
    return;
  }
  if (normalized.length <= maxLength) {
    return normalized;
  }
  return `${normalized.slice(0, Math.max(1, maxLength - 3))}...`;
}
function resolveElementFontSize(modelElement, slide, protoElement) {
  const runFontSizes = collectResolvedRunStyles(modelElement).map((style) => style.fontSize).filter((value) => typeof value === "number" && Number.isFinite(value));
  if (runFontSizes.length > 0) {
    return maybeRound(Math.max(...runFontSizes));
  }
  if (!protoElement?.paragraphs?.length) {
    return;
  }
  const presentation = slide.getPresentation();
  if (!presentation) {
    return;
  }
  const resolvedStyle = resolveStyles(protoElement, presentation, slide);
  const centipoints = resolvedStyle.fontSize;
  if (typeof centipoints !== "number" || !Number.isFinite(centipoints)) {
    return;
  }
  const autoFitScaleRaw = resolvedStyle.autoFit?.normalAutoFit?.fontScale;
  const autoFitScale = typeof autoFitScaleRaw === "number" && Number.isFinite(autoFitScaleRaw) ? autoFitScaleRaw / 1e5 : 1;
  return maybeRound(centipoints / 100 * (96 / 72) * autoFitScale);
}
function resolveElementTextStyle(element, slide, protoElement) {
  const runStyles = collectResolvedRunStyles(element);
  const preferredStyle = runStyles.find((style) => {
    const fontSize = style.fontSize;
    return typeof fontSize === "number" && Number.isFinite(fontSize);
  });
  if (preferredStyle) {
    return preferredStyle;
  }
  if (!protoElement?.paragraphs?.length) {
    return;
  }
  const presentation = slide.getPresentation();
  if (!presentation) {
    return;
  }
  return buildResolvedTextStyleSnapshot(resolveStyles(protoElement, presentation, slide));
}
function buildElementTextLayoutSnapshots(slide) {
  const presentation = slide.getPresentation();
  if (!presentation) {
    return new Map;
  }
  const themeMap = buildThemeMap(presentation.theme, getMasterSchemeRemap(presentation, slide));
  const ctx = getSharedMeasurementContext();
  const snapshots = new Map;
  slide.elements.items.forEach((element) => {
    const protoElement = element.toProto();
    const elementId = protoElement.id?.trim();
    if (!elementId || !protoElement.paragraphs?.length) {
      return;
    }
    const resolvedStyle = resolveStyles(protoElement, presentation, slide);
    const wrap = resolvedStyle?.wrap === 1 /* TEXT_WRAPPING_TYPE_NONE */ ? false : true;
    const textScaleRaw = resolvedStyle?.autoFit?.normalAutoFit?.fontScale;
    const textScale = typeof textScaleRaw === "number" && Number.isFinite(textScaleRaw) ? textScaleRaw / 1e5 : 1;
    const layout = drawText(protoElement, ctx, themeMap, undefined, {
      mode: "layout",
      resolvedStyle,
      masterDefaults: getMasterLevelDefaults(protoElement, presentation, slide),
      bboxPx: getBBox(protoElement, presentation, slide),
      wrap,
      textScale
    });
    if (!layout) {
      return;
    }
    snapshots.set(elementId, buildTextLayoutSnapshot(layout));
  });
  return snapshots;
}
function buildTextLayoutSnapshot(layout) {
  return {
    lineCount: layout.lines.length,
    lines: layout.lines.map((line, index) => ({
      index: index + 1,
      text: line.segments.map((segment) => segment.text).join("")
    }))
  };
}
function buildParagraphs(owner) {
  const paragraphs = owner.paragraphs.items.map((paragraph, paragraphIndex) => {
    const runs = paragraph.runs.items.map((run, runIndex) => {
      const resolvedStyle = buildResolvedTextStyleSnapshot(resolveParagraphRunStyle(paragraph, run));
      return {
        index: runIndex + 1,
        text: run.text,
        ...resolvedStyle
      };
    }).filter((run) => run.text.length > 0);
    const paragraphText = normalizeString(paragraph.toPlainText());
    if (!paragraphText && runs.length === 0) {
      return;
    }
    return {
      index: paragraphIndex + 1,
      ...paragraphText !== undefined ? { text: paragraphText } : {},
      runs
    };
  }).filter((paragraph) => paragraph !== undefined);
  return paragraphs.length > 0 ? paragraphs : undefined;
}
function collectResolvedRunStyles(owner) {
  return owner.paragraphs.items.flatMap((paragraph) => paragraph.runs.items.map((run) => buildResolvedTextStyleSnapshot(run.resolvedTextStyle)).filter((style) => style !== undefined));
}
function resolveParagraphRunStyle(paragraph, run) {
  return run.resolvedTextStyle ?? run.textStyle ?? paragraph.resolvedTextStyle ?? paragraph.textStyle;
}
function buildTableCellSnapshots(table) {
  const rows = table.rows;
  if (rows.length === 0) {
    return;
  }
  const columnWidths = resolveTableColumnWidths(table);
  const rowHeights = resolveTableRowHeights(table);
  const frame = table.frame;
  const cells = [];
  let y2 = frame?.top ?? 0;
  let index = 0;
  rows.forEach((row, rowIndex2) => {
    let x2 = frame?.left ?? 0;
    const rowHeight = rowHeights[rowIndex2] ?? 0;
    row.cells.forEach((cell, columnIndex2) => {
      const colSpan = Math.max(1, cell.gridSpan ?? 1);
      const rowSpan = Math.max(1, cell.rowSpan ?? 1);
      const cellWidth = sumSpans(columnWidths, columnIndex2, colSpan);
      const cellHeight = sumSpans(rowHeights, rowIndex2, rowSpan);
      const paragraphs = buildParagraphs(cell);
      const styles = collectResolvedRunStyles(cell);
      const resolvedTextStyle = pickPreferredTextStyle(styles);
      const text = normalizeString(cell.value);
      const fillColor = cell.fill.color.toConfig();
      cells.push({
        index: ++index,
        row: rowIndex2 + 1,
        column: columnIndex2 + 1,
        rowSpan: rowSpan > 1 ? rowSpan : undefined,
        colSpan: colSpan > 1 ? colSpan : undefined,
        bbox: frame !== undefined ? buildBbox({
          left: x2,
          top: y2,
          width: cellWidth,
          height: cellHeight
        }) : undefined,
        text,
        textPreview: buildTextPreview(text),
        textDirection: normalizeString(cell.textDirection),
        fillColor,
        resolvedTextStyle,
        paragraphs
      });
      x2 += columnWidths[columnIndex2] ?? 0;
    });
    y2 += rowHeight;
  });
  return cells.length > 0 ? cells : undefined;
}
function buildTableText(cells) {
  if (cells.length === 0) {
    return;
  }
  const rows = new Map;
  cells.forEach((cell) => {
    if (!cell.text) {
      return;
    }
    const row = rows.get(cell.row) ?? [];
    row.push(cell.text);
    rows.set(cell.row, row);
  });
  if (rows.size === 0) {
    return;
  }
  return Array.from(rows.entries()).sort(([left], [right]) => left - right).map(([, values]) => values.join(" | ")).join(`
`);
}
function resolveTableColumnWidths(table) {
  const columnCount = table.columnCount;
  if (columnCount <= 0) {
    return [];
  }
  const widths = table.columnWidths;
  if (table.hasExplicitColumnWidths && widths.length > 0) {
    const normalized = widths.map((width) => Number.isFinite(width) && width > 0 ? width : 1);
    if (normalized.length >= columnCount) {
      return normalized.slice(0, columnCount);
    }
    const padWidth = normalized[normalized.length - 1] ?? 1;
    return normalized.concat(new Array(columnCount - normalized.length).fill(padWidth));
  }
  const frameWidth = table.frame?.width;
  if (frameWidth && Number.isFinite(frameWidth) && frameWidth > 0) {
    const width = frameWidth / columnCount;
    return new Array(columnCount).fill(width);
  }
  return new Array(columnCount).fill(1);
}
function resolveTableRowHeights(table) {
  const rows = table.rows;
  const rowCount = rows.length;
  if (rowCount <= 0) {
    return [];
  }
  const explicitHeights = rows.map((row) => row.height);
  if (explicitHeights.some((height) => height > 0)) {
    const frameHeight2 = table.frame?.height;
    const explicitTotal = explicitHeights.reduce((sum2, height) => sum2 + (height > 0 ? height : 0), 0);
    const missingCount = explicitHeights.filter((height) => height <= 0).length;
    const fallbackHeight = frameHeight2 && missingCount > 0 && frameHeight2 > explicitTotal ? (frameHeight2 - explicitTotal) / missingCount : 1;
    return explicitHeights.map((height) => height > 0 ? height : fallbackHeight);
  }
  const frameHeight = table.frame?.height;
  if (frameHeight && Number.isFinite(frameHeight) && frameHeight > 0) {
    const height = frameHeight / rowCount;
    return new Array(rowCount).fill(height);
  }
  return new Array(rowCount).fill(1);
}
function sumSpans(values, start, span) {
  let total = 0;
  for (let index = start;index < start + span; index += 1) {
    total += values[index] ?? 0;
  }
  return total;
}
function pickPreferredTextStyle(styles) {
  return styles.find((style) => {
    const fontSize = style.fontSize;
    return typeof fontSize === "number" && Number.isFinite(fontSize);
  }) ?? styles[0];
}
function buildResolvedTextStyleSnapshot(style) {
  if (!style) {
    return;
  }
  const snapshot = {
    fontSize: normalizeTextFontSize(style.fontSize),
    typeface: normalizeString(style.typeface),
    color: style.color?.toConfig(),
    bold: style.bold === true ? true : undefined,
    italic: style.italic === true ? true : undefined,
    alignment: mapProtoTextHorizontalAlignment(style.alignment)
  };
  return Object.values(snapshot).some((value) => value !== undefined) ? snapshot : undefined;
}
function resolveElementAsset(element) {
  if (!(element instanceof ImageElement2)) {
    return;
  }
  return buildAssetRef(element.image);
}
function resolveElementFillImage(protoElement, presentation) {
  const fillProto = protoElement?.shape?.fill ?? protoElement?.fill;
  const assetId = fillProto?.imageReference?.id;
  if (!presentation || !assetId) {
    return;
  }
  return buildAssetRef(presentation.images.getById(assetId));
}
function resolveBackgroundColor(background) {
  const fillProto = background?.fill;
  if (!fillProto) {
    return;
  }
  return new Fill2({ type: "proto", proto: fillProto }).color.toConfig();
}
function resolveBackgroundImage2(background, presentation) {
  const assetId = background?.fill?.imageReference?.id;
  if (!presentation || !assetId) {
    return;
  }
  return buildAssetRef(presentation.images.getById(assetId));
}
function buildAssetRef(asset) {
  if (!asset) {
    return;
  }
  const snapshot = {
    assetId: normalizeString(asset.id),
    contentType: normalizeString(asset.contentType),
    uri: normalizeString(asset.uri),
    prompt: normalizeString(asset.prompt),
    byteLength: asset.data.byteLength > 0 ? asset.data.byteLength : undefined
  };
  return Object.values(snapshot).some((value) => value !== undefined) ? snapshot : undefined;
}
function attachTableCellOwnership(elements) {
  const cells = [];
  elements.forEach((element) => {
    if (element.kind !== "table") {
      return;
    }
    element.cells?.forEach((cell) => {
      const bboxRect = bboxToRect(cell.bbox);
      if (!bboxRect) {
        return;
      }
      cells.push({
        cell,
        tableAid: element.aid,
        bboxRect
      });
    });
  });
  if (cells.length === 0) {
    return;
  }
  elements.forEach((element) => {
    if (element.kind === "table") {
      return;
    }
    const elementRect = bboxToRect(element.bbox);
    if (!elementRect) {
      return;
    }
    let bestCell;
    let bestOverlap = 0;
    cells.forEach((cell) => {
      const overlapArea = computeOverlapArea(elementRect, cell.bboxRect);
      if (overlapArea <= 0) {
        return;
      }
      const overlap = overlapArea / rectArea(elementRect);
      if (overlap > bestOverlap) {
        bestOverlap = overlap;
        bestCell = cell;
      }
    });
    if (!bestCell || bestOverlap < 0.5) {
      return;
    }
    element.tableCell = {
      tableAid: bestCell.tableAid,
      cellIndex: bestCell.cell.index,
      row: bestCell.cell.row,
      column: bestCell.cell.column,
      overlap: maybeRound(bestOverlap) ?? bestOverlap
    };
    const ownedElementAids = bestCell.cell.ownedElementAids ?? [];
    ownedElementAids.push(element.aid);
    bestCell.cell.ownedElementAids = ownedElementAids;
  });
}
function bboxToRect(bbox) {
  if (!isBBoxTuple(bbox)) {
    return;
  }
  const [left, top, width, height] = bbox;
  if (!Number.isFinite(left) || !Number.isFinite(top) || !Number.isFinite(width) || !Number.isFinite(height)) {
    return;
  }
  return {
    left,
    top,
    right: left + width,
    bottom: top + height
  };
}
function isBBoxTuple(bbox) {
  return bbox !== undefined && bbox.length >= 4;
}
function computeOverlapArea(left, right) {
  const width = Math.min(left.right, right.right) - Math.max(left.left, right.left);
  const height = Math.min(left.bottom, right.bottom) - Math.max(left.top, right.top);
  if (width <= 0 || height <= 0) {
    return 0;
  }
  return width * height;
}
function rectArea(rect) {
  return Math.max(0, rect.right - rect.left) * Math.max(0, rect.bottom - rect.top);
}
function resolveElementFillColor(protoElement) {
  const fillProto = protoElement?.shape?.fill ?? protoElement?.fill;
  if (!fillProto) {
    return;
  }
  return new Fill2({ type: "proto", proto: fillProto }).color.toConfig();
}
function resolveElementLineColor(element) {
  const lineFill = element?.shape?.line?.fill;
  if (!lineFill) {
    return;
  }
  return new Fill2({ type: "proto", proto: lineFill }).color.toConfig();
}
function resolveElementLineWidth(element) {
  const widthEmu = element?.shape?.line?.widthEmu;
  if (typeof widthEmu !== "number" || !Number.isFinite(widthEmu)) {
    return;
  }
  return maybeRound(pixelsFromEmu(widthEmu));
}
function resolveElementGeometry(snapshot, protoElement) {
  if (typeof snapshot.geometry === "string" && snapshot.geometry.trim().length > 0) {
    return snapshot.geometry;
  }
  const geometry = protoElement?.shape?.geometry;
  if (geometry === undefined) {
    return;
  }
  return SHAPE_GEOMETRY_FROM_PROTO[geometry];
}
function snapshotFrame2(frame) {
  return {
    left: maybeRound(frame.left) ?? 0,
    top: maybeRound(frame.top) ?? 0,
    width: maybeRound(frame.width) ?? 0,
    height: maybeRound(frame.height) ?? 0
  };
}
function normalizeString(value) {
  if (typeof value !== "string") {
    return;
  }
  const trimmed = value.trim();
  return trimmed.length > 0 ? value : undefined;
}
function normalizeTextFontSize(value) {
  if (typeof value !== "number" || !Number.isFinite(value)) {
    return;
  }
  if (value > 200) {
    return maybeRound(value / 100 * (96 / 72));
  }
  return maybeRound(value);
}
function maybeRound(value) {
  if (value === undefined || !Number.isFinite(value)) {
    return;
  }
  return Math.round(value * 100) / 100;
}

// node_modules/@oai/granola/dist/models/presentation/compose/sizing.js
var hug = "hug";
var fill = "fill";
var fixed = (value) => ({
  mode: "fixed",
  value: readPositive2(value, "compose.fixed(value)")
});
var grow = (value = 1) => ({
  mode: "fill",
  value: readPositive2(value, "compose.grow(value)")
});
var wrap = (max4) => ({
  mode: "wrap",
  max: readPositive2(max4, "compose.wrap(max)")
});
var normalizeLayoutSize = (value, fallback = "hug", name = "compose.size") => {
  const resolved = value ?? fallback;
  if (resolved === "hug" || resolved === "fill") {
    return resolved === "hug" ? { mode: "hug" } : { mode: "fill", value: 1 };
  }
  if (typeof resolved === "number") {
    return {
      mode: "fixed",
      value: readPositive2(resolved, `${name}.fixed.value`)
    };
  }
  if (resolved.mode === "fixed") {
    return {
      mode: "fixed",
      value: readPositive2(resolved.value, `${name}.fixed.value`)
    };
  }
  if (resolved.mode === "fill") {
    return {
      mode: "fill",
      value: readPositive2(resolved.value, `${name}.fill.value`)
    };
  }
  if (resolved.mode === "wrap") {
    return {
      mode: "wrap",
      max: readPositive2(resolved.max, `${name}.wrap.max`)
    };
  }
  throw new Error(`${name} must be hug, fill, a positive pixel number, grow(...), fixed(...), or wrap(...).`);
};
var readPositive2 = (value, name) => {
  if (!Number.isFinite(value) || value <= 0) {
    throw new Error(`${name} must be a positive number.`);
  }
  return value;
};

// node_modules/@oai/granola/dist/models/presentation/compose/tracks.js
var auto = "auto";
var fr = (value = 1) => ({
  mode: "fr",
  value: readPositive3(value, "compose.fr(value)")
});
var repeat = (count3, value) => {
  if (!Number.isInteger(count3) || count3 <= 0) {
    throw new Error("compose.repeat(count, value) count must be a positive integer.");
  }
  return Array.from({ length: count3 }, () => value);
};
var normalizeTrack = (value, name = "compose.track") => {
  if (value === "auto") {
    return value;
  }
  if (value.mode === "fr") {
    return {
      mode: "fr",
      value: readPositive3(value.value, `${name}.fr.value`)
    };
  }
  if (value.mode === "fixed") {
    return {
      mode: "fixed",
      value: readPositive3(value.value, `${name}.fixed.value`)
    };
  }
  throw new Error(`${name} must be auto, fr(...), or fixed(...).`);
};
var normalizeTracks = (values, name = "compose.tracks") => {
  if (!Array.isArray(values) || values.length === 0) {
    throw new Error(`${name} must include at least one track.`);
  }
  return values.map((value, index) => normalizeTrack(value, `${name}[${index}]`));
};
var readPositive3 = (value, name) => {
  if (!Number.isFinite(value) || value <= 0) {
    throw new Error(`${name} must be a positive number.`);
  }
  return value;
};

// node_modules/@oai/granola/dist/models/presentation/theme-values.js
var DEFAULT_SPACE_STEP = 4;
var DEFAULT_FONT_SIZE_TOKENS = {
  display: 72,
  subtitle: 48,
  section: 24,
  body: 16,
  caption: 11
};
var resolveSpaceValue = (value, options = {}) => {
  const name = options.name ?? "space";
  const step = readPositiveNumber(options.step ?? DEFAULT_SPACE_STEP, `${name}.step`);
  if (typeof value === "number") {
    return readNonNegativeNumber(value, name);
  }
  const token = value.trim().toLowerCase();
  if (!token.startsWith("s-")) {
    throw new Error(`${name} token must start with "s-".`);
  }
  const scale = token.slice(2).trim();
  return readNonNegativeNumber(Number(scale), `${name} token`) * step;
};
var resolveFontSizeValue = (value, options = {}) => {
  const name = options.name ?? "fontSize";
  if (typeof value === "number") {
    return readPositiveNumber(value, name);
  }
  const token = value.trim().toLowerCase();
  if (!token.startsWith("text-")) {
    throw new Error(`${name} token must start with "text-".`);
  }
  const key = token.slice(5).trim();
  if (key.length === 0) {
    throw new Error(`${name} token must include a value after "text-".`);
  }
  const fontSizeTokens = options.fontSizeTokens ?? DEFAULT_FONT_SIZE_TOKENS;
  const mapped = fontSizeTokens[key];
  if (mapped !== undefined) {
    return readPositiveNumber(mapped, `${name} token`);
  }
  const parsed = Number(key);
  if (Number.isFinite(parsed)) {
    return readPositiveNumber(parsed, `${name} token`);
  }
  const available = Object.keys(fontSizeTokens).sort();
  throw new Error(`${name} token "text-${key}" is unknown. Available text tokens: ${available.join(", ")}`);
};
var resolveTokenizedTextStyleConfig = (config, options = {}) => {
  const { fontSize, ...rest } = config;
  const resolved = { ...rest };
  if (fontSize !== undefined) {
    resolved.fontSize = resolveFontSizeValue(fontSize, {
      fontSizeTokens: options.fontSizeTokens,
      name: options.name ? `${options.name}.fontSize` : "fontSize"
    });
  }
  return resolved;
};
var readNonNegativeNumber = (value, name) => {
  if (!Number.isFinite(value) || value < 0) {
    throw new Error(`${name} must be a non-negative number.`);
  }
  return value;
};
var readPositiveNumber = (value, name) => {
  if (!Number.isFinite(value) || value <= 0) {
    throw new Error(`${name} must be a positive number.`);
  }
  return value;
};

// node_modules/@oai/granola/dist/models/presentation/compose/nodes.js
var DEFAULT_PADDING = {
  top: 0,
  right: 0,
  bottom: 0,
  left: 0
};
var text = (value, options = {}) => ({
  kind: "text",
  value,
  name: trimName(options.name),
  style: options.style,
  transform: options.transform ?? "none",
  width: normalizeLayoutSize(options.width, "hug", "compose.text.width"),
  height: normalizeLayoutSize(options.height, "hug", "compose.text.height"),
  columnSpan: readSpan(options.columnSpan, "compose.text.columnSpan"),
  rowSpan: readSpan(options.rowSpan, "compose.text.rowSpan")
});
var rule = (options) => {
  const weight = readPositive4(options.weight ?? 1, "compose.rule.weight");
  const opacity = readOptionalUnit(options.opacity, "compose.rule.opacity");
  return {
    kind: "rule",
    name: trimName(options.name),
    stroke: options.stroke,
    opacity,
    weight,
    width: normalizeLayoutSize(options.width, "fill", "compose.rule.width"),
    height: normalizeLayoutSize(options.height ?? fixed(weight), "hug", "compose.rule.height"),
    columnSpan: readSpan(options.columnSpan, "compose.rule.columnSpan"),
    rowSpan: readSpan(options.rowSpan, "compose.rule.rowSpan")
  };
};
var shape = (options = {}) => ({
  kind: "shape",
  name: trimName(options.name),
  geometry: options.geometry ?? "rect",
  fill: options.fill,
  line: options.line,
  borderRadius: options.borderRadius,
  shadow: options.shadow,
  width: normalizeLayoutSize(options.width, fixed(24), "compose.shape.width"),
  height: normalizeLayoutSize(options.height, fixed(24), "compose.shape.height"),
  columnSpan: readSpan(options.columnSpan, "compose.shape.columnSpan"),
  rowSpan: readSpan(options.rowSpan, "compose.shape.rowSpan")
});
var image = (options) => ({
  kind: "image",
  name: trimName(options.name),
  source: normalizeImageSource(options),
  contentType: trimName(options.contentType),
  fit: options.fit,
  alt: options.alt,
  geometry: options.geometry,
  borderRadius: options.borderRadius,
  crop: options.crop,
  rotation: readOptionalNumber(options.rotation, "compose.image.rotation"),
  flipHorizontal: readOptionalBoolean(options.flipHorizontal, "compose.image.flipHorizontal"),
  flipVertical: readOptionalBoolean(options.flipVertical, "compose.image.flipVertical"),
  lockAspectRatio: readOptionalBoolean(options.lockAspectRatio, "compose.image.lockAspectRatio"),
  width: normalizeLayoutSize(options.width, "fill", "compose.image.width"),
  height: normalizeLayoutSize(options.height, "fill", "compose.image.height"),
  columnSpan: readSpan(options.columnSpan, "compose.image.columnSpan"),
  rowSpan: readSpan(options.rowSpan, "compose.image.rowSpan")
});
var table = (options) => ({
  kind: "table",
  name: trimName(options.name),
  rows: readPositiveInteger(options.rows, "compose.table.rows"),
  columns: readPositiveInteger(options.columns, "compose.table.columns"),
  values: options.values,
  style: trimName(options.style),
  styleOptions: options.styleOptions,
  width: normalizeLayoutSize(options.width, "fill", "compose.table.width"),
  height: normalizeLayoutSize(options.height, "fill", "compose.table.height"),
  columnSpan: readSpan(options.columnSpan, "compose.table.columnSpan"),
  rowSpan: readSpan(options.rowSpan, "compose.table.rowSpan")
});
var chart = (options) => ({
  kind: "chart",
  name: trimName(options.name),
  chartType: options.chartType,
  config: options.config,
  width: normalizeLayoutSize(options.width, "fill", "compose.chart.width"),
  height: normalizeLayoutSize(options.height, "fill", "compose.chart.height"),
  columnSpan: readSpan(options.columnSpan, "compose.chart.columnSpan"),
  rowSpan: readSpan(options.rowSpan, "compose.chart.rowSpan")
});
var row = (options = {}, children = []) => ({
  kind: "row",
  name: trimName(options.name),
  width: normalizeLayoutSize(options.width, "hug", "compose.row.width"),
  height: normalizeLayoutSize(options.height, "hug", "compose.row.height"),
  gap: readSpace(options.gap ?? 0, "compose.row.gap"),
  align: readAxisAlign(options.align ?? "start", "compose.row.align"),
  justify: readAxisJustify(options.justify ?? "start", "compose.row.justify"),
  padding: normalizePadding(options.padding),
  children: [...children],
  columnSpan: readSpan(options.columnSpan, "compose.row.columnSpan"),
  rowSpan: readSpan(options.rowSpan, "compose.row.rowSpan")
});
var column = (options = {}, children = []) => ({
  kind: "column",
  name: trimName(options.name),
  width: normalizeLayoutSize(options.width, "hug", "compose.column.width"),
  height: normalizeLayoutSize(options.height, "hug", "compose.column.height"),
  gap: readSpace(options.gap ?? 0, "compose.column.gap"),
  align: readAxisAlign(options.align ?? "start", "compose.column.align"),
  justify: readAxisJustify(options.justify ?? "start", "compose.column.justify"),
  padding: normalizePadding(options.padding),
  children: [...children],
  columnSpan: readSpan(options.columnSpan, "compose.column.columnSpan"),
  rowSpan: readSpan(options.rowSpan, "compose.column.rowSpan")
});
var grid = (options, children = []) => ({
  kind: "grid",
  name: trimName(options.name),
  width: normalizeLayoutSize(options.width, "hug", "compose.grid.width"),
  height: normalizeLayoutSize(options.height, "hug", "compose.grid.height"),
  columns: normalizeTracks(options.columns, "compose.grid.columns"),
  rows: options.rows ? normalizeTracks(options.rows, "compose.grid.rows") : undefined,
  autoRows: options.autoRows ?? "auto",
  columnGap: readSpace(options.columnGap ?? 0, "compose.grid.columnGap"),
  rowGap: readSpace(options.rowGap ?? 0, "compose.grid.rowGap"),
  alignItems: readAxisAlign(options.alignItems ?? "stretch", "compose.grid.alignItems"),
  justifyItems: readAxisAlign(options.justifyItems ?? "stretch", "compose.grid.justifyItems"),
  padding: normalizePadding(options.padding),
  children: [...children],
  columnSpan: readSpan(options.columnSpan, "compose.grid.columnSpan"),
  rowSpan: readSpan(options.rowSpan, "compose.grid.rowSpan")
});
var panel = (options = {}, child) => ({
  kind: "panel",
  name: trimName(options.name),
  fill: options.fill ?? "white",
  line: options.line ?? {
    style: "solid",
    width: 1,
    fill: "#d7dee7"
  },
  borderRadius: options.borderRadius ?? "rounded-lg",
  shadow: options.shadow,
  align: readAxisAlign(options.align ?? "start", "compose.panel.align"),
  justify: readAxisAlign(options.justify ?? "start", "compose.panel.justify"),
  width: normalizeLayoutSize(options.width, "fill", "compose.panel.width"),
  height: normalizeLayoutSize(options.height, "hug", "compose.panel.height"),
  padding: normalizePadding(options.padding ?? 14),
  child,
  columnSpan: readSpan(options.columnSpan, "compose.panel.columnSpan"),
  rowSpan: readSpan(options.rowSpan, "compose.panel.rowSpan")
});
var card = panel;
var layers = (options = {}, children = []) => ({
  kind: "layers",
  name: trimName(options.name),
  width: normalizeLayoutSize(options.width, "hug", "compose.layers.width"),
  height: normalizeLayoutSize(options.height, "hug", "compose.layers.height"),
  alignItems: readAxisAlign(options.alignItems ?? "stretch", "compose.layers.alignItems"),
  justifyItems: readAxisAlign(options.justifyItems ?? "stretch", "compose.layers.justifyItems"),
  padding: normalizePadding(options.padding),
  children: [...children],
  columnSpan: readSpan(options.columnSpan, "compose.layers.columnSpan"),
  rowSpan: readSpan(options.rowSpan, "compose.layers.rowSpan")
});
var normalizePadding = (value) => {
  if (value === undefined) {
    return { ...DEFAULT_PADDING };
  }
  if (typeof value === "number" || typeof value === "string") {
    const all2 = readSpace(value, "compose.padding");
    return { top: all2, right: all2, bottom: all2, left: all2 };
  }
  const x2 = readSpace(value.x ?? 0, "compose.padding.x");
  const y2 = readSpace(value.y ?? 0, "compose.padding.y");
  const top = readSpace(value.top ?? y2, "compose.padding.top");
  const right = readSpace(value.right ?? x2, "compose.padding.right");
  const bottom = readSpace(value.bottom ?? y2, "compose.padding.bottom");
  const left = readSpace(value.left ?? x2, "compose.padding.left");
  return { top, right, bottom, left };
};
var trimName = (value) => {
  if (value === undefined) {
    return;
  }
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : undefined;
};
var readAxisAlign = (value, name) => {
  if (value === "start" || value === "center" || value === "end" || value === "stretch") {
    return value;
  }
  throw new Error(`${name} must be start, center, end, or stretch.`);
};
var readAxisJustify = (value, name) => {
  if (value === "start" || value === "center" || value === "end" || value === "between") {
    return value;
  }
  throw new Error(`${name} must be start, center, end, or between.`);
};
var readSpace = (value, name) => resolveSpaceValue(value, { name });
var readPositive4 = (value, name) => {
  if (!Number.isFinite(value) || value <= 0) {
    throw new Error(`${name} must be a positive number.`);
  }
  return value;
};
var readPositiveInteger = (value, name) => {
  if (!Number.isFinite(value) || value <= 0 || !Number.isInteger(value)) {
    throw new Error(`${name} must be a positive integer.`);
  }
  return value;
};
var readSpan = (value, name) => {
  if (value === undefined) {
    return 1;
  }
  return readPositiveInteger(value, name);
};
var readOptionalUnit = (value, name) => {
  if (value === undefined) {
    return;
  }
  if (!Number.isFinite(value) || value < 0 || value > 1) {
    throw new Error(`${name} must be between 0 and 1.`);
  }
  return value;
};
var readOptionalBoolean = (value, name) => {
  if (value === undefined) {
    return;
  }
  if (typeof value !== "boolean") {
    throw new Error(`${name} must be a boolean.`);
  }
  return value;
};
var readOptionalNumber = (value, name) => {
  if (value === undefined) {
    return;
  }
  if (!Number.isFinite(value)) {
    throw new Error(`${name} must be a finite number.`);
  }
  return value;
};
var normalizeImageSource = (options) => {
  if ("path" in options) {
    return { path: options.path };
  }
  if ("dataUrl" in options) {
    return { dataUrl: options.dataUrl };
  }
  if ("blob" in options) {
    return { blob: options.blob };
  }
  if ("uri" in options) {
    return { uri: options.uri };
  }
  return { prompt: options.prompt };
};

// node_modules/@oai/granola/dist/presentation-jsx/types.js
var PRESENTATION_JSX_ELEMENT = Symbol.for("@oai/granola/presentation-jsx.element");
var Fragment = Symbol.for("@oai/granola/presentation-jsx.fragment");
function isPresentationJsxElement(value) {
  return typeof value === "object" && value !== null && "$$type" in value && value.$$type === PRESENTATION_JSX_ELEMENT;
}

// node_modules/@oai/granola/dist/presentation-jsx/html/tags.js
var SEMANTIC_CONTAINER_TAGS = [
  "div",
  "section",
  "article",
  "aside",
  "header",
  "footer",
  "figure",
  "nav",
  "stack",
  "vstack",
  "hstack",
  "surface"
];
var SEMANTIC_INLINE_TAGS = [
  "span",
  "em",
  "u",
  "a",
  "br"
];
var SEMANTIC_LIST_TAGS = ["ul", "ol", "li"];
var SEMANTIC_MEDIA_TAGS = ["img", "hr"];
var semanticContainerTagSet = new Set(SEMANTIC_CONTAINER_TAGS);
var semanticInlineTagSet = new Set(SEMANTIC_INLINE_TAGS);
var semanticListTagSet = new Set(SEMANTIC_LIST_TAGS);
var semanticMediaTagSet = new Set(SEMANTIC_MEDIA_TAGS);
var semanticHtmlTagSet = new Set([
  ...SEMANTIC_CONTAINER_TAGS,
  ...SEMANTIC_INLINE_TAGS,
  ...SEMANTIC_LIST_TAGS,
  ...SEMANTIC_MEDIA_TAGS
]);
function isSemanticContainerTag(value) {
  return semanticContainerTagSet.has(value);
}
function isSemanticInlineTag(value) {
  return semanticInlineTagSet.has(value);
}
function isSemanticHtmlTag(value) {
  return semanticHtmlTagSet.has(value);
}

// node_modules/@oai/granola/dist/presentation-jsx/html/text.js
var DEFAULT_SEMANTIC_TEXT_STYLE = {
  fontSize: 14,
  lineSpacing: 1.3
};
var paragraphPropKeys = new Set([
  "bulletCharacter",
  "marginLeft",
  "indent",
  "spaceBefore",
  "spaceAfter",
  "styleId",
  "paragraphStyle"
]);
var listItemPropKeys = new Set([
  ...paragraphPropKeys,
  "children",
  "className",
  "textStyle"
]);
var inlineTextPropKeys = new Set([
  "children",
  "className",
  "textStyle",
  "href",
  "link",
  "underline"
]);
function mergeComposeTextStyle(contextTag, defaultStyle, explicitStyle, className) {
  const classStyle = className ? parseTailwindTextClassName(className) : null;
  const normalizedExplicitStyle = normalizeComposeTextStyleRef(explicitStyle);
  if (typeof normalizedExplicitStyle === "string") {
    if (classStyle) {
      throw new Error(`${contextTag} cannot combine a string style reference with \`className\`. Use an object style instead.`);
    }
    return normalizedExplicitStyle;
  }
  const merged = mergeTextStyleConfigs(defaultStyle, classStyle ?? undefined, normalizedExplicitStyle);
  if (!merged) {
    return;
  }
  if (className) {
    merged.className = mergeClassNames(merged.className, className);
  }
  return merged;
}
function mergeInlineTextStyle(explicitStyle, className) {
  const classStyle = className ? parseTailwindTextClassName(className) : null;
  const next = mergeRunStyles(classStyle ? toRunStyleInput(classStyle) : undefined, explicitStyle);
  return next ?? undefined;
}
function isImplicitTextEntry(value) {
  if (value === null || value === undefined || typeof value === "boolean" || typeof value === "string" || typeof value === "number") {
    return true;
  }
  if (!isPresentationJsxElement(value) || typeof value.type !== "string") {
    return false;
  }
  return value.type === "paragraph" || value.type === "run" || isSemanticInlineTag(value.type);
}
function lowerSemanticTextValue(children, options, helpers) {
  const paragraphs = lowerStructuredTextChildren(children, options, helpers);
  return collapseParagraphValues(paragraphs);
}
function lowerSemanticListValue(listTag, children, props, helpers) {
  const entries = flattenTextEntries(children, helpers);
  const items = entries.filter((entry) => !helpers.isFormattingWhitespace(entry));
  const paragraphs = [];
  const listOptions = readParagraphOptions(props);
  items.forEach((entry, index) => {
    if (!isPresentationJsxElement(entry) || entry.type !== "li") {
      throw new Error(`<${listTag}> only accepts <li> children.`);
    }
    validateKeys("li", entry.props, listItemPropKeys);
    const itemParagraphs = lowerStructuredTextChildren(helpers.toChildArray(entry.props["children"]), {
      contextTag: "<li>"
    }, helpers);
    const itemOptions = mergeParagraphOptions(listOptions, readParagraphOptions(entry.props));
    const bulletCharacter = entry.props["bulletCharacter"] ?? props["bulletCharacter"] ?? (listTag === "ul" ? "•" : undefined);
    const numberedParagraphs = listTag === "ol" ? prefixOrderedListParagraphs(itemParagraphs, index + 1) : itemParagraphs;
    numberedParagraphs.forEach((paragraph, paragraphIndex) => {
      const merged = listTag === "ul" ? applyParagraphOptions(paragraph, {
        ...itemOptions,
        bulletCharacter: paragraphIndex === 0 ? bulletCharacter : itemOptions.bulletCharacter
      }) : applyParagraphOptions(paragraph, itemOptions);
      paragraphs.push(merged);
    });
  });
  return paragraphs;
}
function lowerStructuredTextChildren(children, options, helpers) {
  const entries = flattenTextEntries(children, helpers);
  const paragraphs = entries.filter((entry) => isPresentationJsxElement(entry) && entry.type === "paragraph");
  if (paragraphs.length > 0) {
    const mixed = entries.some((entry) => !(isPresentationJsxElement(entry) && entry.type === "paragraph" || helpers.isFormattingWhitespace(entry)));
    if (mixed) {
      throw new Error(`${options.contextTag} cannot mix raw text or <run> siblings with explicit <paragraph> children.`);
    }
    return paragraphs.map((paragraph) => applyParagraphOptions(lowerExplicitParagraph(paragraph, helpers), options.paragraphOptions));
  }
  const builders = buildParagraphsFromInlineEntries(entries, options.contextTag, helpers);
  return builders.map((builder) => applyParagraphOptions(builder.runs.length > 0 ? builder.runs : [""], options.paragraphOptions));
}
function buildParagraphsFromInlineEntries(entries, contextTag, helpers) {
  const paragraphs = [{ runs: [] }];
  const ensureParagraph = () => {
    const current = paragraphs[paragraphs.length - 1];
    if (current) {
      return current;
    }
    const next = { runs: [] };
    paragraphs.push(next);
    return next;
  };
  const pushParagraph = () => {
    paragraphs.push({ runs: [] });
  };
  const appendRun = (text2, state, existing) => {
    const target = ensureParagraph();
    const mergedRun = existing ? mergeRunInput(existing, state) : state.textStyle || state.link ? {
      run: text2,
      textStyle: state.textStyle,
      link: state.link
    } : text2;
    target.runs.push(mergedRun);
  };
  const visit = (value, state) => {
    if (Array.isArray(value)) {
      value.forEach((entry) => visit(entry, state));
      return;
    }
    if (value === null || value === undefined || typeof value === "boolean" || helpers.isFormattingWhitespace(value)) {
      return;
    }
    if (typeof value === "string" || typeof value === "number") {
      const normalized = typeof value === "number" ? String(value) : normalizeInlineTextFragment(value);
      if (normalized.length > 0) {
        appendRun(normalized, state);
      }
      return;
    }
    if (!isPresentationJsxElement(value)) {
      throw new Error(`${contextTag} contains an unsupported text child.`);
    }
    if (value.type === Fragment) {
      helpers.toChildArray(value.props["children"]).forEach((entry) => visit(entry, state));
      return;
    }
    if (typeof value.type !== "string") {
      throw new Error(`${contextTag} contains an unsupported text child.`);
    }
    if (value.type === "run") {
      const lowered = helpers.lowerRun(value);
      appendRun(lowered.run, state, lowered);
      return;
    }
    if (value.type === "br") {
      pushParagraph();
      return;
    }
    if (value.type === "paragraph") {
      throw new Error(`${contextTag} does not accept nested <paragraph> children in inline text mode.`);
    }
    if (value.type === "small") {
      const nextState = mergeInlineState(state, {
        textStyle: { fontSize: "11px" }
      });
      helpers.toChildArray(value.props["children"]).forEach((entry) => visit(entry, nextState));
      return;
    }
    if (isSemanticInlineTag(value.type)) {
      validateKeys(value.type, value.props, inlineTextPropKeys);
      const nextState = mergeInlineState(state, readInlineState(value.type, value.props));
      helpers.toChildArray(value.props["children"]).forEach((entry) => visit(entry, nextState));
      return;
    }
    throw new Error(`${contextTag} only accepts raw text, inline semantic tags, <run>, <paragraph>, and fragments.`);
  };
  entries.forEach((entry) => visit(entry, {}));
  while (paragraphs.length > 1 && isEmptyParagraph(paragraphs[paragraphs.length - 1])) {
    paragraphs.pop();
  }
  return paragraphs.length > 0 ? paragraphs : [{ runs: [""] }];
}
function lowerExplicitParagraph(element, helpers) {
  const paragraphProps = element.props;
  const runs = [];
  flattenTextEntries(helpers.toChildArray(paragraphProps["children"]), helpers).forEach((entry) => {
    if (entry === null || entry === undefined || typeof entry === "boolean" || helpers.isFormattingWhitespace(entry)) {
      return;
    }
    if (typeof entry === "string" || typeof entry === "number") {
      runs.push(entry);
      return;
    }
    if (!isPresentationJsxElement(entry) || entry.type !== "run") {
      throw new Error("<paragraph> only accepts raw text, <run>, and fragments.");
    }
    runs.push(helpers.lowerRun(entry));
  });
  const paragraphOptions = readParagraphOptions(paragraphProps);
  const paragraphRuns = runs.length > 0 ? runs : [""];
  if (Object.keys(paragraphOptions).length === 0) {
    return paragraphRuns;
  }
  return {
    ...paragraphOptions,
    runs: paragraphRuns
  };
}
function flattenTextEntries(children, helpers) {
  const entries = [];
  children.forEach((child) => {
    if (Array.isArray(child)) {
      entries.push(...flattenTextEntries(child, helpers));
      return;
    }
    if (isPresentationJsxElement(child) && child.type === Fragment) {
      entries.push(...flattenTextEntries(helpers.toChildArray(child.props["children"]), helpers));
      return;
    }
    entries.push(child);
  });
  return entries;
}
function collapseParagraphValues(paragraphs) {
  if (paragraphs.length === 0) {
    return "";
  }
  if (paragraphs.length === 1) {
    const first = paragraphs[0];
    if (first === undefined) {
      return "";
    }
    if (Array.isArray(first) && first.every((entry) => typeof entry === "string")) {
      return first.join("");
    }
    return first;
  }
  return paragraphs;
}
function mergeInlineState(base, next) {
  return {
    textStyle: mergeRunStyles(base.textStyle, next.textStyle),
    link: next.link ?? base.link
  };
}
function mergeRunInput(run, state) {
  return {
    ...run,
    textStyle: mergeRunStyles(state.textStyle, run.textStyle),
    link: run.link ?? state.link
  };
}
function mergeRunStyles(base, override) {
  if (!base && !override) {
    return;
  }
  return {
    ...base ?? {},
    ...override ?? {}
  };
}
function mergeTextStyleConfigs(...configs) {
  let merged;
  configs.forEach((config) => {
    if (!config) {
      return;
    }
    merged = {
      ...merged ?? {},
      ...config,
      insets: {
        ...merged?.insets ?? {},
        ...config.insets ?? {}
      }
    };
  });
  return merged;
}
function readInlineState(tag, props) {
  const classStyle = mergeInlineTextStyle(readInlineTextStyle(props["textStyle"]), readOptionalString(props["className"], `<${tag}> className`));
  const explicitLink = readLinkInput(tag, props);
  if (tag === "em") {
    return {
      textStyle: mergeRunStyles(classStyle, { italic: true }),
      link: explicitLink
    };
  }
  if (tag === "u") {
    return {
      textStyle: mergeRunStyles(classStyle, {
        underline: readOptionalString(props["underline"], "<u> underline") ?? "sng"
      }),
      link: explicitLink
    };
  }
  if (tag === "a") {
    return {
      textStyle: mergeRunStyles(classStyle, {
        underline: readOptionalString(props["underline"], "<a> underline") ?? "sng",
        color: classStyle?.color ?? readInlineTextStyle(props["textStyle"])?.color ?? "#2563EB"
      }),
      link: explicitLink ?? {
        uri: readHref(tag, props),
        isExternal: true
      }
    };
  }
  return {
    textStyle: classStyle,
    link: explicitLink
  };
}
function readHref(tag, props) {
  const href = props["href"];
  if (typeof href !== "string" || href.trim().length === 0) {
    throw new Error(`<${tag}> requires a non-empty \`href\` string when \`link\` is not provided.`);
  }
  return href;
}
function readLinkInput(tag, props) {
  const link2 = props["link"];
  if (link2 === undefined) {
    return;
  }
  if (typeof link2 !== "object" || link2 === null) {
    throw new Error(`<${tag}> link must be a hyperlink config object.`);
  }
  return link2;
}
function readInlineTextStyle(value) {
  if (value === undefined) {
    return;
  }
  if (typeof value === "string") {
    if (!looksLikeTextStyleDeclaration(value)) {
      throw new Error("Inline textStyle strings must use declaration syntax like `color: #2563EB; weight: 700`.");
    }
    return toRunStyleInput(parseTextStyleString(value));
  }
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    throw new Error("Inline textStyle must be an object.");
  }
  return value;
}
function toRunStyleInput(style) {
  if (!style) {
    return;
  }
  const next = {};
  if (style.bold !== undefined) {
    next.bold = style.bold;
  }
  if (style.italic !== undefined) {
    next.italic = style.italic;
  }
  if (style.underline !== undefined) {
    next.underline = style.underline;
  }
  if (style.fontSize !== undefined) {
    next.fontSize = `${style.fontSize}px`;
  }
  if (style.color !== undefined) {
    next.color = style.color;
  } else if (style.fill !== undefined) {
    next.color = style.fill;
  }
  return Object.keys(next).length > 0 ? next : undefined;
}
function prefixOrderedListParagraphs(paragraphs, index) {
  const prefix = `${index}. `;
  return paragraphs.map((paragraph, paragraphIndex) => paragraphIndex === 0 ? prependParagraphPrefix(paragraph, prefix) : paragraph);
}
function prependParagraphPrefix(paragraph, prefix) {
  if (Array.isArray(paragraph)) {
    if (paragraph.length === 0) {
      return [prefix];
    }
    const [first2, ...rest2] = paragraph;
    if (first2 === undefined) {
      return [prefix, ...rest2];
    }
    if (typeof first2 === "string" || typeof first2 === "number") {
      return [`${prefix}${String(first2)}`, ...rest2];
    }
    return [{ ...first2, run: `${prefix}${first2.run}` }, ...rest2];
  }
  const runs = paragraph.runs ?? [];
  if (runs.length === 0) {
    return {
      ...paragraph,
      runs: [prefix]
    };
  }
  const [first, ...rest] = runs;
  if (first === undefined) {
    return {
      ...paragraph,
      runs: [prefix, ...rest]
    };
  }
  return {
    ...paragraph,
    runs: [
      typeof first === "string" || typeof first === "number" ? `${prefix}${String(first)}` : { ...first, run: `${prefix}${first.run}` },
      ...rest
    ]
  };
}
function applyParagraphOptions(paragraph, options) {
  if (!options || Object.keys(options).length === 0) {
    return paragraph;
  }
  if (Array.isArray(paragraph)) {
    return {
      ...options,
      runs: paragraph.length > 0 ? paragraph : [""]
    };
  }
  return {
    ...options,
    ...paragraph,
    paragraphStyle: {
      ...options.paragraphStyle ?? {},
      ...paragraph.paragraphStyle ?? {}
    },
    runs: paragraph.runs ?? [""]
  };
}
function mergeParagraphOptions(base, override) {
  return {
    ...base,
    ...override,
    paragraphStyle: {
      ...base.paragraphStyle ?? {},
      ...override.paragraphStyle ?? {}
    }
  };
}
function readParagraphOptions(props) {
  const next = {};
  Object.entries(props).forEach(([key, value]) => {
    if (!paragraphPropKeys.has(key) || value === undefined) {
      return;
    }
    next[key] = value;
  });
  return next;
}
function validateKeys(tag, props, allowedKeys) {
  Object.keys(props).forEach((key) => {
    if (!allowedKeys.has(key)) {
      throw new Error(`<${tag}> does not support the \`${key}\` prop.`);
    }
  });
}
function readOptionalString(value, label) {
  if (value === undefined) {
    return;
  }
  if (typeof value !== "string") {
    throw new Error(`${label} must be a string.`);
  }
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : undefined;
}
function mergeClassNames(existing, next) {
  return existing ? `${existing} ${next}` : next;
}
function normalizeInlineTextFragment(value) {
  if (value.length === 0) {
    return value;
  }
  let normalized = value.replace(/\r?\n[\t ]*/g, " ");
  if (/^\s*\r?\n/.test(value)) {
    normalized = normalized.trimStart();
  }
  if (/\r?\n[\t ]*$/.test(value)) {
    normalized = normalized.trimEnd();
  }
  return normalized;
}
function isEmptyParagraph(paragraph) {
  return !paragraph || paragraph.runs.length === 0;
}

// node_modules/@oai/granola/dist/presentation-jsx/html/lower.js
var containerKeys = new Set([
  "name",
  "id",
  "className",
  "children",
  "ref",
  "layout",
  "display",
  "contentLayout",
  "surface",
  "width",
  "height",
  "gap",
  "align",
  "justify",
  "padding",
  "columns",
  "rows",
  "autoRows",
  "columnGap",
  "rowGap",
  "alignItems",
  "justifyItems",
  "columnSpan",
  "rowSpan",
  "fill",
  "line",
  "borderRadius",
  "shadow"
]);
var textBlockKeys = new Set([
  "name",
  "id",
  "className",
  "children",
  "ref",
  "width",
  "height",
  "columnSpan",
  "rowSpan",
  "style",
  "transform",
  "bulletCharacter",
  "marginLeft",
  "indent",
  "spaceBefore",
  "spaceAfter",
  "styleId",
  "paragraphStyle"
]);
var mediaImageKeys = new Set([
  "name",
  "id",
  "className",
  "children",
  "ref",
  "width",
  "height",
  "columnSpan",
  "rowSpan",
  "src",
  "path",
  "dataUrl",
  "blob",
  "uri",
  "prompt",
  "contentType",
  "fit",
  "alt",
  "geometry",
  "borderRadius",
  "crop",
  "rotation",
  "flipHorizontal",
  "flipVertical",
  "lockAspectRatio"
]);
var ruleKeys = new Set([
  "name",
  "id",
  "children",
  "ref",
  "width",
  "height",
  "columnSpan",
  "rowSpan",
  "stroke",
  "opacity",
  "weight"
]);
function lowerSemanticHtmlElement(element, context) {
  if (typeof element.type !== "string" || !isSemanticHtmlTag(element.type)) {
    throw new Error("Unsupported semantic presentation JSX tag.");
  }
  if (isSemanticContainerTag(element.type)) {
    return lowerSemanticContainer(element.type, element, context);
  }
  if (element.type === "ul" || element.type === "ol") {
    return lowerSemanticListBlock(element.type, element, context);
  }
  if (element.type === "li") {
    throw new Error("<li> is only valid inside <ul> or <ol>.");
  }
  if (element.type === "img") {
    return lowerSemanticImage(element, context);
  }
  if (element.type === "hr") {
    return lowerSemanticRule(element, context);
  }
  throw new Error(`Unsupported semantic presentation JSX tag <${element.type}>.`);
}
function lowerSemanticContainer(tag, element, context) {
  validateProps(tag, element.props, containerKeys);
  const children = lowerSemanticContainerChildren(context.toChildArray(element.props["children"]), tag, context);
  const layout = resolveContainerLayout(tag, element.props);
  const visual = readSurfaceProps(element.props);
  const shouldWrapInPanel = layout === "panel" || element.props["surface"] === true || hasSurfaceProps(visual);
  if (!shouldWrapInPanel) {
    const node2 = buildLayoutNode(layout, {
      name: readNodeName(element.props),
      width: readDimension(element.props["width"], "width") ?? "fill",
      height: readDimension(element.props["height"], "height"),
      gap: element.props["gap"],
      align: element.props["align"],
      justify: element.props["justify"],
      padding: element.props["padding"],
      columns: element.props["columns"],
      rows: element.props["rows"],
      autoRows: element.props["autoRows"],
      columnGap: element.props["columnGap"],
      rowGap: element.props["rowGap"],
      alignItems: element.props["alignItems"],
      justifyItems: element.props["justifyItems"],
      columnSpan: element.props["columnSpan"],
      rowSpan: element.props["rowSpan"]
    }, children, tag);
    context.registerRef(node2, context.readRef(element.props["ref"], tag), tag);
    return node2;
  }
  const innerLayout = layout === "panel" ? resolveInnerPanelLayout(element.props) : layout;
  const panelChild = buildPanelChild(innerLayout, element.props, children, tag);
  const node = panel({
    name: readNodeName(element.props),
    width: readDimension(element.props["width"], "width") ?? "fill",
    height: readDimension(element.props["height"], "height"),
    columnSpan: readNumber(element.props["columnSpan"], "columnSpan"),
    rowSpan: readNumber(element.props["rowSpan"], "rowSpan"),
    align: element.props["align"],
    justify: element.props["justify"],
    padding: element.props["padding"],
    fill: visual.fill,
    line: visual.line,
    borderRadius: visual.borderRadius,
    shadow: visual.shadow
  }, panelChild);
  context.registerRef(node, context.readRef(element.props["ref"], tag), tag);
  return node;
}
function lowerSemanticListBlock(tag, element, context) {
  validateProps(tag, element.props, textBlockKeys);
  const node = text(lowerSemanticListValue(tag, context.toChildArray(element.props["children"]), element.props, {
    lowerRun: context.lowerRun,
    toChildArray: context.toChildArray,
    isFormattingWhitespace: context.isFormattingWhitespace
  }), {
    name: readNodeName(element.props),
    width: readDimension(element.props["width"], "width") ?? "fill",
    height: readDimension(element.props["height"], "height"),
    columnSpan: readNumber(element.props["columnSpan"], "columnSpan"),
    rowSpan: readNumber(element.props["rowSpan"], "rowSpan"),
    style: mergeComposeTextStyle(`<${tag}>`, DEFAULT_SEMANTIC_TEXT_STYLE, readComposeTextStyle(element.props["style"]), readOptionalString2(element.props["className"], `\`<${tag}> className\``)),
    transform: readTransform(element.props["transform"], tag) ?? "none"
  });
  context.registerRef(node, context.readRef(element.props["ref"], tag), tag);
  return node;
}
function lowerSemanticImage(element, context) {
  validateProps("img", element.props, mediaImageKeys);
  validateLeafChildren("img", element.props["children"], context);
  const className = readOptionalString2(element.props["className"], "`className`");
  const parsed = className ? parseTailwindShapeClassName(className) : null;
  const imageOptions = {
    ...readImageSource(element.props, "img"),
    name: readNodeName(element.props),
    width: readDimension(element.props["width"], "width") ?? "fill",
    height: readDimension(element.props["height"], "height"),
    columnSpan: readNumber(element.props["columnSpan"], "columnSpan"),
    rowSpan: readNumber(element.props["rowSpan"], "rowSpan"),
    contentType: readOptionalString2(element.props["contentType"], "<img> contentType"),
    fit: element.props["fit"],
    alt: readOptionalString2(element.props["alt"], "<img> alt"),
    geometry: element.props["geometry"],
    borderRadius: element.props["borderRadius"] ?? parsed?.borderRadius,
    crop: element.props["crop"],
    rotation: readNumber(element.props["rotation"], "rotation"),
    flipHorizontal: readBoolean(element.props["flipHorizontal"], "flipHorizontal"),
    flipVertical: readBoolean(element.props["flipVertical"], "flipVertical"),
    lockAspectRatio: readBoolean(element.props["lockAspectRatio"], "lockAspectRatio")
  };
  const node = image(imageOptions);
  context.registerRef(node, context.readRef(element.props["ref"], "img"), "img");
  return node;
}
function lowerSemanticRule(element, context) {
  validateProps("hr", element.props, ruleKeys);
  validateLeafChildren("hr", element.props["children"], context);
  const node = rule({
    name: readNodeName(element.props),
    width: readDimension(element.props["width"], "width") ?? "fill",
    height: readDimension(element.props["height"], "height"),
    columnSpan: readNumber(element.props["columnSpan"], "columnSpan"),
    rowSpan: readNumber(element.props["rowSpan"], "rowSpan"),
    stroke: element.props["stroke"] ?? "#D7DEE7",
    opacity: readOptionalNumber2(element.props["opacity"], "opacity"),
    weight: readOptionalNumber2(element.props["weight"], "weight")
  });
  context.registerRef(node, context.readRef(element.props["ref"], "hr"), "hr");
  return node;
}
function lowerSemanticContainerChildren(children, tag, context) {
  const entries = flattenContainerEntries(children, context);
  const nodes = [];
  let pendingText = [];
  const flushPendingText = () => {
    if (pendingText.length === 0) {
      return;
    }
    const value = lowerSemanticTextValue(pendingText, {
      contextTag: `<${tag}>`
    }, {
      lowerRun: context.lowerRun,
      toChildArray: context.toChildArray,
      isFormattingWhitespace: context.isFormattingWhitespace
    });
    pendingText = [];
    if (typeof value === "string" && value.length === 0) {
      return;
    }
    nodes.push(text(value, {
      width: "fill"
    }));
  };
  entries.forEach((entry) => {
    if (entry === null || entry === undefined || typeof entry === "boolean" || context.isFormattingWhitespace(entry)) {
      return;
    }
    if (isImplicitTextEntry(entry)) {
      pendingText.push(entry);
      return;
    }
    flushPendingText();
    if (isComposeNode(entry)) {
      nodes.push(entry);
      return;
    }
    if (!isPresentationJsxElement(entry)) {
      throw new Error(`<${tag}> contains an unsupported child.`);
    }
    if (entry.type === Fragment) {
      throw new Error(`<${tag}> contains an unexpected fragment.`);
    }
    nodes.push(context.lowerElement(entry));
  });
  flushPendingText();
  return nodes;
}
function flattenContainerEntries(children, context) {
  const entries = [];
  children.forEach((child) => {
    if (Array.isArray(child)) {
      entries.push(...flattenContainerEntries(child, context));
      return;
    }
    if (isPresentationJsxElement(child) && child.type === Fragment) {
      entries.push(...flattenContainerEntries(context.toChildArray(child.props["children"]), context));
      return;
    }
    entries.push(child);
  });
  return entries;
}
function buildLayoutNode(layout, props, children, tag) {
  if (layout === "row") {
    return row({
      name: props["name"],
      width: props["width"],
      height: props["height"],
      gap: props["gap"],
      align: props["align"],
      justify: props["justify"],
      padding: props["padding"],
      columnSpan: props["columnSpan"],
      rowSpan: props["rowSpan"]
    }, children);
  }
  if (layout === "grid") {
    const columns = props["columns"];
    if (!Array.isArray(columns) || columns.length === 0) {
      throw new Error(`<${tag}> requires \`columns\` when layout is grid.`);
    }
    return grid({
      name: props["name"],
      width: props["width"],
      height: props["height"],
      columns,
      rows: props["rows"],
      autoRows: props["autoRows"],
      columnGap: props["columnGap"],
      rowGap: props["rowGap"],
      alignItems: props["alignItems"],
      justifyItems: props["justifyItems"],
      padding: props["padding"],
      columnSpan: props["columnSpan"],
      rowSpan: props["rowSpan"]
    }, children);
  }
  return column({
    name: props["name"],
    width: props["width"],
    height: props["height"],
    gap: props["gap"],
    align: props["align"],
    justify: props["justify"],
    padding: props["padding"],
    columnSpan: props["columnSpan"],
    rowSpan: props["rowSpan"]
  }, children);
}
function buildPanelChild(layout, props, children, tag) {
  if (children.length === 0) {
    return;
  }
  if (!needsExplicitPanelChildContainer(layout, props, children.length)) {
    return children[0];
  }
  return buildLayoutNode(layout, {
    name: undefined,
    width: "fill",
    height: "fill",
    gap: props["gap"],
    align: props["align"],
    justify: props["justify"],
    columns: props["columns"],
    rows: props["rows"],
    autoRows: props["autoRows"],
    columnGap: props["columnGap"],
    rowGap: props["rowGap"],
    alignItems: props["alignItems"],
    justifyItems: props["justifyItems"]
  }, children, tag);
}
function needsExplicitPanelChildContainer(layout, props, childCount) {
  if (childCount !== 1) {
    return true;
  }
  if (layout !== "column") {
    return true;
  }
  return props["gap"] !== undefined || props["align"] !== undefined || props["justify"] !== undefined || props["columns"] !== undefined || props["rows"] !== undefined || props["autoRows"] !== undefined || props["columnGap"] !== undefined || props["rowGap"] !== undefined || props["alignItems"] !== undefined || props["justifyItems"] !== undefined;
}
function resolveContainerLayout(tag, props) {
  const explicit = props["layout"] ?? props["display"];
  if (explicit !== undefined) {
    return readLayoutMode(explicit, tag);
  }
  if (props["columns"] !== undefined || props["rows"] !== undefined || props["autoRows"] !== undefined || props["columnGap"] !== undefined || props["rowGap"] !== undefined || props["alignItems"] !== undefined || props["justifyItems"] !== undefined) {
    return "grid";
  }
  if (tag === "nav" || tag === "hstack") {
    return "row";
  }
  if (tag === "surface") {
    return "panel";
  }
  return "column";
}
function resolveInnerPanelLayout(props) {
  const value = props["contentLayout"];
  if (value === undefined) {
    return "column";
  }
  const layout = readLayoutMode(value, "contentLayout");
  if (layout === "panel") {
    throw new Error('Semantic panel containers cannot use `contentLayout="panel"`.');
  }
  return layout;
}
function readLayoutMode(value, label) {
  if (value === "column" || value === "row" || value === "grid" || value === "panel") {
    return value;
  }
  throw new Error(`${label} must be one of column, row, grid, or panel.`);
}
function readSurfaceProps(props) {
  const className = readOptionalString2(props["className"], "`className`");
  const parsed = className ? parseTailwindShapeClassName(className) : null;
  return {
    fill: props["fill"] ?? parsed?.fill,
    line: props["line"],
    borderRadius: props["borderRadius"] ?? parsed?.borderRadius,
    shadow: props["shadow"] ?? parsed?.shadow
  };
}
function hasSurfaceProps(value) {
  return value.fill !== undefined || value.line !== undefined || value.borderRadius !== undefined || value.shadow !== undefined;
}
function readImageSource(props, tag) {
  const explicitSources = ["path", "dataUrl", "blob", "uri", "prompt"].filter((key2) => props[key2] !== undefined);
  if (props["src"] !== undefined && explicitSources.length > 0) {
    throw new Error(`<${tag}> cannot combine \`src\` with explicit image source props.`);
  }
  if (props["src"] !== undefined) {
    const src = props["src"];
    if (typeof src !== "string" || src.trim().length === 0) {
      throw new Error(`<${tag}> src must be a non-empty string.`);
    }
    if (src.startsWith("data:")) {
      return { dataUrl: src };
    }
    if (/^https?:\/\//i.test(src)) {
      return { uri: src };
    }
    return { path: src };
  }
  if (explicitSources.length !== 1) {
    throw new Error(`<${tag}> requires exactly one of \`src\`, \`path\`, \`dataUrl\`, \`blob\`, \`uri\`, or \`prompt\`.`);
  }
  const key = explicitSources[0];
  return key ? { [key]: props[key] } : {};
}
function validateLeafChildren(tag, children, context) {
  const values = context.toChildArray(children).filter((value) => !context.isFormattingWhitespace(value));
  if (values.some((value) => value !== null && value !== undefined && typeof value !== "boolean")) {
    throw new Error(`<${tag}> does not accept children.`);
  }
}
function validateProps(tag, props, allowedKeys) {
  Object.keys(props).forEach((key) => {
    if (!allowedKeys.has(key)) {
      throw new Error(`<${tag}> does not support the \`${key}\` prop.`);
    }
  });
}
function readNodeName(props) {
  const name = props["name"];
  const id2 = props["id"];
  const candidate = typeof name === "string" && name.trim().length > 0 ? name : id2;
  if (typeof candidate !== "string") {
    return;
  }
  const trimmed = candidate.trim();
  return trimmed.length > 0 ? trimmed : undefined;
}
function readComposeTextStyle(value) {
  if (value === undefined) {
    return;
  }
  if (typeof value === "string") {
    const trimmed = value.trim();
    return trimmed.length > 0 ? trimmed : undefined;
  }
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    throw new Error("Text style must be a style name string or style object.");
  }
  return value;
}
function readTransform(value, tag) {
  if (value === undefined) {
    return;
  }
  if (value === "none" || value === "uppercase" || value === "lowercase") {
    return value;
  }
  throw new Error(`<${tag}> transform must be none, uppercase, or lowercase.`);
}
function readOptionalString2(value, label) {
  if (value === undefined) {
    return;
  }
  if (typeof value !== "string") {
    throw new Error(`${label} must be a string.`);
  }
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : undefined;
}
function readOptionalNumber2(value, label) {
  if (value === undefined) {
    return;
  }
  if (typeof value !== "number" || !Number.isFinite(value)) {
    throw new Error(`${label} must be a finite number.`);
  }
  return value;
}
function readNumber(value, label) {
  return readOptionalNumber2(value, label);
}
function readBoolean(value, label) {
  if (value === undefined) {
    return;
  }
  if (typeof value !== "boolean") {
    throw new Error(`${label} must be a boolean.`);
  }
  return value;
}
function readDimension(value, label) {
  if (value === undefined) {
    return;
  }
  if (typeof value === "number" || typeof value === "string" || typeof value === "object" && value !== null) {
    return value;
  }
  throw new Error(`${label} must be a valid layout size.`);
}
function isComposeNode(value) {
  return typeof value === "object" && value !== null && "kind" in value && typeof value.kind === "string";
}
function isSemanticPresentationTag(tag) {
  return isSemanticHtmlTag(tag);
}

// node_modules/@oai/granola/dist/presentation-jsx/chart/lower.js
var composeChartKeys = new Set([
  "name",
  "id",
  "width",
  "height",
  "columnSpan",
  "rowSpan",
  "chartType",
  "config",
  "children",
  "ref",
  "title",
  "titlePlacement",
  "titleTextStyle",
  "styleIndex",
  "displayBlanksAs",
  "showDlblsOverMax",
  "chartFill",
  "chartLine",
  "plotAreaFill",
  "plotAreaLine",
  "categories",
  "series",
  "hasLegend",
  "legend",
  "dataLabels",
  "dataTable",
  "xAxis",
  "yAxis",
  "barOptions",
  "lineOptions",
  "areaOptions",
  "scatterOptions",
  "pieOptions",
  "doughnutOptions",
  "treemapOptions",
  "mapOptions",
  "view3d",
  "funnelOptions",
  "boxWhiskerOptions",
  "histogramOptions"
]);
var legendKeys = new Set([
  "position",
  "overlay",
  "fill",
  "line",
  "stroke",
  "textStyle",
  "visible",
  "children"
]);
var dataLabelsKeys = new Set([
  "position",
  "showValue",
  "showSeriesName",
  "showCategoryName",
  "showPercent",
  "showLeaderLines",
  "fill",
  "line",
  "stroke",
  "textStyle",
  "children"
]);
var dataTableKeys = new Set([
  "visible",
  "showLegendKey",
  "fill",
  "line",
  "stroke",
  "textStyle",
  "children"
]);
var axisKeys = new Set([
  "dimension",
  "visible",
  "axisType",
  "title",
  "numberFormatCode",
  "numberFormatSourceLinked",
  "min",
  "max",
  "majorUnit",
  "minorUnit",
  "deleted",
  "position",
  "orientation",
  "majorTickMark",
  "minorTickMark",
  "tickLabelPosition",
  "tickLabelInterval",
  "tickLabelDistanceFromAxis",
  "crossBetween",
  "crosses",
  "crossesAt",
  "line",
  "majorGridlines",
  "minorGridlines",
  "textStyle",
  "children"
]);
var seriesKeys = new Set([
  "name",
  "categories",
  "values",
  "xValues",
  "bubbleSizes",
  "categoryPaths",
  "fill",
  "line",
  "stroke",
  "marker",
  "valuesFormatCode",
  "xValuesFormatCode",
  "explosion",
  "points",
  "dataLabelOverrides",
  "trendlines",
  "errorBars",
  "children"
]);
var markerKeys = new Set(["symbol", "size", "children"]);
var trendlineKeys = new Set([
  "type",
  "name",
  "polynomialOrder",
  "movingAveragePeriod",
  "forecastForward",
  "forecastBackward",
  "intercept",
  "displayEquation",
  "displayRSquared",
  "line",
  "stroke",
  "label",
  "children"
]);
var trendlineLabelKeys = new Set([
  "text",
  "numberFormatCode",
  "numberFormatSourceLinked",
  "manualLayout",
  "textStyle",
  "fill",
  "line",
  "stroke",
  "textRuns",
  "children"
]);
var errorBarsKeys = new Set(["type", "value", "endStyle", "line", "children"]);
var pointKeys = new Set(["idx", "fill", "line", "stroke", "children"]);
var dataLabelKeys = new Set([
  "idx",
  "text",
  "position",
  "fill",
  "line",
  "stroke",
  "showValue",
  "showSeriesName",
  "showCategoryName",
  "showPercent",
  "textStyle",
  "children"
]);
var gridlinesKeys = new Set(["visible", "line", "stroke", "children"]);
var barKeys = new Set([
  "direction",
  "grouping",
  "varyColors",
  "gapWidth",
  "gapDepth",
  "overlap",
  "bar3dShape",
  "children"
]);
var lineKeys = new Set(["grouping", "smooth", "varyColors", "children"]);
var areaKeys = new Set(["grouping", "varyColors", "children"]);
var scatterKeys = new Set(["style", "varyColors", "children"]);
var pieKeys = new Set(["firstSliceAngle", "children"]);
var doughnutKeys = new Set(["holeSize", "firstSliceAngle", "children"]);
var treemapKeys = new Set(["parentLabelLayout", "children"]);
var mapKeys = new Set([
  "mapArea",
  "projection",
  "labelLayout",
  "dataLevel",
  "showUnknown",
  "onlyRegionsWithData",
  "children"
]);
var view3dKeys = new Set([
  "rotX",
  "rotY",
  "perspective",
  "rightAngleAxes",
  "children"
]);
var funnelKeys = new Set(["gapWidth", "children"]);
var boxWhiskerKeys = new Set([
  "showMeanLine",
  "showMeanMarker",
  "showNonOutliers",
  "showOutliers",
  "quartileMethod",
  "children"
]);
var histogramKeys = new Set([
  "binWidth",
  "intervalClosed",
  "aggregated",
  "children"
]);
var comboKeys = new Set([
  "barOptions",
  "lineOptions",
  "areaOptions",
  "children"
]);
var chartTypeMarkerKeys = new Set(["children"]);
function lowerPresentationJsxChartOptions(element) {
  if (element.type !== "chart") {
    throw new Error("Chart lowering expects a <chart> element.");
  }
  const props = element.props;
  validateProps2("chart", props, composeChartKeys);
  const explicitType = props["chartType"] === undefined ? undefined : props["chartType"];
  let config = mergeChartConfig(undefined, props["config"]);
  config = mergeChartConfig(config, lowerDirectChartConfig(props));
  const childState = parseChartChildren(toChildArray(props["children"]));
  config = mergeChartConfig(config, childState.config);
  const resolvedType = resolveChartType(explicitType, childState.chartType);
  if (!resolvedType) {
    throw new Error("<chart> requires a `chartType` prop or a dedicated chart-type child such as <bar>, <bubble>, <sunburst>, <waterfall>, <line3D>, or <combo>.");
  }
  return {
    name: readNodeName2(props),
    width: props["width"],
    height: props["height"],
    columnSpan: props["columnSpan"],
    rowSpan: props["rowSpan"],
    chartType: resolvedType,
    config: config && Object.keys(config).length > 0 ? config : undefined
  };
}
function lowerDirectChartConfig(props) {
  const next = {};
  assign2(next, "title", props["title"]);
  assign2(next, "titlePlacement", props["titlePlacement"]);
  assign2(next, "titleTextStyle", props["titleTextStyle"]);
  assign2(next, "styleIndex", props["styleIndex"]);
  assign2(next, "displayBlanksAs", props["displayBlanksAs"]);
  assign2(next, "showDlblsOverMax", props["showDlblsOverMax"]);
  assign2(next, "chartFill", props["chartFill"]);
  assign2(next, "chartLine", props["chartLine"]);
  assign2(next, "plotAreaFill", props["plotAreaFill"]);
  assign2(next, "plotAreaLine", props["plotAreaLine"]);
  assign2(next, "categories", props["categories"]);
  assign2(next, "series", props["series"]);
  assign2(next, "hasLegend", props["hasLegend"]);
  assign2(next, "dataLabels", props["dataLabels"]);
  assign2(next, "dataTable", props["dataTable"]);
  const xAxis = normalizeAxisConfig(props["xAxis"]);
  const yAxis = normalizeAxisConfig(props["yAxis"]);
  if (xAxis)
    next.xAxis = xAxis;
  if (yAxis)
    next.yAxis = yAxis;
  assign2(next, "barOptions", props["barOptions"]);
  assign2(next, "lineOptions", props["lineOptions"]);
  assign2(next, "areaOptions", props["areaOptions"]);
  assign2(next, "scatterOptions", props["scatterOptions"]);
  assign2(next, "pieOptions", props["pieOptions"]);
  assign2(next, "doughnutOptions", props["doughnutOptions"]);
  assign2(next, "treemapOptions", props["treemapOptions"]);
  assign2(next, "mapOptions", props["mapOptions"]);
  assign2(next, "view3d", props["view3d"]);
  assign2(next, "funnelOptions", props["funnelOptions"]);
  assign2(next, "boxWhiskerOptions", props["boxWhiskerOptions"]);
  assign2(next, "histogramOptions", props["histogramOptions"]);
  const legend = props["legend"];
  if (legend) {
    const normalizedLegend = normalizeLegendConfig(legend);
    if (normalizedLegend.legend) {
      next.legend = normalizedLegend.legend;
    }
    if (normalizedLegend.hasLegend !== undefined) {
      next.hasLegend = normalizedLegend.hasLegend;
    }
  }
  return Object.keys(next).length > 0 ? next : undefined;
}
function parseChartChildren(values) {
  const state = { config: {} };
  for (const value of values) {
    if (Array.isArray(value)) {
      const nested = parseChartChildren(value);
      state.chartType = resolveChartType(state.chartType, nested.chartType);
      state.config = mergeChartConfig(state.config, nested.config) ?? {};
      continue;
    }
    if (value === null || value === undefined || typeof value === "boolean" || isFormattingWhitespace(value)) {
      continue;
    }
    if (!isPresentationJsxElement(value)) {
      throw new Error("<chart> only accepts chart configuration nodes as children.");
    }
    if (value.type === Fragment) {
      const nested = parseChartChildren(toChildArray(value.props["children"]));
      state.chartType = resolveChartType(state.chartType, nested.chartType);
      state.config = mergeChartConfig(state.config, nested.config) ?? {};
      continue;
    }
    if (typeof value.type !== "string") {
      throw new Error("<chart> contains an unsupported JSX child.");
    }
    switch (value.type) {
      case "legend": {
        const legendState = lowerLegendElement(value.props);
        state.config.legend = mergeObjects(state.config.legend, legendState.legend);
        if (legendState.hasLegend !== undefined) {
          state.config.hasLegend = legendState.hasLegend;
        }
        break;
      }
      case "data-labels":
        state.config.dataLabels = mergeObjects(state.config.dataLabels, lowerLeafProps("data-labels", value.props, dataLabelsKeys));
        break;
      case "data-table":
        state.config.dataTable = mergeObjects(state.config.dataTable, lowerLeafProps("data-table", value.props, dataTableKeys));
        break;
      case "x-axis": {
        const axis = lowerAxisElement("x-axis", value.props);
        state.config.xAxis = mergeObjects(state.config.xAxis, axis);
        break;
      }
      case "y-axis": {
        const axis = lowerAxisElement("y-axis", value.props);
        state.config.yAxis = mergeObjects(state.config.yAxis, axis);
        break;
      }
      case "axis": {
        const lowered = lowerAxisAliasElement(value.props);
        if (lowered.dimension === "x") {
          state.config.xAxis = mergeObjects(state.config.xAxis, lowered.axis);
        } else {
          state.config.yAxis = mergeObjects(state.config.yAxis, lowered.axis);
        }
        break;
      }
      case "series":
        state.config.series = [...state.config.series ?? [], lowerSeriesElement(value.props)];
        break;
      case "bar":
        state.chartType = resolveChartType(state.chartType, "bar");
        state.config.barOptions = mergeObjects(state.config.barOptions, lowerLeafProps("bar", value.props, barKeys));
        break;
      case "line":
        state.chartType = resolveChartType(state.chartType, "line");
        state.config.lineOptions = mergeObjects(state.config.lineOptions, lowerLeafProps("line", value.props, lineKeys));
        break;
      case "area":
        state.chartType = resolveChartType(state.chartType, "area");
        state.config.areaOptions = mergeObjects(state.config.areaOptions, lowerLeafProps("area", value.props, areaKeys));
        break;
      case "scatter":
        state.chartType = resolveChartType(state.chartType, "scatter");
        state.config.scatterOptions = mergeObjects(state.config.scatterOptions, lowerLeafProps("scatter", value.props, scatterKeys));
        break;
      case "bubble":
        state.chartType = resolveChartType(state.chartType, "bubble");
        state.config.scatterOptions = mergeObjects(state.config.scatterOptions, lowerLeafProps("bubble", value.props, scatterKeys));
        break;
      case "radar":
        state.chartType = resolveChartType(state.chartType, "radar");
        validateProps2("radar", value.props, chartTypeMarkerKeys);
        validateNoChildren("radar", value.props["children"]);
        break;
      case "pie":
        state.chartType = resolveChartType(state.chartType, "pie");
        state.config.pieOptions = mergeObjects(state.config.pieOptions, lowerLeafProps("pie", value.props, pieKeys));
        break;
      case "doughnut":
        state.chartType = resolveChartType(state.chartType, "doughnut");
        state.config.doughnutOptions = mergeObjects(state.config.doughnutOptions, lowerLeafProps("doughnut", value.props, doughnutKeys));
        break;
      case "treemap":
        state.chartType = resolveChartType(state.chartType, "treemap");
        state.config.treemapOptions = mergeObjects(state.config.treemapOptions, lowerLeafProps("treemap", value.props, treemapKeys));
        break;
      case "sunburst":
        state.chartType = resolveChartType(state.chartType, "sunburst");
        validateProps2("sunburst", value.props, chartTypeMarkerKeys);
        validateNoChildren("sunburst", value.props["children"]);
        break;
      case "map":
        state.chartType = resolveChartType(state.chartType, "map");
        state.config.mapOptions = mergeObjects(state.config.mapOptions, lowerLeafProps("map", value.props, mapKeys));
        break;
      case "waterfall":
        state.chartType = resolveChartType(state.chartType, "waterfall");
        state.config.barOptions = mergeObjects(state.config.barOptions, lowerLeafProps("waterfall", value.props, barKeys));
        break;
      case "line3D":
        state.chartType = resolveChartType(state.chartType, "line3D");
        state.config.lineOptions = mergeObjects(state.config.lineOptions, lowerLeafProps("line3D", value.props, lineKeys));
        break;
      case "pie3D":
        state.chartType = resolveChartType(state.chartType, "pie3D");
        state.config.pieOptions = mergeObjects(state.config.pieOptions, lowerLeafProps("pie3D", value.props, pieKeys));
        break;
      case "area3D":
        state.chartType = resolveChartType(state.chartType, "area3D");
        state.config.areaOptions = mergeObjects(state.config.areaOptions, lowerLeafProps("area3D", value.props, areaKeys));
        break;
      case "bar3D":
        state.chartType = resolveChartType(state.chartType, "bar3D");
        state.config.barOptions = mergeObjects(state.config.barOptions, lowerLeafProps("bar3D", value.props, barKeys));
        break;
      case "funnel":
        state.chartType = resolveChartType(state.chartType, "funnel");
        state.config.funnelOptions = mergeObjects(state.config.funnelOptions, lowerLeafProps("funnel", value.props, funnelKeys));
        break;
      case "histogram":
        state.chartType = resolveChartType(state.chartType, "histogram");
        state.config.histogramOptions = mergeObjects(state.config.histogramOptions, lowerLeafProps("histogram", value.props, histogramKeys));
        break;
      case "boxWhisker":
      case "box-whisker":
        state.chartType = resolveChartType(state.chartType, "boxWhisker");
        state.config.boxWhiskerOptions = mergeObjects(state.config.boxWhiskerOptions, lowerLeafProps(value.type, value.props, boxWhiskerKeys));
        break;
      case "stock":
        state.chartType = resolveChartType(state.chartType, "stock");
        validateProps2("stock", value.props, chartTypeMarkerKeys);
        validateNoChildren("stock", value.props["children"]);
        break;
      case "surface3D":
        state.chartType = resolveChartType(state.chartType, "surface3D");
        validateProps2("surface3D", value.props, chartTypeMarkerKeys);
        validateNoChildren("surface3D", value.props["children"]);
        break;
      case "ofPie":
        state.chartType = resolveChartType(state.chartType, "ofPie");
        state.config.pieOptions = mergeObjects(state.config.pieOptions, lowerLeafProps("ofPie", value.props, pieKeys));
        break;
      case "surface":
        state.chartType = resolveChartType(state.chartType, "surface");
        validateProps2("surface", value.props, chartTypeMarkerKeys);
        validateNoChildren("surface", value.props["children"]);
        break;
      case "pareto":
        state.chartType = resolveChartType(state.chartType, "pareto");
        validateProps2("pareto", value.props, chartTypeMarkerKeys);
        validateNoChildren("pareto", value.props["children"]);
        break;
      case "combo": {
        state.chartType = resolveChartType(state.chartType, "combo");
        validateProps2("combo", value.props, comboKeys);
        validateNoChildren("combo", value.props["children"]);
        const comboProps = stripUndefined(readOptions(value.props, [
          "children"
        ]));
        state.config.barOptions = mergeObjects(state.config.barOptions, comboProps.barOptions);
        state.config.lineOptions = mergeObjects(state.config.lineOptions, comboProps.lineOptions);
        state.config.areaOptions = mergeObjects(state.config.areaOptions, comboProps.areaOptions);
        break;
      }
      case "view-3d":
        state.config.view3d = mergeObjects(state.config.view3d, lowerLeafProps("view-3d", value.props, view3dKeys));
        break;
      default:
        throw new Error(`Unsupported <chart> child <${value.type}>.`);
    }
  }
  return state;
}
function lowerLegendElement(props) {
  validateProps2("legend", props, legendKeys);
  validateNoChildren("legend", props.children);
  return normalizeLegendConfig(props);
}
function normalizeLegendConfig(props) {
  const { visible, ...rest } = props;
  const legend = stripUndefined(rest);
  const hasLegend = visible !== undefined ? visible : Object.keys(legend).length > 0 ? true : true;
  return {
    legend: Object.keys(legend).length > 0 ? legend : undefined,
    hasLegend
  };
}
function lowerAxisAliasElement(props) {
  validateProps2("axis", props, axisKeys);
  const dimension = props.dimension;
  if (dimension !== "x" && dimension !== "y") {
    throw new Error('<axis> requires `dimension="x"` or `dimension="y"`.');
  }
  const axis = lowerAxisElement("axis", props);
  return { dimension, axis };
}
function lowerAxisElement(tag, props) {
  validateProps2(tag, props, axisKeys);
  const base = normalizeAxisConfig(stripUndefined(readOptions(props, [
    "children",
    "dimension"
  ]))) ?? {};
  for (const value of toChildArray(props.children)) {
    if (Array.isArray(value)) {
      const nested = lowerAxisChildren(tag, value);
      if (nested.majorGridlines !== undefined)
        base.majorGridlines = nested.majorGridlines;
      if (nested.minorGridlines !== undefined)
        base.minorGridlines = nested.minorGridlines;
      continue;
    }
    if (value === null || value === undefined || typeof value === "boolean" || isFormattingWhitespace(value)) {
      continue;
    }
    if (!isPresentationJsxElement(value)) {
      throw new Error(`<${tag}> only accepts gridline configuration children.`);
    }
    if (value.type === Fragment) {
      const nested = lowerAxisChildren(tag, toChildArray(value.props["children"]));
      if (nested.majorGridlines !== undefined)
        base.majorGridlines = nested.majorGridlines;
      if (nested.minorGridlines !== undefined)
        base.minorGridlines = nested.minorGridlines;
      continue;
    }
    if (value.type !== "major-gridlines" && value.type !== "minor-gridlines") {
      throw new Error(`<${tag}> only accepts <major-gridlines> and <minor-gridlines> children.`);
    }
    const line = lowerGridlinesElement(value.type, value.props);
    if (value.type === "major-gridlines") {
      base.majorGridlines = line;
    } else {
      base.minorGridlines = line;
    }
  }
  return base;
}
function lowerAxisChildren(tag, values) {
  const next = {};
  for (const value of values) {
    if (Array.isArray(value)) {
      const nested = lowerAxisChildren(tag, value);
      if (nested.majorGridlines !== undefined)
        next.majorGridlines = nested.majorGridlines;
      if (nested.minorGridlines !== undefined)
        next.minorGridlines = nested.minorGridlines;
      continue;
    }
    if (value === null || value === undefined || typeof value === "boolean" || isFormattingWhitespace(value)) {
      continue;
    }
    if (!isPresentationJsxElement(value)) {
      throw new Error(`<${tag}> only accepts gridline configuration children.`);
    }
    if (value.type === Fragment) {
      const nested = lowerAxisChildren(tag, toChildArray(value.props["children"]));
      if (nested.majorGridlines !== undefined)
        next.majorGridlines = nested.majorGridlines;
      if (nested.minorGridlines !== undefined)
        next.minorGridlines = nested.minorGridlines;
      continue;
    }
    if (value.type !== "major-gridlines" && value.type !== "minor-gridlines") {
      throw new Error(`<${tag}> only accepts <major-gridlines> and <minor-gridlines> children.`);
    }
    const line = lowerGridlinesElement(value.type, value.props);
    if (value.type === "major-gridlines") {
      next.majorGridlines = line;
    } else {
      next.minorGridlines = line;
    }
  }
  return next;
}
function lowerGridlinesElement(tag, props) {
  validateProps2(tag, props, gridlinesKeys);
  validateNoChildren(tag, props.children);
  if (props.visible === false) {
    return null;
  }
  if (props.line !== undefined) {
    return props.line === null ? null : normalizeLineConfig(props.line);
  }
  if (props.stroke !== undefined) {
    return props.stroke === null ? null : normalizeLineConfig(props.stroke);
  }
  return { style: "solid" };
}
function lowerSeriesElement(props) {
  validateProps2("series", props, seriesKeys);
  const base = stripUndefined(readOptions(props, [
    "children"
  ]));
  const trendlines = [...base.trendlines ?? []];
  const points = [...base.points ?? []];
  const dataLabelOverrides = [...base.dataLabelOverrides ?? []];
  let marker = base.marker;
  let errorBars = base.errorBars;
  for (const value of toChildArray(props.children)) {
    if (Array.isArray(value)) {
      const nested = lowerSeriesChildren(value);
      marker = mergeObjects(marker, nested.marker);
      errorBars = mergeObjects(errorBars, nested.errorBars);
      trendlines.push(...nested.trendlines);
      points.push(...nested.points);
      dataLabelOverrides.push(...nested.dataLabelOverrides);
      continue;
    }
    if (value === null || value === undefined || typeof value === "boolean" || isFormattingWhitespace(value)) {
      continue;
    }
    if (!isPresentationJsxElement(value)) {
      throw new Error("<series> only accepts chart series configuration children.");
    }
    if (value.type === Fragment) {
      const nested = lowerSeriesChildren(toChildArray(value.props["children"]));
      marker = mergeObjects(marker, nested.marker);
      errorBars = mergeObjects(errorBars, nested.errorBars);
      trendlines.push(...nested.trendlines);
      points.push(...nested.points);
      dataLabelOverrides.push(...nested.dataLabelOverrides);
      continue;
    }
    switch (value.type) {
      case "marker":
        marker = mergeObjects(marker, lowerLeafProps("marker", value.props, markerKeys));
        break;
      case "trendline":
        trendlines.push(lowerTrendlineElement(value.props));
        break;
      case "error-bars":
        errorBars = mergeObjects(errorBars, lowerLeafProps("error-bars", value.props, errorBarsKeys));
        break;
      case "point":
        points.push(lowerLeafProps("point", value.props, pointKeys));
        break;
      case "data-label":
        dataLabelOverrides.push(lowerLeafProps("data-label", value.props, dataLabelKeys));
        break;
      default:
        throw new Error(`<series> only accepts <marker>, <trendline>, <error-bars>, <point>, and <data-label> children.`);
    }
  }
  const next = {
    ...base,
    marker,
    errorBars
  };
  if (trendlines.length > 0) {
    next.trendlines = trendlines;
  }
  if (points.length > 0) {
    next.points = points;
  }
  if (dataLabelOverrides.length > 0) {
    next.dataLabelOverrides = dataLabelOverrides;
  }
  return next;
}
function lowerSeriesChildren(values) {
  const next = {
    trendlines: [],
    points: [],
    dataLabelOverrides: []
  };
  for (const value of values) {
    if (Array.isArray(value)) {
      const nested = lowerSeriesChildren(value);
      next.marker = mergeObjects(next.marker, nested.marker);
      next.errorBars = mergeObjects(next.errorBars, nested.errorBars);
      next.trendlines.push(...nested.trendlines);
      next.points.push(...nested.points);
      next.dataLabelOverrides.push(...nested.dataLabelOverrides);
      continue;
    }
    if (value === null || value === undefined || typeof value === "boolean" || isFormattingWhitespace(value)) {
      continue;
    }
    if (!isPresentationJsxElement(value)) {
      throw new Error("<series> only accepts chart series configuration children.");
    }
    if (value.type === Fragment) {
      const nested = lowerSeriesChildren(toChildArray(value.props["children"]));
      next.marker = mergeObjects(next.marker, nested.marker);
      next.errorBars = mergeObjects(next.errorBars, nested.errorBars);
      next.trendlines.push(...nested.trendlines);
      next.points.push(...nested.points);
      next.dataLabelOverrides.push(...nested.dataLabelOverrides);
      continue;
    }
    switch (value.type) {
      case "marker":
        next.marker = mergeObjects(next.marker, lowerLeafProps("marker", value.props, markerKeys));
        break;
      case "trendline":
        next.trendlines.push(lowerTrendlineElement(value.props));
        break;
      case "error-bars":
        next.errorBars = mergeObjects(next.errorBars, lowerLeafProps("error-bars", value.props, errorBarsKeys));
        break;
      case "point":
        next.points.push(lowerLeafProps("point", value.props, pointKeys));
        break;
      case "data-label":
        next.dataLabelOverrides.push(lowerLeafProps("data-label", value.props, dataLabelKeys));
        break;
      default:
        throw new Error(`<series> only accepts <marker>, <trendline>, <error-bars>, <point>, and <data-label> children.`);
    }
  }
  return next;
}
function lowerTrendlineElement(props) {
  validateProps2("trendline", props, trendlineKeys);
  const base = stripUndefined(readOptions(props, [
    "children"
  ]));
  let label = base.label;
  for (const value of toChildArray(props.children)) {
    if (Array.isArray(value)) {
      label = mergeObjects(label, lowerTrendlineLabelChildren(value));
      continue;
    }
    if (value === null || value === undefined || typeof value === "boolean" || isFormattingWhitespace(value)) {
      continue;
    }
    if (!isPresentationJsxElement(value)) {
      throw new Error("<trendline> only accepts <trendline-label> children.");
    }
    if (value.type === Fragment) {
      label = mergeObjects(label, lowerTrendlineLabelChildren(toChildArray(value.props["children"])));
      continue;
    }
    if (value.type !== "trendline-label") {
      throw new Error("<trendline> only accepts <trendline-label> children.");
    }
    label = mergeObjects(label, lowerLeafProps("trendline-label", value.props, trendlineLabelKeys));
  }
  return label ? { ...base, label } : base;
}
function lowerTrendlineLabelChildren(values) {
  let next;
  for (const value of values) {
    if (Array.isArray(value)) {
      next = mergeObjects(next, lowerTrendlineLabelChildren(value));
      continue;
    }
    if (value === null || value === undefined || typeof value === "boolean" || isFormattingWhitespace(value)) {
      continue;
    }
    if (!isPresentationJsxElement(value)) {
      throw new Error("<trendline> only accepts <trendline-label> children.");
    }
    if (value.type === Fragment) {
      next = mergeObjects(next, lowerTrendlineLabelChildren(toChildArray(value.props["children"])));
      continue;
    }
    if (value.type !== "trendline-label") {
      throw new Error("<trendline> only accepts <trendline-label> children.");
    }
    next = mergeObjects(next, lowerLeafProps("trendline-label", value.props, trendlineLabelKeys));
  }
  return next;
}
function lowerLeafProps(tag, props, allowedKeys) {
  validateProps2(tag, props, allowedKeys);
  validateNoChildren(tag, props["children"]);
  return stripUndefined(readOptions(props, ["children"]));
}
function resolveChartType(current, next) {
  if (!next) {
    return current;
  }
  if (!current) {
    return next;
  }
  if (current !== next) {
    throw new Error(`Chart type is configured more than once with conflicting values: ${current} vs ${next}.`);
  }
  return current;
}
function mergeChartConfig(base, next) {
  if (!base) {
    return next ? { ...next } : undefined;
  }
  if (!next) {
    return { ...base };
  }
  const merged = {
    ...base,
    ...next
  };
  merged.legend = mergeObjects(base.legend, next.legend);
  merged.dataLabels = mergeObjects(base.dataLabels, next.dataLabels);
  merged.dataTable = mergeObjects(base.dataTable, next.dataTable);
  merged.xAxis = mergeObjects(base.xAxis, next.xAxis);
  merged.yAxis = mergeObjects(base.yAxis, next.yAxis);
  merged.barOptions = mergeObjects(base.barOptions, next.barOptions);
  merged.lineOptions = mergeObjects(base.lineOptions, next.lineOptions);
  merged.areaOptions = mergeObjects(base.areaOptions, next.areaOptions);
  merged.scatterOptions = mergeObjects(base.scatterOptions, next.scatterOptions);
  merged.pieOptions = mergeObjects(base.pieOptions, next.pieOptions);
  merged.doughnutOptions = mergeObjects(base.doughnutOptions, next.doughnutOptions);
  merged.treemapOptions = mergeObjects(base.treemapOptions, next.treemapOptions);
  merged.mapOptions = mergeObjects(base.mapOptions, next.mapOptions);
  merged.view3d = mergeObjects(base.view3d, next.view3d);
  merged.funnelOptions = mergeObjects(base.funnelOptions, next.funnelOptions);
  merged.boxWhiskerOptions = mergeObjects(base.boxWhiskerOptions, next.boxWhiskerOptions);
  merged.series = [...base.series ?? [], ...next.series ?? []];
  return stripUndefined(merged);
}
function mergeObjects(base, next) {
  if (!base) {
    return next ? { ...next } : undefined;
  }
  if (!next) {
    return { ...base };
  }
  return {
    ...base,
    ...next
  };
}
function assign2(target, key, value) {
  if (value !== undefined) {
    target[key] = value;
  }
}
function stripUndefined(value) {
  const next = {};
  Object.entries(value).forEach(([key, entry]) => {
    if (entry !== undefined) {
      next[key] = entry;
    }
  });
  return next;
}
function normalizeAxisConfig(value) {
  if (!value) {
    return;
  }
  const { title, majorGridlines, minorGridlines, ...rest } = value;
  const next = { ...rest };
  if (title !== null && title !== undefined) {
    next["title"] = title;
  }
  if (majorGridlines !== undefined) {
    next["majorGridlines"] = majorGridlines === null ? null : normalizeLineConfig(majorGridlines);
  }
  if (minorGridlines !== undefined) {
    next["minorGridlines"] = minorGridlines === null ? null : normalizeLineConfig(minorGridlines);
  }
  return stripUndefined(next);
}
function normalizeLineConfig(value) {
  return value instanceof Line4 ? value.toConfig() ?? { style: "solid" } : value;
}
function validateProps2(tag, props, allowedKeys) {
  Object.keys(props).forEach((key) => {
    if (!allowedKeys.has(key)) {
      throw new Error(`<${tag}> does not support the \`${key}\` prop.`);
    }
  });
}
function validateNoChildren(tag, children) {
  const values = toChildArray(children).filter((value) => !isFormattingWhitespace(value));
  if (values.some((value) => value !== null && value !== undefined && typeof value !== "boolean")) {
    throw new Error(`<${tag}> does not accept children.`);
  }
}
function readOptions(props, ignoredKeys) {
  const next = {};
  Object.entries(props).forEach(([key, value]) => {
    if (ignoredKeys.includes(key) || value === undefined) {
      return;
    }
    next[key] = value;
  });
  return next;
}
function readNodeName2(props) {
  const candidate = typeof props["name"] === "string" && props["name"].trim().length > 0 ? props["name"] : props["id"];
  if (typeof candidate !== "string") {
    return;
  }
  const trimmed = candidate.trim();
  return trimmed.length > 0 ? trimmed : undefined;
}
function toChildArray(value) {
  if (value === undefined) {
    return [];
  }
  return Array.isArray(value) ? value : [value];
}
function isFormattingWhitespace(value) {
  return typeof value === "string" && value.trim().length === 0 && /[\n\r\t]/.test(value);
}

// node_modules/@oai/granola/dist/presentation-jsx/normalize.js
var COMPOSE_KINDS = new Set([
  "text",
  "rule",
  "shape",
  "image",
  "table",
  "chart",
  "panel",
  "layers",
  "row",
  "column",
  "grid"
]);
var MATERIALIZING_KINDS = new Set([
  "text",
  "rule",
  "shape",
  "image",
  "table",
  "chart",
  "panel"
]);
var rowKeys = new Set([
  "name",
  "id",
  "width",
  "height",
  "gap",
  "align",
  "justify",
  "padding",
  "columnSpan",
  "rowSpan",
  "children"
]);
var columnKeys = new Set(rowKeys);
var layersKeys = new Set([
  "name",
  "id",
  "width",
  "height",
  "alignItems",
  "justifyItems",
  "padding",
  "columnSpan",
  "rowSpan",
  "children"
]);
var gridKeys = new Set([
  "name",
  "id",
  "width",
  "height",
  "columns",
  "rows",
  "autoRows",
  "columnGap",
  "rowGap",
  "alignItems",
  "justifyItems",
  "padding",
  "columnSpan",
  "rowSpan",
  "children"
]);
var panelKeys = new Set([
  "name",
  "id",
  "width",
  "height",
  "columnSpan",
  "rowSpan",
  "fill",
  "line",
  "borderRadius",
  "shadow",
  "align",
  "justify",
  "className",
  "padding",
  "children",
  "ref"
]);
var textKeys = new Set([
  "name",
  "id",
  "width",
  "height",
  "columnSpan",
  "rowSpan",
  "style",
  "className",
  "transform",
  "children",
  "ref"
]);
var paragraphComposeKeys = new Set([
  ...textKeys,
  "bulletCharacter",
  "marginLeft",
  "indent",
  "spaceBefore",
  "spaceAfter",
  "styleId",
  "paragraphStyle"
]);
var shapeKeys = new Set([
  "name",
  "id",
  "width",
  "height",
  "columnSpan",
  "rowSpan",
  "geometry",
  "fill",
  "line",
  "className",
  "borderRadius",
  "shadow",
  "ref"
]);
var imageKeys = new Set([
  "name",
  "id",
  "width",
  "height",
  "columnSpan",
  "rowSpan",
  "src",
  "path",
  "dataUrl",
  "blob",
  "uri",
  "prompt",
  "fit",
  "alt",
  "geometry",
  "borderRadius",
  "crop",
  "contentType",
  "rotation",
  "flipHorizontal",
  "flipVertical",
  "lockAspectRatio",
  "ref"
]);
var tableKeys = new Set([
  "name",
  "id",
  "width",
  "height",
  "columnSpan",
  "rowSpan",
  "rows",
  "columns",
  "values",
  "style",
  "styleOptions",
  "ref"
]);
var ruleKeys2 = new Set([
  "name",
  "id",
  "width",
  "height",
  "columnSpan",
  "rowSpan",
  "stroke",
  "opacity",
  "weight",
  "ref"
]);
var runKeys = new Set(["run", "textStyle", "link", "children"]);
function normalizePresentationComposeInput(input) {
  if (isComposeNode2(input)) {
    return {
      node: input,
      refsByPath: new Map,
      background: undefined
    };
  }
  if (isPresentationJsxElement(input) && input.type === "slide") {
    return normalizeSlideRootElement(input);
  }
  if (isPresentationJsxElement(input) && input.type === "background") {
    throw new Error("<background> can only be used inside <slide>.");
  }
  const refsByNode = new WeakMap;
  const usedRefs = new Set;
  const roots = collectComposeChildren([input], refsByNode, usedRefs, "slide.compose");
  if (roots.length !== 1) {
    throw new Error("slide.compose JSX input must resolve to exactly one compose node. Wrap siblings with <row>, <column>, or <grid>.");
  }
  const root = roots[0];
  if (!root) {
    throw new Error("slide.compose JSX input did not produce a compose node.");
  }
  const refsByPath = new Map;
  collectRefsByPath(root, refsByNode, refsByPath, "0");
  return {
    node: root,
    refsByPath,
    background: undefined
  };
}
function normalizeSlideRootElement(input) {
  const refsByNode = new WeakMap;
  const usedRefs = new Set;
  const slideProps = input.props;
  const { children, background } = collectSlideRootChildren(toChildArray2(slideProps["children"]), {
    fill: slideProps["background"],
    ref: slideProps["backgroundRef"]
  });
  const { background: _ignoredBackground, backgroundRef: _ignoredBackgroundRef, ...rootProps } = slideProps;
  const root = lowerComposeElement({
    $$type: PRESENTATION_JSX_ELEMENT,
    type: "section",
    props: {
      ...rootProps,
      width: rootProps["width"] ?? "fill",
      height: rootProps["height"] ?? "fill",
      children
    }
  }, refsByNode, usedRefs);
  const refsByPath = new Map;
  collectRefsByPath(root, refsByNode, refsByPath, "0");
  return {
    node: root,
    refsByPath,
    background
  };
}
function collectSlideRootChildren(values, seedBackground) {
  const children = [];
  let background = seedBackground.fill !== undefined || seedBackground.ref !== undefined ? { ...seedBackground } : undefined;
  values.forEach((value) => {
    if (Array.isArray(value)) {
      const nested = collectSlideRootChildren(value, background ?? {});
      children.push(...nested.children);
      background = nested.background;
      return;
    }
    if (value === null || value === undefined || typeof value === "boolean") {
      return;
    }
    if (isPresentationJsxElement(value) && value.type === Fragment) {
      const nested = collectSlideRootChildren(toChildArray2(value.props["children"]), background ?? {});
      children.push(...nested.children);
      background = nested.background;
      return;
    }
    if (isPresentationJsxElement(value) && value.type === "background") {
      if (toChildArray2(value.props["children"]).some((child) => child !== null && child !== undefined && child !== false && !isFormattingWhitespace2(child))) {
        throw new Error("<background> does not accept children.");
      }
      background = {
        ...background,
        fill: value.props["fill"],
        ref: value.props["ref"]
      };
      return;
    }
    children.push(value);
  });
  return { children, background };
}
function collectComposeChildren(values, refsByNode, usedRefs, context) {
  const nodes = [];
  values.forEach((value) => {
    if (Array.isArray(value)) {
      nodes.push(...collectComposeChildren(value, refsByNode, usedRefs, context));
      return;
    }
    if (value === null || value === undefined || typeof value === "boolean" || isFormattingWhitespace2(value)) {
      return;
    }
    if (isComposeNode2(value)) {
      nodes.push(value);
      return;
    }
    if (typeof value === "string" || typeof value === "number") {
      throw new Error(`${context} only accepts compose elements. Wrap raw text with <paragraph> or <text-box>.`);
    }
    if (!isPresentationJsxElement(value)) {
      throw new Error(`${context} contains an unsupported JSX value.`);
    }
    if (value.type === Fragment) {
      nodes.push(...collectComposeChildren(toChildArray2(value.props["children"]), refsByNode, usedRefs, context));
      return;
    }
    if (value.type === "run") {
      throw new Error(`${context} does not accept <${String(value.type)}> outside <paragraph> or <text-box>.`);
    }
    if (value.type === "slide") {
      throw new Error("<slide> can only be used as the root passed to slide.compose.");
    }
    if (value.type === "background") {
      throw new Error("<background> can only be used inside <slide>.");
    }
    nodes.push(lowerComposeElement(value, refsByNode, usedRefs));
  });
  return nodes;
}
function lowerComposeElement(element, refsByNode, usedRefs) {
  if (typeof element.type !== "string") {
    throw new Error("Unsupported JSX tag in presentation compose input.");
  }
  const tag = element.type;
  const props = element.props;
  if (isSemanticPresentationTag(tag)) {
    return lowerSemanticHtmlElement(element, {
      refsByNode,
      usedRefs,
      lowerElement: (child) => lowerComposeElement(child, refsByNode, usedRefs),
      lowerRun,
      readRef,
      registerRef: (node, ref, refTag) => registerRef(node, ref, refsByNode, usedRefs, refTag),
      toChildArray: toChildArray2,
      isFormattingWhitespace: isFormattingWhitespace2
    });
  }
  if (tag === "row") {
    validateProps3(tag, props, rowKeys);
    const node = row(readComposeOptions(tag, withNodeName(props), ["children", "id"]), collectComposeChildren(toChildArray2(props["children"]), refsByNode, usedRefs, "<row>"));
    return node;
  }
  if (tag === "column") {
    validateProps3(tag, props, columnKeys);
    const node = column(readComposeOptions(tag, withNodeName(props), ["children", "id"]), collectComposeChildren(toChildArray2(props["children"]), refsByNode, usedRefs, "<column>"));
    return node;
  }
  if (tag === "layers") {
    validateProps3(tag, props, layersKeys);
    const node = layers(readComposeOptions(tag, withNodeName(props), ["children", "id"]), collectComposeChildren(toChildArray2(props["children"]), refsByNode, usedRefs, "<layers>"));
    return node;
  }
  if (tag === "grid") {
    validateProps3(tag, props, gridKeys);
    const node = grid(readComposeOptions(tag, withNodeName(props), ["children", "id"]), collectComposeChildren(toChildArray2(props["children"]), refsByNode, usedRefs, "<grid>"));
    return node;
  }
  if (tag === "box" || tag === "panel" || tag === "card") {
    validateProps3(tag, props, panelKeys);
    const children = collectComposeChildren(toChildArray2(props["children"]), refsByNode, usedRefs, `<${tag}>`);
    if (children.length > 1) {
      throw new Error(`<${tag}> accepts at most one child. Wrap multiple children with <column> or <row>.`);
    }
    const child = children[0];
    const node = tag === "card" ? card(readComposeOptions(tag, withShapeClassName(withNodeName(props), tag), ["children", "ref", "className", "id"]), child) : panel(readComposeOptions(tag, withShapeClassName(withNodeName(props), tag), ["children", "ref", "className", "id"]), child);
    registerRef(node, readRef(props["ref"], tag), refsByNode, usedRefs, tag);
    return node;
  }
  if (tag === "text-box" || tag === "text") {
    validateProps3(tag, props, textKeys);
    const node = text(lowerTextValue(toChildArray2(props["children"]), `<${tag}>`), readComposeOptions(tag, withTextClassName(withNodeName(props), tag), ["children", "ref", "className", "id"]));
    registerRef(node, readRef(props["ref"], tag), refsByNode, usedRefs, tag);
    return node;
  }
  if (tag === "paragraph") {
    validateProps3(tag, props, paragraphComposeKeys);
    const node = text(lowerTextValue([element], "<paragraph>"), readComposeOptions(tag, withTextClassName(withNodeName(props), tag), [
      "children",
      "ref",
      "className",
      "id",
      "bulletCharacter",
      "marginLeft",
      "indent",
      "spaceBefore",
      "spaceAfter",
      "styleId",
      "paragraphStyle"
    ]));
    registerRef(node, readRef(props["ref"], tag), refsByNode, usedRefs, tag);
    return node;
  }
  if (tag === "shape") {
    validateProps3(tag, props, shapeKeys);
    validateLeafChildren2(tag, props["children"]);
    const node = shape(readComposeOptions(tag, withShapeClassName(withNodeName(props), tag), ["ref", "className", "id"]));
    registerRef(node, readRef(props["ref"], tag), refsByNode, usedRefs, tag);
    return node;
  }
  if (tag === "image") {
    validateProps3(tag, props, imageKeys);
    validateLeafChildren2(tag, props["children"]);
    const node = image(readComposeOptions(tag, withImageSource(withNodeName(props), tag), ["ref", "id", "src"]));
    registerRef(node, readRef(props["ref"], tag), refsByNode, usedRefs, tag);
    return node;
  }
  if (tag === "table") {
    validateProps3(tag, props, tableKeys);
    validateLeafChildren2(tag, props["children"]);
    const node = table(readComposeOptions(tag, withNodeName(props), ["ref", "id"]));
    registerRef(node, readRef(props["ref"], tag), refsByNode, usedRefs, tag);
    return node;
  }
  if (tag === "chart") {
    const node = chart(lowerPresentationJsxChartOptions(element));
    registerRef(node, readRef(props["ref"], tag), refsByNode, usedRefs, tag);
    return node;
  }
  if (tag === "rule") {
    validateProps3(tag, props, ruleKeys2);
    validateLeafChildren2(tag, props["children"]);
    const node = rule(readComposeOptions(tag, withNodeName(props), ["ref", "id"]));
    registerRef(node, readRef(props["ref"], tag), refsByNode, usedRefs, tag);
    return node;
  }
  throw new Error(`Unsupported presentation JSX tag <${tag}>.`);
}
function lowerTextValue(children, contextTag = "<text-box>") {
  return lowerSemanticTextValue(children, {
    contextTag
  }, {
    lowerRun,
    toChildArray: toChildArray2,
    isFormattingWhitespace: isFormattingWhitespace2
  });
}
function lowerRun(element) {
  validateProps3("run", element.props, runKeys);
  const options = readOptions2(element.props, ["children"]);
  const childText = readRunChildren(element.props["children"]);
  const propText = options.run;
  if (propText !== undefined && typeof propText !== "string") {
    throw new Error("<run> `run` must be a string when provided.");
  }
  if (propText !== undefined && childText !== undefined) {
    throw new Error("<run> accepts text either as children or as the `run` prop, not both.");
  }
  const run = childText ?? propText;
  if (run === undefined) {
    throw new Error("<run> requires text as children or a string `run` prop.");
  }
  return {
    ...options,
    run
  };
}
function readRunChildren(children) {
  let text2 = "";
  let sawText = false;
  const visit = (value) => {
    if (value === null || value === undefined || typeof value === "boolean") {
      return;
    }
    if (Array.isArray(value)) {
      value.forEach(visit);
      return;
    }
    if (typeof value === "string" || typeof value === "number") {
      if (isFormattingWhitespace2(value)) {
        return;
      }
      text2 += String(value);
      sawText = true;
      return;
    }
    if (isPresentationJsxElement(value) && value.type === Fragment) {
      visit(value.props["children"]);
      return;
    }
    throw new Error("<run> only accepts raw text and fragments.");
  };
  visit(children);
  return sawText ? text2 : undefined;
}
function validateLeafChildren2(tag, children) {
  const values = toChildArray2(children).filter((value) => !isFormattingWhitespace2(value));
  if (values.some((value) => value !== null && value !== undefined && typeof value !== "boolean")) {
    throw new Error(`<${tag}> does not accept children.`);
  }
}
function validateProps3(tag, props, allowedKeys) {
  Object.keys(props).forEach((key) => {
    if (!allowedKeys.has(key)) {
      throw new Error(`<${tag}> does not support the \`${key}\` prop.`);
    }
  });
}
function readOptions2(props, ignoredKeys) {
  const next = {};
  Object.entries(props).forEach(([key, value]) => {
    if (ignoredKeys.includes(key) || value === undefined) {
      return;
    }
    next[key] = value;
  });
  return next;
}
var fillWidthDefaultTags = new Set([
  "row",
  "column",
  "layers",
  "grid",
  "box",
  "panel",
  "card",
  "text-box",
  "text",
  "paragraph",
  "shape",
  "image",
  "table",
  "chart",
  "rule"
]);
function readComposeOptions(tag, props, ignoredKeys) {
  const next = readOptions2(props, ignoredKeys);
  if (!("width" in next) && fillWidthDefaultTags.has(tag)) {
    next["width"] = "fill";
  }
  return next;
}
function readRef(value, tag) {
  if (value === undefined) {
    return;
  }
  if (typeof value !== "object" || value === null || !("current" in value)) {
    throw new Error(`<${tag}> ref must be a mutable ref object created by createRef().`);
  }
  return value;
}
function registerRef(node, ref, refsByNode, usedRefs, tag) {
  if (!ref) {
    return;
  }
  if (!MATERIALIZING_KINDS.has(node.kind)) {
    throw new Error(`<${tag}> does not materialize an element ref.`);
  }
  if (usedRefs.has(ref)) {
    throw new Error("A JSX ref object can only be used once within a compose tree.");
  }
  usedRefs.add(ref);
  refsByNode.set(node, ref);
}
function collectRefsByPath(node, refsByNode, refsByPath, path3) {
  const ref = refsByNode.get(node);
  if (ref) {
    refsByPath.set(path3, ref);
  }
  if (node.kind === "panel") {
    if (node.child) {
      collectRefsByPath(node.child, refsByNode, refsByPath, buildChildPath2(path3, 0));
    }
    return;
  }
  if (node.kind === "row" || node.kind === "column" || node.kind === "layers" || node.kind === "grid") {
    node.children.forEach((child, index) => {
      collectRefsByPath(child, refsByNode, refsByPath, buildChildPath2(path3, index));
    });
  }
}
function buildChildPath2(path3, index) {
  return `${path3}.${index}`;
}
function withNodeName(props) {
  const name = readNodeName3(props);
  if (name === undefined) {
    return props;
  }
  return {
    ...props,
    name
  };
}
function withShapeClassName(props, tag) {
  const className = props["className"];
  if (typeof className !== "string" || className.trim().length === 0) {
    return props;
  }
  const parsed = parseTailwindShapeClassName(className);
  if (!parsed) {
    return props;
  }
  return {
    ...props,
    fill: props["fill"] ?? parsed.fill,
    borderRadius: props["borderRadius"] ?? parsed.borderRadius,
    shadow: props["shadow"] ?? parsed.shadow,
    name: readNodeName3(props) ?? props["name"] ?? tag
  };
}
function withTextClassName(props, tag) {
  const className = typeof props["className"] === "string" ? props["className"] : undefined;
  if (!className) {
    return props;
  }
  return {
    ...props,
    style: mergeComposeTextStyle(`<${tag}>`, undefined, props["style"], className)
  };
}
function withImageSource(props, tag) {
  if (props["src"] === undefined) {
    return props;
  }
  const src = props["src"];
  if (typeof src !== "string" || src.trim().length === 0) {
    throw new Error(`<${tag}> src must be a non-empty string.`);
  }
  if (props["path"] !== undefined || props["dataUrl"] !== undefined || props["blob"] !== undefined || props["uri"] !== undefined || props["prompt"] !== undefined) {
    throw new Error(`<${tag}> cannot combine \`src\` with explicit image source props.`);
  }
  if (src.startsWith("data:")) {
    return { ...props, dataUrl: src };
  }
  if (/^https?:\/\//i.test(src)) {
    return { ...props, uri: src };
  }
  return { ...props, path: src };
}
function readNodeName3(props) {
  const candidate = typeof props["name"] === "string" && props["name"].trim().length > 0 ? props["name"] : props["id"];
  if (typeof candidate !== "string") {
    return;
  }
  const trimmed = candidate.trim();
  return trimmed.length > 0 ? trimmed : undefined;
}
function toChildArray2(value) {
  if (value === undefined) {
    return [];
  }
  return Array.isArray(value) ? value : [value];
}
function isComposeNode2(value) {
  return typeof value === "object" && value !== null && "kind" in value && typeof value.kind === "string" && COMPOSE_KINDS.has(value.kind);
}
function isFormattingWhitespace2(value) {
  return typeof value === "string" && value.trim().length === 0 && /[\n\r\t]/.test(value);
}

// node_modules/@oai/granola/dist/models/presentation/slide.js
class Slide2 {
  #context;
  #data;
  #elements;
  #speakerNotes;
  #background;
  #placeholders;
  #composeRuns;
  #themeFacade;
  constructor(context, proto) {
    this.#context = context;
    this.#data = {
      id: proto?.id ?? "",
      index: proto?.index ?? 0,
      useLayoutId: proto?.useLayoutId ?? "",
      widthEmu: proto?.widthEmu ?? DEFAULT_SLIDE_WIDTH_EMU,
      heightEmu: proto?.heightEmu ?? DEFAULT_SLIDE_HEIGHT_EMU,
      creationId: proto?.creationId ?? generateSlideCreationId()
    };
    this.#elements = new ElementsCollection(this.#elementsContext(), proto?.elements ?? []);
    this.#speakerNotes = new SpeakerNotes(this.#speakerNotesContext(), proto?.notesSlide);
    this.#background = new SlideBackground(this.#backgroundContext(), proto?.background ?? undefined);
    this.#composeRuns = [];
  }
  get speakerNotes() {
    return this.#speakerNotes;
  }
  get background() {
    return this.#background;
  }
  get id() {
    return this.#data.id;
  }
  get index() {
    return this.#data.index;
  }
  get creationId() {
    return this.#data.creationId;
  }
  get shapes() {
    return this.#elements.shapes;
  }
  get useLayoutId() {
    return this.#data.useLayoutId;
  }
  get images() {
    return this.#elements.images;
  }
  get tables() {
    return this.#elements.tables;
  }
  get charts() {
    return this.#elements.charts;
  }
  get elements() {
    return this.#elements;
  }
  get theme() {
    if (!this.#themeFacade) {
      this.#themeFacade = new SlideComposeThemeFacade(() => this.#context.getPresentation?.(), this.id);
    }
    return this.#themeFacade;
  }
  get frame() {
    return {
      left: 0,
      top: 0,
      width: pixelsFromEmu(this.#data.widthEmu),
      height: pixelsFromEmu(this.#data.heightEmu)
    };
  }
  set frame(value) {
    const widthEmu = emuFromPixels(value.width);
    if (widthEmu !== undefined) {
      this.#data.widthEmu = widthEmu;
    }
    const heightEmu = emuFromPixels(value.height);
    if (heightEmu !== undefined) {
      this.#data.heightEmu = heightEmu;
    }
    this.#queueCollaborativePublish();
  }
  setViewportSize(widthPx, heightPx) {
    const widthEmu = widthPx ? emuFromPixels(widthPx) : undefined;
    if (widthEmu !== undefined) {
      this.#data.widthEmu = widthEmu;
    }
    const heightEmu = heightPx ? emuFromPixels(heightPx) : undefined;
    if (heightEmu !== undefined) {
      this.#data.heightEmu = heightEmu;
    }
    this.#queueCollaborativePublish();
  }
  get placeholders() {
    if (!this.#placeholders) {
      this.#placeholders = new PlaceholderCollection(this.#elements.shapes, "slide");
    }
    return this.#placeholders;
  }
  setLayout(layout) {
    this.#data.useLayoutId = layout.id;
    const placeholderProtos = layout.placeholders.getAll().map((placeholder) => placeholder.toProto());
    this.#elements.shapes.setPlaceholdersFromProtos(placeholderProtos);
    this.#queueCollaborativePublish();
  }
  duplicate() {
    return this.#context.duplicateSlide(this);
  }
  setIndex(index) {
    this.#data.index = index;
    this.#queueCollaborativePublish();
  }
  hydrateCollaborativeRefsFromProto() {
    this.#elements.hydrateCollaborativeRefsFromProto();
  }
  toSnapshot() {
    const shapes = this.shapes.items.map((shape2) => shape2.toSnapshot());
    const charts = this.charts.items.map((chart2) => chart2.toSnapshot());
    const images = this.images.items.map((image2) => image2.toSnapshot());
    const tables = this.tables.items.map((table2) => table2.toSnapshot());
    const notes = this.#speakerNotes.toSnapshot(this.id);
    const title = resolveSlideTitle(shapes, this.index);
    const layoutId = this.useLayoutId.trim();
    return {
      aid: `sl/${this.id}`,
      kind: "slide",
      id: this.id,
      index: this.index,
      title,
      layoutId: layoutId.length > 0 ? layoutId : undefined,
      shapes,
      charts,
      images,
      tables,
      notes
    };
  }
  gridFrame(area, options = {}) {
    return getSlideGridFrame(this.frame, area, options);
  }
  gridLayout(items, options = {}) {
    const placements = computeSlideGridLayoutPlacements(this.frame, items, options);
    placements.forEach(({ shape: shape2, frame }) => {
      shape2.position = frame;
    });
  }
  stackVertical(shapes, options = {}) {
    this.autoLayout(shapes, {
      ...options,
      direction: AutoLayoutDirection.vertical
    });
  }
  stackHorizontal(shapes, options = {}) {
    this.autoLayout(shapes, {
      ...options,
      direction: AutoLayoutDirection.horizontal
    });
  }
  autoLayout(shapes, options = {}) {
    AutoLayout.apply(this, shapes, options);
  }
  compose(node, options = {}) {
    const normalized = normalizePresentationComposeInput(node);
    if (normalized.background?.fill !== undefined) {
      this.background.fill = normalized.background.fill;
    }
    if (normalized.background?.ref !== undefined) {
      this.background.ref = normalized.background.ref;
    }
    const { elements, elementsByPath, run } = composeSlideDetailed(this, normalized.node, options);
    normalized.refsByPath.forEach((ref, path3) => {
      ref.current = elementsByPath.get(path3) ?? null;
    });
    this.#composeRuns.push(run);
    return elements;
  }
  getPresentation() {
    return this.#context.getPresentation?.();
  }
  copyComposeRunsFrom(source) {
    this.#composeRuns = JSON.parse(JSON.stringify(source.#composeRuns));
  }
  moveTo(index) {
    this.#context.moveSlide(this, index);
  }
  delete() {
    const recorder = this.#context.getPresentation?.()?.getRecorder?.();
    if (recorder) {
      const anchor = `sl/${this.id}`;
      recorder.record({
        op: "slide.remove",
        target: recorder.targetRefForElement(this, anchor)
      });
    }
    this.#context.deleteSlide(this);
  }
  export(options = { format: "png" }) {
    const format2 = options.format ?? "png";
    if (format2 === "layout") {
      return Promise.resolve(createPresentationLayoutExportBlob(this, this.#composeRuns));
    }
    return this.#context.renderSlidePreview(this, {
      ...options,
      format: format2
    });
  }
  toProto() {
    const notesSlide = this.#speakerNotes.toProto();
    if (notesSlide && this.#data.useLayoutId) {
      notesSlide.useLayoutId = this.#data.useLayoutId;
    }
    return {
      id: this.#data.id,
      index: this.#data.index,
      useLayoutId: this.#data.useLayoutId,
      widthEmu: this.#data.widthEmu,
      heightEmu: this.#data.heightEmu,
      creationId: this.#data.creationId,
      elements: this.#elements.toProto(),
      background: this.#background.toProto(),
      notesSlide
    };
  }
  #speakerNotesContext() {
    return {
      stub: () => {},
      getSlideId: () => this.id,
      recordOp: (op) => {
        this.#queueCollaborativePublish();
        const recorder = this.#context.getPresentation?.()?.getRecorder?.();
        if (recorder) {
          recorder.record(op);
        }
      }
    };
  }
  #elementsContext() {
    return {
      ...this.#context,
      getSlide: () => this,
      getSlideCollabState: () => {
        const presentation = this.#context.getPresentation?.();
        return presentation?.getSlideCollabState(this.id);
      }
    };
  }
  #backgroundContext() {
    return {
      stub: () => {},
      getTargetRef: () => {
        const anchor = `sl/${this.id}`;
        const recorder = this.#context.getPresentation?.()?.getRecorder?.();
        return recorder ? recorder.targetRefForElement(this, anchor) : anchor;
      },
      recordOp: (op) => {
        this.#queueCollaborativePublish();
        const recorder = this.#context.getPresentation?.()?.getRecorder?.();
        if (recorder) {
          recorder.record(op);
        }
      }
    };
  }
  #queueCollaborativePublish() {
    this.#context.getPresentation?.()?.queuePresentationCollabPublish();
  }
}
var resolveSlideTitle = (shapes, index) => {
  for (const shape2 of shapes) {
    const rawText = shape2.text?.trim();
    if (rawText) {
      const firstLine = rawText.split(/\r?\n/).find((line) => line.trim().length > 0) ?? rawText;
      return clipSlideTitle(firstLine.trim());
    }
  }
  return `Slide ${index + 1}`;
};
var clipSlideTitle = (value, maxLength = 80) => {
  if (value.length <= maxLength) {
    return value;
  }
  const sliceLength = Math.max(1, maxLength - 3);
  return `${value.slice(0, sliceLength)}...`;
};

// node_modules/@oai/granola/dist/models/presentation/slide-collection.js
var DEFAULT_WIDTH_EMU = 12192000;
var DEFAULT_HEIGHT_EMU = 6858000;

class SlideCollection {
  #context;
  #items;
  #activeIndex;
  #defaultWidthEmu;
  #defaultHeightEmu;
  #itemsById;
  constructor(context, proto, options = {}) {
    this.#context = context;
    this.#defaultWidthEmu = options.defaultWidthEmu ?? DEFAULT_WIDTH_EMU;
    this.#defaultHeightEmu = options.defaultHeightEmu ?? DEFAULT_HEIGHT_EMU;
    this.#items = [];
    this.#itemsById = new Map;
    (proto ?? []).forEach((slide) => {
      const facade = new Slide2(this.#slideContext(), slide);
      this.#attachSlide(facade);
    });
    this.#activeIndex = this.#items.length > 0 ? 0 : -1;
  }
  get items() {
    return [...this.#items];
  }
  getItem(selector) {
    if (typeof selector === "number") {
      const slide2 = this.#items[selector];
      if (!slide2) {
        throw new Error(`Slide index out of range: ${selector}`);
      }
      return slide2;
    }
    const id2 = selector?.id ?? "";
    if (!id2) {
      throw new Error("Slide id selector requires an id value.");
    }
    const slide = this.#itemsById.get(id2);
    if (!slide) {
      throw new Error(`Slide with id ${id2} not found.`);
    }
    return slide;
  }
  add(options = {}) {
    const { layout: layoutName, layoutId } = options;
    const slideProto = {
      id: generateAidSuffix(),
      index: this.#items.length,
      elements: [],
      useLayoutId: "",
      widthEmu: this.#defaultWidthEmu,
      heightEmu: this.#defaultHeightEmu
    };
    const slide = new Slide2(this.#slideContext(), slideProto);
    if (options.width !== undefined || options.height !== undefined) {
      slide.setViewportSize(options.width, options.height);
    }
    if (layoutId) {
      const layoutById = this.#context.getLayoutById(layoutId);
      if (!layoutById) {
        throw new Error(`Layout id not found: ${layoutId}`);
      }
      slide.setLayout(layoutById);
    } else if (layoutName) {
      const layout = this.#context.getLayoutByName(layoutName);
      slide.setLayout(layout);
    } else {
      const defaultLayout = this.#context.getDefaultLayout?.();
      if (defaultLayout) {
        slide.setLayout(defaultLayout);
      }
    }
    this.#attachSlide(slide);
    this.#context.getPresentation?.()?.hydrateSlideCollaborativeState(slide);
    this.#context.getPresentation?.()?.queuePresentationCollabPublish();
    if (this.#activeIndex === -1) {
      this.#activeIndex = 0;
    }
    const recorder = this.#context.getPresentation?.()?.getRecorder?.();
    if (recorder) {
      const anchor = `sl/${slide.id}`;
      const alias = recorder.assignAlias(slide, anchor, "slide");
      const frame = slide.frame;
      recorder.record({
        op: "slide.add",
        as: alias,
        layout: layoutName,
        layoutId,
        width: frame.width,
        height: frame.height
      });
    }
    return slide;
  }
  insert(options = {}) {
    const { after, ...addOptions } = options;
    const newSlide = this.add(addOptions);
    const targetIndex = this.#resolveInsertIndex(after);
    if (targetIndex !== this.#items.length - 1) {
      newSlide.moveTo(targetIndex);
    }
    return { slide: newSlide, index: targetIndex };
  }
  #duplicateSlide(slide) {
    const sourceIndex = this.#items.indexOf(slide);
    if (sourceIndex === -1) {
      throw new Error("Cannot duplicate a slide that is not in this collection.");
    }
    const duplicateProto = {
      ...slide.toProto(),
      id: generateAidSuffix(),
      index: sourceIndex + 1
    };
    const duplicate = new Slide2(this.#slideContext(), duplicateProto);
    duplicate.copyComposeRunsFrom(slide);
    this.#attachSlide(duplicate, sourceIndex + 1);
    this.#context.getPresentation?.()?.hydrateSlideCollaborativeState(duplicate);
    this.#reindexSlides(sourceIndex);
    this.#context.getPresentation?.()?.queuePresentationCollabPublish();
    const recorder = this.#context.getPresentation?.()?.getRecorder?.();
    if (recorder) {
      const anchor = `sl/${duplicate.id}`;
      const alias = recorder.assignAlias(duplicate, anchor, "slide");
      recorder.record({
        op: "slide.duplicate",
        target: recorder.targetRefForElement(slide, `sl/${slide.id}`),
        as: alias
      });
    }
    return duplicate;
  }
  #moveSlide(slide, targetIndex) {
    const sourceIndex = this.#items.indexOf(slide);
    if (sourceIndex === -1) {
      throw new Error("Cannot move a slide that is not in this collection.");
    }
    const normalizedTarget = Number.isFinite(targetIndex) ? Math.trunc(targetIndex) : 0;
    const clampedTarget = Math.max(0, Math.min(normalizedTarget, this.#items.length - 1));
    if (clampedTarget === sourceIndex) {
      return;
    }
    const activeSlide = this.#activeIndex >= 0 && this.#activeIndex < this.#items.length ? this.#items[this.#activeIndex] : undefined;
    this.#items.splice(sourceIndex, 1);
    const insertionIndex = Math.max(0, Math.min(clampedTarget, this.#items.length));
    this.#items.splice(insertionIndex, 0, slide);
    const reindexStart = Math.min(sourceIndex, insertionIndex);
    this.#reindexSlides(reindexStart < 0 ? 0 : reindexStart);
    this.#context.getPresentation?.()?.queuePresentationCollabPublish();
    if (activeSlide) {
      const nextActiveIndex = this.#items.indexOf(activeSlide);
      this.#activeIndex = nextActiveIndex;
    } else {
      this.#activeIndex = -1;
    }
  }
  #reindexSlides(startIndex) {
    for (let index = startIndex;index < this.#items.length; index += 1) {
      const item = this.#items[index];
      if (item) {
        item.setIndex(index);
      }
    }
  }
  remove(index) {
    const slide = this.#items[index];
    if (!slide) {
      return;
    }
    slide.delete();
  }
  replace(proto) {
    const activeSlideId = this.getActive()?.id;
    this.#items = [];
    this.#itemsById = new Map;
    for (const slide of proto ?? []) {
      this.#attachSlide(new Slide2(this.#slideContext(), slide));
    }
    for (let index = 0;index < this.#items.length; index += 1) {
      this.#items[index]?.setIndex(index);
    }
    if (activeSlideId) {
      const nextActiveIndex = this.#items.findIndex((slide) => slide.id === activeSlideId);
      this.#activeIndex = nextActiveIndex >= 0 ? nextActiveIndex : -1;
      return;
    }
    this.#activeIndex = this.#items.length > 0 ? 0 : -1;
  }
  #deleteSlide(slide) {
    const index = this.#items.indexOf(slide);
    if (index === -1) {
      return;
    }
    this.#context.getPresentation?.()?.removeSlideCollaborativeState(slide.id);
    this.#detachSlide(slide, index);
    if (this.#items.length === 0) {
      this.#activeIndex = -1;
    } else if (this.#activeIndex > index) {
      this.#activeIndex -= 1;
    } else if (this.#activeIndex === index) {
      this.#activeIndex = Math.min(index, this.#items.length - 1);
    }
    this.#reindexSlides(index);
    this.#context.getPresentation?.()?.queuePresentationCollabPublish();
  }
  getActive() {
    if (this.#activeIndex < 0) {
      return;
    }
    return this.#items[this.#activeIndex];
  }
  setActive(slide) {
    const index = this.#items.indexOf(slide);
    if (index >= 0) {
      this.#activeIndex = index;
    }
  }
  get count() {
    return this.#items.length;
  }
  toProto() {
    return this.#items.map((slide) => slide.toProto());
  }
  #slideContext() {
    return {
      ...this.#context,
      duplicateSlide: (slide) => this.#duplicateSlide(slide),
      moveSlide: (slide, index) => this.#moveSlide(slide, index),
      deleteSlide: (slide) => this.#deleteSlide(slide),
      renderSlidePreview: (slide, options) => this.#context.renderSlidePreview(slide, options)
    };
  }
  #attachSlide(slide, index) {
    if (typeof index === "number" && Number.isFinite(index)) {
      const normalized = Math.max(0, Math.min(Math.trunc(index), this.#items.length));
      this.#items.splice(normalized, 0, slide);
    } else {
      this.#items.push(slide);
    }
    if (slide.id) {
      this.#itemsById.set(slide.id, slide);
    }
  }
  #detachSlide(slide, index) {
    const removalIndex = index ?? this.#items.findIndex((candidate) => candidate === slide);
    if (removalIndex >= 0 && removalIndex < this.#items.length) {
      this.#items.splice(removalIndex, 1);
    }
    if (slide.id) {
      const entry = this.#itemsById.get(slide.id);
      if (entry === slide) {
        this.#itemsById.delete(slide.id);
      }
    }
  }
  #resolveInsertIndex(after) {
    if (after === undefined || after === null || this.#items.length <= 1) {
      return this.#items.length - 1;
    }
    let afterIndex;
    if (typeof after === "number") {
      if (!Number.isFinite(after)) {
        throw new Error("Insert index must be a finite number.");
      }
      afterIndex = Math.trunc(after);
      if (afterIndex < 0 || afterIndex >= this.#items.length) {
        throw new Error("Insert index is out of range.");
      }
    } else {
      afterIndex = this.#items.indexOf(after);
      if (afterIndex === -1) {
        throw new Error("Cannot insert relative to a slide outside this collection.");
      }
    }
    const candidate = afterIndex + 1;
    return Math.min(Math.max(candidate, 0), this.#items.length - 1);
  }
}

// node_modules/@oai/granola/dist/models/presentation/templates/office-theme.js
var buildOuterShadowEffectStyle = (alpha, blurPx, distancePx) => ({
  effects: [
    {
      type: 1 /* EFFECT_TYPE_OUTER_SHADOW */,
      shadow: {
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "000000",
          transform: {
            alpha: Math.round(alpha * 1e5)
          }
        },
        blurRadius: emuFromPixels(blurPx),
        distance: emuFromPixels(distancePx),
        direction: 5400000
      }
    }
  ]
});
var officeThemeTemplate = {
  colorScheme: {
    name: "ChatGPT",
    colors: [
      {
        name: "accent1",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "D53D4F",
          transform: undefined
        }
      },
      {
        name: "accent2",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "FDAE60",
          transform: undefined
        }
      },
      {
        name: "accent3",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "FEDE8A",
          transform: undefined
        }
      },
      {
        name: "accent4",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "E4F596",
          transform: undefined
        }
      },
      {
        name: "accent5",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "66C1A4",
          transform: undefined
        }
      },
      {
        name: "accent6",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "2F81B4",
          transform: undefined
        }
      },
      {
        name: "dk1",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "000000",
          transform: undefined
        }
      },
      {
        name: "lt1",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "FFFFFF",
          transform: undefined
        }
      },
      {
        name: "dk2",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "0E2841",
          transform: undefined
        }
      },
      {
        name: "lt2",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "E8E8E8",
          transform: undefined
        }
      },
      {
        name: "hlink",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "467886",
          transform: undefined
        }
      },
      {
        name: "folHlink",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "96607D",
          transform: undefined
        }
      }
    ]
  },
  backgroundFillStyleList: [
    {
      type: 1 /* FILL_TYPE_SOLID */,
      color: {
        type: 2 /* COLOR_TYPE_SCHEME */,
        value: "phClr",
        transform: undefined
      },
      gradientStops: [],
      pattern: undefined
    },
    {
      type: 1 /* FILL_TYPE_SOLID */,
      color: {
        type: 2 /* COLOR_TYPE_SCHEME */,
        value: "phClr",
        transform: {
          tint: 95000,
          satMod: 170000
        }
      },
      gradientStops: [],
      pattern: undefined
    },
    {
      type: 2 /* FILL_TYPE_GRADIENT */,
      color: undefined,
      gradientStops: [
        {
          position: 0,
          color: {
            type: 2 /* COLOR_TYPE_SCHEME */,
            value: "phClr",
            transform: {
              tint: 93000,
              shade: 98000,
              lumMod: 102000,
              satMod: 150000
            }
          }
        },
        {
          position: 50000,
          color: {
            type: 2 /* COLOR_TYPE_SCHEME */,
            value: "phClr",
            transform: {
              tint: 98000,
              shade: 90000,
              lumMod: 103000,
              satMod: 130000
            }
          }
        },
        {
          position: 1e5,
          color: {
            type: 2 /* COLOR_TYPE_SCHEME */,
            value: "phClr",
            transform: {
              shade: 63000,
              satMod: 120000
            }
          }
        }
      ],
      gradientKind: 1 /* GRADIENT_KIND_LINEAR */,
      angleDeg: 90,
      isScaled: false,
      pattern: undefined
    }
  ],
  lineStyleList: [
    {
      style: 1 /* LINE_STYLE_SOLID */,
      widthEmu: 12700,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "phClr",
          transform: undefined
        },
        gradientStops: [],
        pattern: undefined
      }
    },
    {
      style: 1 /* LINE_STYLE_SOLID */,
      widthEmu: 19050,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "phClr",
          transform: undefined
        },
        gradientStops: [],
        pattern: undefined
      }
    },
    {
      style: 1 /* LINE_STYLE_SOLID */,
      widthEmu: 25400,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "phClr",
          transform: undefined
        },
        gradientStops: [],
        pattern: undefined
      }
    }
  ],
  effectStyleList: [
    { effects: [] },
    { effects: [] },
    buildOuterShadowEffectStyle(0.16, 6, 2),
    buildOuterShadowEffectStyle(0.06, 2, 1),
    buildOuterShadowEffectStyle(0.08, 3, 1),
    buildOuterShadowEffectStyle(0.1, 6, 2),
    buildOuterShadowEffectStyle(0.12, 12, 4),
    buildOuterShadowEffectStyle(0.16, 18, 6),
    buildOuterShadowEffectStyle(0.24, 28, 10)
  ]
};

// node_modules/@oai/granola/dist/models/presentation/theme.js
var DEFAULT_THEME_COLORS = {
  accent1: new Color4("#156082"),
  accent2: new Color4("#E97132"),
  accent3: new Color4("#196B24"),
  accent4: new Color4("#0F9ED5"),
  accent5: new Color4("#A02B93"),
  accent6: new Color4("#4EA72E"),
  bg1: new Color4("#FFFFFF"),
  bg2: new Color4("#000000"),
  tx1: new Color4("#1F1F1F"),
  tx2: new Color4("#FFFFFF"),
  dk1: new Color4("#000000"),
  lt1: new Color4("#FFFFFF"),
  dk2: new Color4("#0E2841"),
  lt2: new Color4("#E8E8E8"),
  hlink: new Color4("#467886"),
  folHlink: new Color4("#96607D")
};
var DEFAULT_THEME_TEXT_STYLES = {
  display: {
    fontSize: "text-display",
    bold: true,
    alignment: "center",
    wrap: "none"
  },
  subtitle: {
    fontSize: "text-subtitle",
    italic: true,
    alignment: "center",
    wrap: "none"
  },
  section: {
    fontSize: "text-section",
    bold: true,
    alignment: "left",
    wrap: "none"
  },
  body: {
    fontSize: "text-body",
    alignment: "left",
    wrap: "square"
  },
  caption: {
    fontSize: "text-caption",
    alignment: "left",
    wrap: "none"
  }
};

class Theme2 {
  #context;
  #colorScheme;
  #data;
  #runtime;
  constructor(context, proto, runtime) {
    this.#context = context;
    this.#context;
    this.#runtime = runtime;
    const themeColors = proto?.colorScheme?.colors?.reduce((acc, color2) => {
      acc[color2.name] = new Color4({
        type: "proto",
        proto: color2.color
      }, runtime);
      return acc;
    }, {}) ?? DEFAULT_THEME_COLORS;
    this.#colorScheme = {
      name: proto?.colorScheme?.name ?? "ChatGPT",
      themeColors
    };
    this.#data = {
      backgroundFillStyleList: proto?.backgroundFillStyleList ?? officeThemeTemplate.backgroundFillStyleList,
      lineStyleList: proto?.lineStyleList ?? officeThemeTemplate.lineStyleList,
      effectStyleList: proto?.effectStyleList ?? officeThemeTemplate.effectStyleList
    };
    if (this.#canManageTextStyles()) {
      this.textStyles();
    }
  }
  replaceFromProto(proto) {
    const themeColors = proto?.colorScheme?.colors?.reduce((acc, color2) => {
      acc[color2.name] = new Color4({
        type: "proto",
        proto: color2.color
      }, this.#runtime);
      return acc;
    }, {}) ?? DEFAULT_THEME_COLORS;
    this.#colorScheme = {
      name: proto?.colorScheme?.name ?? "ChatGPT",
      themeColors
    };
    this.#data = {
      backgroundFillStyleList: proto?.backgroundFillStyleList ?? officeThemeTemplate.backgroundFillStyleList,
      lineStyleList: proto?.lineStyleList ?? officeThemeTemplate.lineStyleList,
      effectStyleList: proto?.effectStyleList ?? officeThemeTemplate.effectStyleList
    };
  }
  get lineStyleList() {
    return this.#data.lineStyleList;
  }
  get effectStyleList() {
    return this.#data.effectStyleList;
  }
  get backgroundFillStyleList() {
    return this.#data.backgroundFillStyleList;
  }
  set colorScheme(colorScheme) {
    this.#colorScheme = {
      name: colorScheme.name,
      themeColors: Object.entries(colorScheme.themeColors).reduce((acc, [name, color2]) => {
        acc[name] = new Color4(color2, this.#runtime);
        return acc;
      }, {})
    };
    this.#context.queueCollaborativePublish?.();
  }
  get colorScheme() {
    return this.#colorScheme;
  }
  get hexColorMap() {
    return Object.fromEntries(Object.entries(this.#colorScheme.themeColors).map(([key, color2]) => [
      key,
      color2?.hex ?? ""
    ]));
  }
  resolveThemeColorHex(name) {
    const color2 = this.#colorScheme.themeColors[name];
    if (!color2) {
      return;
    }
    return color2.hex;
  }
  ensureEffectStyle(effectStyle) {
    const key = JSON.stringify(effectStyle);
    const existingIndex = this.#data.effectStyleList.findIndex((candidate) => JSON.stringify(candidate) === key);
    if (existingIndex >= 0) {
      return String(existingIndex + 1);
    }
    this.#data.effectStyleList.push(effectStyle);
    this.#context.queueCollaborativePublish?.();
    return String(this.#data.effectStyleList.length);
  }
  textStyles(styles) {
    const styleConfigMap = styles ?? DEFAULT_THEME_TEXT_STYLES;
    if (!this.#canManageTextStyles()) {
      throw new Error("presentation.theme.textStyles(...) requires a presentation-backed theme context.");
    }
    const result = {};
    for (const [rawName, config] of Object.entries(styleConfigMap)) {
      const styleName = readStyleName(rawName);
      const style = this.#context.addTextStyle(styleName);
      const resolvedConfig = resolveTokenizedTextStyleConfig(config, {
        fontSizeTokens: DEFAULT_FONT_SIZE_TOKENS,
        name: `presentation.theme.textStyles(${styleName})`
      });
      applyTextStyleConfig(style, resolvedConfig);
      result[rawName] = styleName;
    }
    return result;
  }
  toProto() {
    return {
      colorScheme: {
        name: this.#colorScheme.name,
        colors: Object.entries(this.#colorScheme.themeColors).map(([name, color2]) => ({
          name,
          color: color2.toProto()
        }))
      },
      backgroundFillStyleList: this.#data.backgroundFillStyleList,
      lineStyleList: this.#data.lineStyleList,
      effectStyleList: this.#data.effectStyleList
    };
  }
  #canManageTextStyles() {
    return typeof this.#context.addTextStyle === "function" && typeof this.#context.resolveTextStyle === "function";
  }
}
var readStyleName = (value) => {
  const trimmed = value.trim();
  if (trimmed.length === 0) {
    throw new Error("theme text style names must be non-empty.");
  }
  return trimmed;
};

// node_modules/@oai/granola/dist/models/presentation/scripts/registry.js
var DEFAULT_CHART_POSITION = {
  left: 60,
  top: 80,
  width: 600,
  height: 360
};
var DEFAULT_SHAPE_SIZE = { width: 100, height: 100 };
var DEFAULT_SHAPE_FILL_THEME = "accent1";
var DEFAULT_SHAPE_STROKE_HEX = "#000000";
var DEFAULT_SHAPE_STROKE_WIDTH_PX = 2;
var DEFAULT_SLIDE_BACKGROUND_FILL_THEME = "bg1";
var PX_PER_POINT2 = 96 / 72;
var DEFAULT_SERIES_COLORS = [
  "accent1",
  "accent2",
  "accent3",
  "accent4"
];
function buildCenteredPosition(slide, size2) {
  const frame = slide.frame;
  const left = Math.max(0, (frame.width - size2.width) / 2);
  const top = Math.max(0, (frame.height - size2.height) / 2);
  return {
    unit: ShapePositionUnit.pixels,
    left,
    top,
    width: size2.width,
    height: size2.height
  };
}
function defaultCategories() {
  return ["2020", "2021", "2022", "2023"];
}
function buildDefaultSeriesPayload(categories) {
  const normalizedCategories = categories.length > 0 ? categories : defaultCategories();
  return [
    {
      name: "Milky Way",
      values: [1.8, 1.9, 2, 2.2],
      categories: normalizedCategories,
      strokeTheme: "accent1"
    },
    {
      name: "Andromeda",
      values: [2.4, 2.5, 2.6, 2.8],
      categories: normalizedCategories,
      strokeTheme: "accent2"
    }
  ];
}
function ptToPx2(value) {
  if (value === undefined) {
    return;
  }
  return value * PX_PER_POINT2;
}
function getRuntimeSlide(runtime) {
  const slides = runtime.presentation.slides;
  if (slides.count === 0) {
    throw new Error("Presentation has no slides to edit.");
  }
  if (!runtime.slideId) {
    throw new Error("Slide id is required to edit a slide.");
  }
  const slide = slides.getItem({ id: runtime.slideId });
  if (!slide) {
    throw new Error(`Slide with id ${runtime.slideId} not found.`);
  }
  return slide;
}
function getShapeById(slide, shapeId) {
  const shape2 = slide.shapes.getItem({ id: shapeId });
  if (!shape2) {
    throw new Error(`Shape ${shapeId} not found on slide.`);
  }
  return shape2;
}
function resolveReferenceSlide(runtime) {
  const slides = runtime.presentation.slides;
  if (runtime.slideId) {
    try {
      return slides.getItem({ id: runtime.slideId });
    } catch {}
  }
  return runtime.presentation.getActiveSlide() ?? null;
}
function insertSlideMutator(runtime, options) {
  const presentation = runtime.presentation;
  const slides = presentation.slides;
  const referenceSlide = resolveReferenceSlide(runtime);
  const { slide, index } = slides.insert({
    ...options,
    after: referenceSlide ?? undefined
  });
  return {
    slideId: slide.id,
    index
  };
}
function insertShapeMutator(runtime, options) {
  const slide = getRuntimeSlide(runtime);
  const targetPosition = options.position ?? buildCenteredPosition(slide, DEFAULT_SHAPE_SIZE);
  const shape2 = slide.shapes.add({
    geometry: options.geometry,
    position: targetPosition
  });
  shape2.fill = options.fillTheme || options.fillHex || DEFAULT_SHAPE_FILL_THEME;
  shape2.line.width = DEFAULT_SHAPE_STROKE_WIDTH_PX;
  shape2.line.style = "solid";
  shape2.line.fill = DEFAULT_SHAPE_STROKE_HEX;
  console.log("[slides][insertShape] shape", shape2.toProto());
  console.log("[slides][insertShape] presentation", runtime.presentation.toProto());
  return {
    shapeId: shape2.id,
    geometry: options.geometry
  };
}
function insertChartFromTemplateMutator(runtime, options) {
  const slide = getRuntimeSlide(runtime);
  const chart2 = slide.charts.add(options.chartType);
  chart2.position = options.position ?? DEFAULT_CHART_POSITION;
  chart2.title = options.title ?? "New chart";
  const categories = options.categories ?? defaultCategories();
  if (categories.length) {
    chart2.categories = categories;
  }
  const seriesPayload = options.series?.map((series) => ({ ...series })) ?? buildDefaultSeriesPayload(categories);
  seriesPayload.forEach((entry, index) => {
    const series = chart2.series.add(entry.name);
    series.values = entry.values;
    series.categories = entry.categories ?? categories;
    const strokeTheme = entry.strokeTheme ?? DEFAULT_SERIES_COLORS[index];
    if (strokeTheme) {
      series.stroke.width = 1.5;
      series.stroke.style = "solid";
      series.stroke.fill = strokeTheme;
    }
    const fillTheme = entry.fillTheme ?? strokeTheme;
    if (fillTheme) {
      series.fill = fillTheme;
    }
  });
  chart2.hasLegend = seriesPayload.length > 1;
  return {
    chartId: chart2.id,
    chartType: options.chartType,
    seriesCount: seriesPayload.length
  };
}
function setShapeFillMutator(runtime, options) {
  const slide = getRuntimeSlide(runtime);
  const shape2 = getShapeById(slide, options.shapeId);
  const color2 = options.theme || options.hex || DEFAULT_SHAPE_FILL_THEME;
  shape2.fill = color2;
  return { shapeId: shape2.id };
}
function setShapeStrokeMutator(runtime, options) {
  const slide = getRuntimeSlide(runtime);
  const shape2 = getShapeById(slide, options.shapeId);
  const color2 = options.theme || options.hex || DEFAULT_SHAPE_STROKE_HEX;
  shape2.line.fill = color2;
  shape2.line.width = options.widthPx ?? shape2.line.width ?? 1;
  shape2.line.style = "solid";
  return { shapeId: shape2.id };
}
function setSlideBackgroundFillMutator(runtime, options) {
  const slide = getRuntimeSlide(runtime);
  const color2 = options.theme || options.hex || DEFAULT_SLIDE_BACKGROUND_FILL_THEME;
  slide.background.fill = { type: "solid", color: color2 };
  return { slideId: slide.id };
}
function setTextRangeFormattingMutator(runtime, options) {
  const slide = getRuntimeSlide(runtime);
  const shape2 = getShapeById(slide, options.shapeId);
  const text2 = shape2.text;
  if (!text2) {
    throw new Error(`Shape ${options.shapeId} has no text content to edit.`);
  }
  const selection = text2.selectRunRanges(options.ranges ?? []);
  const hasFormattingSelection = !selection.isEmpty;
  if (hasFormattingSelection) {
    if (options.color) {
      const newColor = options.color.theme || options.color.hex;
      if (newColor) {
        selection.color = { type: "rgb", value: newColor };
      }
    }
    const nextFontSize = ptToPx2(options.fontSizePt);
    if (nextFontSize !== undefined) {
      selection.fontSize = nextFontSize;
    }
    if (options.bold !== undefined) {
      selection.bold = options.bold;
    }
    if (options.italic !== undefined) {
      selection.italic = options.italic;
    }
    if (options.alignment !== undefined) {
      selection.alignment = options.alignment;
    }
    if (options.spacingBefore !== undefined) {
      selection.spacingBefore = options.spacingBefore;
    }
    if (options.spacingAfter !== undefined) {
      selection.spacingAfter = options.spacingAfter;
    }
    if (options.lineSpacing !== undefined) {
      selection.lineSpacing = options.lineSpacing;
    }
  }
  if (options.verticalAlignment !== undefined) {
    text2.verticalAlignment = options.verticalAlignment;
  }
  if (options.insets !== undefined) {
    text2.insets = { ...options.insets };
  }
  return { shapeId: shape2.id };
}
var registry = {
  insertSlide: {
    feature: "walnut_insert_slide_from_layout",
    run: insertSlideMutator
  },
  insertShape: {
    feature: "walnut_insert_shape",
    run: insertShapeMutator
  },
  insertChartFromTemplate: {
    feature: "walnut_insert_chart_from_template",
    run: insertChartFromTemplateMutator
  },
  setShapeFill: {
    feature: "walnut_set_shape_fill",
    run: setShapeFillMutator
  },
  setShapeStroke: {
    feature: "walnut_set_shape_stroke",
    run: setShapeStrokeMutator
  },
  setSlideBackgroundFill: {
    feature: "walnut_set_slide_background_fill",
    run: setSlideBackgroundFillMutator
  },
  setTextRangeFormatting: {
    feature: "walnut_set_text_range_formatting",
    run: setTextRangeFormattingMutator
  }
};
var presentationScriptRegistry = registry;

// node_modules/@oai/granola/dist/models/presentation/scripts/scripts.js
class Scripts {
  #context;
  #resolveSlideId = null;
  #afterRun = null;
  #onError = null;
  constructor(context) {
    this.#context = context;
  }
  configureRuntime(config) {
    if (Object.prototype.hasOwnProperty.call(config, "resolveSlideId")) {
      this.#resolveSlideId = config.resolveSlideId ?? null;
    }
  }
  onAfterRun(callback) {
    this.#afterRun = callback ?? null;
  }
  onError(callback) {
    this.#onError = callback ?? null;
  }
  run(kind, options) {
    const descriptor = presentationScriptRegistry[kind];
    if (!descriptor) {
      const error = new Error(`Unknown presentation script: ${String(kind)}`);
      this.#onError?.(error, { kind });
      return null;
    }
    const runtime = {
      presentation: this.#context.presentation,
      slideId: this.#resolveSlideId?.() ?? null
    };
    try {
      const context = descriptor.run(runtime, options) ?? undefined;
      const result = {
        kind,
        feature: descriptor.feature,
        context
      };
      this.#afterRun?.(result);
      return result;
    } catch (error) {
      this.#onError?.(error, { kind });
      return null;
    }
  }
}

// node_modules/@oai/granola/dist/models/presentation/defaults/default-master-body-level-styles.js
var DEFAULT_MASTER_BODY_LEVEL_STYLES = [
  {
    level: 1,
    textStyle: {
      fontSize: 2800,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      bulletCharacter: "•",
      marginLeft: 228600,
      indent: -228600,
      lineSpacingPercent: 90000
    },
    spaceBefore: 1000
  },
  {
    level: 2,
    textStyle: {
      fontSize: 2400,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      bulletCharacter: "•",
      marginLeft: 685800,
      indent: -228600,
      lineSpacingPercent: 90000
    },
    spaceBefore: 500
  },
  {
    level: 3,
    textStyle: {
      fontSize: 2000,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      bulletCharacter: "•",
      marginLeft: 1143000,
      indent: -228600,
      lineSpacingPercent: 90000
    },
    spaceBefore: 500
  },
  {
    level: 4,
    textStyle: {
      fontSize: 1800,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      bulletCharacter: "•",
      marginLeft: 1600200,
      indent: -228600,
      lineSpacingPercent: 90000
    },
    spaceBefore: 500
  },
  {
    level: 5,
    textStyle: {
      fontSize: 1800,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      bulletCharacter: "•",
      marginLeft: 2057400,
      indent: -228600,
      lineSpacingPercent: 90000
    },
    spaceBefore: 500
  },
  {
    level: 6,
    textStyle: {
      fontSize: 1800,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      bulletCharacter: "•",
      marginLeft: 2514600,
      indent: -228600,
      lineSpacingPercent: 90000
    },
    spaceBefore: 500
  },
  {
    level: 7,
    textStyle: {
      fontSize: 1800,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      bulletCharacter: "•",
      marginLeft: 2971800,
      indent: -228600,
      lineSpacingPercent: 90000
    },
    spaceBefore: 500
  },
  {
    level: 8,
    textStyle: {
      fontSize: 1800,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      bulletCharacter: "•",
      marginLeft: 3429000,
      indent: -228600,
      lineSpacingPercent: 90000
    },
    spaceBefore: 500
  },
  {
    level: 9,
    textStyle: {
      fontSize: 1800,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      bulletCharacter: "•",
      marginLeft: 3886200,
      indent: -228600,
      lineSpacingPercent: 90000
    },
    spaceBefore: 500
  }
];

// node_modules/@oai/granola/dist/models/presentation/defaults/default-master-color-map.js
var DEFAULT_MASTER_COLOR_MAP = {
  accent1: "accent1",
  accent2: "accent2",
  accent3: "accent3",
  accent4: "accent4",
  accent5: "accent5",
  accent6: "accent6",
  bg1: "lt1",
  bg2: "lt2",
  tx1: "dk1",
  tx2: "dk2",
  hlink: "hlink",
  folHlink: "folHlink"
};

// node_modules/@oai/granola/dist/models/presentation/defaults/default-master-other-level-styles.js
var DEFAULT_MASTER_OTHER_LEVEL_STYLES = [
  {
    level: 1,
    textStyle: {
      fontSize: 1800,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      marginLeft: 0
    }
  },
  {
    level: 2,
    textStyle: {
      fontSize: 1800,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      marginLeft: 457200
    }
  },
  {
    level: 3,
    textStyle: {
      fontSize: 1800,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      marginLeft: 914400
    }
  },
  {
    level: 4,
    textStyle: {
      fontSize: 1800,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      marginLeft: 1371600
    }
  },
  {
    level: 5,
    textStyle: {
      fontSize: 1800,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      marginLeft: 1828800
    }
  },
  {
    level: 6,
    textStyle: {
      fontSize: 1800,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      marginLeft: 2286000
    }
  },
  {
    level: 7,
    textStyle: {
      fontSize: 1800,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      marginLeft: 2743200
    }
  },
  {
    level: 8,
    textStyle: {
      fontSize: 1800,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      marginLeft: 3200400
    }
  },
  {
    level: 9,
    textStyle: {
      fontSize: 1800,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mn-lt"
    },
    paragraphStyle: {
      marginLeft: 3657600
    }
  }
];

// node_modules/@oai/granola/dist/models/presentation/defaults/default-master-placeholders.js
var DEFAULT_MASTER_PLACEHOLDERS = [];

// node_modules/@oai/granola/dist/models/presentation/defaults/default-master-title-level-styles.js
var DEFAULT_MASTER_TITLE_LEVEL_STYLES = [
  {
    level: 1,
    textStyle: {
      fontSize: 4400,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "tx1",
          transform: undefined
        },
        gradientStops: []
      },
      alignment: 1 /* ALIGNMENT_TYPE_LEFT */,
      typeface: "+mj-lt"
    },
    paragraphStyle: {
      bulletCharacter: "",
      lineSpacingPercent: 90000
    },
    spaceBefore: 0
  }
];

// node_modules/@oai/granola/dist/models/presentation/defaults/default-presentation-context.js
var DEFAULT_PRESENTATION_CONTEXT = {
  stub: () => {}
};

// node_modules/@oai/granola/dist/models/presentation/defaults/default-slide-dimension-emu.js
var DEFAULT_SLIDE_DIMENSION_EMU = 914400;

// node_modules/@oai/granola/dist/models/presentation/defaults/default-table-style-id.js
var DEFAULT_TABLE_STYLE_ID = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}";

// node_modules/@oai/granola/dist/models/presentation/defaults/default-table-style-xml.js
var DEFAULT_TABLE_STYLE_XML = '<a:tblStyleLst xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" def="{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}" />';

// node_modules/@oai/granola/dist/models/presentation/defaults/default-table-styles.js
var DEFAULT_TABLE_STYLES = {
  defaultStyleId: DEFAULT_TABLE_STYLE_ID,
  outerXml: DEFAULT_TABLE_STYLE_XML
};

// node_modules/@oai/granola/dist/models/presentation/defaults/default-title-layout-placeholders.js
var DEFAULT_TITLE_LAYOUT_PLACEHOLDERS = [];

// node_modules/@oai/granola/dist/models/comments/annotation-target.js
init_address_utils();

class AnnotationTarget3 {
  #data;
  constructor(proto) {
    this.#data = cloneAnnotationTarget(proto);
  }
  static fromProto(proto) {
    return new AnnotationTarget3(proto);
  }
  static fromConfig(config) {
    if ("proto" in config) {
      return new AnnotationTarget3(config.proto);
    }
    if ("slide" in config) {
      return new AnnotationTarget3({ slide: buildSlideTarget(config.slide) });
    }
    if ("element" in config) {
      return new AnnotationTarget3({
        element: buildElementTarget(config.element)
      });
    }
    if ("textRange" in config) {
      return new AnnotationTarget3({
        textRange: buildTextRangeTarget(config.textRange)
      });
    }
    if ("textMatch" in config) {
      return new AnnotationTarget3({
        textRange: buildTextMatchTarget(config.textMatch)
      });
    }
    if ("cell" in config) {
      return new AnnotationTarget3({
        spreadsheetCell: buildSpreadsheetCellTarget(config.cell)
      });
    }
    return new AnnotationTarget3({
      spreadsheetRange: buildSpreadsheetRangeTarget(config.range)
    });
  }
  toProto() {
    return cloneAnnotationTarget(this.#data);
  }
  get kind() {
    if (this.#data.slide) {
      return "slide";
    }
    if (this.#data.element) {
      return "element";
    }
    if (this.#data.textRange) {
      return "textRange";
    }
    if (this.#data.spreadsheetCell) {
      return "spreadsheetCell";
    }
    if (this.#data.spreadsheetRange) {
      return "spreadsheetRange";
    }
    return "unknown";
  }
  get slideId() {
    return this.#data.slide?.slideId ?? this.#data.element?.slideId ?? this.#data.textRange?.slideId;
  }
  get elementId() {
    return this.#data.element?.elementId ?? this.#data.textRange?.elementId;
  }
  get spreadsheetCell() {
    const cell = this.#data.spreadsheetCell;
    if (!cell) {
      return;
    }
    return {
      sheetName: cell.sheetName,
      sheetId: cell.sheetId,
      address: cell.address
    };
  }
  get spreadsheetRange() {
    const range2 = this.#data.spreadsheetRange;
    if (!range2) {
      return;
    }
    return {
      sheetName: range2.sheetName,
      sheetId: range2.sheetId,
      startAddress: range2.startAddress,
      endAddress: range2.endAddress
    };
  }
}
var buildSlideTarget = (slide) => {
  if (!slide.id) {
    throw new Error("Slide target requires a slide id.");
  }
  return { slideId: slide.id };
};
var buildElementTarget = (element) => {
  if (!element.id) {
    throw new Error("Element target requires an element id.");
  }
  const slideId = element.slideId;
  if (!slideId) {
    throw new Error("Element target requires a slide id.");
  }
  return { slideId, elementId: element.id };
};
var buildTextRangeTarget = (config) => {
  const { element, startCp, length: length2 } = config;
  if (!element.id) {
    throw new Error("Text range target requires an element id.");
  }
  const slideId = element.slideId;
  if (!slideId) {
    throw new Error("Text range target requires a slide id.");
  }
  return {
    slideId,
    elementId: element.id,
    startCp,
    length: length2,
    context: buildTextRangeContext(config.context)
  };
};
var buildTextMatchTarget = (config) => {
  const { element, query } = config;
  if (!element.id) {
    throw new Error("Text match target requires an element id.");
  }
  const slideId = element.slideId;
  if (!slideId) {
    throw new Error("Text match target requires a slide id.");
  }
  if (!query) {
    throw new Error("Text match target requires a query.");
  }
  const text2 = element.text.toString();
  const occurrence = config.occurrence ?? 0;
  const startCp = findOccurrenceIndex(text2, query, occurrence);
  if (startCp < 0) {
    throw new Error(`Text match target could not find "${query}".`);
  }
  return {
    slideId,
    elementId: element.id,
    startCp,
    length: query.length,
    context: buildTextRangeContext(config.context)
  };
};
var buildTextRangeContext = (context) => {
  if (!context) {
    return;
  }
  const hasValue = context.contextLength !== undefined || context.contextHash !== undefined;
  if (!hasValue) {
    return;
  }
  return {
    contextLength: context.contextLength,
    contextHash: context.contextHash
  };
};
var buildSpreadsheetCellTarget = (input) => {
  const { worksheet, address } = resolveWorksheetTarget(input);
  const parsed = parseRangeAddress(address);
  if (!parsed) {
    throw new Error(`Invalid cell address: ${address}`);
  }
  if (parsed.ref.includes(":")) {
    throw new Error(`Cell target expects a single cell: ${address}`);
  }
  return {
    sheetName: worksheet.name,
    sheetId: worksheet.sheetId,
    address: parsed.ref
  };
};
var buildSpreadsheetRangeTarget = (input) => {
  const { worksheet, address } = resolveWorksheetTarget(input);
  const parsed = parseRangeAddress(address);
  if (!parsed) {
    throw new Error(`Invalid range address: ${address}`);
  }
  const startAddress = makeCellAddress(parsed.bounds.startRow, parsed.bounds.startCol);
  const endAddress = makeCellAddress(parsed.bounds.endRow, parsed.bounds.endCol);
  return {
    sheetName: worksheet.name,
    sheetId: worksheet.sheetId,
    startAddress,
    endAddress
  };
};
var resolveWorksheetTarget = (input) => {
  if (isRange(input)) {
    const worksheet2 = input.__getWorksheet();
    if (!worksheet2) {
      throw new Error("Range target requires a worksheet.");
    }
    const { ref: ref2 } = splitSheetAddress(input.address);
    return { worksheet: worksheet2, address: ref2 };
  }
  const { worksheet, address } = input;
  const { ref } = splitSheetAddress(address);
  return { worksheet, address: ref };
};
var isRange = (value) => {
  return typeof value === "object" && value !== null && "__getWorksheet" in value;
};
var findOccurrenceIndex = (text2, query, occurrence) => {
  let index = -1;
  let fromIndex = 0;
  for (let i = 0;i <= occurrence; i += 1) {
    index = text2.indexOf(query, fromIndex);
    if (index === -1) {
      return -1;
    }
    fromIndex = index + query.length;
  }
  return index;
};
var cloneAnnotationTarget = (proto) => {
  if (proto.spreadsheetCell) {
    const cell = proto.spreadsheetCell;
    return {
      spreadsheetCell: {
        sheetName: cell.sheetName,
        sheetId: cell.sheetId,
        address: cell.address
      }
    };
  }
  if (proto.spreadsheetRange) {
    const range2 = proto.spreadsheetRange;
    return {
      spreadsheetRange: {
        sheetName: range2.sheetName,
        sheetId: range2.sheetId,
        startAddress: range2.startAddress,
        endAddress: range2.endAddress
      }
    };
  }
  if (proto.slide) {
    return { slide: { slideId: proto.slide.slideId } };
  }
  if (proto.element) {
    return {
      element: {
        slideId: proto.element.slideId,
        elementId: proto.element.elementId
      }
    };
  }
  if (proto.textRange) {
    const context = proto.textRange.context;
    return {
      textRange: {
        slideId: proto.textRange.slideId,
        elementId: proto.textRange.elementId,
        startCp: proto.textRange.startCp,
        length: proto.textRange.length,
        context: context ? {
          contextLength: context.contextLength,
          contextHash: context.contextHash
        } : undefined
      }
    };
  }
  return {};
};

// node_modules/@oai/granola/dist/models/comments/comment.js
class Comment2 {
  #data;
  #context;
  constructor(proto, context) {
    this.#data = cloneComment(proto);
    this.#context = context;
    this.#data.reactions ??= [];
    this.#data.citations ??= [];
  }
  static fromProto(proto, context) {
    return new Comment2(proto, context);
  }
  static create(config, context) {
    if (!config.id) {
      throw new Error("Comment id is required.");
    }
    if (!config.authorId) {
      throw new Error("Comment authorId is required.");
    }
    const body = buildTextBody(config.body);
    const position = buildCommentPosition(config.position);
    return new Comment2({
      id: config.id,
      parentId: config.parentId,
      authorId: config.authorId,
      createdAt: config.createdAt ?? context.now(),
      editedAt: config.editedAt,
      body,
      isDeleted: config.isDeleted ?? false,
      reactions: config.reactions ? cloneReactions(config.reactions) : [],
      citations: config.citations ?? [],
      position
    }, context);
  }
  get id() {
    return this.#data.id;
  }
  get parentId() {
    return this.#data.parentId;
  }
  get authorId() {
    return this.#data.authorId;
  }
  get createdAt() {
    return this.#data.createdAt;
  }
  get editedAt() {
    return this.#data.editedAt;
  }
  get text() {
    return this.#data.body?.plainText ?? "";
  }
  set text(value) {
    this.edit(value);
  }
  get reactions() {
    return this.#data.reactions ? cloneReactions(this.#data.reactions) : [];
  }
  get position() {
    return this.#data.position ? { ...this.#data.position } : undefined;
  }
  get positionPx() {
    const position = this.#data.position;
    if (!position) {
      return;
    }
    return {
      x: pixelsFromEmu(position.xEmu),
      y: pixelsFromEmu(position.yEmu)
    };
  }
  edit(text2, options = {}) {
    this.#data.body = { plainText: text2 };
    this.#data.editedAt = options.editedAt ?? this.#context.now();
  }
  delete() {
    this.#data.isDeleted = true;
  }
  toggleReaction(type, author) {
    if (!type) {
      throw new Error("Reaction type is required.");
    }
    const authorId = this.#context.resolveAuthorId(author);
    const reactions = this.#data.reactions ?? [];
    const existing = reactions.find((entry) => entry.type === type);
    if (!existing) {
      reactions.push({
        type,
        instances: [{ authorId, time: this.#context.now() }]
      });
      this.#data.reactions = reactions;
      return;
    }
    const instanceIndex = existing.instances.findIndex((instance) => instance.authorId === authorId);
    if (instanceIndex >= 0) {
      existing.instances.splice(instanceIndex, 1);
      if (existing.instances.length === 0) {
        const reactionIndex = reactions.indexOf(existing);
        if (reactionIndex >= 0) {
          reactions.splice(reactionIndex, 1);
        }
      }
    } else {
      existing.instances.push({ authorId, time: this.#context.now() });
    }
    this.#data.reactions = reactions;
  }
  toProto() {
    return cloneComment(this.#data);
  }
}
var buildTextBody = (body) => {
  if (typeof body === "string") {
    return { plainText: body };
  }
  if (body.plainText === undefined) {
    throw new Error("Comment body requires plainText.");
  }
  return { plainText: body.plainText };
};
var isPbCommentPosition = (input) => {
  return "xEmu" in input && "yEmu" in input;
};
var buildCommentPosition = (input) => {
  if (!input) {
    return;
  }
  if (isPbCommentPosition(input)) {
    return {
      xEmu: input.xEmu,
      yEmu: input.yEmu
    };
  }
  const unit2 = input.unit ?? "px";
  if (unit2 === "emu") {
    return { xEmu: input.x, yEmu: input.y };
  }
  return {
    xEmu: emuFromPixels(input.x),
    yEmu: emuFromPixels(input.y)
  };
};
var cloneComment = (proto) => {
  if (!proto.id) {
    throw new Error("Comment id is required.");
  }
  if (!proto.authorId) {
    throw new Error("Comment authorId is required.");
  }
  if (!proto.createdAt) {
    throw new Error("Comment createdAt is required.");
  }
  return {
    id: proto.id,
    parentId: proto.parentId,
    authorId: proto.authorId,
    createdAt: proto.createdAt,
    editedAt: proto.editedAt,
    body: proto.body ? { plainText: proto.body.plainText } : undefined,
    isDeleted: proto.isDeleted ?? false,
    reactions: proto.reactions ? cloneReactions(proto.reactions) : [],
    citations: proto.citations ? [...proto.citations] : [],
    position: proto.position ? { xEmu: proto.position.xEmu, yEmu: proto.position.yEmu } : undefined
  };
};
var cloneReactions = (reactions) => {
  return reactions.map((reaction) => {
    if (!reaction.type) {
      throw new Error("Comment reaction requires a type.");
    }
    return {
      type: reaction.type,
      instances: cloneReactionInstances(reaction.instances ?? [])
    };
  });
};
var cloneReactionInstances = (instances) => {
  return instances.map((instance) => {
    if (!instance.authorId) {
      throw new Error("Reaction instance requires authorId.");
    }
    if (!instance.time) {
      throw new Error("Reaction instance requires time.");
    }
    return {
      authorId: instance.authorId,
      time: instance.time
    };
  });
};

// node_modules/@oai/granola/dist/models/comments/person.js
class Person2 {
  #data;
  constructor(data) {
    this.#data = data;
  }
  static create(config) {
    if (!config.displayName.trim()) {
      throw new Error("Person displayName is required.");
    }
    return new Person2({
      id: config.id ?? generateGuid(),
      displayName: config.displayName,
      initials: config.initials,
      email: config.email,
      avatarUrl: config.avatarUrl,
      userId: config.userId,
      providerId: config.providerId
    });
  }
  static fromProto(proto) {
    return new Person2(personFromProto(proto));
  }
  get id() {
    return this.#data.id;
  }
  get displayName() {
    return this.#data.displayName;
  }
  set displayName(value) {
    if (!value.trim()) {
      throw new Error("Person displayName is required.");
    }
    this.#data.displayName = value;
  }
  get initials() {
    return this.#data.initials;
  }
  set initials(value) {
    this.#data.initials = value;
  }
  get email() {
    return this.#data.email;
  }
  set email(value) {
    this.#data.email = value;
  }
  get avatarUrl() {
    return this.#data.avatarUrl;
  }
  set avatarUrl(value) {
    this.#data.avatarUrl = value;
  }
  get userId() {
    return this.#data.userId;
  }
  set userId(value) {
    this.#data.userId = value;
  }
  get providerId() {
    return this.#data.providerId;
  }
  set providerId(value) {
    this.#data.providerId = value;
  }
  update(config) {
    if (config.displayName !== undefined) {
      this.displayName = config.displayName;
    }
    if (config.initials !== undefined) {
      this.initials = config.initials;
    }
    if (config.email !== undefined) {
      this.email = config.email;
    }
    if (config.avatarUrl !== undefined) {
      this.avatarUrl = config.avatarUrl;
    }
    if (config.userId !== undefined) {
      this.userId = config.userId;
    }
    if (config.providerId !== undefined) {
      this.providerId = config.providerId;
    }
  }
  toProto() {
    return {
      id: this.#data.id,
      displayName: this.#data.displayName,
      initials: this.#data.initials,
      email: this.#data.email,
      avatarUrl: this.#data.avatarUrl,
      userId: this.#data.userId,
      providerId: this.#data.providerId
    };
  }
}
var isPersonConfig = (value) => {
  if (value instanceof Person2) {
    return false;
  }
  return typeof value === "object" && value !== null && "displayName" in value;
};
var isPersonReference = (value) => {
  if (value instanceof Person2) {
    return true;
  }
  return typeof value === "object" && value !== null && "id" in value;
};
var personFromProto = (proto) => {
  if (!proto.id) {
    throw new Error("Person id is required.");
  }
  if (!proto.displayName) {
    throw new Error("Person displayName is required.");
  }
  return {
    id: proto.id,
    displayName: proto.displayName,
    initials: proto.initials,
    email: proto.email,
    avatarUrl: proto.avatarUrl,
    userId: proto.userId,
    providerId: proto.providerId
  };
};

// node_modules/@oai/granola/dist/models/comments/people-collection.js
class PeopleCollection {
  #items = [];
  #byId = new Map;
  constructor(people = []) {
    people.forEach((person) => {
      this.#registerProto(person);
    });
  }
  get items() {
    return [...this.#items];
  }
  getById(id2) {
    return this.#byId.get(id2);
  }
  add(config) {
    const person = Person2.create(config);
    const existing = this.#byId.get(person.id);
    if (existing) {
      existing.update(person.toProto());
      return existing;
    }
    this.#items.push(person);
    this.#byId.set(person.id, person);
    return person;
  }
  register(person) {
    const existing = this.#byId.get(person.id);
    if (existing) {
      existing.update(person.toProto());
      return existing;
    }
    this.#items.push(person);
    this.#byId.set(person.id, person);
    return person;
  }
  toProto() {
    return this.#items.map((person) => person.toProto());
  }
  replace(people = []) {
    this.#items = [];
    this.#byId = new Map;
    people.forEach((person) => {
      this.#registerProto(person);
    });
  }
  #registerProto(proto) {
    const person = Person2.fromProto(proto);
    this.#items.push(person);
    this.#byId.set(person.id, person);
  }
}

// node_modules/@oai/granola/dist/models/range.js
init_address_utils();

// node_modules/@oai/granola/dist/models/spreadsheet/engine/evaluator.js
var IF_TRUE_SENTINEL = "__IF_TRUE_SENTINEL__";
var IF_FALSE_SENTINEL = "__IF_FALSE_SENTINEL__";
var NUMBER_COMPARISON_EPSILON = 0.000000000001;
var EXCEL_NUMBER_PRECISION = 15;
var RANGE_METADATA = Symbol("rangeMetadata");
function makeArrayValue(rows) {
  const normalizedRows = rows.map((row2) => row2.map((cell) => isArrayValue(cell) ? makeError("#VALUE!") : cell));
  const maxCols = normalizedRows.reduce((max4, row2) => Math.max(max4, row2.length), 0);
  for (const row2 of normalizedRows) {
    while (row2.length < maxCols) {
      row2.push(null);
    }
  }
  return {
    kind: "Array",
    rows: normalizedRows.length,
    cols: maxCols,
    values: normalizedRows
  };
}
function isArrayValue(value) {
  return typeof value === "object" && value !== null && "kind" in value && value.kind === "Array";
}
function arrayValueToGrid(value) {
  return value.values.map((row2) => [...row2]);
}
function mapArrayValue(value, mapper) {
  const mapped = value.values.map((row2) => row2.map((cell) => mapper(cell)));
  return makeArrayValue(mapped);
}
function mapArrayBinary(left, right, mapper) {
  if (isArrayValue(left) && isArrayValue(right)) {
    if (left.rows !== right.rows || left.cols !== right.cols) {
      return makeError("#VALUE!");
    }
    const combined = [];
    for (let r = 0;r < left.rows; r += 1) {
      const leftRow = left.values[r];
      const rightRow = right.values[r];
      if (!leftRow || !rightRow) {
        throw new Error("ArrayValue row metadata is inconsistent");
      }
      const row2 = [];
      for (let c = 0;c < left.cols; c += 1) {
        const leftCell = leftRow[c];
        const rightCell = rightRow[c];
        if (leftCell === undefined || rightCell === undefined) {
          throw new Error("ArrayValue column metadata is inconsistent");
        }
        row2.push(mapper(leftCell, rightCell));
      }
      combined.push(row2);
    }
    return makeArrayValue(combined);
  }
  if (isArrayValue(left)) {
    return mapArrayValue(left, (cell) => mapper(cell, right));
  }
  if (isArrayValue(right)) {
    return mapArrayValue(right, (cell) => mapper(left, cell));
  }
  return mapper(left, right);
}
function attachRangeMetadata(grid2, addresses) {
  Object.defineProperty(grid2, RANGE_METADATA, {
    value: addresses,
    enumerable: false,
    configurable: false
  });
}
function getRangeMetadata(grid2) {
  if (!Array.isArray(grid2)) {
    return null;
  }
  const carrier = grid2;
  return carrier[RANGE_METADATA] ?? null;
}
function copyRangeMetadata(source, target) {
  const metadata = getRangeMetadata(source);
  if (metadata) {
    attachRangeMetadata(target, metadata);
  }
}
function evaluateExpr(expr, ctx) {
  switch (expr.kind) {
    case "NumberLiteral":
      return expr.value;
    case "StringLiteral":
      return expr.value;
    case "BooleanLiteral":
      return expr.value;
    case "ErrorLiteral":
      return makeError(expr.value);
    case "ArrayLiteral":
      return makeArrayValue(expr.elements.map((row2) => row2.map((item) => evaluateExpr(item, ctx))));
    case "RangeRef":
      return evaluateRangeRef(expr.ref, ctx);
    case "FunctionCall":
      return evaluateFunctionCall(expr, ctx);
    case "CallExpr":
      return evaluateInvocation(expr, ctx);
    case "UnaryOp":
      return evaluateUnary(expr, ctx);
    case "BinaryOp":
      return evaluateBinary(expr, ctx);
    case "MissingArg":
      return null;
    default:
      return makeError("#NOT_IMPLEMENTED!");
  }
}
function evaluateUnary(expr, ctx) {
  const value = evaluateExpr(expr.expr, ctx);
  if (isErrorValue(value)) {
    return value;
  }
  if (isArrayValue(value)) {
    return mapArrayValue(value, (cell) => applyUnaryToScalar(expr.op, cell));
  }
  return applyUnaryToScalar(expr.op, value);
}
function applyUnaryToScalar(op, value) {
  const coerced = coerceNumberStrict(value);
  if (isErrorValue(coerced)) {
    if (op === "+") {
      return value;
    }
    return coerced;
  }
  const numeric = coerced;
  switch (op) {
    case "-":
      return -numeric;
    case "+":
      return numeric;
    case "%":
      return numeric / 100;
    default:
      return makeError("#VALUE!");
  }
}
function evaluateBinary(expr, ctx) {
  if (expr.op === ":") {
    return evaluateDynamicRangeOperator(expr.left, expr.right, ctx);
  }
  const left = evaluateExpr(expr.left, ctx);
  if (isErrorValue(left)) {
    return left;
  }
  const right = evaluateExpr(expr.right, ctx);
  if (isErrorValue(right)) {
    return right;
  }
  switch (expr.op) {
    case "+":
    case "-":
    case "*":
    case "/":
    case "^":
      return evaluateArithmetic(expr.op, left, right);
    case "&":
      return evaluateConcatenation(left, right);
    case "=":
    case "<>":
    case "<":
    case ">":
    case "<=":
    case ">=":
      return evaluateComparison(expr.op, left, right);
    default:
      return makeError("#VALUE!");
  }
}
function evaluateDynamicRangeOperator(leftExpr, rightExpr, ctx) {
  const leftAddr = resolveRangeEndpointAddress(leftExpr, ctx);
  if (isErrorValue(leftAddr)) {
    return leftAddr;
  }
  const rightAddr = resolveRangeEndpointAddress(rightExpr, ctx);
  if (isErrorValue(rightAddr)) {
    return rightAddr;
  }
  const sheetName = leftAddr.sheet?.sheetName ?? rightAddr.sheet?.sheetName ?? ctx.currentSheet;
  if (!sheetName) {
    return makeError("#REF!");
  }
  const leftSheet = leftAddr.sheet?.sheetName ?? sheetName;
  const rightSheet = rightAddr.sheet?.sheetName ?? sheetName;
  if (leftSheet !== rightSheet) {
    return makeError("#REF!");
  }
  const start = { ...leftAddr, sheet: { sheetName: leftSheet } };
  const end = { ...rightAddr, sheet: { sheetName: rightSheet } };
  const rows = evaluateRangeArgument({ kind: "Range", start, end }, ctx);
  return makeArrayValue(rows);
}
function resolveRangeEndpointAddress(expr, ctx) {
  if (expr.kind === "RangeRef" && expr.ref.kind === "Cell") {
    const sheetName = expr.ref.addr.sheet?.sheetName ?? ctx.currentSheet;
    if (!sheetName) {
      return makeError("#REF!");
    }
    return { ...expr.ref.addr, sheet: { sheetName } };
  }
  if (expr.kind === "FunctionCall") {
    const normalized = expr.name.toUpperCase();
    if (normalized === "INDEX" || normalized === "_XLFN.INDEX") {
      return resolveIndexEndpointAddress(expr, ctx);
    }
  }
  return makeError("#VALUE!");
}
function resolveIndexEndpointAddress(expr, ctx) {
  const arrayExpr = expr.args[0];
  const rowExpr = expr.args[1];
  const colExpr = expr.args[2];
  if (!arrayExpr || !rowExpr || !colExpr) {
    return makeError("#VALUE!");
  }
  const arrayArg = evaluateFunctionArgument(arrayExpr, ctx);
  if (!Array.isArray(arrayArg)) {
    return makeError("#REF!");
  }
  const metadata = getRangeMetadata(arrayArg);
  if (!metadata) {
    return makeError("#REF!");
  }
  const rowValue = coerceFunctionArgToScalar(evaluateFunctionArgument(rowExpr, ctx));
  if (isErrorValue(rowValue)) {
    return rowValue;
  }
  const colValue = coerceFunctionArgToScalar(evaluateFunctionArgument(colExpr, ctx));
  if (isErrorValue(colValue)) {
    return colValue;
  }
  const rowNumber = coerceNumberStrict(rowValue);
  if (isErrorValue(rowNumber)) {
    return rowNumber;
  }
  const colNumber = coerceNumberStrict(colValue);
  if (isErrorValue(colNumber)) {
    return colNumber;
  }
  if (!Number.isInteger(rowNumber) || !Number.isInteger(colNumber)) {
    return makeError("#VALUE!");
  }
  if (rowNumber < 1 || colNumber < 1) {
    return makeError("#VALUE!");
  }
  const addr = metadata[rowNumber - 1]?.[colNumber - 1];
  if (!addr) {
    return makeError("#REF!");
  }
  const sheetName = addr.sheet?.sheetName ?? ctx.currentSheet;
  if (!sheetName) {
    return makeError("#REF!");
  }
  return { ...addr, sheet: { sheetName } };
}
function evaluateArithmetic(op, left, right) {
  if (isArrayValue(left) || isArrayValue(right)) {
    return mapArrayBinary(left, right, (a, b) => evaluateArithmeticScalar(op, a, b));
  }
  return evaluateArithmeticScalar(op, left, right);
}
function evaluateArithmeticScalar(op, left, right) {
  const leftNum = coerceNumberStrict(left);
  if (isErrorValue(leftNum)) {
    return leftNum;
  }
  const rightNum = coerceNumberStrict(right);
  if (isErrorValue(rightNum)) {
    return rightNum;
  }
  const a = leftNum;
  const b = rightNum;
  switch (op) {
    case "+":
      return a + b;
    case "-":
      return a - b;
    case "*":
      return a * b;
    case "/":
      if (b === 0) {
        return makeError("#DIV/0!");
      }
      return a / b;
    case "^":
      return Number.isNaN(a) || Number.isNaN(b) ? makeError("#NUM!") : Math.pow(a, b);
    default:
      return makeError("#VALUE!");
  }
}
function evaluateConcatenation(left, right) {
  if (isArrayValue(left) || isArrayValue(right)) {
    return mapArrayBinary(left, right, (a, b) => evaluateConcatenationScalar(a, b));
  }
  return evaluateConcatenationScalar(left, right);
}
function evaluateConcatenationScalar(left, right) {
  const leftText = coerceToText(left);
  if (isErrorValue(leftText)) {
    return leftText;
  }
  const rightText = coerceToText(right);
  if (isErrorValue(rightText)) {
    return rightText;
  }
  return `${leftText}${rightText}`;
}
function evaluateComparison(op, left, right) {
  if (isArrayValue(left) || isArrayValue(right)) {
    return mapArrayBinary(left, right, (a, b) => evaluateComparisonScalar(op, a, b));
  }
  return evaluateComparisonScalar(op, left, right);
}
function evaluateComparisonScalar(op, left, right) {
  const leftNum = coerceNumberLoose(left);
  const rightNum = coerceNumberLoose(right);
  if (isErrorValue(leftNum)) {
    return leftNum;
  }
  if (isErrorValue(rightNum)) {
    return rightNum;
  }
  if (typeof leftNum === "number" && typeof rightNum === "number") {
    return applyComparison(op, leftNum, rightNum);
  }
  if (typeof leftNum === "number" && rightNum === null && typeof right === "string") {
    return evaluateNumberTextComparison(op, {
      numberOnLeft: true,
      numberValue: leftNum,
      textValue: right
    });
  }
  if (typeof rightNum === "number" && leftNum === null && typeof left === "string") {
    return evaluateNumberTextComparison(op, {
      numberOnLeft: false,
      numberValue: rightNum,
      textValue: left
    });
  }
  const leftText = coerceToText(left);
  if (isErrorValue(leftText)) {
    return leftText;
  }
  const rightText = coerceToText(right);
  if (isErrorValue(rightText)) {
    return rightText;
  }
  return applyComparison(op, leftText, rightText);
}
function applyComparison(op, left, right) {
  if (typeof left === "number" && typeof right === "number") {
    return applyNumericComparison(op, left, right);
  }
  if (typeof left === "string" && typeof right === "string") {
    return applyTextComparison(op, left, right);
  }
  switch (op) {
    case "=":
      return left === right;
    case "<>":
      return left !== right;
    case "<":
      return left < right;
    case ">":
      return left > right;
    case "<=":
      return left <= right;
    case ">=":
      return left >= right;
    default:
      return false;
  }
}
function applyTextComparison(op, left, right) {
  const normalizedLeft = normalizeTextForComparison(left);
  const normalizedRight = normalizeTextForComparison(right);
  switch (op) {
    case "=":
      return normalizedLeft === normalizedRight;
    case "<>":
      return normalizedLeft !== normalizedRight;
    case "<":
      return normalizedLeft < normalizedRight;
    case ">":
      return normalizedLeft > normalizedRight;
    case "<=":
      return normalizedLeft <= normalizedRight;
    case ">=":
      return normalizedLeft >= normalizedRight;
    default:
      return false;
  }
}
function normalizeTextForComparison(value) {
  return value.toLocaleUpperCase();
}
function applyNumericComparison(op, left, right) {
  const normalizedLeft = normalizeNumberForComparison(left);
  const normalizedRight = normalizeNumberForComparison(right);
  const diff = normalizedLeft - normalizedRight;
  const within = Math.abs(diff) <= NUMBER_COMPARISON_EPSILON;
  switch (op) {
    case "=":
      return within;
    case "<>":
      return !within;
    case "<":
      return within ? false : diff < 0;
    case ">":
      return within ? false : diff > 0;
    case "<=":
      return within ? true : diff < 0;
    case ">=":
      return within ? true : diff > 0;
    default:
      return false;
  }
}
function evaluateNumberTextComparison(op, context) {
  const { numberOnLeft, numberValue, textValue } = context;
  const trimmed = textValue.trim();
  if (textValue === "") {
    const textAsNumber = 0;
    const leftOperand = numberOnLeft ? numberValue : textAsNumber;
    const rightOperand = numberOnLeft ? textAsNumber : numberValue;
    return applyComparison(op, leftOperand, rightOperand);
  }
  const isWhitespaceOnly = trimmed === "";
  if (isWhitespaceOnly) {
    return compareNumberAndNonNumericText(op, numberOnLeft);
  }
  switch (op) {
    case "=":
      return false;
    case "<>":
      return true;
    default:
      return compareNumberAndNonNumericText(op, numberOnLeft);
  }
}
function compareNumberAndNonNumericText(op, numberOnLeft) {
  switch (op) {
    case "<":
    case "<=":
      return numberOnLeft;
    case ">":
    case ">=":
      return !numberOnLeft;
    case "=":
      return false;
    case "<>":
      return true;
    default:
      return makeError("#VALUE!");
  }
}
function normalizeNumberForComparison(value) {
  if (!Number.isFinite(value)) {
    return value;
  }
  const normalized = Number(value.toPrecision(EXCEL_NUMBER_PRECISION));
  return normalized;
}
function evaluateFunctionCall(expr, ctx) {
  if (ctx.handleFunctionCall) {
    const handled = ctx.handleFunctionCall(expr);
    if (handled !== undefined) {
      return handled;
    }
  }
  if (expr.name.toUpperCase() === "IF") {
    return evaluateIfFunction(expr, ctx);
  }
  const args2 = [];
  for (const argExpr of expr.args) {
    const value = evaluateFunctionArgument(argExpr, ctx);
    args2.push(value);
  }
  return ctx.callFunction(expr.name, args2);
}
function evaluateIfFunction(expr, ctx) {
  if (expr.args.length === 0) {
    return makeError("#VALUE!");
  }
  const logicalTestExpr = expr.args[0];
  if (!logicalTestExpr) {
    return makeError("#VALUE!");
  }
  const logicalTest = evaluateFunctionArgument(logicalTestExpr, ctx);
  const selection = ctx.callFunction(expr.name, [
    logicalTest,
    IF_TRUE_SENTINEL,
    IF_FALSE_SENTINEL
  ]);
  if (selection === IF_TRUE_SENTINEL) {
    const trueExpr = expr.args[1];
    if (trueExpr && trueExpr.kind !== "MissingArg") {
      const trueValue = evaluateFunctionArgument(trueExpr, ctx);
      return coerceFunctionArgToScalar(trueValue);
    }
    return 0;
  }
  if (selection === IF_FALSE_SENTINEL) {
    const falseExpr = expr.args[2];
    if (falseExpr && falseExpr.kind !== "MissingArg") {
      const falseValue = evaluateFunctionArgument(falseExpr, ctx);
      return coerceFunctionArgToScalar(falseValue);
    }
    return 0;
  }
  return selection;
}
function evaluateFunctionArgument(expr, ctx) {
  if (expr.kind === "MissingArg") {
    return;
  }
  if (expr.kind === "RangeRef") {
    if (expr.ref.kind === "Cell") {
      const sheetName = expr.ref.addr.sheet?.sheetName ?? ctx.currentSheet;
      if (!sheetName) {
        return [[makeError("#REF!")]];
      }
      const key = resolveCellKey(expr.ref.addr, ctx);
      const value = key ? ctx.getCellValue(key) : makeError("#REF!");
      const rows = [[value ?? null]];
      const address = {
        ...expr.ref.addr,
        sheet: { sheetName }
      };
      attachRangeMetadata(rows, [[address]]);
      return rows;
    }
    if (expr.ref.kind === "Range") {
      return evaluateRangeArgument(expr.ref, ctx);
    }
    if (expr.ref.kind === "ColumnRange") {
      return evaluateColumnRangeArgument(expr.ref, ctx);
    }
    if (expr.ref.kind === "WholeColumn") {
      return evaluateWholeColumnArgument(expr.ref, ctx);
    }
    if (expr.ref.kind === "WholeRow") {
      return evaluateWholeRowArgument(expr.ref, ctx);
    }
    if (expr.ref.kind === "Named") {
      if (isRefErrorName(expr.ref.name)) {
        return [[makeError("#REF!")]];
      }
      const resolved = ctx.resolveNamedReference?.(expr.ref.name, "range", expr.ref.sheet?.sheetName);
      if (resolved && Array.isArray(resolved)) {
        return resolved;
      }
      const scalarValue = ctx.resolveNamedReference?.(expr.ref.name, "scalar", expr.ref.sheet?.sheetName);
      if (scalarValue !== null && scalarValue !== undefined) {
        if (isLambdaValue(scalarValue)) {
          return makeError("#VALUE!");
        }
        if (Array.isArray(scalarValue)) {
          return scalarValue;
        }
        if (isErrorValue(scalarValue)) {
          return scalarValue;
        }
        return [[scalarValue]];
      }
      return makeError("#NAME?");
    }
    if (expr.ref.kind === "Structured") {
      const resolved = ctx.resolveStructuredReference?.(expr.ref.reference, "range");
      if (Array.isArray(resolved)) {
        return resolved;
      }
      if (resolved !== null && resolved !== undefined) {
        if (isErrorValue(resolved)) {
          return resolved;
        }
        return [[resolved]];
      }
      return makeError("#NAME?");
    }
  }
  const result = evaluateExpr(expr, ctx);
  if (isArrayValue(result)) {
    return arrayValueToGrid(result);
  }
  return result;
}
function coerceFunctionArgToScalar(value) {
  if (value === undefined) {
    return "";
  }
  if (Array.isArray(value)) {
    return value[0]?.[0] ?? makeError("#VALUE!");
  }
  return value;
}
function evaluateRangeRef(ref, ctx) {
  switch (ref.kind) {
    case "Cell": {
      const key = resolveCellKey(ref.addr, ctx);
      if (!key) {
        return makeError("#REF!");
      }
      return ctx.getCellValue(key);
    }
    case "Spill":
      return evaluateRangeRef(ref.base, ctx);
    case "Range": {
      const rows = evaluateRangeArgument(ref, ctx);
      return makeArrayValue(rows);
    }
    case "ColumnRange": {
      const rows = evaluateColumnRangeArgument(ref, ctx);
      return makeArrayValue(rows);
    }
    case "Named": {
      if (isRefErrorName(ref.name)) {
        return makeError("#REF!");
      }
      const scalar = ctx.resolveNamedReference?.(ref.name, "scalar", ref.sheet?.sheetName);
      if (scalar === null || scalar === undefined) {
        return makeError("#NAME?");
      }
      if (Array.isArray(scalar)) {
        return scalar[0]?.[0] ?? makeError("#VALUE!");
      }
      if (isErrorValue(scalar)) {
        return scalar;
      }
      if (isLambdaValue(scalar)) {
        return makeError("#VALUE!");
      }
      return scalar;
    }
    case "Structured": {
      const resolved = ctx.resolveStructuredReference?.(ref.reference, "scalar");
      if (resolved === null || resolved === undefined) {
        return makeError("#NAME?");
      }
      if (Array.isArray(resolved)) {
        return resolved[0]?.[0] ?? makeError("#VALUE!");
      }
      if (isErrorValue(resolved)) {
        return resolved;
      }
      return resolved;
    }
    default:
      return makeError("#VALUE!");
  }
}
function evaluateInvocation(expr, ctx) {
  const callee = evaluateExpr(expr.callee, ctx);
  if (!isLambdaValue(callee)) {
    return makeError("#VALUE!");
  }
  const args2 = [];
  for (const arg of expr.args) {
    args2.push(evaluateFunctionArgument(arg, ctx));
  }
  return callee.invoke(args2, ctx);
}
function evaluateRangeArgument(ref, ctx) {
  const sheetName = ref.start.sheet?.sheetName ?? ref.end.sheet?.sheetName ?? ctx.currentSheet;
  if (!sheetName) {
    return [[{ kind: "Error", code: "#REF!" }]];
  }
  const startRow = Math.min(ref.start.row, ref.end.row);
  const endRow = Math.max(ref.start.row, ref.end.row);
  const startCol = Math.min(ref.start.col, ref.end.col);
  const endCol = Math.max(ref.start.col, ref.end.col);
  const rows = [];
  const addressRows = [];
  for (let row2 = startRow;row2 <= endRow; row2 += 1) {
    const rowValues = [];
    const rowAddresses = [];
    for (let col = startCol;col <= endCol; col += 1) {
      const cellAddr = {
        sheet: { sheetName },
        row: row2,
        col,
        absRow: false,
        absCol: false
      };
      rowAddresses.push(cellAddr);
      const key = ctx.cellAddressToKey(cellAddr);
      if (!key) {
        rowValues.push({ kind: "Error", code: "#REF!" });
        continue;
      }
      rowValues.push(ctx.getCellValue(key));
    }
    rows.push(rowValues);
    addressRows.push(rowAddresses);
  }
  attachRangeMetadata(rows, addressRows);
  return rows;
}
function evaluateColumnRangeArgument(ref, ctx) {
  const sheetName = ref.sheet?.sheetName ?? ctx.currentSheet;
  if (!sheetName) {
    return [[makeError("#REF!")]];
  }
  if (!ctx.getColumnExtent) {
    return [];
  }
  const startCol = Math.min(ref.startCol, ref.endCol);
  const endCol = Math.max(ref.startCol, ref.endCol);
  let minRow = Infinity;
  let maxRow = -Infinity;
  for (let col = startCol;col <= endCol; col += 1) {
    const bounds = ctx.getColumnExtent(sheetName, col);
    if (!bounds) {
      continue;
    }
    minRow = Math.min(minRow, bounds.startRow);
    maxRow = Math.max(maxRow, bounds.endRow);
  }
  if (!Number.isFinite(minRow) || !Number.isFinite(maxRow)) {
    return [];
  }
  const rows = [];
  const addressRows = [];
  for (let row2 = minRow;row2 <= maxRow; row2 += 1) {
    const rowValues = [];
    const rowAddresses = [];
    for (let col = startCol;col <= endCol; col += 1) {
      const cellAddr = {
        sheet: { sheetName },
        row: row2,
        col,
        absRow: false,
        absCol: false
      };
      rowAddresses.push(cellAddr);
      const key = ctx.cellAddressToKey(cellAddr);
      if (!key) {
        rowValues.push({ kind: "Error", code: "#REF!" });
        continue;
      }
      rowValues.push(ctx.getCellValue(key));
    }
    rows.push(rowValues);
    addressRows.push(rowAddresses);
  }
  attachRangeMetadata(rows, addressRows);
  return rows;
}
function evaluateWholeColumnArgument(ref, ctx) {
  const sheetName = ref.sheet?.sheetName ?? ctx.currentSheet;
  if (!sheetName) {
    return [[makeError("#REF!")]];
  }
  const bounds = ctx.getColumnExtent?.(sheetName, ref.col);
  if (!bounds) {
    return [];
  }
  const rows = [];
  const addressRows = [];
  for (let row2 = bounds.startRow;row2 <= bounds.endRow; row2 += 1) {
    const cellAddr = {
      sheet: { sheetName },
      row: row2,
      col: ref.col,
      absRow: false,
      absCol: false
    };
    addressRows.push([cellAddr]);
    const key = ctx.cellAddressToKey(cellAddr);
    rows.push([ctx.getCellValue(key)]);
  }
  attachRangeMetadata(rows, addressRows);
  return rows;
}
function evaluateWholeRowArgument(ref, ctx) {
  const sheetName = ref.sheet?.sheetName ?? ctx.currentSheet;
  if (!sheetName) {
    return [[makeError("#REF!")]];
  }
  const bounds = ctx.getRowExtent?.(sheetName, ref.row);
  if (!bounds) {
    return [];
  }
  const rowValues = [];
  const addressRow = [];
  for (let col = bounds.startCol;col <= bounds.endCol; col += 1) {
    const cellAddr = {
      sheet: { sheetName },
      row: ref.row,
      col,
      absRow: false,
      absCol: false
    };
    addressRow.push(cellAddr);
    const key = ctx.cellAddressToKey(cellAddr);
    rowValues.push(ctx.getCellValue(key));
  }
  const rows = [rowValues];
  attachRangeMetadata(rows, [addressRow]);
  return rows;
}
function coerceNumberStrict(value) {
  const result = coerceNumberLoose(value);
  if (result === null) {
    return makeError("#VALUE!");
  }
  return result;
}
function coerceNumberLoose(value) {
  if (isArrayValue(value)) {
    return makeError("#VALUE!");
  }
  if (isErrorValue(value)) {
    return value;
  }
  if (isLambdaValue(value)) {
    return makeError("#VALUE!");
  }
  if (value == null) {
    return 0;
  }
  if (typeof value === "number") {
    return value;
  }
  if (typeof value === "boolean") {
    return value ? 1 : 0;
  }
  if (typeof value === "string") {
    if (value === "") {
      return 0;
    }
    const trimmed = value.trim();
    if (trimmed === "") {
      return null;
    }
    const num = Number(value);
    return Number.isNaN(num) ? null : num;
  }
  return null;
}
function coerceToText(value) {
  if (isArrayValue(value)) {
    return makeError("#VALUE!");
  }
  if (isErrorValue(value)) {
    return value;
  }
  if (isLambdaValue(value)) {
    return makeError("#VALUE!");
  }
  if (value == null) {
    return "";
  }
  return String(value);
}
function resolveCellKey(addr, ctx) {
  const sheetName = addr.sheet?.sheetName ?? ctx.currentSheet;
  if (!sheetName) {
    return null;
  }
  const normalized = {
    ...addr,
    sheet: { sheetName }
  };
  return ctx.cellAddressToKey(normalized);
}
function makeError(code) {
  return { kind: "Error", code };
}
function isErrorValue(value) {
  return typeof value === "object" && value !== null && value.kind === "Error";
}
function isLambdaValue(value) {
  return typeof value === "object" && value !== null && value.kind === "Lambda";
}
function isRefErrorName(name) {
  if (typeof name !== "string") {
    return false;
  }
  const normalized = name.trim().toUpperCase();
  if (normalized === "#REF!") {
    return true;
  }
  if (normalized.endsWith("!#REF!")) {
    return true;
  }
  const bangIndex = normalized.lastIndexOf("!");
  if (bangIndex >= 0) {
    return normalized.slice(bangIndex + 1) === "#REF!";
  }
  return false;
}

// node_modules/@oai/granola/dist/models/enums.js
var AggregationFunction;
(function(AggregationFunction2) {
  AggregationFunction2["automatic"] = "Automatic";
  AggregationFunction2["sum"] = "Sum";
  AggregationFunction2["count"] = "Count";
  AggregationFunction2["average"] = "Average";
  AggregationFunction2["max"] = "Max";
  AggregationFunction2["min"] = "Min";
  AggregationFunction2["product"] = "Product";
  AggregationFunction2["countNumbers"] = "CountNumbers";
  AggregationFunction2["standardDeviation"] = "StandardDeviation";
  AggregationFunction2["standardDeviationP"] = "StandardDeviationP";
  AggregationFunction2["variance"] = "Variance";
  AggregationFunction2["varianceP"] = "VarianceP";
})(AggregationFunction || (AggregationFunction = {}));
var ShowAsCalculation;
(function(ShowAsCalculation2) {
  ShowAsCalculation2["none"] = "None";
  ShowAsCalculation2["percentOfColumnTotal"] = "PercentOfColumnTotal";
  ShowAsCalculation2["percentOfRowTotal"] = "PercentOfRowTotal";
  ShowAsCalculation2["percentOfGrandTotal"] = "PercentOfGrandTotal";
  ShowAsCalculation2["differenceFrom"] = "DifferenceFrom";
  ShowAsCalculation2["percentDifferenceFrom"] = "PercentDifferenceFrom";
})(ShowAsCalculation || (ShowAsCalculation = {}));
var DateFilterCondition;
(function(DateFilterCondition2) {
  DateFilterCondition2["before"] = "Before";
  DateFilterCondition2["after"] = "After";
  DateFilterCondition2["between"] = "Between";
  DateFilterCondition2["equals"] = "Equals";
  DateFilterCondition2["yesterday"] = "Yesterday";
  DateFilterCondition2["today"] = "Today";
  DateFilterCondition2["tomorrow"] = "Tomorrow";
  DateFilterCondition2["thisWeek"] = "ThisWeek";
  DateFilterCondition2["lastWeek"] = "LastWeek";
  DateFilterCondition2["nextWeek"] = "NextWeek";
  DateFilterCondition2["thisMonth"] = "ThisMonth";
  DateFilterCondition2["lastMonth"] = "LastMonth";
  DateFilterCondition2["nextMonth"] = "NextMonth";
  DateFilterCondition2["thisQuarter"] = "ThisQuarter";
  DateFilterCondition2["lastQuarter"] = "LastQuarter";
  DateFilterCondition2["nextQuarter"] = "NextQuarter";
  DateFilterCondition2["thisYear"] = "ThisYear";
  DateFilterCondition2["lastYear"] = "LastYear";
  DateFilterCondition2["nextYear"] = "NextYear";
  DateFilterCondition2["yearToDate"] = "YearToDate";
  DateFilterCondition2["allDatesInPeriodJanuary"] = "AllDatesInPeriodJanuary";
  DateFilterCondition2["allDatesInPeriodFebruary"] = "AllDatesInPeriodFebruary";
  DateFilterCondition2["allDatesInPeriodMarch"] = "AllDatesInPeriodMarch";
  DateFilterCondition2["allDatesInPeriodApril"] = "AllDatesInPeriodApril";
  DateFilterCondition2["allDatesInPeriodMay"] = "AllDatesInPeriodMay";
  DateFilterCondition2["allDatesInPeriodJune"] = "AllDatesInPeriodJune";
  DateFilterCondition2["allDatesInPeriodJuly"] = "AllDatesInPeriodJuly";
  DateFilterCondition2["allDatesInPeriodAugust"] = "AllDatesInPeriodAugust";
  DateFilterCondition2["allDatesInPeriodSeptember"] = "AllDatesInPeriodSeptember";
  DateFilterCondition2["allDatesInPeriodOctober"] = "AllDatesInPeriodOctober";
  DateFilterCondition2["allDatesInPeriodNovember"] = "AllDatesInPeriodNovember";
  DateFilterCondition2["allDatesInPeriodDecember"] = "AllDatesInPeriodDecember";
})(DateFilterCondition || (DateFilterCondition = {}));
var LabelFilterCondition;
(function(LabelFilterCondition2) {
  LabelFilterCondition2["beginsWith"] = "BeginsWith";
  LabelFilterCondition2["endsWith"] = "EndsWith";
  LabelFilterCondition2["contains"] = "Contains";
  LabelFilterCondition2["notContains"] = "NotContains";
  LabelFilterCondition2["equals"] = "Equals";
  LabelFilterCondition2["notEquals"] = "NotEquals";
  LabelFilterCondition2["greaterThan"] = "GreaterThan";
  LabelFilterCondition2["greaterThanOrEqualTo"] = "GreaterThanOrEqualTo";
  LabelFilterCondition2["lessThan"] = "LessThan";
  LabelFilterCondition2["lessThanOrEqualTo"] = "LessThanOrEqualTo";
  LabelFilterCondition2["between"] = "Between";
})(LabelFilterCondition || (LabelFilterCondition = {}));
var ValueFilterCondition;
(function(ValueFilterCondition2) {
  ValueFilterCondition2["equals"] = "Equals";
  ValueFilterCondition2["notEquals"] = "NotEquals";
  ValueFilterCondition2["greaterThan"] = "GreaterThan";
  ValueFilterCondition2["greaterThanOrEqualTo"] = "GreaterThanOrEqualTo";
  ValueFilterCondition2["lessThan"] = "LessThan";
  ValueFilterCondition2["lessThanOrEqualTo"] = "LessThanOrEqualTo";
  ValueFilterCondition2["between"] = "Between";
  ValueFilterCondition2["topN"] = "TopN";
  ValueFilterCondition2["bottomN"] = "BottomN";
  ValueFilterCondition2["topPercent"] = "TopPercent";
  ValueFilterCondition2["bottomPercent"] = "BottomPercent";
})(ValueFilterCondition || (ValueFilterCondition = {}));
var HorizontalAlignment;
(function(HorizontalAlignment2) {
  HorizontalAlignment2["general"] = "General";
  HorizontalAlignment2["left"] = "Left";
  HorizontalAlignment2["center"] = "Center";
  HorizontalAlignment2["right"] = "Right";
  HorizontalAlignment2["fill"] = "Fill";
  HorizontalAlignment2["justify"] = "Justify";
  HorizontalAlignment2["centerAcrossSelection"] = "CenterAcrossSelection";
  HorizontalAlignment2["distributed"] = "Distributed";
})(HorizontalAlignment || (HorizontalAlignment = {}));
var LayoutType;
(function(LayoutType2) {
  LayoutType2["compact"] = "Compact";
  LayoutType2["outline"] = "Outline";
  LayoutType2["tabular"] = "Tabular";
})(LayoutType || (LayoutType = {}));
var FilterDatetimeSpecificity;
(function(FilterDatetimeSpecificity2) {
  FilterDatetimeSpecificity2["year"] = "Year";
  FilterDatetimeSpecificity2["month"] = "Month";
  FilterDatetimeSpecificity2["day"] = "Day";
  FilterDatetimeSpecificity2["hour"] = "Hour";
  FilterDatetimeSpecificity2["minute"] = "Minute";
  FilterDatetimeSpecificity2["second"] = "Second";
})(FilterDatetimeSpecificity || (FilterDatetimeSpecificity = {}));

// node_modules/@oai/granola/dist/models/spreadsheet/defaults.const.js
var DEFAULT_XLSX_FONT = {
  fontSize: 11,
  typeface: "Carlito"
};
var DEFAULT_XLSX_FILLS = [
  {
    type: 3 /* FILL_TYPE_PATTERN */,
    color: undefined,
    gradientStops: [],
    pattern: {
      patternType: 1 /* PATTERN_TYPE_NONE */,
      color: undefined
    }
  },
  {
    type: 3 /* FILL_TYPE_PATTERN */,
    color: undefined,
    gradientStops: [],
    pattern: {
      patternType: 18 /* PATTERN_TYPE_GRAY125 */,
      color: undefined
    }
  }
];
var DEFAULT_XLSX_CELL_XF = {
  numFmtId: 0,
  fontId: 0,
  fillId: 0,
  borderId: 0,
  xfId: 0
};
var DEFAULT_XLSX_BORDER_LINE = {
  style: "",
  color: undefined,
  indexedColorId: undefined
};
var DEFAULT_XLSX_BORDER = {
  left: { ...DEFAULT_XLSX_BORDER_LINE },
  right: { ...DEFAULT_XLSX_BORDER_LINE },
  top: { ...DEFAULT_XLSX_BORDER_LINE },
  bottom: { ...DEFAULT_XLSX_BORDER_LINE },
  diagonal: { ...DEFAULT_XLSX_BORDER_LINE }
};
var DEFAULT_XLSX_CELL_STYLE = {
  index: 0,
  builtinId: "0",
  name: "Normal",
  xfId: 0
};
var DEFAULT_XLSX_CELL_STYLE_XF = {
  index: 0,
  format: {
    numFmtId: 0,
    fontId: 0,
    fillId: 0,
    borderId: 0
  }
};
var DEFAULT_XLSX_THEME = {
  colorScheme: {
    name: "ChatGPT",
    colors: [
      {
        name: "accent1",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "156082",
          transform: {}
        }
      },
      {
        name: "accent2",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "E97132",
          transform: {}
        }
      },
      {
        name: "accent3",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "196B24",
          transform: {}
        }
      },
      {
        name: "accent4",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "0F9ED5",
          transform: {}
        }
      },
      {
        name: "accent5",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "A02B93",
          transform: {}
        }
      },
      {
        name: "accent6",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "4EA72E",
          transform: {}
        }
      },
      {
        name: "dk1",
        color: {
          type: 3 /* COLOR_TYPE_SYSTEM */,
          value: "windowText",
          lastColor: "000000",
          transform: {}
        }
      },
      {
        name: "lt1",
        color: {
          type: 3 /* COLOR_TYPE_SYSTEM */,
          value: "window",
          lastColor: "FFFFFF",
          transform: {}
        }
      },
      {
        name: "dk2",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "0E2841",
          transform: {}
        }
      },
      {
        name: "lt2",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "E8E8E8",
          transform: {}
        }
      },
      {
        name: "hlink",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "467886",
          transform: {}
        }
      },
      {
        name: "folHlink",
        color: {
          type: 1 /* COLOR_TYPE_RGB */,
          value: "96607D",
          transform: {}
        }
      }
    ]
  },
  backgroundFillStyleList: [
    {
      type: 1 /* FILL_TYPE_SOLID */,
      color: {
        type: 2 /* COLOR_TYPE_SCHEME */,
        value: "phClr",
        transform: {}
      },
      gradientStops: [],
      pattern: undefined
    },
    {
      type: 1 /* FILL_TYPE_SOLID */,
      color: {
        type: 2 /* COLOR_TYPE_SCHEME */,
        value: "phClr",
        transform: {
          tint: 95000,
          satMod: 170000
        }
      },
      gradientStops: [],
      pattern: undefined
    },
    {
      type: 2 /* FILL_TYPE_GRADIENT */,
      color: undefined,
      gradientStops: [
        {
          position: 0,
          color: {
            type: 2 /* COLOR_TYPE_SCHEME */,
            value: "phClr",
            transform: {
              tint: 93000,
              shade: 98000,
              lumMod: 102000,
              satMod: 150000
            }
          }
        },
        {
          position: 50000,
          color: {
            type: 2 /* COLOR_TYPE_SCHEME */,
            value: "phClr",
            transform: {
              tint: 98000,
              shade: 90000,
              lumMod: 103000,
              satMod: 130000
            }
          }
        },
        {
          position: 1e5,
          color: {
            type: 2 /* COLOR_TYPE_SCHEME */,
            value: "phClr",
            transform: {
              shade: 63000,
              satMod: 120000
            }
          }
        }
      ],
      gradientKind: 1 /* GRADIENT_KIND_LINEAR */,
      angleDeg: 90,
      isScaled: false,
      pattern: undefined
    }
  ],
  lineStyleList: [
    {
      style: 1 /* LINE_STYLE_SOLID */,
      widthEmu: 12700,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "phClr",
          transform: {}
        },
        gradientStops: [],
        pattern: undefined
      }
    },
    {
      style: 1 /* LINE_STYLE_SOLID */,
      widthEmu: 19050,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "phClr",
          transform: {}
        },
        gradientStops: [],
        pattern: undefined
      }
    },
    {
      style: 1 /* LINE_STYLE_SOLID */,
      widthEmu: 25400,
      fill: {
        type: 1 /* FILL_TYPE_SOLID */,
        color: {
          type: 2 /* COLOR_TYPE_SCHEME */,
          value: "phClr",
          transform: {}
        },
        gradientStops: [],
        pattern: undefined
      }
    }
  ],
  effectStyleList: [
    { effects: [] },
    { effects: [] },
    {
      effects: [
        {
          type: 1 /* EFFECT_TYPE_OUTER_SHADOW */,
          shadow: {
            color: {
              type: 1 /* COLOR_TYPE_RGB */,
              value: "000000",
              transform: {
                alpha: 63000
              }
            },
            blurRadius: 57150,
            distance: 19050,
            direction: 5400000
          }
        }
      ]
    }
  ]
};

// node_modules/@oai/granola/dist/models/spreadsheet/style-registry.js
var SPREADSHEET_COLOR_OPTIONS = { colorSpace: "spreadsheetml" };

class StyleRegistry {
  #fonts;
  #fills;
  #borders;
  #cellFormats;
  #cellStyles;
  #cellStyleXfs;
  #dxfs;
  #indexedColors;
  #mruColors;
  #numberFormats;
  #nextNumberFormatId;
  constructor(styles) {
    const source = styles ?? {};
    const fontsSource = source.fonts && source.fonts.length > 0 ? source.fonts : [DEFAULT_XLSX_FONT];
    this.#fonts = fontsSource.map((font) => new TextStyleModel(font));
    const fillsSource = (() => {
      const fills = source.fills ?? [];
      if (fills.length === 0) {
        return DEFAULT_XLSX_FILLS;
      }
      if (fills.length === 1) {
        const first = fills[0];
        const patternType = first?.pattern?.patternType;
        if (first?.type === 3 /* FILL_TYPE_PATTERN */ && patternType === 1 /* PATTERN_TYPE_NONE */) {
          return [...fills, DEFAULT_XLSX_FILLS[1]];
        }
      }
      return fills;
    })();
    this.#fills = fillsSource.map((fill2) => new Fill2({ type: "proto", proto: fill2 }));
    const bordersSource = source.borders && source.borders.length > 0 ? source.borders : [DEFAULT_XLSX_BORDER];
    this.#borders = bordersSource.map((border) => new BorderModel(border));
    const cellFormatSource = source.cellXfs && source.cellXfs.length > 0 ? source.cellXfs : [DEFAULT_XLSX_CELL_XF];
    this.#cellFormats = cellFormatSource.map((format2) => new CellFormatModel(format2));
    this.#cellStyles = cloneProtoArray(source.cellStyles);
    this.#cellStyleXfs = cloneProtoArray(source.cellStyleXfs);
    if (this.#cellStyles.length === 0) {
      this.#cellStyles = [{ ...DEFAULT_XLSX_CELL_STYLE }];
    }
    if (this.#cellStyleXfs.length === 0) {
      const format2 = DEFAULT_XLSX_CELL_STYLE_XF.format;
      const index = DEFAULT_XLSX_CELL_STYLE_XF.index;
      this.#cellStyleXfs = [
        {
          index,
          format: format2 ? {
            ...format2
          } : undefined
        }
      ];
    }
    this.#dxfs = cloneProtoArray(source.dxfs);
    this.#indexedColors = cloneProtoArray(source.indexedColors);
    this.#mruColors = cloneProtoArray(source.mruColors);
    this.#numberFormats = (source.numberFormats ?? []).map((format2) => new NumberFormatModel(format2));
    this.#nextNumberFormatId = this.#computeNextNumberFormatId();
  }
  describe(styleIndex) {
    const safeIndex = typeof styleIndex === "number" && styleIndex >= 0 && styleIndex < this.#cellFormats.length ? styleIndex : 0;
    const format2 = this.#cellFormats[safeIndex];
    if (!format2) {
      throw new Error(`Missing cell format at index ${safeIndex}`);
    }
    return {
      styleIndex: safeIndex,
      fill: this.#cloneFill(format2.fillId),
      font: this.#cloneFont(format2.fontId),
      border: this.#cloneBorder(format2.borderId),
      numberFormatId: format2.numberFormatId,
      numberFormatCode: this.#numberFormatCodeForId(format2.numberFormatId),
      wrapText: format2.wrapText,
      horizontalAlignment: format2.horizontalAlignment,
      verticalAlignment: format2.verticalAlignment,
      featurePropertyBagIndex: format2.featurePropertyBagIndex
    };
  }
  getStyleCount() {
    return this.#cellFormats.length;
  }
  getNumberFormatCode(numberFormatId) {
    return this.#numberFormatCodeForId(numberFormatId);
  }
  register(input) {
    const fontId = input.font ? this.#registerFont(input.font) : undefined;
    const fillId = input.fill ? this.#registerFill(input.fill) : undefined;
    const borderId = input.border ? this.#registerBorder(input.border) : undefined;
    const numberFormatId = this.#resolveNumberFormatId(input.numberFormatId, input.numberFormatCode);
    const cellFormat = new CellFormatModel;
    cellFormat.fontId = fontId;
    cellFormat.fillId = fillId;
    cellFormat.borderId = borderId;
    cellFormat.xfId = 0;
    cellFormat.numberFormatId = numberFormatId;
    cellFormat.wrapText = input.wrapText;
    cellFormat.horizontalAlignment = input.horizontalAlignment;
    cellFormat.verticalAlignment = input.verticalAlignment;
    cellFormat.featurePropertyBagIndex = input.featurePropertyBagIndex;
    cellFormat.applyFont = fontId !== undefined;
    cellFormat.applyFill = fillId !== undefined;
    cellFormat.applyBorder = borderId !== undefined;
    cellFormat.applyNumberFormat = numberFormatId !== undefined;
    if (input.horizontalAlignment !== undefined || input.verticalAlignment !== undefined || input.wrapText !== undefined) {
      cellFormat.applyAlignment = true;
    }
    const existing = this.#findCellFormat(cellFormat);
    if (existing !== undefined) {
      return existing;
    }
    this.#cellFormats.push(cellFormat);
    return this.#cellFormats.length - 1;
  }
  resolveFeaturePropertyBagStyleIndex(sourceStyleIndex, featurePropertyBagIndex) {
    const safeIndex = typeof sourceStyleIndex === "number" && sourceStyleIndex >= 0 && sourceStyleIndex < this.#cellFormats.length ? sourceStyleIndex : 0;
    const source = this.#cellFormats[safeIndex] ?? new CellFormatModel;
    if (source.featurePropertyBagIndex === featurePropertyBagIndex) {
      return safeIndex;
    }
    const next = new CellFormatModel(source.toProto());
    next.featurePropertyBagIndex = featurePropertyBagIndex;
    const existing = this.#findCellFormat(next);
    if (existing !== undefined) {
      return existing;
    }
    this.#cellFormats.push(next);
    return this.#cellFormats.length - 1;
  }
  toProto() {
    return {
      fonts: this.#fonts.map((font) => font.toProto()),
      fills: this.#fills.map((fill2) => {
        const proto = fill2.toProto();
        if (!proto) {
          throw new Error("Stored fill is missing proto data.");
        }
        return proto;
      }),
      cellXfs: this.#cellFormats.map((format2) => format2.toProto()),
      borders: this.#borders.map((border) => border.toProto()),
      cellStyles: cloneProtoArray(this.#cellStyles),
      cellStyleXfs: cloneProtoArray(this.#cellStyleXfs),
      numberFormats: this.#numberFormats.map((format2) => format2.toProto()),
      dxfs: cloneProtoArray(this.#dxfs),
      indexedColors: cloneProtoArray(this.#indexedColors),
      mruColors: cloneProtoArray(this.#mruColors)
    };
  }
  registerDifferentialFormat(config, themeMap) {
    const dxf = {};
    if (config.fill) {
      const fill2 = config.fill instanceof Fill2 ? config.fill : new Fill2(config.fill);
      const fillProto = fill2.toProto();
      if (fillProto) {
        dxf.fill = normalizeDifferentialFill(fillProto);
      }
    }
    if (config.font) {
      const font = new TextStyleModel;
      font.bold = config.font.bold;
      font.italic = config.font.italic;
      font.size = config.font.size;
      font.name = config.font.name;
      if (config.font.color) {
        font.color = config.font.color instanceof Color4 ? config.font.color : new Color4(config.font.color);
      }
      dxf.font = font.toProto();
    }
    if (config.border) {
      const border = buildDifferentialBorder(config.border);
      if (border.hasValues()) {
        dxf.border = border.toProto();
      }
    }
    if (config.numberFormat) {
      const numberFormatId = this.#resolveNumberFormatId(undefined, config.numberFormat);
      if (numberFormatId !== undefined) {
        const numberFormat = {
          id: numberFormatId,
          formatCode: config.numberFormat
        };
        dxf.numberFormat = numberFormat;
      }
    }
    if (themeMap) {
      resolveDxfThemeColors(dxf, themeMap);
    }
    this.#dxfs.push(dxf);
    return this.#dxfs.length - 1;
  }
  #cloneFill(index) {
    if (index === undefined) {
      return;
    }
    const fill2 = this.#fills[index];
    if (!fill2) {
      return;
    }
    return cloneFillInstance(fill2);
  }
  #cloneFont(index) {
    if (index === undefined) {
      return;
    }
    const font = this.#fonts[index];
    return font ? font.clone() : undefined;
  }
  #cloneBorder(index) {
    if (index === undefined) {
      return;
    }
    const border = this.#borders[index];
    return border ? border.clone() : undefined;
  }
  #registerFont(font) {
    const candidate = font.clone();
    const existing = this.#findFontIndex(candidate);
    if (existing !== undefined) {
      return existing;
    }
    this.#fonts.push(candidate);
    return this.#fonts.length - 1;
  }
  #registerFill(fill2) {
    const proto = fill2.toProto();
    if (!proto) {
      throw new Error("Fill is missing proto data.");
    }
    const candidate = new Fill2({ type: "proto", proto });
    const existing = this.#findFillIndex(candidate);
    if (existing !== undefined) {
      return existing;
    }
    this.#fills.push(candidate);
    return this.#fills.length - 1;
  }
  #registerBorder(border) {
    const candidate = border.clone();
    const existing = this.#findBorderIndex(candidate);
    if (existing !== undefined) {
      return existing;
    }
    this.#borders.push(candidate);
    return this.#borders.length - 1;
  }
  #resolveNumberFormatId(existingId, formatCode) {
    if (formatCode && formatCode.trim() !== "") {
      const existing = this.#numberFormats.find((entry) => entry.formatCode === formatCode);
      if (existing?.id !== undefined) {
        return existing.id;
      }
      const id2 = this.#nextNumberFormatId++;
      this.#numberFormats.push(new NumberFormatModel({ id: id2, formatCode }));
      return id2;
    }
    return existingId;
  }
  #computeNextNumberFormatId() {
    const ids = this.#numberFormats.map((format2) => format2.id ?? 0).filter((id2) => id2 > 0);
    const maxExisting = ids.length ? Math.max(...ids) : 0;
    return Math.max(200, maxExisting + 1);
  }
  #numberFormatCodeForId(id2) {
    if (id2 === undefined) {
      return;
    }
    const entry = this.#numberFormats.find((format2) => format2.id === id2);
    return entry?.formatCode;
  }
  #findFontIndex(font) {
    for (let index = 0;index < this.#fonts.length; index += 1) {
      const entry = this.#fonts[index];
      if (entry && entry.equals(font)) {
        return index;
      }
    }
    return;
  }
  #findFillIndex(fill2) {
    const proto = fill2.toProto();
    if (!proto) {
      throw new Error("Fill is missing proto data.");
    }
    const targetSignature = serialize(proto);
    for (let index = 0;index < this.#fills.length; index += 1) {
      const entry = this.#fills[index];
      if (!entry) {
        continue;
      }
      const entryProto = entry.toProto();
      if (!entryProto) {
        continue;
      }
      if (serialize(entryProto) === targetSignature) {
        return index;
      }
    }
    return;
  }
  #findBorderIndex(border) {
    for (let index = 0;index < this.#borders.length; index += 1) {
      const entry = this.#borders[index];
      if (entry && entry.equals(border)) {
        return index;
      }
    }
    return;
  }
  #findCellFormat(format2) {
    for (let index = 0;index < this.#cellFormats.length; index += 1) {
      const entry = this.#cellFormats[index];
      if (entry && entry.equals(format2)) {
        return index;
      }
    }
    return;
  }
}

class TextStyleModel {
  bold;
  italic;
  size;
  name;
  color;
  constructor(proto) {
    const source = proto ?? {};
    this.bold = source.bold;
    this.italic = source.italic;
    this.size = source.fontSize;
    this.name = source.typeface;
    this.color = source.fill?.color ? new Color4({ type: "proto", proto: source.fill.color }) : undefined;
  }
  clone() {
    const clone = new TextStyleModel;
    clone.bold = this.bold;
    clone.italic = this.italic;
    clone.size = this.size;
    clone.name = this.name;
    clone.color = this.color;
    return clone;
  }
  equals(other) {
    return this.bold === other.bold && this.italic === other.italic && this.size === other.size && this.name === other.name && colorsEqual2(this.color, other.color);
  }
  toProto() {
    const proto = {};
    proto.bold = this.bold;
    proto.italic = this.italic;
    proto.fontSize = this.size;
    proto.typeface = this.name;
    if (this.color) {
      const colorProto = this.color.toProto();
      if (colorProto) {
        proto.fill = {
          type: 0,
          color: colorProto,
          gradientStops: []
        };
      }
    }
    return proto;
  }
}

class BorderLineModel {
  style;
  color;
  weight;
  constructor(proto) {
    const style = proto?.style;
    this.style = style && style.trim() !== "" ? style : undefined;
    this.weight = proto?.indexedColorId;
    this.color = proto?.color ? new Color4({ type: "proto", proto: proto.color }) : undefined;
  }
  clone() {
    const clone = new BorderLineModel;
    clone.style = this.style;
    clone.weight = this.weight;
    clone.color = this.color;
    return clone;
  }
  equals(other) {
    if (!other) {
      return false;
    }
    return this.style === other.style && this.weight === other.weight && colorsEqual2(this.color, other.color);
  }
  toProto() {
    if ((this.style === undefined || this.style.trim() === "") && this.color === undefined && this.weight === undefined) {
      return;
    }
    const proto = {};
    if (this.style !== undefined && this.style.trim() !== "") {
      proto.style = this.style;
    }
    if (this.weight !== undefined) {
      proto.indexedColorId = this.weight;
    }
    if (this.color) {
      proto.color = this.color.toProto();
    }
    return proto;
  }
}

class BorderModel {
  top;
  bottom;
  left;
  right;
  diagonal;
  diagonalUp;
  diagonalDown;
  constructor(proto) {
    this.top = proto?.top ? new BorderLineModel(proto.top) : undefined;
    this.bottom = proto?.bottom ? new BorderLineModel(proto.bottom) : undefined;
    this.left = proto?.left ? new BorderLineModel(proto.left) : undefined;
    this.right = proto?.right ? new BorderLineModel(proto.right) : undefined;
    this.diagonal = proto?.diagonal ? new BorderLineModel(proto.diagonal) : undefined;
    this.diagonalUp = proto?.diagonalUp;
    this.diagonalDown = proto?.diagonalDown;
  }
  clone() {
    const clone = new BorderModel;
    clone.top = this.top ? this.top.clone() : undefined;
    clone.bottom = this.bottom ? this.bottom.clone() : undefined;
    clone.left = this.left ? this.left.clone() : undefined;
    clone.right = this.right ? this.right.clone() : undefined;
    clone.diagonal = this.diagonal ? this.diagonal.clone() : undefined;
    clone.diagonalUp = this.diagonalUp;
    clone.diagonalDown = this.diagonalDown;
    return clone;
  }
  equals(other) {
    if (!other) {
      return false;
    }
    return this.#lineEquals(this.top, other.top) && this.#lineEquals(this.bottom, other.bottom) && this.#lineEquals(this.left, other.left) && this.#lineEquals(this.right, other.right) && this.#lineEquals(this.diagonal, other.diagonal) && this.diagonalUp === other.diagonalUp && this.diagonalDown === other.diagonalDown;
  }
  hasValues() {
    return Boolean(this.top || this.bottom || this.left || this.right || this.diagonal || this.diagonalUp || this.diagonalDown);
  }
  toProto() {
    const proto = {};
    proto.top = this.top?.toProto();
    proto.bottom = this.bottom?.toProto();
    proto.left = this.left?.toProto();
    proto.right = this.right?.toProto();
    proto.diagonal = this.diagonal?.toProto();
    proto.diagonalUp = this.diagonalUp;
    proto.diagonalDown = this.diagonalDown;
    return proto;
  }
  #lineEquals(a, b) {
    if (!a && !b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    return a.equals(b);
  }
}

class CellFormatModel {
  fontId;
  fillId;
  borderId;
  xfId;
  featurePropertyBagIndex;
  numberFormatId;
  wrapText;
  horizontalAlignment;
  verticalAlignment;
  applyFont;
  applyFill;
  applyBorder;
  applyNumberFormat;
  applyAlignment;
  constructor(proto) {
    const source = proto ?? {};
    this.fontId = source.fontId;
    this.fillId = source.fillId;
    this.borderId = source.borderId;
    this.xfId = source.xfId;
    this.featurePropertyBagIndex = source.featurePropertyBagIndex;
    this.numberFormatId = source.numFmtId;
    this.wrapText = source.wrapText;
    this.horizontalAlignment = source.horizontalAlignment;
    this.verticalAlignment = source.verticalAlignment;
    this.applyFont = source.applyFont;
    this.applyFill = source.applyFill;
    this.applyBorder = source.applyBorder;
    this.applyNumberFormat = source.applyNumberFormat;
    this.applyAlignment = source.applyAlignment;
  }
  equals(other) {
    return this.fontId === other.fontId && this.fillId === other.fillId && this.borderId === other.borderId && this.xfId === other.xfId && this.featurePropertyBagIndex === other.featurePropertyBagIndex && this.numberFormatId === other.numberFormatId && this.wrapText === other.wrapText && this.horizontalAlignment === other.horizontalAlignment && this.verticalAlignment === other.verticalAlignment && this.applyFont === other.applyFont && this.applyFill === other.applyFill && this.applyBorder === other.applyBorder && this.applyNumberFormat === other.applyNumberFormat && this.applyAlignment === other.applyAlignment;
  }
  toProto() {
    const proto = {};
    proto.fontId = this.fontId;
    proto.fillId = this.fillId;
    proto.borderId = this.borderId;
    proto.xfId = this.xfId;
    proto.featurePropertyBagIndex = this.featurePropertyBagIndex;
    proto.numFmtId = this.numberFormatId;
    proto.wrapText = this.wrapText;
    proto.horizontalAlignment = this.horizontalAlignment;
    proto.verticalAlignment = this.verticalAlignment;
    proto.applyFont = this.applyFont;
    proto.applyFill = this.applyFill;
    proto.applyBorder = this.applyBorder;
    proto.applyNumberFormat = this.applyNumberFormat;
    proto.applyAlignment = this.applyAlignment;
    return proto;
  }
}

class NumberFormatModel {
  id;
  formatCode;
  constructor(proto) {
    const source = proto ?? {};
    this.id = source.id;
    this.formatCode = source.formatCode;
  }
  toProto() {
    if (this.id === undefined || this.formatCode === undefined) {
      throw new Error("Number format requires both id and formatCode");
    }
    return {
      id: this.id,
      formatCode: this.formatCode
    };
  }
}
function buildDifferentialBorder(config) {
  const border = new BorderModel;
  border.top = buildDifferentialBorderLine(config.top);
  border.bottom = buildDifferentialBorderLine(config.bottom);
  border.left = buildDifferentialBorderLine(config.left);
  border.right = buildDifferentialBorderLine(config.right);
  border.diagonal = buildDifferentialBorderLine(config.diagonal);
  border.diagonalUp = config.diagonalUp;
  border.diagonalDown = config.diagonalDown;
  return border;
}
function buildDifferentialBorderLine(config) {
  if (!config) {
    return;
  }
  const line = new BorderLineModel;
  line.style = config.style;
  line.weight = config.weight;
  if (config.color) {
    line.color = config.color instanceof Color4 ? config.color : new Color4(config.color);
  }
  return line;
}
function cloneFillInstance(fill2) {
  const proto = fill2.toProto();
  if (!proto) {
    throw new Error("Fill is missing proto data.");
  }
  return new Fill2({ type: "proto", proto });
}
function colorsEqual2(a, b) {
  if (!a && !b) {
    return true;
  }
  if (!a || !b) {
    return false;
  }
  return serialize(a.toProto()) === serialize(b.toProto());
}
function cloneProtoArray(items) {
  if (!items?.length) {
    return [];
  }
  return items.map((item) => cloneProtoValue(item));
}
function cloneProtoValue(value) {
  if (value === null || value === undefined) {
    return value;
  }
  if (Array.isArray(value)) {
    return value.map((item) => cloneProtoValue(item));
  }
  if (typeof value === "object") {
    const record = value;
    const cloned = {};
    for (const [key, entry] of Object.entries(record)) {
      cloned[key] = cloneProtoValue(entry);
    }
    return cloned;
  }
  return value;
}
function serialize(value) {
  return JSON.stringify(value ?? null);
}
function normalizeDifferentialFill(fill2) {
  if (fill2.type !== 1 /* FILL_TYPE_SOLID */) {
    return fill2;
  }
  return {
    ...fill2,
    type: 3 /* FILL_TYPE_PATTERN */,
    pattern: {
      patternType: 2 /* PATTERN_TYPE_SOLID */,
      color: fill2.color
    }
  };
}
function resolveDxfThemeColors(dxf, themeMap) {
  if (dxf.fill?.color) {
    const resolved = resolveThemeColor(dxf.fill.color, themeMap);
    if (resolved) {
      dxf.fill = { ...dxf.fill, color: resolved };
    }
  }
  if (dxf.font?.fill?.color) {
    const resolved = resolveThemeColor(dxf.font.fill.color, themeMap);
    if (resolved) {
      dxf.font = {
        ...dxf.font,
        fill: {
          ...dxf.font.fill,
          color: resolved
        }
      };
    }
  }
  if (dxf.border) {
    dxf.border = {
      ...dxf.border,
      top: resolveBorderLineColor(dxf.border.top, themeMap),
      bottom: resolveBorderLineColor(dxf.border.bottom, themeMap),
      left: resolveBorderLineColor(dxf.border.left, themeMap),
      right: resolveBorderLineColor(dxf.border.right, themeMap),
      diagonal: resolveBorderLineColor(dxf.border.diagonal, themeMap)
    };
  }
}
function resolveBorderLineColor(line, themeMap) {
  if (!line?.color) {
    return line;
  }
  const resolved = resolveThemeColor(line.color, themeMap);
  if (!resolved) {
    return line;
  }
  return {
    ...line,
    color: resolved
  };
}
function resolveThemeColor(color2, themeMap) {
  if (color2.type !== 2 /* COLOR_TYPE_SCHEME */ && color2.type !== 3 /* COLOR_TYPE_SYSTEM */) {
    return color2;
  }
  const rgba2 = colorToRgba(color2, themeMap, SPREADSHEET_COLOR_OPTIONS);
  const parsed = parseRgba(rgba2);
  if (!parsed) {
    return color2;
  }
  const { r, g, b, a } = parsed;
  const to2 = (value) => value.toString(16).padStart(2, "0");
  const alpha = Math.max(0, Math.min(1, a));
  const alphaHex = to2(Math.round(alpha * 255));
  return {
    type: 1 /* COLOR_TYPE_RGB */,
    value: `${alphaHex}${to2(r)}${to2(g)}${to2(b)}`.toUpperCase(),
    transform: undefined
  };
}
function parseRgba(css) {
  const match = css.match(/^rgba?\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\)$/i);
  if (!match) {
    return null;
  }
  const r = Math.max(0, Math.min(255, Number(match[1])));
  const g = Math.max(0, Math.min(255, Number(match[2])));
  const b = Math.max(0, Math.min(255, Number(match[3])));
  const a = match[4] === undefined ? 1 : Number(match[4]);
  if ([r, g, b, a].some((value) => Number.isNaN(value))) {
    return null;
  }
  return { r, g, b, a };
}

// node_modules/@oai/granola/dist/spreadsheet/workbook-theme.js
var EXCEL_COLOR_SCHEME_REMAP = {
  accent1: "accent1",
  accent2: "accent2",
  accent3: "accent3",
  accent4: "accent4",
  accent5: "accent5",
  accent6: "accent6",
  bg1: "lt1",
  tx1: "dk1",
  bg2: "lt2",
  tx2: "dk2",
  hlink: "hlink",
  folHlink: "folHlink"
};
function buildWorkbookThemeMap(workbookTheme) {
  const themeObj = new Theme2({ stub: () => {} }, workbookTheme);
  return buildThemeMap(themeObj, EXCEL_COLOR_SCHEME_REMAP);
}
// node_modules/@oai/granola/dist/spreadsheet/build-style-maps.js
var import_ssf5 = __toESM(require_ssf(), 1);
var SPREADSHEET_COLOR_OPTIONS2 = { colorSpace: "spreadsheetml" };
var SSF_TABLE = import_ssf5.default.get_table();
var BUILTIN_FALLBACK_FORMATS = {
  5: '"$"#,##0_);\\("$"#,##0\\)',
  6: '"$"#,##0_);[Red]\\("$"#,##0\\)',
  7: '"$"#,##0.00_);\\("$"#,##0.00\\)',
  8: '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  41: '_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)',
  42: '_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)',
  43: '_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)',
  44: '_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)'
};
function applyFormat(fmt, styles, info, respectApplyFlags, themeMap, source, _logLabel) {
  if (!fmt || !styles)
    return;
  const allowAlignment = !respectApplyFlags || fmt.applyAlignment || fmt.applyAlignment === undefined;
  if (fmt.numFmtId != null) {
    info.numberFormatId = fmt.numFmtId;
    const match = styles.numberFormats?.find((nf) => nf.id === fmt.numFmtId);
    if (match?.formatCode) {
      info.numberFormatCode = match.formatCode;
    } else if (SSF_TABLE[fmt.numFmtId]) {
      info.numberFormatCode = SSF_TABLE[fmt.numFmtId];
    } else if (BUILTIN_FALLBACK_FORMATS[fmt.numFmtId]) {
      info.numberFormatCode = BUILTIN_FALLBACK_FORMATS[fmt.numFmtId];
    } else {
      info.numberFormatCode = undefined;
    }
  }
  if (fmt.fillId != null && (!respectApplyFlags || fmt.applyFill || fmt.applyFill === undefined)) {
    const fill2 = styles.fills?.[fmt.fillId];
    const patternType = fill2?.pattern?.patternType;
    const isSolidPattern = patternType === 2 /* PATTERN_TYPE_SOLID */;
    const fillHasColor = !!(fill2?.color || fill2?.pattern?.color);
    if (fill2?.color) {
      const css = resolveColor(fill2.color, themeMap, SPREADSHEET_COLOR_OPTIONS2);
      if (css)
        info.fill = css;
    } else {
      const hex2 = fill2?.pattern?.color?.value;
      if (hex2) {
        info.fill = argbHexToCss(hex2);
      } else if (isSolidPattern && !fillHasColor) {
        info.fill = "#000000";
      }
    }
  }
  if (fmt.fontId != null && ((!respectApplyFlags || fmt.applyFont) ?? true)) {
    const src = styles.fonts[fmt.fontId];
    const dst = info.font ??= {};
    if (typeof src?.fontSize === "number") {
      const px = src.fontSize * (96 / 72);
      dst.size = px;
      (info.fontSources ??= {}).size = source;
    }
    if (src?.bold != null) {
      dst.bold = src.bold;
      (info.fontSources ??= {}).bold = source;
    }
    if (src?.italic != null) {
      dst.italic = src.italic;
      (info.fontSources ??= {}).italic = source;
    }
    if (src?.underline != null) {
      dst.underline = !!src.underline;
      (info.fontSources ??= {}).underline = source;
    }
    if (src?.name) {
      dst.family = src.name;
      (info.fontSources ??= {}).family = source;
    }
    const colorObj = src?.fill?.color;
    if (colorObj) {
      let css;
      if (colorObj.type === 3 /* COLOR_TYPE_SYSTEM */ && typeof colorObj.value === "string") {
        if (colorObj.value === "auto") {
          css = "#000000";
        } else if (colorObj.value.startsWith("indexed:")) {
          const idx = parseInt(colorObj.value.split(":")[1] ?? "", 10);
          if (!Number.isNaN(idx))
            css = excelIndexedColorToCss(idx);
        }
      }
      if (!css) {
        css = resolveColor(colorObj, themeMap, SPREADSHEET_COLOR_OPTIONS2);
      }
      if (css) {
        dst.color = css;
        info.textColor = css;
        (info.fontSources ??= {}).color = source;
      }
    }
  }
  if (fmt.horizontalAlignment && allowAlignment) {
    switch (fmt.horizontalAlignment) {
      case "left":
      case "center":
      case "right":
        info.align = fmt.horizontalAlignment;
        break;
      default:
        break;
    }
  }
  if (fmt.verticalAlignment && allowAlignment) {
    const vAlign = String(fmt.verticalAlignment).toLowerCase();
    switch (vAlign) {
      case "top":
        info.verticalAlign = 1 /* ANCHOR_TYPE_TOP */;
        break;
      case "center":
      case "middle":
        info.verticalAlign = 2 /* ANCHOR_TYPE_MIDDLE */;
        break;
      case "bottom":
        info.verticalAlign = 3 /* ANCHOR_TYPE_BOTTOM */;
        break;
    }
  }
  if (fmt.wrapText !== undefined && allowAlignment) {
    info.wrapText = fmt.wrapText;
  }
  if (fmt.borderId != null && (!respectApplyFlags || fmt.applyBorder || fmt.applyBorder === undefined)) {
    const border = styles.borders[fmt.borderId];
    if (border) {
      info.borders ??= {};
      info.borderStyles ??= {};
      const resolveBorderColor = (colorObj, indexed) => {
        if (colorObj) {
          const isSystem = colorObj.type === 3 /* COLOR_TYPE_SYSTEM */;
          const value = colorObj.value;
          if (colorObj.type === 2 /* COLOR_TYPE_SCHEME */ && typeof value === "string" && value.startsWith("theme:")) {
            const css = resolveColor(colorObj, themeMap, SPREADSHEET_COLOR_OPTIONS2);
            if (css)
              return css;
          }
          if (colorObj.type === 1 /* COLOR_TYPE_RGB */ && typeof value === "string") {
            const hex2 = value.replace(/^#/i, "");
            if (hex2.length === 8) {
              return argbHexToCss(hex2);
            }
            if (hex2.length === 6) {
              return `#${hex2}`;
            }
          }
          if (isSystem && (value?.startsWith("indexed:") || value === "auto")) {
            const idxCss2 = excelIndexedColorToCss(indexed);
            if (idxCss2)
              return idxCss2;
          }
          return resolveColor(colorObj, themeMap, SPREADSHEET_COLOR_OPTIONS2);
        }
        const idxCss = excelIndexedColorToCss(indexed);
        return idxCss;
      };
      if (border.left?.style) {
        let c = resolveBorderColor(border.left.color, border.left.indexedColorId);
        if (!c)
          c = "#000000";
        if (c)
          info.borders.left = c;
        info.borderStyles.left = border.left.style;
        (info.borderSources ??= {}).left = source;
      }
      if (border.right?.style) {
        let c = resolveBorderColor(border.right.color, border.right.indexedColorId);
        if (!c)
          c = "#000000";
        if (c)
          info.borders.right = c;
        info.borderStyles.right = border.right.style;
        (info.borderSources ??= {}).right = source;
      }
      if (border.top?.style) {
        let c = resolveBorderColor(border.top.color, border.top.indexedColorId);
        if (!c)
          c = "#000000";
        if (c)
          info.borders.top = c;
        info.borderStyles.top = border.top.style;
        (info.borderSources ??= {}).top = source;
      }
      if (border.bottom?.style) {
        let c = resolveBorderColor(border.bottom.color, border.bottom.indexedColorId);
        if (!c)
          c = "#000000";
        if (c)
          info.borders.bottom = c;
        info.borderStyles.bottom = border.bottom.style;
        (info.borderSources ??= {}).bottom = source;
      }
      if (border.diagonal?.style) {
        let c = resolveBorderColor(border.diagonal.color, border.diagonal.indexedColorId);
        if (!c)
          c = "#000000";
        if (c)
          info.borders.diagonal = c;
        info.borderStyles.diagonal = border.diagonal.style;
        (info.borderSources ??= {}).diagonal = source;
      }
      if (border.diagonalUp != null)
        info.borderDiagonalUp = !!border.diagonalUp;
      if (border.diagonalDown != null)
        info.borderDiagonalDown = !!border.diagonalDown;
    }
  }
}
function pruneDuplicateBaseReferences(fmt, baseFmt) {
  if (!baseFmt)
    return fmt;
  const next = { ...fmt };
  if (next.fontId != null && next.fontId === baseFmt.fontId) {
    next.fontId = undefined;
  }
  if (next.fillId != null && next.fillId === baseFmt.fillId) {
    next.fillId = undefined;
  }
  if (next.borderId != null && next.borderId === baseFmt.borderId) {
    next.borderId = undefined;
  }
  if (next.numFmtId != null && next.numFmtId === baseFmt.numFmtId) {
    next.numFmtId = undefined;
  }
  return next;
}
function buildStyleMaps(workbook) {
  const { styles } = workbook;
  const themeMap = buildWorkbookThemeMap(workbook.theme);
  const styleInfos = {};
  if (!styles)
    return styleInfos;
  styles.cellXfs.forEach((xf, idx) => {
    const info = {};
    const baseFmt = xf.xfId != null && styles.cellStyleXfs && styles.cellStyleXfs[xf.xfId] ? styles.cellStyleXfs[xf.xfId]?.format : undefined;
    if (baseFmt) {
      applyFormat(baseFmt, styles, info, false, themeMap, "base", `base:${idx}`);
    }
    applyFormat(pruneDuplicateBaseReferences(xf, baseFmt), styles, info, true, themeMap, "cell", `cell:${idx}`);
    styleInfos[idx] = info;
  });
  return styleInfos;
}

// node_modules/@oai/granola/dist/spreadsheet/adapter/dimensions.js
function buildColumnWidthsPx(sheet) {
  const paddingChars = 5 / 7;
  const fallbackColWidth = typeof sheet.defaultColWidth === "number" && sheet.defaultColWidth > 0 ? sheet.defaultColWidth : typeof sheet.baseColWidth === "number" && sheet.baseColWidth > 0 ? sheet.baseColWidth + paddingChars : 8.43;
  const defaultWidth = colWidthToPx(fallbackColWidth);
  const widths = [];
  const maxCol = sheet.columns?.reduce((max4, col) => Math.max(max4, (col.max ?? col.min ?? 1) - 1), 0) ?? 0;
  const maxCellCol = sheet.rows?.reduce((max4, row2) => {
    const rowMax = row2.cells?.reduce((acc, cell) => Math.max(acc, columnIndex(cell.address ?? "A1")), 0) ?? 0;
    return Math.max(max4, rowMax);
  }, 0) ?? 0;
  const count3 = Math.max(1, Math.max(maxCol, maxCellCol) + 1);
  for (let i = 0;i < count3; i++)
    widths.push(defaultWidth);
  for (const col of sheet.columns ?? []) {
    const min3 = Math.max(0, (col.min ?? 1) - 1);
    const max4 = Math.max(min3, (col.max ?? col.min ?? 1) - 1);
    const px = col.hidden ? 0 : colWidthToPx(col.width);
    for (let idx = min3;idx <= max4; idx++) {
      if (idx < widths.length)
        widths[idx] = px;
    }
  }
  return widths;
}
function buildRowHeightsPx(sheet) {
  const defaultPt = sheet.defaultRowHeight && sheet.defaultRowHeight !== 0 ? sheet.defaultRowHeight : FALLBACK_ROW_H_PT;
  const heights = [];
  const maxRow = sheet.rows?.reduce((max4, row2) => Math.max(max4, (row2.index ?? 1) - 1), 0) ?? 0;
  const mergedRows = sheet.mergedCells?.reduce((max4, range2) => Math.max(max4, rowIndex(range2.endAddress ?? range2.startAddress) - 1), 0) ?? 0;
  const count3 = Math.max(1, Math.max(maxRow, mergedRows) + 1);
  for (let i = 0;i < count3; i++)
    heights.push(pointsToPx(defaultPt));
  for (const row2 of sheet.rows ?? []) {
    const idx = (row2.index ?? 1) - 1;
    if (idx < 0 || idx >= heights.length)
      continue;
    if (row2.hidden) {
      heights[idx] = 0;
      continue;
    }
    if ((row2.customHeight || row2.height !== 0) && row2.height != null) {
      heights[idx] = pointsToPx(row2.height);
    }
  }
  return heights;
}

// node_modules/@oai/granola/dist/spreadsheet/autofit.js
init_address_utils();

// node_modules/@oai/granola/dist/spreadsheet/resolve-cell-text-emphasis.js
function toSolidFill(color2) {
  return {
    color: color2,
    type: 1 /* FILL_TYPE_SOLID */,
    gradientStops: []
  };
}
function resolveCellTextEmphasis({ currentTextStyle, baseStyle, baseStyleFontColor, tableCellStyle, pivotFontColor, pivotBold, conditionalFormattingTextColor, numberFormatColorOverride }) {
  const resolved = {};
  const directCellFontColor = baseStyle.fontSources?.color === "cell" ? baseStyleFontColor : null;
  const inheritedFontColor = baseStyle.fontSources?.color === "cell" ? null : baseStyleFontColor;
  if (pivotBold || tableCellStyle?.font?.bold === true) {
    resolved.bold = true;
  } else if (currentTextStyle.bold != null) {
    resolved.bold = currentTextStyle.bold;
  } else if (tableCellStyle?.font?.bold != null) {
    resolved.bold = tableCellStyle.font.bold;
  } else if (baseStyle.font?.bold != null) {
    resolved.bold = !!baseStyle.font.bold;
  }
  const color2 = conditionalFormattingTextColor ?? numberFormatColorOverride ?? pivotFontColor ?? directCellFontColor ?? tableCellStyle?.font?.color ?? currentTextStyle.fill?.color ?? inheritedFontColor ?? null;
  if (color2) {
    resolved.fill = toSolidFill(color2);
  }
  return resolved;
}

// node_modules/@oai/granola/dist/spreadsheet/data-validation-dropdown-layout.js
var DATA_VALIDATION_ARROW_INSET_PX = 4;
var DATA_VALIDATION_ARROW_MAX_SIZE_PX = 8;
function showsListValidationDropdown(validation) {
  return validation.type === 4 /* DATA_VALIDATION_TYPE_LIST */ && validation.showDropDown !== true;
}
function getListValidationArrowSizePx(cellHeightPx) {
  return Math.min(DATA_VALIDATION_ARROW_MAX_SIZE_PX, Math.max(0, cellHeightPx - DATA_VALIDATION_ARROW_INSET_PX * 2));
}
function getListValidationArrowReservePx(cellHeightPx) {
  const arrowSizePx = getListValidationArrowSizePx(cellHeightPx);
  return arrowSizePx > 0 ? arrowSizePx + DATA_VALIDATION_ARROW_INSET_PX * 2 : 0;
}

// node_modules/@oai/granola/dist/spreadsheet/autofit.js
var TABLE_HEADER_BUTTON_ICON_MAX_W_PX = 12;
var TABLE_HEADER_BUTTON_BORDER_W_PX = 2;
var TABLE_HEADER_BUTTON_RIGHT_INSET_PX = 4;
var TABLE_HEADER_BUTTON_LABEL_GAP_PX = 4;
function parseColumnTarget(address, bounds) {
  const colRange = /^([A-Z]+):([A-Z]+)$/i.exec(address.trim());
  if (colRange) {
    const startToken = colRange[1];
    const endToken = colRange[2];
    if (!startToken || !endToken)
      return null;
    const startCol = columnIndex(startToken);
    const endCol = columnIndex(endToken);
    return {
      startCol: Math.min(startCol, endCol),
      endCol: Math.max(startCol, endCol)
    };
  }
  const parsed = bounds ?? parseRangeAddress(address)?.bounds ?? null;
  if (!parsed)
    return null;
  return {
    startCol: parsed.startCol,
    endCol: parsed.endCol,
    rowStart: parsed.startRow,
    rowEnd: parsed.endRow
  };
}
function parseRowTarget(address, bounds) {
  const rowRange = /^(\d+):(\d+)$/i.exec(address.trim());
  if (rowRange) {
    const startRow = Number(rowRange[1]) - 1;
    const endRow = Number(rowRange[2]) - 1;
    return {
      startRow: Math.min(startRow, endRow),
      endRow: Math.max(startRow, endRow)
    };
  }
  const parsed = bounds ?? parseRangeAddress(address)?.bounds ?? null;
  if (!parsed)
    return null;
  return {
    startRow: parsed.startRow,
    endRow: parsed.endRow,
    colStart: parsed.startCol,
    colEnd: parsed.endCol
  };
}
function buildColumnStyleMap(sheet) {
  const colStyleIdxs = [];
  for (const colDef of sheet.columns ?? []) {
    const anyCol = colDef;
    const sIdx = typeof anyCol?.styleIndex === "number" ? anyCol.styleIndex : undefined;
    if (typeof sIdx === "number") {
      const min0 = Math.max(0, (colDef.min ?? 1) - 1);
      const max0 = Math.max(min0, (colDef.max ?? colDef.min ?? 1) - 1);
      for (let i = min0;i <= max0; i++) {
        if (colStyleIdxs[i] == null)
          colStyleIdxs[i] = sIdx;
      }
    }
  }
  return colStyleIdxs;
}
function buildRowStyleMap(sheet) {
  const byRow = new Map;
  for (const row2 of sheet.rows ?? []) {
    if (typeof row2.styleIndex === "number") {
      const idx = Math.max(0, (row2.index ?? 1) - 1);
      byRow.set(idx, row2.styleIndex);
    }
  }
  return byRow;
}
function effectiveStyleIndex(cell, rowIdx, colIdx, rowStyleByIdx, colStyleIdxs) {
  const rowStyleIdx = rowStyleByIdx.get(rowIdx);
  const colStyleIdx = colStyleIdxs[colIdx];
  return cell?.styleIndex ?? rowStyleIdx ?? colStyleIdx ?? 0;
}
function resolveAlignment(style) {
  if (style?.align === "center")
    return 2 /* ALIGNMENT_TYPE_CENTER */;
  if (style?.align === "right")
    return 3 /* ALIGNMENT_TYPE_RIGHT */;
  return 1 /* ALIGNMENT_TYPE_LEFT */;
}
function applyMeasuredCellRunTextStyles(params2) {
  const { element, style, tableCellStyle } = params2;
  if (!style) {
    return;
  }
  for (const para of element.paragraphs ?? []) {
    for (const run of para.runs ?? []) {
      run.textStyle = run.textStyle ?? {};
      if (typeof run.textStyle.fontSize === "number" && run.textStyle.fontSize > 0 && run.textStyle.fontSize < 100) {
        run.textStyle.fontSize = Math.round(run.textStyle.fontSize * 100);
      }
      if (!(typeof run.textStyle.fontSize === "number" && run.textStyle.fontSize > 0)) {
        const px = style.font?.size;
        const pt = typeof px === "number" && px > 0 ? px * 72 / 96 : 11;
        run.textStyle.fontSize = Math.round(pt * 100);
      }
      if (run.textStyle.italic == null && style.font?.italic != null) {
        run.textStyle.italic = !!style.font.italic;
      }
      if (run.textStyle.name == null) {
        run.textStyle.name = normalizeFamilyName2(style.font?.family);
      }
      if (run.textStyle.underline == null && style.font?.underline != null) {
        run.textStyle.underline = style.font.underline ? "single" : "none";
      }
      const emphasis = resolveCellTextEmphasis({
        currentTextStyle: run.textStyle,
        baseStyle: style,
        baseStyleFontColor: null,
        tableCellStyle
      });
      if (emphasis.bold != null) {
        run.textStyle.bold = emphasis.bold;
      }
    }
  }
}
function measureCell(params2) {
  const { style, themeMap, wrap: wrap2, boxWidthPx, paragraphs, tableCellStyle } = params2;
  const basePx = style?.font?.size ?? 11 * (96 / 72);
  const { padLr, padTb } = resolveCellPadding(basePx);
  const resolvedAlignment = resolveAlignment(style);
  const el = {
    paragraphs,
    textStyle: {
      alignment: resolvedAlignment,
      anchor: 1 /* ANCHOR_TYPE_TOP */
    },
    bbox: {
      xEmu: 0,
      yEmu: 0,
      widthEmu: Math.round(Math.max(boxWidthPx, 1) * 9525),
      heightEmu: Math.round(Math.max(basePx + padTb * 2, 1) * 9525)
    },
    type: 1 /* ELEMENT_TYPE_TEXT */,
    effects: [],
    children: [],
    levelsStyles: [],
    id: "",
    citations: []
  };
  applyMeasuredCellRunTextStyles({ element: el, style, tableCellStyle });
  const layout = layoutTextBlock(el, themeMap, {
    resolvedStyle: { alignment: resolvedAlignment },
    bboxPx: {
      x: 0,
      y: 0,
      width: Math.max(boxWidthPx, 1),
      height: Math.max(basePx + padTb * 2, 1)
    },
    paddingPx: {
      left: padLr,
      right: padLr,
      top: padTb,
      bottom: padTb
    },
    mode: "layout",
    textScale: 1,
    wrap: wrap2
  });
  const widthPx = (layout?.lines?.reduce((maxWidth, line) => Math.max(maxWidth, line.widthPx), 0) ?? 0) + padLr * 2;
  const heightPx = layout?.lines?.reduce((height, line) => height + line.heightPx, 0) ?? 0;
  return { widthPx, heightPx };
}
function makeDisplayText(cell, styleInfos, cache, styleIdx) {
  const cacheKey = `${cell.value ?? ""}__${styleIdx}`;
  if (cache.has(cacheKey)) {
    return cache.get(cacheKey) ?? "";
  }
  const text2 = formatCell(cell, styleInfos, cache, styleIdx);
  cache.set(cacheKey, text2);
  return text2;
}
function hasVisibleCellText(cell, displayText) {
  if (displayText !== "") {
    return true;
  }
  for (const paragraph of cell.paragraphs ?? []) {
    for (const run of paragraph.runs ?? []) {
      if (run.text !== "") {
        return true;
      }
    }
  }
  return false;
}
function buildTableHeaderOverlayCellSet(tableResolvers) {
  const headerCells = new Set;
  for (const resolver of tableResolvers) {
    if (resolver.headerRows === 0) {
      continue;
    }
    const headerEndRow = resolver.startRow + resolver.headerRows - 1;
    for (let row2 = resolver.startRow;row2 <= headerEndRow; row2++) {
      for (let col = resolver.startCol;col <= resolver.endCol; col++) {
        headerCells.add(`${row2}:${col}`);
      }
    }
  }
  return headerCells;
}
function getContainingTableStyleResolver(tableResolvers, row2, col) {
  return tableResolvers.find((resolver) => resolver.contains(row2, col));
}
function getTableHeaderOverlayReservePx(style) {
  const basePx = style?.font?.size ?? 11 * (96 / 72);
  const { padLr } = resolveCellPadding(basePx);
  return Math.max(0, TABLE_HEADER_BUTTON_ICON_MAX_W_PX + TABLE_HEADER_BUTTON_BORDER_W_PX + TABLE_HEADER_BUTTON_RIGHT_INSET_PX + TABLE_HEADER_BUTTON_LABEL_GAP_PX - padLr);
}
function buildListValidationRangeBounds(listValidationEntries) {
  const validationRangeBounds = [];
  for (const entry of listValidationEntries) {
    for (const range2 of entry.ranges) {
      const startAddress = range2.startAddress;
      const endAddress = range2.endAddress;
      if (!startAddress || !endAddress) {
        continue;
      }
      const startRow = rowIndex(startAddress);
      const endRow = rowIndex(endAddress);
      const startCol = columnIndex(startAddress);
      const endCol = columnIndex(endAddress);
      validationRangeBounds.push({
        startRow: Math.min(startRow, endRow),
        endRow: Math.max(startRow, endRow),
        startCol: Math.min(startCol, endCol),
        endCol: Math.max(startCol, endCol)
      });
    }
  }
  return validationRangeBounds;
}
function hasListValidationDropdown(validationRangeBounds, row2, col) {
  return validationRangeBounds.some((rangeBounds) => row2 >= rangeBounds.startRow && row2 <= rangeBounds.endRow && col >= rangeBounds.startCol && col <= rangeBounds.endCol);
}
function autofitColumns(params2) {
  const { address, bounds, workbook, worksheet } = params2;
  const target = parseColumnTarget(address, bounds);
  if (!target)
    return;
  const workbookProto = workbook.toProto();
  const sheetProto = workbookProto.sheets?.find((s) => s.name === worksheet.name) ?? null;
  if (!sheetProto)
    return;
  const themeMap = buildWorkbookThemeMap(workbookProto.theme);
  const styleInfos = buildStyleMaps(workbookProto);
  const renderMetadata = worksheet.__getSpreadsheetRenderMetadata(themeMap);
  const colStyleIdxs = buildColumnStyleMap(sheetProto);
  const rowStyleByIdx = buildRowStyleMap(sheetProto);
  const tableResolvers = renderMetadata.tableResolvers;
  const tableHeaderOverlayCells = buildTableHeaderOverlayCellSet(tableResolvers);
  const listValidationRangeBounds = buildListValidationRangeBounds(renderMetadata.listValidationEntries);
  const formatCache = new Map;
  const rowHeightsPx = buildRowHeightsPx(sheetProto);
  const defaultRowHeightPx = pointsToPx(sheetProto.defaultRowHeight && sheetProto.defaultRowHeight !== 0 ? sheetProto.defaultRowHeight : FALLBACK_ROW_H_PT);
  const columns = worksheet.__getColumns();
  for (let col = target.startCol;col <= target.endCol; col++) {
    const extent2 = worksheet.__getColumnExtent(col);
    const rowMin = target.rowStart ?? extent2?.minRow ?? 0;
    const rowMax = target.rowEnd ?? extent2?.maxRow ?? rowMin;
    if (rowMin > rowMax)
      continue;
    let maxPx = 0;
    for (let row2 = rowMin;row2 <= rowMax; row2++) {
      const cell = worksheet.__getCell(row2, col);
      if (!cell)
        continue;
      const styleIdx = effectiveStyleIndex(cell, row2, col, rowStyleByIdx, colStyleIdxs);
      const style = styleInfos[styleIdx];
      const tableCellStyle = getContainingTableStyleResolver(tableResolvers, row2, col)?.resolveCell(row2, col);
      const displayText = makeDisplayText(cell, styleInfos, formatCache, styleIdx);
      if (!hasVisibleCellText(cell, displayText)) {
        continue;
      }
      const paragraphs = cell.paragraphs && cell.paragraphs.length > 0 ? cell.paragraphs : [
        {
          runs: [
            {
              text: displayText,
              citations: [],
              reviewMarkIds: []
            }
          ]
        }
      ];
      const { widthPx } = measureCell({
        style,
        themeMap,
        wrap: false,
        boxWidthPx: 1e6,
        paragraphs,
        tableCellStyle
      });
      let reservedWidthPx = widthPx;
      if (tableHeaderOverlayCells.has(`${row2}:${col}`)) {
        reservedWidthPx += getTableHeaderOverlayReservePx(style);
      }
      if (hasListValidationDropdown(listValidationRangeBounds, row2, col)) {
        reservedWidthPx += getListValidationArrowReservePx(rowHeightsPx[row2] ?? defaultRowHeightPx);
      }
      if (reservedWidthPx > maxPx) {
        maxPx = reservedWidthPx;
      }
    }
    if (maxPx <= 0)
      continue;
    const widthUnits = pxToColWidth(Math.ceil(maxPx));
    const colIndex = col + 1;
    let column2 = columns.find((entry) => {
      const min3 = entry.min ?? entry.max ?? 1;
      const max4 = entry.max ?? entry.min ?? min3;
      return colIndex >= min3 && colIndex <= max4;
    }) ?? null;
    if (!column2) {
      column2 = {
        min: colIndex,
        max: colIndex,
        width: widthUnits,
        customWidth: true
      };
      columns.push(column2);
    }
    column2.min = colIndex;
    column2.max = colIndex;
    column2.width = widthUnits;
    column2.customWidth = true;
    column2.hidden = column2.hidden ?? false;
  }
}
function autofitRows(params2) {
  const { address, bounds, workbook, worksheet } = params2;
  const target = parseRowTarget(address, bounds);
  if (!target)
    return;
  const workbookProto = workbook.toProto();
  const sheetProto = workbookProto.sheets?.find((s) => s.name === worksheet.name) ?? null;
  if (!sheetProto)
    return;
  const themeMap = buildWorkbookThemeMap(workbookProto.theme);
  const styleInfos = buildStyleMaps(workbookProto);
  const renderMetadata = worksheet.__getSpreadsheetRenderMetadata(themeMap);
  const colStyleIdxs = buildColumnStyleMap(sheetProto);
  const rowStyleByIdx = buildRowStyleMap(sheetProto);
  const tableResolvers = renderMetadata.tableResolvers;
  const formatCache = new Map;
  const colWidthsPx = buildColumnWidthsPx(sheetProto);
  const defaultRowHeightPx = pointsToPx(sheetProto.defaultRowHeight && sheetProto.defaultRowHeight !== 0 ? sheetProto.defaultRowHeight : FALLBACK_ROW_H_PT);
  const rows = worksheet.__getRows();
  for (let rowIdx = target.startRow;rowIdx <= target.endRow; rowIdx++) {
    const extent2 = worksheet.__getRowExtent(rowIdx);
    const colStart = target.colStart ?? extent2?.minCol ?? 0;
    const colEnd = target.colEnd ?? extent2?.maxCol ?? colStart;
    if (colStart > colEnd)
      continue;
    let desiredHeightPx = 0;
    for (let col = colStart;col <= colEnd; col++) {
      const cell = worksheet.__getCell(rowIdx, col);
      if (!cell)
        continue;
      const styleIdx = effectiveStyleIndex(cell, rowIdx, col, rowStyleByIdx, colStyleIdxs);
      const style = styleInfos[styleIdx];
      const tableCellStyle = getContainingTableStyleResolver(tableResolvers, rowIdx, col)?.resolveCell(rowIdx, col);
      const displayText = makeDisplayText(cell, styleInfos, formatCache, styleIdx);
      const paragraphs = cell.paragraphs && cell.paragraphs.length > 0 ? cell.paragraphs : [
        {
          runs: [
            {
              text: displayText,
              citations: [],
              reviewMarkIds: []
            }
          ]
        }
      ];
      const widthPx = colWidthsPx[col] ?? colWidthsPx[colWidthsPx.length - 1];
      const { heightPx } = measureCell({
        style,
        themeMap,
        wrap: style?.wrapText === true,
        boxWidthPx: style?.wrapText === true ? Math.max(widthPx ?? 0, 1) : 1e6,
        paragraphs,
        tableCellStyle
      });
      if (heightPx > desiredHeightPx) {
        desiredHeightPx = heightPx;
      }
    }
    if (desiredHeightPx <= 0)
      continue;
    const row2 = worksheet.__getOrCreateRow(rowIdx);
    row2.height = pxToPoints(Math.max(defaultRowHeightPx, desiredHeightPx));
    row2.customHeight = true;
    row2.hidden = row2.hidden ?? false;
    if (!rows.includes(row2)) {
      rows.push(row2);
    }
  }
}

// node_modules/@oai/granola/dist/models/range-format.js
class LiveFill extends Fill2 {
  #onChange;
  constructor(source, onChange) {
    const proto = source.toProto();
    super(proto ? { type: "proto", proto } : undefined);
    this.#onChange = onChange;
  }
  get color() {
    return super.color;
  }
  set color(value) {
    super.color = value;
    this.#onChange(this);
  }
}

class RangeFormat {
  #context;
  #state;
  #borderBlueprint;
  #font;
  #borders;
  constructor(context) {
    this.#context = context;
    const record = (props) => this.#recordFormat(props);
    this.#font = new RangeFont({
      readState: () => this.#resolveState(),
      applyChange: (mutator) => this.#applyFontChange(mutator),
      record
    });
    this.#borders = new RangeBorders(this, record);
  }
  reset() {
    this.#state = undefined;
    this.#borderBlueprint = undefined;
  }
  get font() {
    return this.#font;
  }
  set font(value) {
    if (value instanceof RangeFont) {
      return;
    }
    if (!value || typeof value !== "object") {
      throw new Error("RangeFormat.font setter requires a config object.");
    }
    this.setFont(value);
  }
  setFont(patch) {
    if (!patch || typeof patch !== "object") {
      throw new Error("RangeFormat.setFont(patch) requires a config object.");
    }
    const recordPatch = {};
    const colorPatch = toPatchColorConfig2(patch.color);
    this.#applyFontChange((font) => {
      if (patch.bold !== undefined)
        font.bold = patch.bold;
      if (patch.italic !== undefined)
        font.italic = patch.italic;
      if (patch.size !== undefined)
        font.size = patch.size;
      if (patch.name !== undefined)
        font.name = patch.name;
      if (patch.color !== undefined)
        font.color = toColorInstance(patch.color);
    });
    if (patch.bold !== undefined)
      recordPatch.bold = patch.bold;
    if (patch.italic !== undefined)
      recordPatch.italic = patch.italic;
    if (patch.size !== undefined)
      recordPatch.size = patch.size;
    if (patch.name !== undefined)
      recordPatch.name = patch.name;
    if (colorPatch !== undefined)
      recordPatch.color = colorPatch;
    if (Object.keys(recordPatch).length > 0) {
      this.#recordFormat({ font: recordPatch });
    }
  }
  get borders() {
    return this.#borders;
  }
  set borders(config) {
    if (!config) {
      throw new Error("RangeFormat.borders setter requires a config object.");
    }
    if ("preset" in config) {
      const { preset, style, color: color2 } = config;
      if (style !== undefined || color2 !== undefined) {
        this.#borders.apply({ preset, style, color: color2 });
      } else {
        this.#borders.setPreset(preset);
      }
      return;
    }
    this.#borders.assign(config);
  }
  get fill() {
    const fill2 = this.#resolveState().fill;
    return fill2 ? new LiveFill(fill2, (next) => this.#applyFill(next)) : undefined;
  }
  set fill(value) {
    this.#applyFill(value);
  }
  get numberFormat() {
    return this.#resolveState().numberFormatCode;
  }
  #applyFillToCells(fill2) {
    const registry2 = this.#getStyleRegistry();
    const makeFill = () => fill2 ? cloneFill(fill2) : undefined;
    let firstState;
    this.#runCollaborativeStyleWrite(() => {
      this.#context.editCells(true, (visit) => {
        if (!visit.cell) {
          return;
        }
        const currentStyleIndex = visit.cell.styleIndex ?? this.#context.getLogicalStyleIndex(visit.row, visit.col) ?? 0;
        const description = registry2.describe(currentStyleIndex);
        const cellState = this.#descriptionToState(description);
        cellState.fill = makeFill();
        const { styleId, styleIndex } = this.#registerStyleState(cellState);
        visit.cell.styleIndex = styleIndex;
        this.#context.setLogicalStyleIndex(visit.row, visit.col, styleIndex);
        this.#setCellStyleRef(visit.row, visit.col, styleId);
        if (!firstState) {
          firstState = this.#cloneState(cellState);
          firstState.styleIndex = styleIndex;
        }
      });
    });
    if (firstState) {
      this.#state = firstState;
      return;
    }
    const fallback = this.#cloneState(this.#resolveState());
    fallback.fill = makeFill();
    this.#state = fallback;
  }
  #applyFill(value) {
    const patchFill = toPatchFillConfig(value);
    if (patchFill !== undefined) {
      this.#recordFormat({ fill: patchFill });
    }
    const normalized = toFillInstance(value);
    this.#applyFillToCells(normalized);
  }
  set numberFormat(value) {
    if (value === undefined || typeof value === "string") {
      this.#applyStateChange((state) => {
        state.numberFormatCode = value;
        state.numberFormatId = undefined;
      });
      if (value !== undefined) {
        this.#recordFormat({ numberFormat: value });
      }
      return;
    }
    if (!Array.isArray(value)) {
      throw new Error("RangeFormat.numberFormat expects a format code string or a 2D array of strings.");
    }
    const bounds = this.#context.getBounds();
    if (!bounds) {
      throw new Error("RangeFormat.numberFormat 2D array assignment requires a range with bounds.");
    }
    const shape2 = getStringMatrixShape(value);
    if (shape2.ragged) {
      const address = this.#context.getAddress() || "range";
      throw new Error(`RangeFormat.numberFormat expects a rectangular 2D array for ${address} ` + `(ragged rows: ${shape2.colCounts.join(", ")}).`);
    }
    let matrix = value;
    const exact = shape2.rows === bounds.rows && shape2.cols === bounds.cols && !shape2.ragged;
    const broadcastAcrossColumns = shape2.rows === bounds.rows && shape2.cols === 1 && bounds.cols >= 1;
    const broadcastAcrossRows = shape2.rows === 1 && shape2.cols === bounds.cols && bounds.rows >= 1;
    const scalarMatrix = shape2.rows === 1 && shape2.cols === 1;
    if (!exact) {
      if (scalarMatrix) {
        const scalar = matrix[0]?.[0];
        if (typeof scalar !== "string") {
          throw new Error("RangeFormat.numberFormat 2D array expects string values for every cell.");
        }
        this.numberFormat = scalar;
        return;
      }
      if (broadcastAcrossColumns) {
        matrix = Array.from({ length: bounds.rows }, (_unused, r) => {
          const code = matrix[r]?.[0];
          return Array.from({ length: bounds.cols }, () => code);
        });
      } else if (broadcastAcrossRows) {
        matrix = Array.from({ length: bounds.rows }, () => [
          ...matrix[0] ?? []
        ]);
      } else {
        const canExpand = shape2.rows > 0 && shape2.cols > 0 && shape2.rows <= bounds.rows && shape2.cols <= bounds.cols;
        if (!canExpand) {
          const address2 = this.#context.getAddress() || "range";
          throw new Error(`RangeFormat.numberFormat expects a ${bounds.rows}x${bounds.cols} matrix for ${address2}, ` + `got ${shape2.rows}x${shape2.cols}. ` + "You can also pass a 1xN or Nx1 matrix to broadcast across rows/columns.");
        }
        const address = this.#context.getAddress() || "range";
        const tileRows = bounds.rows % shape2.rows === 0;
        const tileCols = bounds.cols % shape2.cols === 0;
        const strategy = tileRows && tileCols ? "tiled" : "stretched";
        console.warn(`RangeFormat.numberFormat expanded a ${shape2.rows}x${shape2.cols} matrix to ` + `${bounds.rows}x${bounds.cols} for ${address} (${strategy}).`);
        matrix = Array.from({ length: bounds.rows }, (_unused, r) => {
          const srcRow = tileRows ? r % shape2.rows : Math.min(r, shape2.rows - 1);
          return Array.from({ length: bounds.cols }, (_unused2, c) => {
            const srcCol = tileCols ? c % shape2.cols : Math.min(c, shape2.cols - 1);
            return value[srcRow]?.[srcCol] ?? "";
          });
        });
      }
    }
    const uniform = getUniformStringMatrixValue(matrix);
    if (uniform !== null) {
      this.numberFormat = uniform;
      return;
    }
    this.#applyNumberFormatMatrix(matrix);
  }
  #applyNumberFormatMatrix(matrix) {
    const registry2 = this.#getStyleRegistry();
    let firstState;
    this.#runCollaborativeStyleWrite(() => {
      this.#context.editCells(true, (visit) => {
        if (!visit.cell) {
          return;
        }
        const formatCode = matrix[visit.relativeRow]?.[visit.relativeCol];
        if (typeof formatCode !== "string") {
          throw new Error("RangeFormat.numberFormat 2D array expects string values for every cell.");
        }
        const currentStyleIndex = this.#context.getLogicalStyleIndex(visit.row, visit.col) ?? visit.cell.styleIndex ?? 0;
        const description = registry2.describe(currentStyleIndex);
        const cellState = this.#descriptionToState(description);
        cellState.numberFormatCode = formatCode;
        cellState.numberFormatId = undefined;
        const { styleId, styleIndex } = this.#registerStyleState(cellState);
        visit.cell.styleIndex = styleIndex;
        this.#context.setLogicalStyleIndex(visit.row, visit.col, styleIndex);
        this.#setCellStyleRef(visit.row, visit.col, styleId);
        if (!firstState) {
          firstState = this.#cloneState(cellState);
          firstState.styleIndex = styleIndex;
        }
      });
    });
    if (firstState) {
      this.#state = firstState;
      return;
    }
    const fallback = this.#cloneState(this.#resolveState());
    fallback.numberFormatCode = matrix[0]?.[0];
    fallback.numberFormatId = undefined;
    this.#state = fallback;
  }
  get wrapText() {
    return this.#resolveState().wrapText ?? false;
  }
  set wrapText(value) {
    this.#applyStateChange((state) => {
      state.wrapText = value;
    });
    this.#recordFormat({ wrapText: value });
  }
  get horizontalAlignment() {
    const value = this.#resolveState().horizontalAlignment ?? HorizontalAlignment.general;
    return alignmentToProto(value);
  }
  set horizontalAlignment(value) {
    const normalized = normalizeHorizontalAlignment(value);
    this.#applyStateChange((state) => {
      state.horizontalAlignment = normalized;
    });
    this.#recordFormat({
      horizontalAlignment: alignmentToProto(normalized)
    });
  }
  get verticalAlignment() {
    return this.#resolveState().verticalAlignment ?? "bottom";
  }
  set verticalAlignment(value) {
    const normalized = normalizeVerticalAlignment(value);
    this.#applyStateChange((state) => {
      state.verticalAlignment = normalized;
    });
    this.#recordFormat({ verticalAlignment: normalized });
  }
  get rowHeight() {
    return this.#resolveRowHeight();
  }
  set rowHeight(value) {
    this.#applyRowHeight(value);
    if (Number.isFinite(value)) {
      this.#recordFormat({ rowHeight: value });
    }
  }
  get rowHeightPx() {
    const height = this.rowHeight;
    return height === undefined ? undefined : pointsToPx(height);
  }
  set rowHeightPx(value) {
    if (!Number.isFinite(value) || value < 0) {
      throw new Error("RangeFormat.rowHeightPx must be a non-negative number.");
    }
    this.rowHeight = pxToPoints(value);
  }
  get columnWidth() {
    return this.#resolveColumnWidth();
  }
  set columnWidth(value) {
    this.#applyColumnWidth(value);
    if (Number.isFinite(value)) {
      this.#recordFormat({ columnWidth: value });
    }
  }
  get columnWidthPx() {
    const width = this.columnWidth;
    return width === undefined ? undefined : colWidthToPx(width);
  }
  set columnWidthPx(value) {
    if (!Number.isFinite(value) || value < 0) {
      throw new Error("RangeFormat.columnWidthPx must be a non-negative number.");
    }
    this.columnWidth = pxToColWidth(value);
  }
  get styleId() {
    const first = this.#context.getFirstCell(false);
    if (first) {
      const logical = this.#context.getLogicalStyleIndex(first.row, first.col);
      if (logical != null) {
        return logical;
      }
    }
    return this.#resolveState().styleIndex;
  }
  autofitColumns() {
    const bounds = this.#context.getBounds();
    const autofitBounds = bounds ? {
      startRow: bounds.startRow,
      startCol: bounds.startCol,
      endRow: bounds.startRow + bounds.rows - 1,
      endCol: bounds.startCol + bounds.cols - 1
    } : null;
    const workbook = this.#context.getWorkbook();
    const worksheet = this.#context.getWorksheet();
    if (!workbook || !worksheet) {
      return;
    }
    workbook.recalculate();
    autofitColumns({
      address: this.#context.getAddress(),
      bounds: autofitBounds,
      workbook,
      worksheet
    });
    if (bounds) {
      for (let c = 0;c < bounds.cols; c += 1) {
        worksheet.__syncColumnSizeRef(bounds.startCol + c);
      }
    }
    worksheet.__invalidateViewportLayout();
  }
  autofitRows() {
    const bounds = this.#context.getBounds();
    const autofitBounds = bounds ? {
      startRow: bounds.startRow,
      startCol: bounds.startCol,
      endRow: bounds.startRow + bounds.rows - 1,
      endCol: bounds.startCol + bounds.cols - 1
    } : null;
    const workbook = this.#context.getWorkbook();
    const worksheet = this.#context.getWorksheet();
    if (!workbook || !worksheet) {
      return;
    }
    workbook.recalculate();
    autofitRows({
      address: this.#context.getAddress(),
      bounds: autofitBounds,
      workbook,
      worksheet
    });
    if (bounds) {
      for (let r = 0;r < bounds.rows; r += 1) {
        worksheet.__syncRowSizeRef(bounds.startRow + r);
      }
    }
    worksheet.__invalidateViewportLayout();
  }
  #resolveRowHeight() {
    const bounds = this.#context.getBounds();
    const worksheet = this.#context.getWorksheet();
    if (!bounds || !worksheet) {
      return;
    }
    let resolved;
    let hasValue = false;
    for (let r = 0;r < bounds.rows; r += 1) {
      const row2 = worksheet.__getRow(bounds.startRow + r);
      const rowHeight = row2 && (row2.customHeight || row2.height !== 0) ? row2.height : undefined;
      if (rowHeight === undefined) {
        if (hasValue) {
          return;
        }
        continue;
      }
      if (!hasValue) {
        resolved = rowHeight;
        hasValue = true;
        continue;
      }
      if (resolved !== rowHeight) {
        return;
      }
    }
    return hasValue ? resolved : undefined;
  }
  #applyRowHeight(value) {
    if (!Number.isFinite(value) || value < 0) {
      throw new Error("RangeFormat.rowHeight must be a non-negative number.");
    }
    const bounds = this.#context.getBounds();
    const worksheet = this.#context.getWorksheet();
    if (!bounds || !worksheet) {
      return;
    }
    for (let r = 0;r < bounds.rows; r += 1) {
      const row2 = worksheet.__getOrCreateRow(bounds.startRow + r);
      row2.height = value;
      row2.customHeight = true;
      worksheet.__syncRowSizeRef(bounds.startRow + r);
    }
    worksheet.__invalidateViewportLayout();
  }
  #resolveColumnWidth() {
    const bounds = this.#context.getBounds();
    const worksheet = this.#context.getWorksheet();
    if (!bounds || !worksheet) {
      return;
    }
    const columns = worksheet.__getColumns();
    let resolved;
    let hasValue = false;
    for (let c = 0;c < bounds.cols; c += 1) {
      const colIdx = bounds.startCol + c;
      let colWidth;
      for (const col of columns) {
        const min3 = Math.max(0, (col.min ?? 1) - 1);
        const max4 = Math.max(min3, (col.max ?? col.min ?? 1) - 1);
        if (colIdx >= min3 && colIdx <= max4) {
          colWidth = col.hidden ? 0 : col.width;
        }
      }
      if (colWidth === undefined) {
        if (hasValue) {
          return;
        }
        continue;
      }
      if (!hasValue) {
        resolved = colWidth;
        hasValue = true;
        continue;
      }
      if (resolved !== colWidth) {
        return;
      }
    }
    return hasValue ? resolved : undefined;
  }
  #applyColumnWidth(value) {
    if (!Number.isFinite(value) || value < 0) {
      throw new Error("RangeFormat.columnWidth must be a non-negative number.");
    }
    const bounds = this.#context.getBounds();
    const worksheet = this.#context.getWorksheet();
    if (!bounds || !worksheet) {
      return;
    }
    const columns = worksheet.__getColumns();
    for (let c = 0;c < bounds.cols; c += 1) {
      const colIndex = bounds.startCol + c + 1;
      const existing = columns.find((col) => col.min === colIndex && (col.max ?? col.min) === colIndex);
      if (existing) {
        existing.width = value;
        existing.customWidth = true;
        existing.hidden = false;
        continue;
      }
      columns.push({
        min: colIndex,
        max: colIndex,
        width: value,
        customWidth: true,
        hidden: false
      });
      worksheet.__syncColumnSizeRef(bounds.startCol + c);
      continue;
    }
    for (let c = 0;c < bounds.cols; c += 1) {
      worksheet.__syncColumnSizeRef(bounds.startCol + c);
    }
    worksheet.__invalidateViewportLayout();
  }
  applyBorderBlueprint(blueprint) {
    const bounds = this.#context.getBounds();
    if (!bounds) {
      return;
    }
    const registry2 = this.#getStyleRegistry();
    this.#runCollaborativeStyleWrite(() => {
      this.#context.editCells(true, (visit) => {
        if (!visit.cell) {
          return;
        }
        const currentStyleIndex = this.#context.getLogicalStyleIndex(visit.row, visit.col) ?? visit.cell.styleIndex ?? 0;
        const description = registry2.describe(currentStyleIndex);
        const cellState = this.#descriptionToState(description);
        cellState.border = this.#deriveBorderForCell(blueprint, cellState.border, visit.relativeRow, visit.relativeCol, bounds.rows, bounds.cols);
        const { styleId, styleIndex } = this.#registerStyleState(cellState);
        visit.cell.styleIndex = styleIndex;
        this.#context.setLogicalStyleIndex(visit.row, visit.col, styleIndex);
        this.#setCellStyleRef(visit.row, visit.col, styleId);
        if (visit.relativeRow === 0 && visit.relativeCol === 0) {
          this.#state = cellState;
          this.#state.styleIndex = styleIndex;
        }
      });
    });
    this.#borderBlueprint = this.#cloneBorderBlueprint(blueprint);
  }
  updateBorders(mutate) {
    const blueprint = this.#cloneBorderBlueprint(this.#borderBlueprint) ?? this.#currentBorderBlueprint();
    mutate(blueprint);
    this.applyBorderBlueprint(blueprint);
    this.#borderBlueprint = this.#cloneBorderBlueprint(blueprint);
  }
  getBorderBlueprintSnapshot() {
    return this.#cloneBorderBlueprint(this.#borderBlueprint) ?? this.#currentBorderBlueprint();
  }
  #resolveState() {
    if (this.#state) {
      return this.#state;
    }
    const first = this.#context.getFirstCell(true);
    const registry2 = this.#getStyleRegistry();
    if (!first || !first.cell) {
      const description2 = registry2.describe(0);
      this.#state = this.#descriptionToState(description2);
      return this.#state;
    }
    const styleIndex = first.cell.styleIndex ?? 0;
    const description = registry2.describe(styleIndex);
    this.#state = this.#descriptionToState(description);
    return this.#state;
  }
  #descriptionToState(description) {
    return {
      styleIndex: description.styleIndex,
      fill: description.fill ? cloneFill(description.fill) : undefined,
      font: cloneFontState(description.font),
      border: cloneBorderState(description.border),
      numberFormatCode: description.numberFormatCode,
      numberFormatId: description.numberFormatId,
      wrapText: description.wrapText,
      horizontalAlignment: description.horizontalAlignment ? protoToAlignment(description.horizontalAlignment) : undefined,
      verticalAlignment: description.verticalAlignment ? protoToVerticalAlignment(description.verticalAlignment) : undefined,
      featurePropertyBagIndex: description.featurePropertyBagIndex
    };
  }
  #applyFontChange(mutator) {
    this.#applyStateChange((state) => {
      state.font ??= new TextStyleModel;
      mutator(state.font);
    });
  }
  #applyStateChange(mutator) {
    const registry2 = this.#getStyleRegistry();
    let firstState;
    this.#runCollaborativeStyleWrite(() => {
      this.#context.editCells(true, (visit) => {
        if (!visit.cell) {
          return;
        }
        const currentStyleIndex = this.#context.getLogicalStyleIndex(visit.row, visit.col) ?? visit.cell.styleIndex ?? 0;
        const description = registry2.describe(currentStyleIndex);
        const cellState = this.#descriptionToState(description);
        mutator(cellState);
        const { styleId, styleIndex } = this.#registerStyleState(cellState);
        visit.cell.styleIndex = styleIndex;
        this.#context.setLogicalStyleIndex(visit.row, visit.col, styleIndex);
        this.#setCellStyleRef(visit.row, visit.col, styleId);
        if (!firstState) {
          firstState = this.#cloneState(cellState);
          firstState.styleIndex = styleIndex;
        }
      });
    });
    if (firstState) {
      this.#state = firstState;
      return;
    }
    const fallback = this.#cloneState(this.#resolveState());
    mutator(fallback);
    this.#state = fallback;
  }
  #cloneState(state) {
    return {
      styleIndex: state.styleIndex,
      fill: state.fill ? cloneFill(state.fill) : undefined,
      font: cloneFontState(state.font),
      border: cloneBorderState(state.border),
      numberFormatCode: state.numberFormatCode,
      numberFormatId: state.numberFormatId,
      wrapText: state.wrapText,
      horizontalAlignment: state.horizontalAlignment,
      verticalAlignment: state.verticalAlignment,
      featurePropertyBagIndex: state.featurePropertyBagIndex
    };
  }
  #currentBorderBlueprint() {
    const state = this.#resolveState();
    const blueprint = {};
    const border = state.border;
    if (border) {
      blueprint.top = borderLineToBlueprint(border.top);
      blueprint.bottom = borderLineToBlueprint(border.bottom);
      blueprint.left = borderLineToBlueprint(border.left);
      blueprint.right = borderLineToBlueprint(border.right);
      blueprint.diagonal = borderLineToBlueprint(border.diagonal);
      blueprint.diagonalUp = border.diagonalUp;
      blueprint.diagonalDown = border.diagonalDown;
    }
    return blueprint;
  }
  #cloneBorderBlueprint(source) {
    if (!source)
      return;
    const clone = {};
    clone.top = cloneBorderLine(source.top);
    clone.bottom = cloneBorderLine(source.bottom);
    clone.left = cloneBorderLine(source.left);
    clone.right = cloneBorderLine(source.right);
    clone.insideHorizontal = cloneBorderLine(source.insideHorizontal);
    clone.insideVertical = cloneBorderLine(source.insideVertical);
    clone.diagonal = cloneBorderLine(source.diagonal);
    if (source.diagonalUp !== undefined)
      clone.diagonalUp = source.diagonalUp;
    if (source.diagonalDown !== undefined)
      clone.diagonalDown = source.diagonalDown;
    return clone;
  }
  #deriveBorderForCell(blueprint, existing, relativeRow, relativeCol, rows, cols) {
    const next = cloneBorderState(existing) ?? new BorderModel;
    const isTopRow = relativeRow === 0;
    const isBottomRow = relativeRow === rows - 1;
    const isLeftCol = relativeCol === 0;
    const isRightCol = relativeCol === cols - 1;
    if (blueprint.top && isTopRow) {
      next.top = blueprintToBorderLine(blueprint.top);
    }
    if (blueprint.bottom && isBottomRow) {
      next.bottom = blueprintToBorderLine(blueprint.bottom);
    }
    if (blueprint.left && isLeftCol) {
      next.left = blueprintToBorderLine(blueprint.left);
    }
    if (blueprint.right && isRightCol) {
      next.right = blueprintToBorderLine(blueprint.right);
    }
    if (blueprint.insideHorizontal) {
      if (relativeRow > 0) {
        next.top = blueprintToBorderLine(blueprint.insideHorizontal);
      }
      if (relativeRow < rows - 1) {
        next.bottom = blueprintToBorderLine(blueprint.insideHorizontal);
      }
    }
    if (blueprint.insideVertical) {
      if (relativeCol > 0) {
        next.left = blueprintToBorderLine(blueprint.insideVertical);
      }
      if (relativeCol < cols - 1) {
        next.right = blueprintToBorderLine(blueprint.insideVertical);
      }
    }
    if (blueprint.diagonal) {
      next.diagonal = blueprintToBorderLine(blueprint.diagonal);
      next.diagonalUp = blueprint.diagonalUp;
      next.diagonalDown = blueprint.diagonalDown;
    } else {
      next.diagonalUp = blueprint.diagonalUp ?? next.diagonalUp;
      next.diagonalDown = blueprint.diagonalDown ?? next.diagonalDown;
    }
    return next.hasValues() ? next : undefined;
  }
  #toStyleDescription(state) {
    return {
      styleIndex: state.styleIndex,
      fill: state.fill ? cloneFill(state.fill) : undefined,
      font: cloneFontState(state.font),
      border: cloneBorderState(state.border),
      numberFormatCode: state.numberFormatCode,
      numberFormatId: state.numberFormatId,
      wrapText: state.wrapText,
      horizontalAlignment: state.horizontalAlignment ? alignmentToProto(state.horizontalAlignment) : undefined,
      verticalAlignment: state.verticalAlignment ? verticalAlignmentToProto(state.verticalAlignment) : undefined,
      featurePropertyBagIndex: state.featurePropertyBagIndex
    };
  }
  #registerStyleState(state) {
    const style = this.#toStyleDescription(state);
    const workbook = this.#context.getWorkbook();
    if (!workbook) {
      const styleIndex = this.#getStyleRegistry().register(style);
      return { styleIndex };
    }
    return workbook.__registerCollaborativeStyle(style);
  }
  #runCollaborativeStyleWrite(fn) {
    const workbook = this.#context.getWorkbook();
    if (!workbook) {
      return fn();
    }
    return workbook.runLocalCollabTransaction(fn);
  }
  #setCellStyleRef(row2, col, styleId) {
    if (!styleId) {
      return;
    }
    if (this.#context.setCellStyleRef) {
      this.#context.setCellStyleRef(row2, col, styleId);
      return;
    }
    this.#context.getWorksheet()?.__setCellStyleRef(row2, col, styleId);
  }
  #recordFormat(props) {
    const workbook = this.#context.getWorkbook();
    const worksheet = this.#context.getWorksheet();
    const address = this.#context.getAddress();
    if (!workbook || !worksheet || !worksheet.name || !address) {
      return;
    }
    const recorder = workbook.getRecorder();
    if (!recorder) {
      return;
    }
    if (Object.keys(props).length === 0) {
      return;
    }
    const op = {
      op: "range.format.set",
      target: { sheet: worksheet.name, range: address },
      props
    };
    recorder.record(op);
  }
  #getStyleRegistry() {
    const workbook = this.#context.getWorkbook();
    if (!workbook) {
      throw new Error("Range is not attached to a workbook.");
    }
    return workbook.getStyleRegistry();
  }
}

class RangeFont {
  #readState;
  #applyChange;
  #record;
  constructor(config) {
    this.#readState = config.readState;
    this.#applyChange = config.applyChange;
    this.#record = config.record;
  }
  get bold() {
    return this.#readState().font?.bold;
  }
  set bold(value) {
    this.#applyChange((font) => {
      font.bold = value;
    });
    if (value !== undefined) {
      this.#recordFont({ bold: value });
    }
  }
  get italic() {
    return this.#readState().font?.italic;
  }
  set italic(value) {
    this.#applyChange((font) => {
      font.italic = value;
    });
    if (value !== undefined) {
      this.#recordFont({ italic: value });
    }
  }
  get size() {
    return this.#readState().font?.size;
  }
  set size(value) {
    this.#applyChange((font) => {
      font.size = value;
    });
    if (value !== undefined) {
      this.#recordFont({ size: value });
    }
  }
  get name() {
    return this.#readState().font?.name;
  }
  set name(value) {
    this.#applyChange((font) => {
      font.name = value;
    });
    if (value !== undefined) {
      this.#recordFont({ name: value });
    }
  }
  get color() {
    const color2 = this.#readState().font?.color;
    return color2 ? color2.clone() : undefined;
  }
  set color(value) {
    this.#applyChange((font) => {
      font.color = toColorInstance(value);
    });
    const color2 = toPatchColorConfig2(value);
    if (color2 !== undefined) {
      this.#recordFont({ color: color2 });
    }
  }
  #recordFont(patch) {
    if (Object.keys(patch).length === 0) {
      return;
    }
    this.#record({ font: patch });
  }
}

class RangeBorders {
  #format;
  #record;
  constructor(format2, record) {
    this.#format = format2;
    this.#record = record;
  }
  get top() {
    return new RangeBorderLine(this, "top");
  }
  set top(value) {
    this.setEdgeState("top", normalizeBorderLineInput(value));
  }
  get bottom() {
    return new RangeBorderLine(this, "bottom");
  }
  set bottom(value) {
    this.setEdgeState("bottom", normalizeBorderLineInput(value));
  }
  get left() {
    return new RangeBorderLine(this, "left");
  }
  set left(value) {
    this.setEdgeState("left", normalizeBorderLineInput(value));
  }
  get right() {
    return new RangeBorderLine(this, "right");
  }
  set right(value) {
    this.setEdgeState("right", normalizeBorderLineInput(value));
  }
  get insideHorizontal() {
    return new RangeBorderLine(this, "insideHorizontal");
  }
  set insideHorizontal(value) {
    this.setEdgeState("insideHorizontal", normalizeBorderLineInput(value));
  }
  get insideVertical() {
    return new RangeBorderLine(this, "insideVertical");
  }
  set insideVertical(value) {
    this.setEdgeState("insideVertical", normalizeBorderLineInput(value));
  }
  get diagonalUp() {
    return new RangeBorderLine(this, "diagonalUp");
  }
  set diagonalUp(value) {
    this.setEdgeState("diagonalUp", normalizeBorderLineInput(value));
  }
  get diagonalDown() {
    return new RangeBorderLine(this, "diagonalDown");
  }
  set diagonalDown(value) {
    this.setEdgeState("diagonalDown", normalizeBorderLineInput(value));
  }
  assign(definition) {
    this.#format.updateBorders((blueprint) => {
      for (const [key, value] of Object.entries(definition)) {
        if (key === "inside") {
          const normalized2 = normalizeBorderLineInput(value);
          blueprint.insideHorizontal = cloneBorderLine(normalized2);
          blueprint.insideVertical = cloneBorderLine(normalized2);
          continue;
        }
        const edge = normalizeEdgeName(key);
        if (!edge) {
          continue;
        }
        if (edge === "diagonalUp" || edge === "diagonalDown") {
          const normalized2 = normalizeBorderLineInput(value);
          if (!normalized2) {
            if (edge === "diagonalUp") {
              blueprint.diagonalUp = false;
            } else {
              blueprint.diagonalDown = false;
            }
            if (!blueprint.diagonalUp && !blueprint.diagonalDown) {
              blueprint.diagonal = undefined;
            }
            continue;
          }
          blueprint.diagonal = cloneBorderLine(normalized2);
          if (edge === "diagonalUp") {
            blueprint.diagonalUp = true;
          } else {
            blueprint.diagonalDown = true;
          }
          continue;
        }
        const normalized = normalizeBorderLineInput(value);
        if (normalized) {
          blueprint[edge] = cloneBorderLine(normalized);
        } else {
          delete blueprint[edge];
        }
      }
    });
    const patch = toPatchBordersAssignment(definition);
    this.#recordBorders(patch);
  }
  getItem(name) {
    const edge = normalizeEdgeName(name);
    if (!edge) {
      throw new Error(`Unsupported border edge "${name}"`);
    }
    return new RangeBorderLine(this, edge);
  }
  setPreset(preset) {
    this.#format.updateBorders((blueprint) => {
      if (preset === "none") {
        const noneLine = normalizeBorderLineInput({ style: "none" });
        blueprint.top = cloneBorderLine(noneLine);
        blueprint.bottom = cloneBorderLine(noneLine);
        blueprint.left = cloneBorderLine(noneLine);
        blueprint.right = cloneBorderLine(noneLine);
        blueprint.insideHorizontal = undefined;
        blueprint.insideVertical = undefined;
        blueprint.diagonal = undefined;
        blueprint.diagonalUp = false;
        blueprint.diagonalDown = false;
        return;
      }
      const edges = edgesForPreset(preset);
      const defaultLine = normalizeBorderLineInput({ style: "thin" });
      for (const edge of edges) {
        if (edge === "diagonalUp" || edge === "diagonalDown") {
          continue;
        }
        blueprint[edge] = cloneBorderLine(defaultLine);
      }
      if (preset === "doubleBottom") {
        const doubleLine = normalizeBorderLineInput({ style: "double" });
        blueprint.bottom = cloneBorderLine(doubleLine);
      }
    });
    this.#recordBorders({ preset });
  }
  apply(options) {
    this.#format.updateBorders((blueprint) => {
      if (options.preset === "none") {
        Object.keys(blueprint).forEach((key) => {
          delete blueprint[key];
        });
        blueprint.diagonalUp = false;
        blueprint.diagonalDown = false;
        return;
      }
      const edges = edgesForPreset(options.preset);
      for (const edge of edges) {
        if (edge === "diagonalUp" || edge === "diagonalDown") {
          continue;
        }
        blueprint[edge] = cloneBorderLine(normalizeBorderLineInput({
          style: options.style,
          color: options.color
        }));
      }
      if (options.preset === "doubleBottom") {
        blueprint.bottom = cloneBorderLine(normalizeBorderLineInput({
          style: "double",
          color: options.color
        }));
      }
    });
    const patch = toPatchBordersPreset(options);
    this.#recordBorders(patch);
  }
  setEdgeState(edge, value) {
    this.#format.updateBorders((blueprint) => {
      if (value === undefined) {
        if (edge === "diagonalUp") {
          blueprint.diagonalUp = false;
          if (!blueprint.diagonalDown) {
            blueprint.diagonal = undefined;
          }
        } else if (edge === "diagonalDown") {
          blueprint.diagonalDown = false;
          if (!blueprint.diagonalUp) {
            blueprint.diagonal = undefined;
          }
        } else {
          delete blueprint[edge];
        }
        return;
      }
      if (edge === "diagonalUp" || edge === "diagonalDown") {
        blueprint.diagonal = cloneBorderLine(value);
        if (edge === "diagonalUp") {
          blueprint.diagonalUp = true;
        } else {
          blueprint.diagonalDown = true;
        }
        return;
      }
      blueprint[edge] = cloneBorderLine(value);
    });
    const patchLine = value === undefined ? { style: "none" } : toPatchBorderLine(value);
    if (patchLine) {
      this.#recordBorders({ [edge]: patchLine });
    }
  }
  getEdgeState(edge) {
    const blueprint = this.#format.getBorderBlueprintSnapshot();
    if (edge === "diagonalUp" || edge === "diagonalDown") {
      const isActive = edge === "diagonalUp" ? blueprint.diagonalUp : blueprint.diagonalDown;
      if (!isActive) {
        return;
      }
      return cloneBorderLine(blueprint.diagonal);
    }
    return cloneBorderLine(blueprint[edge]);
  }
  #recordBorders(patch) {
    if (!patch || Object.keys(patch).length === 0) {
      return;
    }
    this.#record({ borders: patch });
  }
  toProto() {
    const blueprint = this.#format.getBorderBlueprintSnapshot();
    const proto = {};
    const toLine = (line) => {
      const model = blueprintToBorderLine(line);
      return model ? model.toProto() : undefined;
    };
    proto.top = toLine(blueprint.top);
    proto.bottom = toLine(blueprint.bottom);
    proto.left = toLine(blueprint.left);
    proto.right = toLine(blueprint.right);
    proto.diagonal = toLine(blueprint.diagonal);
    proto.diagonalUp = blueprint.diagonalUp;
    proto.diagonalDown = blueprint.diagonalDown;
    return proto;
  }
}

class RangeBorderLine {
  #owner;
  #edge;
  constructor(owner, edge) {
    this.#owner = owner;
    this.#edge = edge;
  }
  get style() {
    return this.#currentState()?.style;
  }
  set style(value) {
    const next = { ...this.#currentState() ?? {}, style: value };
    this.#owner.setEdgeState(this.#edge, next);
  }
  get color() {
    const color2 = this.#currentState()?.color;
    return color2 ? color2.clone() : undefined;
  }
  set color(value) {
    const next = {
      ...this.#currentState() ?? {},
      color: value
    };
    this.#owner.setEdgeState(this.#edge, normalizeBorderLineInput(next));
  }
  get fill() {
    const color2 = this.#currentState()?.color;
    if (!color2)
      return;
    const colorProto = color2.toProto();
    if (!colorProto)
      return;
    return new Fill2({
      type: "solid",
      color: { type: "proto", proto: colorProto }
    });
  }
  set fill(value) {
    const normalized = toFillInstance(value);
    const color2 = normalized ? extractColorFromFill(normalized) : undefined;
    this.color = color2;
  }
  get weight() {
    return this.#currentState()?.weight;
  }
  set weight(value) {
    const next = {
      ...this.#currentState() ?? {},
      weight: value
    };
    this.#owner.setEdgeState(this.#edge, next);
  }
  #currentState() {
    return this.#owner.getEdgeState(this.#edge);
  }
}
function cloneFill(fill2) {
  const proto = fill2.toProto();
  if (!proto) {
    return new Fill2;
  }
  return new Fill2({ type: "proto", proto });
}
function cloneFontState(font) {
  return font ? font.clone() : undefined;
}
function cloneBorderState(border) {
  return border ? border.clone() : undefined;
}
function cloneBorderLine(line) {
  if (!line)
    return;
  const clone = {};
  if (line.style !== undefined)
    clone.style = line.style;
  if (line.color)
    clone.color = line.color.clone();
  if (line.weight !== undefined)
    clone.weight = line.weight;
  return Object.keys(clone).length > 0 ? clone : undefined;
}
function toFillInstance(input) {
  if (input === undefined || input === null) {
    return;
  }
  const fill2 = input instanceof Fill2 ? input : new Fill2(input);
  return fill2.toProto() ? fill2 : undefined;
}
function getStringMatrixShape(matrix) {
  if (!Array.isArray(matrix)) {
    throw new Error("Expected a 2D array.");
  }
  const colCounts = [];
  for (let r = 0;r < matrix.length; r += 1) {
    const row2 = matrix[r];
    if (!Array.isArray(row2)) {
      throw new Error(`Expected a 2D array; row ${r + 1} is not an array.`);
    }
    colCounts.push(row2.length);
  }
  const rows = matrix.length;
  const cols = colCounts[0] ?? 0;
  const ragged = colCounts.some((count3) => count3 !== cols);
  return { rows, cols, ragged, colCounts };
}
function getUniformStringMatrixValue(matrix) {
  const first = matrix[0]?.[0];
  if (typeof first !== "string") {
    return null;
  }
  for (let r = 0;r < matrix.length; r += 1) {
    const row2 = matrix[r];
    if (!row2)
      continue;
    for (let c = 0;c < row2.length; c += 1) {
      if (row2[c] !== first) {
        return null;
      }
    }
  }
  return first;
}
function toColorInstance(input) {
  if (input === undefined) {
    return;
  }
  if (input instanceof Color4) {
    return input.clone();
  }
  return new Color4(input);
}
function isPatchFillConfig3(value) {
  return !(typeof value === "object" && value !== null && ("type" in value) && value.type === "proto");
}
function isPatchColorConfig(value) {
  return !(typeof value === "object" && value !== null && ("type" in value) && value.type === "proto");
}
function toPatchFillConfig(value) {
  if (value === undefined) {
    return;
  }
  if (value === null) {
    return null;
  }
  if (value instanceof Fill2) {
    const config = value.toConfig();
    if (!config) {
      return value.isSet ? undefined : null;
    }
    return isPatchFillConfig3(config) ? config : undefined;
  }
  if (typeof value === "object" && value && "type" in value) {
    return isPatchFillConfig3(value) ? value : undefined;
  }
  return value;
}
function toPatchColorConfig2(value) {
  if (!value) {
    return;
  }
  if (value instanceof Color4) {
    return value.toConfig();
  }
  return isPatchColorConfig(value) ? value : undefined;
}
function toPatchBorderLine(input) {
  if (!input) {
    return;
  }
  const patch = {};
  if ("style" in input && input.style !== undefined) {
    patch.style = input.style;
  }
  if ("weight" in input && input.weight !== undefined) {
    patch.weight = input.weight;
  }
  if ("color" in input && input.color !== undefined) {
    const color2 = toPatchColorConfig2(input.color);
    if (color2 !== undefined) {
      patch.color = color2;
    }
  }
  return Object.keys(patch).length > 0 ? patch : undefined;
}
function toPatchBordersPreset(options) {
  const patch = { preset: options.preset };
  if (options.style !== undefined) {
    patch.style = options.style;
  }
  const color2 = toPatchColorConfig2(options.color);
  if (color2 !== undefined) {
    patch.color = color2;
  }
  return patch;
}
function toPatchBordersAssignment(definition) {
  const patch = {};
  for (const [key, value] of Object.entries(definition)) {
    if (key === "inside") {
      const inside = toPatchBorderLine(value);
      if (inside) {
        patch["inside"] = inside;
      }
      continue;
    }
    const edge = normalizeEdgeName(key);
    if (!edge) {
      continue;
    }
    const line = toPatchBorderLine(value);
    if (line) {
      patch[edge] = line;
    }
  }
  return Object.keys(patch).length > 0 ? patch : undefined;
}
function normalizeBorderLineInput(input) {
  if (!input) {
    return;
  }
  const blueprint = {};
  if (input.style !== undefined) {
    blueprint.style = input.style;
  }
  if (input.weight !== undefined) {
    blueprint.weight = input.weight;
  }
  if (input.color !== undefined) {
    const color2 = toColorInstance(input.color);
    if (color2) {
      blueprint.color = color2;
    }
  }
  return Object.keys(blueprint).length > 0 ? blueprint : undefined;
}
function blueprintToBorderLine(line) {
  if (!line) {
    return;
  }
  const model = new BorderLineModel;
  model.style = line.style;
  model.weight = line.weight;
  model.color = line.color ? line.color.clone() : undefined;
  return model;
}
function borderLineToBlueprint(line) {
  if (!line) {
    return;
  }
  return {
    style: line.style,
    color: line.color ? line.color.clone() : undefined,
    weight: line.weight
  };
}
function protoToAlignment(value) {
  const normalized = value.toLowerCase();
  switch (normalized) {
    case "left":
      return HorizontalAlignment.left;
    case "center":
      return HorizontalAlignment.center;
    case "right":
      return HorizontalAlignment.right;
    case "fill":
      return HorizontalAlignment.fill;
    case "justify":
      return HorizontalAlignment.justify;
    case "centeracrossselection":
      return HorizontalAlignment.centerAcrossSelection;
    case "distributed":
      return HorizontalAlignment.distributed;
    case "general":
      return HorizontalAlignment.general;
    default:
      return;
  }
}
function normalizeHorizontalAlignment(value) {
  const normalized = protoToAlignment(String(value));
  if (!normalized) {
    throw new Error(`Unsupported horizontal alignment "${value}".`);
  }
  return normalized;
}
function alignmentToProto(value) {
  switch (value) {
    case HorizontalAlignment.left:
      return "left";
    case HorizontalAlignment.center:
      return "center";
    case HorizontalAlignment.right:
      return "right";
    case HorizontalAlignment.fill:
      return "fill";
    case HorizontalAlignment.justify:
      return "justify";
    case HorizontalAlignment.centerAcrossSelection:
      return "centerAcrossSelection";
    case HorizontalAlignment.distributed:
      return "distributed";
    case HorizontalAlignment.general:
    default:
      return "general";
  }
}
function protoToVerticalAlignment(value) {
  switch (value.toLowerCase()) {
    case "top":
      return "top";
    case "center":
    case "middle":
      return "middle";
    case "bottom":
      return "bottom";
    default:
      return;
  }
}
function normalizeVerticalAlignment(value) {
  const normalized = protoToVerticalAlignment(String(value));
  if (!normalized) {
    throw new Error(`Unsupported vertical alignment "${value}".`);
  }
  return normalized;
}
function verticalAlignmentToProto(value) {
  switch (value) {
    case "top":
      return "top";
    case "middle":
      return "center";
    case "bottom":
      return "bottom";
  }
}
function edgesForPreset(preset) {
  switch (preset) {
    case "outside":
      return ["top", "bottom", "left", "right"];
    case "inside":
      return ["insideHorizontal", "insideVertical"];
    case "all":
      return [
        "top",
        "bottom",
        "left",
        "right",
        "insideHorizontal",
        "insideVertical"
      ];
    case "doubleBottom":
      return ["bottom"];
    case "none":
    default:
      return [];
  }
}
function normalizeEdgeName(name) {
  const normalized = name.trim().toLowerCase();
  switch (normalized) {
    case "top":
    case "edgetop":
      return "top";
    case "bottom":
    case "edgebottom":
      return "bottom";
    case "left":
    case "edgeleft":
      return "left";
    case "right":
    case "edgeright":
      return "right";
    case "insidehorizontal":
      return "insideHorizontal";
    case "insidevertical":
      return "insideVertical";
    case "diagonalup":
      return "diagonalUp";
    case "diagonaldown":
      return "diagonalDown";
    default:
      return;
  }
}
function extractColorFromFill(fill2) {
  const proto = fill2.toProto();
  if (!proto) {
    return;
  }
  if (proto.color) {
    return new Color4({ type: "proto", proto: proto.color });
  }
  if (proto.pattern?.color) {
    return new Color4({ type: "proto", proto: proto.pattern.color });
  }
  const lastStop = proto.gradientStops?.[proto.gradientStops.length - 1];
  if (lastStop?.color) {
    return new Color4({ type: "proto", proto: lastStop.color });
  }
  return;
}

// node_modules/@oai/granola/dist/models/spreadsheet/conditional-formatting.js
init_address_utils();
var SPREADSHEET_COLOR_OPTIONS3 = { colorSpace: "spreadsheetml" };

class ConditionalFormat {
  #rule;
  constructor(rule2) {
    this.#rule = rule2;
  }
  get type() {
    return this.#rule.type;
  }
  get rule() {
    return this.#rule;
  }
}

class WorksheetConditionalFormattingCollection {
  #worksheet;
  constructor(worksheet) {
    this.#worksheet = worksheet;
  }
  get items() {
    return this.#worksheet.__getConditionalFormattings();
  }
  add(options) {
    const { range: range2, rule: rule2 } = options;
    const { target } = normalizeRangeForWorksheet(this.#worksheet, range2);
    const group = findGroupForRange(this.#worksheet.__getConditionalFormattings(), target) ?? createGroup(this.#worksheet.__getConditionalFormattings(), target);
    const cfRule = buildRule(this.#worksheet, rule2, this.#nextPriority());
    group.rules = group.rules ?? [];
    group.rules.push(cfRule);
    this.#worksheet.workbook.invalidateConditionalFormattingCache(this.#worksheet.name);
    recordConditionalFormat(this.#worksheet, target, rule2);
    return new ConditionalFormat(cfRule);
  }
  clear(range2) {
    const { target } = normalizeRangeForWorksheet(this.#worksheet, range2);
    const rangeRef = targetToRangeRef(target);
    const groups = this.#worksheet.__getConditionalFormattings();
    let removed = false;
    for (let index = groups.length - 1;index >= 0; index -= 1) {
      const group = groups[index];
      if (!group)
        continue;
      if (groupHasTarget(group, target)) {
        groups.splice(index, 1);
        removed = true;
      }
    }
    this.#worksheet.workbook.invalidateConditionalFormattingCache(this.#worksheet.name);
    this.#worksheet.__queueCollaborativePublish();
    if (!removed || !rangeRef) {
      return;
    }
    const recorder = this.#worksheet.workbook.getRecorder();
    if (!recorder) {
      return;
    }
    const op = {
      op: "conditionalformat.clear",
      target: {
        sheet: this.#worksheet.name,
        range: rangeRef
      }
    };
    recorder.record(op);
  }
  #nextPriority() {
    let max4 = 0;
    for (const group of this.#worksheet.__getConditionalFormattings()) {
      for (const rule2 of group.rules ?? []) {
        const priority = typeof rule2.priority === "number" ? rule2.priority : 0;
        max4 = Math.max(max4, priority);
      }
    }
    return max4 + 1;
  }
}

class RangeConditionalFormats {
  #range;
  constructor(range2) {
    this.#range = range2;
  }
  addColorScale(options) {
    if (typeof options === "object" && options !== null && "minColor" in options && "maxColor" in options) {
      const config = options;
      const colors = [
        config.minColor,
        ...config.midColor ? [config.midColor] : [],
        config.maxColor
      ];
      return this.add("colorScale", {
        colors,
        thresholds: config.thresholds
      });
    }
    return this.add("colorScale", options);
  }
  addDataBar(options) {
    return this.add("dataBar", options);
  }
  addIconSet(options) {
    return this.add("iconSet", options);
  }
  addExpression(options, format2) {
    const isOptions = typeof options === "object" && options !== null && "formula" in options;
    const formula = isOptions ? options.formula : options;
    const resolvedFormat = isOptions && "format" in options ? options.format : format2;
    const config = { formula };
    if (resolvedFormat) {
      config.format = resolvedFormat;
    }
    return this.add("expression", config);
  }
  addCustom(options, format2) {
    return this.addExpression(options, format2);
  }
  addCellIs(options) {
    return this.add("cellIs", options);
  }
  add(type, config) {
    const worksheet = this.#getWorksheet();
    const rangeAddress = this.#range.address;
    const normalizedType = normalizeConditionalFormatType(String(type));
    const normalized = normalizeConditionalFormatConfig(normalizedType, config);
    const rulePayload = {
      ...normalized,
      type: normalizedType
    };
    return worksheet.conditionalFormattings.add({
      range: rangeAddress,
      rule: rulePayload
    });
  }
  get items() {
    const worksheet = this.#getWorksheet();
    const { target } = normalizeRangeForWorksheet(worksheet, this.#range.address);
    return collectRulesForRange(worksheet.__getConditionalFormattings(), target);
  }
  getItemAt(index) {
    const item = this.items[index];
    if (!item) {
      throw new Error(`Conditional format at index ${index} not found.`);
    }
    return item;
  }
  clearAll() {
    const worksheet = this.#getWorksheet();
    worksheet.conditionalFormattings.clear(this.#range.address);
  }
  deleteAll() {
    this.clearAll();
  }
  clear() {
    this.clearAll();
  }
  #getWorksheet() {
    const worksheet = getRangeWorksheet(this.#range);
    if (!worksheet) {
      throw new Error("Range is not attached to a worksheet.");
    }
    return worksheet;
  }
}
function normalizeRangeForWorksheet(worksheet, address) {
  const { sheetName, ref } = splitSheetAddress(address);
  if (sheetName && sheetName !== worksheet.name) {
    throw new Error(`Conditional formatting range must target "${worksheet.name}", received "${sheetName}".`);
  }
  const parsed = parseRangeAddress(ref);
  if (!parsed) {
    throw new Error(`Invalid range address: ${address}`);
  }
  const bounds = parsed.bounds;
  const startAddress = makeCellAddress(bounds.startRow, bounds.startCol);
  const endAddress = makeCellAddress(bounds.endRow, bounds.endCol);
  return {
    ref: parsed.ref,
    target: {
      sheetName: worksheet.name,
      sheetId: worksheet.id ?? "",
      startAddress,
      endAddress
    }
  };
}
function findGroupForRange(groups, target) {
  return groups.find((group) => groupHasTarget(group, target));
}
function groupHasTarget(group, target) {
  return (group.ranges ?? []).some((range2) => range2.startAddress === target.startAddress && range2.endAddress === target.endAddress && (!range2.sheetName || range2.sheetName === target.sheetName));
}
function createGroup(groups, target) {
  const group = {
    ranges: [target],
    rules: []
  };
  groups.push(group);
  return group;
}
function collectRulesForRange(groups, target) {
  const formats = [];
  for (const group of groups) {
    if (!groupHasTarget(group, target))
      continue;
    for (const rule2 of group.rules ?? []) {
      formats.push(new ConditionalFormat(rule2));
    }
  }
  return formats;
}
function buildRule(worksheet, rule2, priority) {
  switch (rule2.type) {
    case "aboveAverage":
      return buildAboveAverageRule(worksheet, rule2, priority);
    case "beginsWith":
    case "containsText":
    case "endsWith":
    case "notContainsText":
      return buildTextRule(worksheet, rule2, priority);
    case "cellIs":
      return buildCellIsRule(worksheet, rule2, priority);
    case "expression":
      return buildExpressionRule(worksheet, rule2, priority);
    case "colorScale":
      return buildColorScaleRule(worksheet, rule2, priority);
    case "containsBlanks":
    case "containsErrors":
    case "duplicateValues":
    case "notContainsBlanks":
    case "notContainsErrors":
    case "uniqueValues":
      return buildFormatOnlyRule(worksheet, rule2, priority);
    case "timePeriod":
      return buildTimePeriodRule(worksheet, rule2, priority);
    case "top10":
      return buildTop10Rule(worksheet, rule2, priority);
    case "dataBar":
      return buildDataBarRule(worksheet, rule2, priority);
    case "iconSet":
      return buildIconSetRule(rule2, priority);
  }
}
function resolveDifferentialFormatConfig(input) {
  if (!input || typeof input !== "object" || Array.isArray(input)) {
    return;
  }
  const record = input;
  const nested = record["format"];
  if (nested && typeof nested === "object" && !Array.isArray(nested)) {
    return nested;
  }
  return input;
}
function recordConditionalFormat(worksheet, target, rule2) {
  worksheet.__queueCollaborativePublish();
  const recorder = worksheet.workbook.getRecorder();
  if (!recorder) {
    return;
  }
  const op = buildConditionalFormatAddOp({
    sheet: worksheet.name,
    target,
    rule: rule2
  });
  if (op) {
    recorder.record(op);
  }
}
function targetToRangeRef(target) {
  const startAddress = target.startAddress;
  if (!startAddress) {
    return null;
  }
  const endAddress = target.endAddress;
  return endAddress && endAddress !== startAddress ? `${startAddress}:${endAddress}` : startAddress;
}
function registerConditionalFormattingDxf(worksheet, input) {
  const format2 = resolveDifferentialFormatConfig(input);
  if (!format2) {
    return;
  }
  return worksheet.workbook.getStyleRegistry().registerDifferentialFormat(format2, buildWorkbookThemeMap(worksheet.workbook.theme));
}
function buildCellIsRule(worksheet, rule2, priority) {
  const formula = normalizeFormulaList(rule2.formula);
  const dxfId = registerConditionalFormattingDxf(worksheet, rule2.format);
  return {
    type: "cellIs",
    priority,
    operator: rule2.operator,
    formula,
    dxfId
  };
}
function buildExpressionRule(worksheet, rule2, priority) {
  const formula = normalizeFormulaList(rule2.formula);
  const dxfId = registerConditionalFormattingDxf(worksheet, rule2.format);
  return {
    type: "expression",
    priority,
    formula,
    dxfId
  };
}
function buildTextRule(worksheet, rule2, priority) {
  return {
    type: rule2.type,
    priority,
    dxfId: registerConditionalFormattingDxf(worksheet, rule2.format),
    operator: rule2.type,
    text: rule2.text,
    formula: []
  };
}
function buildFormatOnlyRule(worksheet, rule2, priority) {
  return {
    type: rule2.type,
    priority,
    dxfId: registerConditionalFormattingDxf(worksheet, rule2.format),
    formula: []
  };
}
function buildTimePeriodRule(worksheet, rule2, priority) {
  return {
    type: "timePeriod",
    priority,
    dxfId: registerConditionalFormattingDxf(worksheet, rule2.format),
    formula: [],
    timePeriod: rule2.timePeriod
  };
}
function buildTop10Rule(worksheet, rule2, priority) {
  return {
    type: "top10",
    priority,
    dxfId: registerConditionalFormattingDxf(worksheet, rule2.format),
    formula: [],
    rank: rule2.rank,
    percent: rule2.percent,
    bottom: rule2.bottom
  };
}
function buildAboveAverageRule(worksheet, rule2, priority) {
  return {
    type: "aboveAverage",
    priority,
    dxfId: registerConditionalFormattingDxf(worksheet, rule2.format),
    formula: [],
    aboveAverage: rule2.aboveAverage,
    equalAverage: rule2.equalAverage,
    stdDev: rule2.stdDev
  };
}
function buildColorScaleRule(worksheet, rule2, priority) {
  const themeMap = buildWorkbookThemeMap(worksheet.workbook.theme);
  const colors = (rule2.colors ?? []).map((config) => resolveThemeColor2(new Color4(config).toProto(), themeMap)).filter((entry) => Boolean(entry));
  const cfvos = normalizeCfvos(rule2.thresholds, colors.length, "percentile");
  const colorScale = {
    cfvos,
    colors
  };
  return {
    type: "colorScale",
    priority,
    formula: [],
    colorScale
  };
}
var normalizeConditionalFormatType = (raw) => {
  const normalized = raw.replace(/[^a-z0-9]/gi, "").toLowerCase();
  switch (normalized) {
    case "aboveaverage":
      return "aboveAverage";
    case "beginswith":
      return "beginsWith";
    case "cellis":
    case "cellvalue":
      return "cellIs";
    case "colorscale":
      return "colorScale";
    case "containsblanks":
      return "containsBlanks";
    case "containserrors":
      return "containsErrors";
    case "containstext":
      return "containsText";
    case "databar":
      return "dataBar";
    case "duplicatevalues":
      return "duplicateValues";
    case "endswith":
      return "endsWith";
    case "iconset":
      return "iconSet";
    case "notcontainsblanks":
      return "notContainsBlanks";
    case "notcontainserrors":
      return "notContainsErrors";
    case "notcontainstext":
      return "notContainsText";
    case "expression":
    case "custom":
      return "expression";
    case "timeperiod":
      return "timePeriod";
    case "top10":
      return "top10";
    case "uniquevalues":
      return "uniqueValues";
    default:
      break;
  }
  const supported = [
    "aboveAverage",
    "beginsWith",
    "cellIs",
    "colorScale",
    "containsBlanks",
    "containsErrors",
    "containsText",
    "dataBar",
    "duplicateValues",
    "endsWith",
    "iconSet",
    "expression",
    "notContainsBlanks",
    "notContainsErrors",
    "notContainsText",
    "timePeriod",
    "top10",
    "uniqueValues"
  ].join(", ");
  throw new Error(`Unsupported conditional format type: ${raw}. Supported types: ${supported}. ` + "Use Custom as an alias for expression rules.");
};
function normalizeConditionalFormatConfig(type, config) {
  if (!config || typeof config !== "object") {
    throw new Error(`Conditional format "${type}" requires a config object. ` + `Example: range.conditionalFormats.add("${type}", { ... })`);
  }
  if (type === "cellIs") {
    const payload = config;
    if (payload.operator === undefined || payload.formula === undefined) {
      throw new Error(`cellIs rules require "operator" and "formula" fields.
` + `Example: range.conditionalFormats.add("CellValue", { operator: "lessThan", formula: 0, format: { fill: "#F8CBAD" } })
` + 'Or: range.conditionalFormats.addCellIs({ operator: "lessThan", formula: 0, format: { fill: "#F8CBAD" } })');
    }
  }
  if (type === "iconSet") {
    const payload = config;
    if (!payload.iconSet) {
      throw new Error('iconSet rules require an "iconSet" value.');
    }
  }
  if (type === "expression") {
    const payload = config;
    if (payload.formula === undefined) {
      throw new Error('expression rules require a "formula" value.');
    }
  }
  if (type === "containsText" || type === "notContainsText" || type === "beginsWith" || type === "endsWith") {
    const payload = config;
    if (!payload.text || !payload.text.trim()) {
      throw new Error(`${type} rules require a non-empty "text" value.`);
    }
  }
  if (type === "timePeriod") {
    const payload = config;
    if (!payload.timePeriod) {
      throw new Error('timePeriod rules require a "timePeriod" value.');
    }
  }
  if (type === "top10") {
    const payload = config;
    if (payload.rank !== undefined && (!Number.isFinite(payload.rank) || payload.rank <= 0)) {
      throw new Error('top10 rules require "rank" to be a positive number.');
    }
  }
  if (type === "aboveAverage") {
    const payload = config;
    if (payload.stdDev !== undefined && (!Number.isFinite(payload.stdDev) || payload.stdDev < 0)) {
      throw new Error('aboveAverage rules require "stdDev" to be zero or a positive number.');
    }
  }
  if (type === "colorScale") {
    return normalizeColorScaleConfig(config);
  }
  return config;
}
function normalizeColorScaleConfig(config) {
  if (config.colors && config.colors.length >= 2) {
    return config;
  }
  const criteriaInput = config.criteria;
  if (!criteriaInput) {
    throw new Error('colorScale rules require "colors" (2-3 entries) or "criteria".');
  }
  const criteria = normalizeColorScaleCriteria(criteriaInput);
  const colors = criteria.map((entry) => entry.color).filter((color2) => Boolean(color2));
  if (colors.length < 2) {
    throw new Error("colorScale criteria require at least 2 color entries.");
  }
  const thresholds = criteria.map((entry) => normalizeColorScaleThreshold(entry));
  return { colors, thresholds };
}
function normalizeColorScaleCriteria(input) {
  if (Array.isArray(input)) {
    return input;
  }
  const criteria = [];
  if (input.minimum) {
    criteria.push(input.minimum);
  }
  if (input.midpoint) {
    criteria.push(input.midpoint);
  }
  if (input.maximum) {
    criteria.push(input.maximum);
  }
  return criteria;
}
function normalizeColorScaleThreshold(entry) {
  const rawType = entry.type ?? "";
  const type = rawType.toLowerCase();
  const rawValue = entry.value !== undefined && entry.value !== null ? entry.value : entry.formula;
  const normalizedValue = typeof rawValue === "string" ? rawValue.trim().replace(/^=/, "") : rawValue ?? undefined;
  switch (type) {
    case "lowestvalue":
    case "min":
      return "min";
    case "highestvalue":
    case "max":
      return "max";
    case "percent":
      return { type: "percent", value: normalizedValue };
    case "percentile":
      return { type: "percentile", value: normalizedValue };
    case "num":
    case "number":
      return { type: "num", value: normalizedValue };
    default:
      if (normalizedValue !== undefined) {
        return { type: "num", value: normalizedValue };
      }
      throw new Error('colorScale criteria entries require a "type" or a numeric "value".');
  }
}
function buildDataBarRule(worksheet, rule2, priority) {
  const themeMap = buildWorkbookThemeMap(worksheet.workbook.theme);
  const color2 = rule2.color !== undefined ? rule2.color : "accent1";
  const resolvedColor = resolveThemeColor2(new Color4(color2).toProto(), themeMap);
  const cfvos = normalizeCfvos(rule2.thresholds, 2, "percent");
  const dataBar = {
    cfvos,
    color: resolvedColor ?? new Color4("accent1").toProto(),
    gradient: rule2.gradient
  };
  return {
    type: "dataBar",
    priority,
    formula: [],
    dataBar
  };
}
function buildIconSetRule(rule2, priority) {
  const thresholdCount = getConditionalFormattingIconSetThresholdCount({
    iconSetName: rule2.iconSet,
    fallbackThresholdCount: rule2.thresholds?.length
  });
  const iconSet = {
    iconSet: rule2.iconSet,
    showValue: rule2.showValue,
    reverse: rule2.reverse,
    custom: rule2.custom,
    percent: rule2.percent,
    cfvos: normalizeIconSetCfvos(rule2.thresholds, thresholdCount)
  };
  return {
    type: "iconSet",
    priority,
    formula: [],
    iconSet
  };
}
function normalizeFormulaList(formula) {
  const list = Array.isArray(formula) ? formula : [formula];
  return list.map((entry) => normalizeFormulaEntry(entry));
}
function normalizeFormulaEntry(entry) {
  if (typeof entry === "number") {
    return String(entry);
  }
  const trimmed = entry.trim();
  return trimmed.startsWith("=") ? trimmed.slice(1) : trimmed;
}
function normalizeCfvos(cfvos, count3, percentType) {
  const normalized = cfvos && cfvos.length > 0 ? cfvos.map((entry) => toCfvo(entry, percentType)) : defaultCfvos(count3);
  return normalized.slice(0, Math.max(1, count3));
}
function normalizeIconSetCfvos(cfvos, count3) {
  const desiredCount = Math.max(1, count3);
  const provided = cfvos?.map((entry) => toCfvo(entry, "percent")) ?? [];
  const defaults = getDefaultConditionalFormattingIconSetThresholdPercents(desiredCount).map((value) => ({
    type: "percent",
    val: String(value)
  }));
  const normalized = defaults.map((fallback, index) => provided[index] ?? fallback);
  return normalized.slice(0, desiredCount);
}
function defaultCfvos(count3) {
  if (count3 <= 2) {
    return [{ type: "min" }, { type: "max" }];
  }
  return [{ type: "min" }, { type: "percentile", val: "50" }, { type: "max" }];
}
function toCfvo(entry, percentType) {
  if (typeof entry === "number") {
    return { type: "num", val: String(entry) };
  }
  if (typeof entry === "string") {
    const trimmed = entry.trim();
    if (trimmed === "min" || trimmed === "max") {
      return { type: trimmed };
    }
    if (trimmed.endsWith("%")) {
      return { type: percentType, val: trimmed.slice(0, -1) };
    }
    return { type: "num", val: trimmed };
  }
  const value = entry.value === undefined || entry.value === null ? undefined : String(entry.value);
  return {
    type: entry.type,
    val: value
  };
}
function resolveThemeColor2(color2, themeMap) {
  if (!color2) {
    return;
  }
  if (color2.type !== 2 /* COLOR_TYPE_SCHEME */ && color2.type !== 3 /* COLOR_TYPE_SYSTEM */) {
    return color2;
  }
  const rgba2 = colorToRgba(color2, themeMap, SPREADSHEET_COLOR_OPTIONS3);
  const parsed = parseRgba2(rgba2);
  if (!parsed) {
    return color2;
  }
  const { r, g, b, a } = parsed;
  const to2 = (value) => value.toString(16).padStart(2, "0");
  const alpha = Math.max(0, Math.min(1, a));
  const alphaHex = to2(Math.round(alpha * 255));
  return {
    type: 1 /* COLOR_TYPE_RGB */,
    value: `${alphaHex}${to2(r)}${to2(g)}${to2(b)}`.toUpperCase(),
    transform: undefined,
    lastColor: undefined
  };
}
function parseRgba2(css) {
  const match = css.match(/^rgba?\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\)$/i);
  if (!match) {
    return null;
  }
  const r = Math.max(0, Math.min(255, Number(match[1])));
  const g = Math.max(0, Math.min(255, Number(match[2])));
  const b = Math.max(0, Math.min(255, Number(match[3])));
  const a = match[4] === undefined ? 1 : Number(match[4]);
  if ([r, g, b, a].some((value) => Number.isNaN(value))) {
    return null;
  }
  return { r, g, b, a };
}

// node_modules/@oai/granola/dist/models/spreadsheet/data-validation.js
init_address_utils();
var RULE_TYPE_TO_PROTO = {
  none: 1 /* DATA_VALIDATION_TYPE_NONE */,
  whole: 2 /* DATA_VALIDATION_TYPE_WHOLE */,
  decimal: 3 /* DATA_VALIDATION_TYPE_DECIMAL */,
  list: 4 /* DATA_VALIDATION_TYPE_LIST */,
  date: 5 /* DATA_VALIDATION_TYPE_DATE */,
  time: 6 /* DATA_VALIDATION_TYPE_TIME */,
  textLength: 7 /* DATA_VALIDATION_TYPE_TEXT_LENGTH */,
  custom: 8 /* DATA_VALIDATION_TYPE_CUSTOM */
};
var OPERATOR_TO_PROTO = {
  between: 1 /* DATA_VALIDATION_OPERATOR_BETWEEN */,
  notBetween: 2 /* DATA_VALIDATION_OPERATOR_NOT_BETWEEN */,
  equal: 3 /* DATA_VALIDATION_OPERATOR_EQUAL */,
  notEqual: 4 /* DATA_VALIDATION_OPERATOR_NOT_EQUAL */,
  lessThan: 5 /* DATA_VALIDATION_OPERATOR_LESS_THAN */,
  lessThanOrEqual: 6 /* DATA_VALIDATION_OPERATOR_LESS_THAN_OR_EQUAL */,
  greaterThan: 7 /* DATA_VALIDATION_OPERATOR_GREATER_THAN */,
  greaterThanOrEqual: 8 /* DATA_VALIDATION_OPERATOR_GREATER_THAN_OR_EQUAL */
};
var ERROR_STYLE_TO_PROTO = {
  stop: 1 /* DATA_VALIDATION_ERROR_STYLE_STOP */,
  warning: 2 /* DATA_VALIDATION_ERROR_STYLE_WARNING */,
  information: 3 /* DATA_VALIDATION_ERROR_STYLE_INFORMATION */
};

class WorksheetDataValidationCollection {
  #worksheet;
  constructor(worksheet) {
    this.#worksheet = worksheet;
  }
  get items() {
    return this.#worksheet.__getDataValidations();
  }
  getForAddress(address) {
    const ref = normalizeRangeRef(this.#worksheet, address);
    const targetBounds = parseRangeAddress(ref)?.bounds;
    if (!targetBounds) {
      return null;
    }
    let bestMatch = null;
    let bestArea = Number.POSITIVE_INFINITY;
    for (const item of this.#worksheet.__getDataValidations()) {
      const itemRef = item.sqref;
      if (!itemRef) {
        continue;
      }
      const bounds = parseRangeAddress(itemRef)?.bounds;
      if (!bounds || !rangeContains(bounds, targetBounds)) {
        continue;
      }
      const area = rangeArea(bounds);
      if (area < bestArea) {
        bestMatch = item;
        bestArea = area;
      }
    }
    return bestMatch;
  }
  add(options) {
    const record = buildValidationRecord(this.#worksheet, options.range, options);
    this.#worksheet.__getDataValidations().push(record);
    recordValidationState(this.#worksheet, record);
    return record;
  }
  clear(range2) {
    const ref = normalizeRangeRef(this.#worksheet, range2);
    const items = this.#worksheet.__getDataValidations();
    let removed = false;
    for (let index = items.length - 1;index >= 0; index -= 1) {
      if (items[index]?.sqref === ref) {
        items.splice(index, 1);
        removed = true;
      }
    }
    if (!removed) {
      return;
    }
    this.#worksheet.__invalidateViewportLayout();
    this.#worksheet.__queueCollaborativePublish();
    const recorder = this.#worksheet.workbook.getRecorder();
    if (!recorder) {
      return;
    }
    const op = {
      op: "datavalidation.clear",
      target: {
        sheet: this.#worksheet.name,
        range: ref
      }
    };
    recorder.record(op);
  }
}

class RangeDataValidation {
  #range;
  constructor(range2) {
    this.#range = range2;
  }
  get rule() {
    const record = this.#getRecord();
    if (!record) {
      return null;
    }
    const type = reverseRuleType(record.type);
    return {
      type,
      operator: reverseOperator(record.operator),
      formula1: record.formula1 ?? undefined,
      formula2: record.formula2 ?? undefined,
      values: type === "list" ? parseInlineListValidationValues(record.formula1) : undefined
    };
  }
  set rule(rule2) {
    if (!rule2) {
      this.clear();
      return;
    }
    const record = this.#getOrCreateRecord();
    applyRule(record, rule2);
    recordValidationState(this.#getWorksheet(), record);
  }
  get prompt() {
    const record = this.#getRecord();
    if (!record) {
      return null;
    }
    return {
      title: record.promptTitle ?? undefined,
      message: record.promptMessage ?? undefined,
      show: record.showInputMessage ?? undefined
    };
  }
  set prompt(value) {
    if (!value) {
      const record2 = this.#getRecord();
      if (!record2) {
        return;
      }
      record2.promptTitle = undefined;
      record2.promptMessage = undefined;
      record2.showInputMessage = undefined;
      recordValidationState(this.#getWorksheet(), record2);
      return;
    }
    const record = this.#getOrCreateRecord();
    record.promptTitle = value.title ?? undefined;
    record.promptMessage = value.message ?? undefined;
    record.showInputMessage = value.show ?? true;
    recordValidationState(this.#getWorksheet(), record);
  }
  get errorAlert() {
    const record = this.#getRecord();
    if (!record) {
      return null;
    }
    return {
      title: record.errorTitle ?? undefined,
      message: record.errorMessage ?? undefined,
      style: reverseErrorStyle(record.errorStyle),
      show: record.showErrorMessage ?? undefined
    };
  }
  set errorAlert(value) {
    if (!value) {
      const record2 = this.#getRecord();
      if (!record2) {
        return;
      }
      record2.errorTitle = undefined;
      record2.errorMessage = undefined;
      record2.errorStyle = undefined;
      record2.showErrorMessage = undefined;
      recordValidationState(this.#getWorksheet(), record2);
      return;
    }
    const record = this.#getOrCreateRecord();
    record.errorTitle = value.title ?? undefined;
    record.errorMessage = value.message ?? undefined;
    record.showErrorMessage = value.show ?? true;
    if (value.style) {
      record.errorStyle = ERROR_STYLE_TO_PROTO[value.style];
    }
    recordValidationState(this.#getWorksheet(), record);
  }
  get ignoreBlanks() {
    const record = this.#getRecord();
    return record?.allowBlank ?? false;
  }
  set ignoreBlanks(value) {
    const record = this.#getOrCreateRecord();
    record.allowBlank = Boolean(value);
    recordValidationState(this.#getWorksheet(), record);
  }
  get inCellDropDown() {
    const record = this.#getRecord();
    if (!record || record.showDropDown === undefined) {
      return true;
    }
    return !record.showDropDown;
  }
  set inCellDropDown(value) {
    const record = this.#getOrCreateRecord();
    record.showDropDown = !value;
    recordValidationState(this.#getWorksheet(), record);
  }
  clear() {
    const worksheet = this.#getWorksheet();
    worksheet.dataValidations.clear(this.#range.address);
  }
  #getWorksheet() {
    const worksheet = getRangeWorksheet(this.#range);
    if (!worksheet) {
      throw new Error("Range is not attached to a worksheet.");
    }
    return worksheet;
  }
  #getRecord() {
    const worksheet = this.#getWorksheet();
    return worksheet.dataValidations.getForAddress(this.#range.address) ?? undefined;
  }
  #getOrCreateRecord() {
    const worksheet = this.#getWorksheet();
    const ref = normalizeRangeRef(worksheet, this.#range.address);
    let record = worksheet.__getDataValidations().find((item) => item.sqref === ref);
    if (!record) {
      record = { sqref: ref };
      worksheet.__getDataValidations().push(record);
    }
    return record;
  }
}
function buildValidationRecord(worksheet, range2, options) {
  const ref = normalizeRangeRef(worksheet, range2);
  const record = { sqref: ref };
  applyRule(record, options.rule);
  applyPrompt(record, options.prompt);
  applyErrorAlert(record, options.errorAlert);
  if (options.ignoreBlanks !== undefined) {
    record.allowBlank = Boolean(options.ignoreBlanks);
  }
  if (options.inCellDropDown !== undefined) {
    record.showDropDown = !options.inCellDropDown;
  }
  return record;
}
function applyRule(record, rule2) {
  record.type = RULE_TYPE_TO_PROTO[rule2.type];
  record.operator = rule2.operator ? OPERATOR_TO_PROTO[rule2.operator] : undefined;
  const formulas = normalizeRuleFormulas(rule2);
  record.formula1 = formulas.formula1;
  record.formula2 = formulas.formula2;
}
function applyPrompt(record, prompt) {
  if (!prompt) {
    return;
  }
  record.promptTitle = prompt.title ?? undefined;
  record.promptMessage = prompt.message ?? undefined;
  record.showInputMessage = prompt.show ?? true;
}
function applyErrorAlert(record, errorAlert) {
  if (!errorAlert) {
    return;
  }
  record.errorTitle = errorAlert.title ?? undefined;
  record.errorMessage = errorAlert.message ?? undefined;
  record.showErrorMessage = errorAlert.show ?? true;
  if (errorAlert.style) {
    record.errorStyle = ERROR_STYLE_TO_PROTO[errorAlert.style];
  }
}
function normalizeRuleFormulas(rule2) {
  if (rule2.type === "list" && rule2.values && rule2.values.length > 0) {
    const escaped = rule2.values.join(",");
    return { formula1: `"${escaped}"` };
  }
  const formula1 = normalizeFormulaValue(rule2.formula1);
  const formula2 = normalizeFormulaValue(rule2.formula2);
  return { formula1, formula2 };
}
function normalizeFormulaValue(value) {
  if (value === undefined || value === null) {
    return;
  }
  if (typeof value === "number") {
    return String(value);
  }
  const trimmed = value.trim();
  return trimmed.startsWith("=") ? trimmed.slice(1) : trimmed;
}
function normalizeRangeRef(worksheet, address) {
  const { sheetName, ref } = splitSheetAddress(address);
  if (sheetName && sheetName !== worksheet.name) {
    throw new Error(`Data validation range must target "${worksheet.name}", received "${sheetName}".`);
  }
  const parsed = parseRangeAddress(ref);
  if (!parsed) {
    throw new Error(`Invalid range address: ${address}`);
  }
  return parsed.ref;
}
function parseInlineListValidationValues(formula) {
  if (!formula) {
    return;
  }
  const trimmed = formula.trim();
  if (trimmed.length < 2 || !trimmed.startsWith('"') || !trimmed.endsWith('"')) {
    return;
  }
  return trimmed.slice(1, -1).split(",").map((value) => value.replaceAll('""', '"'));
}
function rangeContains(outer, inner) {
  return outer.startRow <= inner.startRow && outer.startCol <= inner.startCol && outer.endRow >= inner.endRow && outer.endCol >= inner.endCol;
}
function rangeArea(bounds) {
  return (bounds.endRow - bounds.startRow + 1) * (bounds.endCol - bounds.startCol + 1);
}
function reverseRuleType(value) {
  switch (value) {
    case 1 /* DATA_VALIDATION_TYPE_NONE */:
      return "none";
    case 2 /* DATA_VALIDATION_TYPE_WHOLE */:
      return "whole";
    case 3 /* DATA_VALIDATION_TYPE_DECIMAL */:
      return "decimal";
    case 4 /* DATA_VALIDATION_TYPE_LIST */:
      return "list";
    case 5 /* DATA_VALIDATION_TYPE_DATE */:
      return "date";
    case 6 /* DATA_VALIDATION_TYPE_TIME */:
      return "time";
    case 7 /* DATA_VALIDATION_TYPE_TEXT_LENGTH */:
      return "textLength";
    case 8 /* DATA_VALIDATION_TYPE_CUSTOM */:
      return "custom";
    default:
      return "custom";
  }
}
function reverseOperator(value) {
  switch (value) {
    case 1 /* DATA_VALIDATION_OPERATOR_BETWEEN */:
      return "between";
    case 2 /* DATA_VALIDATION_OPERATOR_NOT_BETWEEN */:
      return "notBetween";
    case 3 /* DATA_VALIDATION_OPERATOR_EQUAL */:
      return "equal";
    case 4 /* DATA_VALIDATION_OPERATOR_NOT_EQUAL */:
      return "notEqual";
    case 5 /* DATA_VALIDATION_OPERATOR_LESS_THAN */:
      return "lessThan";
    case 6 /* DATA_VALIDATION_OPERATOR_LESS_THAN_OR_EQUAL */:
      return "lessThanOrEqual";
    case 7 /* DATA_VALIDATION_OPERATOR_GREATER_THAN */:
      return "greaterThan";
    case 8 /* DATA_VALIDATION_OPERATOR_GREATER_THAN_OR_EQUAL */:
      return "greaterThanOrEqual";
    default:
      return;
  }
}
function reverseErrorStyle(value) {
  switch (value) {
    case 1 /* DATA_VALIDATION_ERROR_STYLE_STOP */:
      return "stop";
    case 2 /* DATA_VALIDATION_ERROR_STYLE_WARNING */:
      return "warning";
    case 3 /* DATA_VALIDATION_ERROR_STYLE_INFORMATION */:
      return "information";
    default:
      return;
  }
}
function recordValidationState(worksheet, record) {
  worksheet.__invalidateViewportLayout();
  worksheet.__queueCollaborativePublish();
  const recorder = worksheet.workbook.getRecorder();
  if (!recorder || !record.sqref) {
    return;
  }
  recorder.deferOnce(`datavalidation.set:${worksheet.name}:${record.sqref}`, () => buildDataValidationSetOp({
    sheet: worksheet.name,
    record
  }));
}

// node_modules/@oai/granola/dist/models/spreadsheet/engine/expression-parser.js
var BOOLEAN_LITERALS = new Set(["TRUE", "FALSE"]);
var DEFAULT_EXPR = { kind: "NumberLiteral", value: 0 };
var MAX_COLUMN = 16384;
var CELL_REF_REGEX = /^(\$?)([A-Za-z]{1,3})(\$?)(\d{1,7})$/;
var COLUMN_ONLY_REGEX = /^(\$?)([A-Za-z]{1,3})$/;
var BINARY_PRECEDENCE = {
  ":": 150,
  ",": 140,
  "^": 110,
  "*": 100,
  "/": 100,
  "+": 90,
  "-": 90,
  "&": 80,
  "=": 70,
  "<>": 70,
  "<": 70,
  ">": 70,
  "<=": 70,
  ">=": 70
};
var RIGHT_ASSOCIATIVE = new Set(["^"]);
var UNARY_PRECEDENCE = 130;
function isWhitespace(ch) {
  if (!ch) {
    return false;
  }
  return ch === " " || ch === "\t" || ch === `
` || ch === "\r";
}
function isDigit(ch) {
  if (!ch) {
    return false;
  }
  return ch >= "0" && ch <= "9";
}
function isIdentifierStart(ch) {
  if (!ch) {
    return false;
  }
  return ch >= "A" && ch <= "Z" || ch >= "a" && ch <= "z" || ch === "_" || ch === "$" || ch === "\\";
}
function isIdentifierPart(ch) {
  if (!ch) {
    return false;
  }
  return isIdentifierStart(ch) || isDigit(ch) || ch === "." || ch === "?" || ch === "#";
}
function readQuotedIdentifier(src, start) {
  let i = start + 1;
  let value = "";
  while (i < src.length) {
    const ch = src[i] ?? "";
    if (ch === "'") {
      const nextCh = src[i + 1];
      if (nextCh === "'") {
        value += "'";
        i += 2;
        continue;
      }
      i += 1;
      break;
    }
    value += ch;
    i += 1;
  }
  return {
    token: { type: "Identifier", value, start, end: i },
    next: i
  };
}
function readStringLiteral(src, start) {
  let i = start + 1;
  let value = "";
  while (i < src.length) {
    const ch = src[i] ?? "";
    if (ch === '"') {
      const nextCh = src[i + 1];
      if (nextCh === '"') {
        value += '"';
        i += 2;
        continue;
      }
      i += 1;
      break;
    }
    value += ch;
    i += 1;
  }
  return {
    token: { type: "String", value, start, end: i },
    next: i
  };
}
function readNumberLiteral(src, start) {
  let i = start;
  let hasDigits = false;
  while (i < src.length && isDigit(src[i])) {
    hasDigits = true;
    i += 1;
  }
  if (i < src.length && src[i] === ".") {
    i += 1;
    while (i < src.length && isDigit(src[i])) {
      hasDigits = true;
      i += 1;
    }
  }
  if (i < src.length && (src[i] === "E" || src[i] === "e") && i + 1 < src.length && (isDigit(src[i + 1]) || src[i + 1] === "+" || src[i + 1] === "-")) {
    i += 1;
    if (src[i] === "+" || src[i] === "-") {
      i += 1;
    }
    while (i < src.length && isDigit(src[i])) {
      i += 1;
    }
  }
  if (!hasDigits) {
    const fallback = src[start] ?? "";
    return {
      token: { type: "Operator", value: fallback, start, end: start + 1 },
      next: start + 1
    };
  }
  return {
    token: { type: "Number", value: src.slice(start, i), start, end: i },
    next: i
  };
}
function readIdentifier(src, start) {
  let i = start;
  while (i < src.length && isIdentifierPart(src[i])) {
    i += 1;
  }
  return {
    token: { type: "Identifier", value: src.slice(start, i), start, end: i },
    next: i
  };
}
function readErrorLiteral(src, start) {
  let i = start + 1;
  while (i < src.length) {
    const ch = src[i] ?? "";
    if (/[A-Za-z0-9/?!]/.test(ch)) {
      i += 1;
      continue;
    }
    if (ch === "!" || ch === "?" || ch === "/") {
      i += 1;
      continue;
    }
    break;
  }
  if ((src[i - 1] ?? "") !== "!") {}
  return {
    token: { type: "Error", value: src.slice(start, i), start, end: i },
    next: i
  };
}
function readStructuredReferenceToken(src, start) {
  let i = start;
  let depth = 0;
  while (i < src.length) {
    const ch = src[i] ?? "";
    if (ch === "[") {
      depth += 1;
      i += 1;
      continue;
    }
    if (ch === "]") {
      depth -= 1;
      i += 1;
      if (depth <= 0) {
        break;
      }
      continue;
    }
    i += 1;
  }
  return {
    token: {
      type: "StructuredRef",
      value: src.slice(start, i),
      start,
      end: i
    },
    next: i
  };
}
function tokenizeFormula(formula) {
  const tokens = [];
  const src = formula ?? "";
  let i = src.startsWith("=") ? 1 : 0;
  while (i < src.length) {
    const ch = src[i] ?? "";
    if (isWhitespace(ch)) {
      const start = i;
      while (i < src.length && isWhitespace(src[i])) {
        i += 1;
      }
      tokens.push({
        type: "Whitespace",
        value: src.slice(start, i),
        start,
        end: i
      });
      continue;
    }
    if (ch === "'") {
      const { token, next } = readQuotedIdentifier(src, i);
      tokens.push(token);
      i = next;
      continue;
    }
    if (ch === '"') {
      const { token, next } = readStringLiteral(src, i);
      tokens.push(token);
      i = next;
      continue;
    }
    if (ch === "#") {
      const nextCh = src[i + 1];
      if (nextCh && /[A-Za-z]/.test(nextCh)) {
        const { token, next } = readErrorLiteral(src, i);
        tokens.push(token);
        i = next;
      } else {
        tokens.push({ type: "Hash", value: "#", start: i, end: i + 1 });
        i += 1;
      }
      continue;
    }
    if (isDigit(ch) || ch === "." && i + 1 < src.length && isDigit(src[i + 1])) {
      const { token, next } = readNumberLiteral(src, i);
      tokens.push(token);
      i = next;
      continue;
    }
    if (ch === "[") {
      const { token, next } = readStructuredReferenceToken(src, i);
      tokens.push(token);
      i = next;
      continue;
    }
    if (isIdentifierStart(ch)) {
      const { token, next } = readIdentifier(src, i);
      const upper = token.value.toUpperCase();
      if (BOOLEAN_LITERALS.has(upper)) {
        tokens.push({
          type: "Boolean",
          value: upper,
          start: token.start,
          end: token.end
        });
      } else {
        tokens.push(token);
      }
      i = next;
      continue;
    }
    switch (ch) {
      case "+":
      case "-":
      case "*":
      case "/":
      case "^":
      case "&":
      case "%":
        tokens.push({ type: "Operator", value: ch, start: i, end: i + 1 });
        i += 1;
        continue;
      case "=":
        tokens.push({ type: "Operator", value: "=", start: i, end: i + 1 });
        i += 1;
        continue;
      case ">":
      case "<": {
        const startPos = i;
        let value = ch;
        if (i + 1 < src.length && (src[i + 1] === "=" || ch === "<" && src[i + 1] === ">")) {
          value += src[i + 1];
          i += 1;
        }
        tokens.push({ type: "Operator", value, start: startPos, end: i + 1 });
        i += 1;
        continue;
      }
      case "(":
        tokens.push({ type: "ParenOpen", value: ch, start: i, end: i + 1 });
        i += 1;
        continue;
      case ")":
        tokens.push({ type: "ParenClose", value: ch, start: i, end: i + 1 });
        i += 1;
        continue;
      case ",":
        tokens.push({ type: "Comma", value: ch, start: i, end: i + 1 });
        i += 1;
        continue;
      case ":":
        tokens.push({ type: "Colon", value: ch, start: i, end: i + 1 });
        i += 1;
        continue;
      case "!":
        tokens.push({ type: "Bang", value: ch, start: i, end: i + 1 });
        i += 1;
        continue;
      case "@":
        tokens.push({ type: "At", value: ch, start: i, end: i + 1 });
        i += 1;
        continue;
      case "{":
        tokens.push({ type: "LBrace", value: ch, start: i, end: i + 1 });
        i += 1;
        continue;
      case "}":
        tokens.push({ type: "RBrace", value: ch, start: i, end: i + 1 });
        i += 1;
        continue;
      case ";":
        tokens.push({ type: "Semicolon", value: ch, start: i, end: i + 1 });
        i += 1;
        continue;
      default:
        tokens.push({ type: "Operator", value: ch, start: i, end: i + 1 });
        i += 1;
    }
  }
  tokens.push({ type: "EOF", value: "", start: src.length, end: src.length });
  return tokens;
}

class Parser {
  tokens;
  index = 0;
  errors = [];
  constructor(tokens) {
    this.tokens = tokens;
  }
  parse() {
    const expr = this.parseExpression();
    this.consumeUntilEOF();
    return expr;
  }
  consumeUntilEOF() {
    while (!this.isAtEnd()) {
      const token = this.peekToken();
      if (token?.type === "EOF") {
        return;
      }
      if (token && token.type !== "Whitespace") {
        this.errors.push(`Unexpected token ${token.value}`);
      }
      this.index += 1;
    }
  }
  parseExpression(minPrec = 0, stopTokens = []) {
    let left = this.parsePrefix(stopTokens);
    left = this.parsePostfix(left);
    while (true) {
      const next = this.peekNonWhitespace();
      if (!next || stopTokens.includes(next.type) || next.type === "EOF") {
        break;
      }
      const opInfo = this.getBinaryOperatorInfo(next, stopTokens);
      if (!opInfo || opInfo.precedence < minPrec) {
        break;
      }
      this.advanceToken();
      const right = this.parseExpression(opInfo.precedence + (opInfo.rightAssociative ? 0 : 1), stopTokens);
      left = this.buildBinaryExpr(left, opInfo.operator, right);
      left = this.parsePostfix(left);
    }
    return left;
  }
  parsePrefix(stopTokens) {
    const token = this.peekNonWhitespace();
    if (!token) {
      this.errors.push("Unexpected end of formula");
      return DEFAULT_EXPR;
    }
    if (token.type === "Operator" && (token.value === "+" || token.value === "-")) {
      this.advanceToken();
      const expr = this.parseExpression(UNARY_PRECEDENCE, stopTokens);
      return { kind: "UnaryOp", op: token.value, expr };
    }
    if (token.type === "At") {
      this.advanceToken();
      this.errors.push("Implicit intersection operator '@' is not implemented yet.");
      return this.parseExpression(UNARY_PRECEDENCE, stopTokens);
    }
    return this.parsePrimary();
  }
  parsePostfix(expr) {
    while (true) {
      const token = this.peekNonWhitespace();
      if (!token) {
        break;
      }
      if (token.type === "ParenOpen") {
        expr = this.parseInvocation(expr);
        continue;
      }
      if (token.type === "Operator" && token.value === "%") {
        this.advanceToken();
        expr = { kind: "UnaryOp", op: "%", expr };
        continue;
      }
      if (token.type === "Hash") {
        this.advanceToken();
        if (expr.kind === "RangeRef") {
          expr = {
            kind: "RangeRef",
            ref: { kind: "Spill", base: expr.ref }
          };
        } else {
          this.errors.push("Spill operator (#) must follow a reference.");
        }
        continue;
      }
      break;
    }
    return expr;
  }
  parseInvocation(callee) {
    this.matchToken("ParenOpen");
    const args2 = [];
    const nextToken = this.peekNonWhitespace();
    if (nextToken?.type === "ParenClose") {
      this.matchToken("ParenClose");
      return { kind: "CallExpr", callee, args: args2 };
    }
    let closed = false;
    let expectArgument = true;
    while (!this.isAtEnd()) {
      const next = this.peekNonWhitespace();
      if (!next) {
        break;
      }
      if (next.type === "ParenClose") {
        if (expectArgument && args2.length > 0) {
          args2.push({ kind: "MissingArg" });
        }
        this.matchToken("ParenClose");
        closed = true;
        break;
      }
      if (next.type === "Comma") {
        if (expectArgument) {
          args2.push({ kind: "MissingArg" });
        }
        this.matchToken("Comma");
        expectArgument = true;
        continue;
      }
      const expr = this.parseExpression(0, ["Comma", "ParenClose"]);
      args2.push(expr);
      expectArgument = false;
      const delimiter = this.peekNonWhitespace();
      if (delimiter?.type === "Comma") {
        this.matchToken("Comma");
        expectArgument = true;
        continue;
      }
      if (delimiter?.type === "ParenClose") {
        this.matchToken("ParenClose");
        closed = true;
        break;
      }
      if (!delimiter) {
        break;
      }
      this.errors.push(`Unexpected token ${delimiter.value} in invocation arguments`);
      this.advanceToken();
    }
    if (!closed) {
      this.errors.push("Missing closing parenthesis after invocation");
    }
    return { kind: "CallExpr", callee, args: args2 };
  }
  parsePrimary() {
    const token = this.peekNonWhitespace();
    if (!token) {
      return DEFAULT_EXPR;
    }
    switch (token.type) {
      case "Number":
        this.advanceToken();
        return { kind: "NumberLiteral", value: Number(token.value) };
      case "String":
        this.advanceToken();
        return { kind: "StringLiteral", value: token.value };
      case "Boolean": {
        this.advanceToken();
        const literal = {
          kind: "BooleanLiteral",
          value: token.value === "TRUE"
        };
        const next = this.peekNonWhitespace();
        if (next?.type === "ParenOpen") {
          this.matchToken("ParenOpen");
          if (this.peekNonWhitespace()?.type === "ParenClose") {
            this.matchToken("ParenClose");
          } else {
            this.errors.push(`Boolean literal ${token.value} cannot accept arguments`);
            this.parseExpression(0, ["ParenClose"]);
            if (!this.matchToken("ParenClose")) {
              this.errors.push(`Missing closing parenthesis after boolean literal ${token.value}`);
            }
          }
        }
        return literal;
      }
      case "Error":
        this.advanceToken();
        return { kind: "ErrorLiteral", value: token.value };
      case "Identifier":
        return this.parseIdentifierExpression();
      case "StructuredRef":
        return this.parseStructuredReferenceExpression();
      case "ParenOpen":
        return this.parseParenthesizedExpression();
      case "LBrace":
        return this.parseArrayLiteral();
      default:
        this.errors.push(`Unexpected token ${token.value}`);
        this.advanceToken();
        return DEFAULT_EXPR;
    }
  }
  parseParenthesizedExpression() {
    this.matchToken("ParenOpen");
    const expr = this.parseExpression(0, ["ParenClose"]);
    if (!this.matchToken("ParenClose")) {
      this.errors.push("Missing closing parenthesis");
    }
    return expr;
  }
  parseArrayLiteral() {
    this.matchToken("LBrace");
    const rows = [];
    let currentRow = [];
    while (!this.isAtEnd()) {
      const next = this.peekNonWhitespace();
      if (!next) {
        break;
      }
      if (next.type === "RBrace") {
        this.matchToken("RBrace");
        rows.push(currentRow);
        return { kind: "ArrayLiteral", elements: rows };
      }
      const expr = this.parseExpression(0, ["Comma", "Semicolon", "RBrace"]);
      currentRow.push(expr);
      const delimiter = this.peekNonWhitespace();
      if (!delimiter) {
        break;
      }
      if (delimiter.type === "Comma") {
        this.matchToken("Comma");
        continue;
      }
      if (delimiter.type === "Semicolon") {
        this.matchToken("Semicolon");
        rows.push(currentRow);
        currentRow = [];
        continue;
      }
      if (delimiter.type === "RBrace") {
        this.matchToken("RBrace");
        rows.push(currentRow);
        return { kind: "ArrayLiteral", elements: rows };
      }
      this.errors.push(`Unexpected token ${delimiter.value} in array literal`);
      this.advanceToken();
    }
    this.errors.push("Unterminated array literal");
    return { kind: "ArrayLiteral", elements: rows };
  }
  parseIdentifierExpression() {
    const nameToken = this.consumeToken("Identifier");
    if (!nameToken) {
      return DEFAULT_EXPR;
    }
    const next = this.peekNonWhitespace();
    if (next?.type === "Bang") {
      return this.parseSheetQualifiedReference(nameToken.value);
    }
    if (next?.type === "ParenOpen") {
      return this.parseFunctionCall(nameToken.value);
    }
    if (next?.type === "StructuredRef") {
      return this.parseStructuredReferenceExpression(nameToken.value);
    }
    return this.createRangeRefFromIdentifier(nameToken.value);
  }
  parseStructuredReferenceExpression(tableName) {
    const token = this.consumeToken("StructuredRef");
    if (!token) {
      return DEFAULT_EXPR;
    }
    const reference = parseStructuredReference(token.value, tableName);
    if (!reference) {
      const prefix = tableName ? `${tableName}` : "";
      this.errors.push(`Invalid structured reference ${prefix}${token.value}`);
      return DEFAULT_EXPR;
    }
    return {
      kind: "RangeRef",
      ref: { kind: "Structured", reference }
    };
  }
  parseSheetQualifiedReference(sheetName) {
    const normalizedSheet = sheetName.replace(/!+$/, "");
    if (!this.matchToken("Bang")) {
      this.errors.push(`Expected '!' after sheet name ${sheetName}`);
      return DEFAULT_EXPR;
    }
    const sheet = { sheetName: normalizedSheet };
    const next = this.peekNonWhitespace();
    if (!next) {
      this.errors.push(`Missing reference after '${sheetName}!'`);
      return DEFAULT_EXPR;
    }
    if (next.type === "Identifier") {
      const ident = this.consumeToken("Identifier");
      if (!ident) {
        return DEFAULT_EXPR;
      }
      return this.createRangeRefFromIdentifier(ident.value, sheet);
    }
    if (next.type === "Number") {
      const numToken = this.consumeToken("Number");
      if (!numToken) {
        return DEFAULT_EXPR;
      }
      const row2 = Number(numToken.value);
      if (Number.isInteger(row2) && row2 > 0) {
        return {
          kind: "RangeRef",
          ref: { kind: "WholeRow", sheet, row: row2 }
        };
      }
    }
    if (next.type === "Error") {
      const errorToken = this.consumeToken("Error");
      if (!errorToken) {
        return DEFAULT_EXPR;
      }
      return {
        kind: "RangeRef",
        ref: { kind: "Named", name: errorToken.value, sheet }
      };
    }
    this.errors.push(`Unsupported sheet-qualified reference near ${sheetName}!${next.value}`);
    this.advanceToken();
    return DEFAULT_EXPR;
  }
  parseFunctionCall(name) {
    const normalized = name.toUpperCase();
    this.matchToken("ParenOpen");
    const args2 = [];
    const nextToken = this.peekNonWhitespace();
    if (nextToken?.type === "ParenClose") {
      this.matchToken("ParenClose");
      return { kind: "FunctionCall", name: normalized, args: args2 };
    }
    let closed = false;
    let expectArgument = true;
    while (!this.isAtEnd()) {
      const next = this.peekNonWhitespace();
      if (!next) {
        break;
      }
      if (next.type === "ParenClose") {
        if (expectArgument && args2.length > 0) {
          args2.push({ kind: "MissingArg" });
        }
        this.matchToken("ParenClose");
        closed = true;
        break;
      }
      if (next.type === "Comma") {
        if (expectArgument) {
          args2.push({ kind: "MissingArg" });
        }
        this.matchToken("Comma");
        expectArgument = true;
        continue;
      }
      const expr = this.parseExpression(0, ["Comma", "ParenClose"]);
      args2.push(expr);
      expectArgument = false;
      const delimiter = this.peekNonWhitespace();
      if (delimiter?.type === "Comma") {
        this.matchToken("Comma");
        expectArgument = true;
        continue;
      }
      if (delimiter?.type === "ParenClose") {
        this.matchToken("ParenClose");
        closed = true;
        break;
      }
      if (!delimiter) {
        break;
      }
      this.errors.push(`Unexpected token ${delimiter.value} in function arguments`);
      this.advanceToken();
    }
    if (!closed) {
      this.errors.push(`Missing closing parenthesis for function ${normalized}`);
    }
    return { kind: "FunctionCall", name: normalized, args: args2 };
  }
  createRangeRefFromIdentifier(value, sheet) {
    const normalized = value.trim();
    const cell = parseCellAddress2(normalized, sheet);
    if (cell) {
      return { kind: "RangeRef", ref: { kind: "Cell", addr: cell } };
    }
    return {
      kind: "RangeRef",
      ref: { kind: "Named", name: normalized, sheet }
    };
  }
  buildBinaryExpr(left, operator, right) {
    if (operator === ":") {
      const range2 = this.combineRange(left, right);
      if (range2) {
        return { kind: "RangeRef", ref: range2 };
      }
    }
    return { kind: "BinaryOp", op: operator, left, right };
  }
  combineRange(left, right) {
    const leftRef = this.exprToRangeRef(left, true);
    const rightRef = this.exprToRangeRef(right, true);
    if (!leftRef || !rightRef) {
      return null;
    }
    if (leftRef.kind === "Cell" && rightRef.kind === "Cell") {
      const leftSheetName = leftRef.addr.sheet?.sheetName;
      const rightSheetName = rightRef.addr.sheet?.sheetName;
      if (leftSheetName && rightSheetName && leftSheetName !== rightSheetName) {
        return null;
      }
      const sharedSheet = leftRef.addr.sheet ?? rightRef.addr.sheet;
      const start = normalizeCellSheet(leftRef.addr, sharedSheet);
      const end = normalizeCellSheet(rightRef.addr, sharedSheet ?? rightRef.addr.sheet);
      if (!start.sheet && end.sheet) {
        start.sheet = { ...end.sheet };
      }
      if (!end.sheet && start.sheet) {
        end.sheet = { ...start.sheet };
      }
      return { kind: "Range", start, end };
    }
    if (leftRef.kind === "WholeColumn" && rightRef.kind === "WholeColumn" && sheetsMatch(leftRef.sheet, rightRef.sheet)) {
      const sheet = leftRef.sheet && leftRef.sheet.sheetName ? { ...leftRef.sheet } : rightRef.sheet && rightRef.sheet.sheetName ? { ...rightRef.sheet } : undefined;
      if (leftRef.col === rightRef.col) {
        return {
          kind: "WholeColumn",
          sheet,
          col: leftRef.col
        };
      }
      const startCol = Math.min(leftRef.col, rightRef.col);
      const endCol = Math.max(leftRef.col, rightRef.col);
      return {
        kind: "ColumnRange",
        sheet,
        startCol,
        endCol
      };
    }
    if (leftRef.kind === "WholeRow" && rightRef.kind === "WholeRow" && leftRef.row === rightRef.row && sheetsMatch(leftRef.sheet, rightRef.sheet)) {
      return {
        kind: "WholeRow",
        sheet: leftRef.sheet ? { ...leftRef.sheet } : rightRef.sheet ? { ...rightRef.sheet } : undefined,
        row: leftRef.row
      };
    }
    return null;
  }
  exprToRangeRef(expr, allowColumnFallback = false) {
    if (expr.kind === "RangeRef") {
      if (allowColumnFallback && expr.ref.kind === "Named") {
        const column2 = parseColumnReference(expr.ref.name, expr.ref.sheet);
        if (column2) {
          return column2;
        }
      }
      return expr.ref;
    }
    if (expr.kind === "NumberLiteral" && Number.isInteger(expr.value) && expr.value > 0) {
      return { kind: "WholeRow", row: expr.value, sheet: undefined };
    }
    return null;
  }
  getBinaryOperatorInfo(token, stopTokens) {
    if (token.type === "Comma" && !stopTokens.includes("Comma")) {
      return {
        operator: ",",
        precedence: BINARY_PRECEDENCE[","] ?? 0,
        rightAssociative: false
      };
    }
    if (token.type === "Colon") {
      return {
        operator: ":",
        precedence: BINARY_PRECEDENCE[":"] ?? 0,
        rightAssociative: false
      };
    }
    if (token.type === "Operator") {
      const precedence = BINARY_PRECEDENCE[token.value];
      if (precedence === undefined) {
        return null;
      }
      return {
        operator: token.value,
        precedence,
        rightAssociative: RIGHT_ASSOCIATIVE.has(token.value)
      };
    }
    return null;
  }
  consumeToken(expected) {
    const token = this.peekToken();
    if (!token || token.type !== expected) {
      this.errors.push(`Expected token ${expected} but found ${token ? token.value : "EOF"}`);
      return null;
    }
    this.index += 1;
    return token;
  }
  matchToken(expected) {
    const token = this.peekToken();
    if (token?.type === expected) {
      this.index += 1;
      return true;
    }
    return false;
  }
  peekToken() {
    this.skipWhitespace();
    return this.tokens[this.index] ?? null;
  }
  peekNonWhitespace() {
    this.skipWhitespace();
    return this.tokens[this.index] ?? null;
  }
  advanceToken() {
    this.skipWhitespace();
    if (!this.isAtEnd()) {
      this.index += 1;
    }
  }
  isAtEnd() {
    return this.index >= this.tokens.length;
  }
  skipWhitespace() {
    while (!this.isAtEnd() && this.tokens[this.index]?.type === "Whitespace") {
      this.index += 1;
    }
  }
}
function parseFormula(formula) {
  const tokens = tokenizeFormula(formula);
  const parser = new Parser(tokens);
  const expr = parser.parse();
  return { expr, errors: parser.errors };
}
function parseStructuredReference(raw, tableName) {
  if (!raw.startsWith("[") || !raw.endsWith("]")) {
    return null;
  }
  const parts = splitStructuredReferenceParts(raw);
  if (parts.length === 0) {
    return null;
  }
  if (parts.length === 1 && parts[0]?.trim() === "") {
    return {
      tableName: tableName?.trim() || undefined,
      section: "All"
    };
  }
  let section = null;
  let columnName;
  for (const part of parts) {
    const trimmed = part.trim();
    if (!trimmed) {
      return null;
    }
    const currentRowMatch = /^@(.+)$/.exec(trimmed);
    if (currentRowMatch) {
      if (section !== null) {
        return null;
      }
      const currentRowColumn = currentRowMatch[1]?.trim();
      if (!currentRowColumn) {
        return null;
      }
      section = "ThisRow";
      columnName = currentRowColumn;
      continue;
    }
    const normalized = trimmed.toUpperCase();
    const parsedSection = parseStructuredReferenceSection(normalized);
    if (parsedSection) {
      if (section !== null) {
        return null;
      }
      section = parsedSection;
      continue;
    }
    if (columnName !== undefined) {
      return null;
    }
    columnName = trimmed;
  }
  if (section === null) {
    section = "Data";
  }
  return {
    tableName: tableName?.trim() || undefined,
    section,
    columnName
  };
}
function parseCellAddress2(value, sheet) {
  const match = CELL_REF_REGEX.exec(value);
  if (!match) {
    return null;
  }
  const absColToken = match[1] ?? "";
  const colLabel = match[2];
  const absRowToken = match[3] ?? "";
  const rowText = match[4];
  if (!colLabel || !rowText) {
    return null;
  }
  const col = columnLabelToNumber(colLabel);
  if (!col) {
    return null;
  }
  const row2 = Number(rowText);
  return {
    sheet: sheet ? { ...sheet } : undefined,
    row: row2,
    col,
    absRow: absRowToken === "$",
    absCol: absColToken === "$"
  };
}
function parseColumnReference(value, sheet) {
  const match = COLUMN_ONLY_REGEX.exec(value);
  if (!match) {
    return null;
  }
  const label = match[2];
  if (!label) {
    return null;
  }
  const col = columnLabelToNumber(label);
  if (!col || col > MAX_COLUMN) {
    return null;
  }
  return { kind: "WholeColumn", sheet: sheet ? { ...sheet } : undefined, col };
}
function normalizeCellSheet(addr, sheet) {
  const cloned = cloneCellAddress(addr);
  if (sheet && !cloned.sheet) {
    cloned.sheet = { ...sheet };
  }
  return cloned;
}
function sheetsMatch(a, b) {
  if (!a || !a.sheetName) {
    return true;
  }
  if (!b || !b.sheetName) {
    return true;
  }
  return a.sheetName === b.sheetName;
}
function columnLabelToNumber(label) {
  const upper = label.toUpperCase();
  let result = 0;
  for (let i = 0;i < upper.length; i += 1) {
    const code = upper.charCodeAt(i);
    if (code < 65 || code > 90) {
      return 0;
    }
    result = result * 26 + (code - 64);
  }
  return result;
}
function columnNumberToLabel(col) {
  if (col <= 0) {
    return "";
  }
  let n = col;
  let label = "";
  while (n > 0) {
    n -= 1;
    label = String.fromCharCode(65 + n % 26) + label;
    n = Math.floor(n / 26);
  }
  return label;
}
function cloneCellAddress(addr) {
  return {
    sheet: addr.sheet ? { ...addr.sheet } : undefined,
    row: addr.row,
    col: addr.col,
    absRow: addr.absRow,
    absCol: addr.absCol
  };
}
function splitStructuredReferenceParts(raw) {
  if (raw.startsWith("[[") && raw.endsWith("]]")) {
    const inner = raw.slice(2, -2);
    return inner.split(/\]\s*,\s*\[/);
  }
  return [raw.slice(1, -1)];
}
function parseStructuredReferenceSection(value) {
  switch (value) {
    case "#ALL":
      return "All";
    case "#DATA":
      return "Data";
    case "#HEADERS":
      return "Headers";
    case "#TOTALS":
      return "Totals";
    case "#THIS ROW":
      return "ThisRow";
    default:
      return null;
  }
}

// node_modules/@oai/granola/dist/models/range/fill-from.js
function fillRangeFrom(args2) {
  const direction = resolveFillFromDirection(args2.sourceBounds, args2.destinationBounds);
  if (direction === "none") {
    return null;
  }
  if (!direction) {
    throw new Error(`Range.fillFrom requires destination to extend source in exactly one direction while sharing the other axis. ` + `Source is ${args2.sourceRangeAddress || "(unnamed range)"}, destination is ${args2.destinationRangeAddress || "(unnamed range)"}.`);
  }
  const valueMatrix = [];
  for (let r = 0;r < args2.destinationBounds.rows; r += 1) {
    const valueRow = [];
    const destinationRow = args2.destinationBounds.startRow + r;
    for (let c = 0;c < args2.destinationBounds.cols; c += 1) {
      const destinationCol = args2.destinationBounds.startCol + c;
      const sourceCellPosition = isCellInBounds(destinationRow, destinationCol, args2.sourceBounds) ? { row: destinationRow, col: destinationCol } : resolveFillSourceCell({
        destinationCol,
        destinationRow,
        direction,
        sourceBounds: args2.sourceBounds
      });
      const sourceCell = args2.readSourceCell(sourceCellPosition.row, sourceCellPosition.col);
      const sourceFormula = sourceCell?.formula;
      const isSourceCell = isCellInBounds(destinationRow, destinationCol, args2.sourceBounds);
      if (sourceFormula && sourceFormula.trim()) {
        const shiftedFormula = args2.shiftFormulaRefs(sourceFormula, destinationRow - sourceCellPosition.row, destinationCol - sourceCellPosition.col);
        if (!isSourceCell) {
          args2.writeFormulaCell(destinationRow, destinationCol, shiftedFormula);
        }
        if (args2.shouldCollectValues) {
          valueRow.push(`=${shiftedFormula}`);
        }
        continue;
      }
      if (sourceCell?.value !== undefined) {
        if (!isSourceCell) {
          args2.writeValueCell(destinationRow, destinationCol, sourceCell);
        }
        if (args2.shouldCollectValues) {
          valueRow.push(args2.coerceCellValue(sourceCell));
        }
        continue;
      }
      if (!isSourceCell) {
        args2.clearCell(destinationRow, destinationCol);
      }
      if (args2.shouldCollectValues) {
        valueRow.push(null);
      }
    }
    if (args2.shouldCollectValues) {
      valueMatrix.push(valueRow);
    }
  }
  return args2.shouldCollectValues ? valueMatrix : null;
}
function getBoundsEndRow(bounds) {
  return bounds.startRow + bounds.rows - 1;
}
function getBoundsEndCol(bounds) {
  return bounds.startCol + bounds.cols - 1;
}
function isCellInBounds(row2, col, bounds) {
  return row2 >= bounds.startRow && row2 <= getBoundsEndRow(bounds) && col >= bounds.startCol && col <= getBoundsEndCol(bounds);
}
function resolveFillFromDirection(sourceBounds, destinationBounds) {
  const sourceEndRow = getBoundsEndRow(sourceBounds);
  const sourceEndCol = getBoundsEndCol(sourceBounds);
  const destinationEndRow = getBoundsEndRow(destinationBounds);
  const destinationEndCol = getBoundsEndCol(destinationBounds);
  const sameColumnSpan = destinationBounds.startCol === sourceBounds.startCol && destinationEndCol === sourceEndCol;
  const sameRowSpan = destinationBounds.startRow === sourceBounds.startRow && destinationEndRow === sourceEndRow;
  if (sameColumnSpan && destinationBounds.startRow === sourceBounds.startRow && destinationEndRow >= sourceEndRow) {
    return destinationEndRow === sourceEndRow ? "none" : "down";
  }
  if (sameColumnSpan && destinationEndRow === sourceEndRow && destinationBounds.startRow <= sourceBounds.startRow) {
    return destinationBounds.startRow === sourceBounds.startRow ? "none" : "up";
  }
  if (sameRowSpan && destinationBounds.startCol === sourceBounds.startCol && destinationEndCol >= sourceEndCol) {
    return destinationEndCol === sourceEndCol ? "none" : "right";
  }
  if (sameRowSpan && destinationEndCol === sourceEndCol && destinationBounds.startCol <= sourceBounds.startCol) {
    return destinationBounds.startCol === sourceBounds.startCol ? "none" : "left";
  }
  return null;
}
function resolveFillSourceCell(args2) {
  const sourceEndRow = getBoundsEndRow(args2.sourceBounds);
  const sourceEndCol = getBoundsEndCol(args2.sourceBounds);
  if (args2.direction === "down") {
    return {
      row: args2.sourceBounds.startRow + (args2.destinationRow - sourceEndRow - 1) % args2.sourceBounds.rows,
      col: args2.destinationCol
    };
  }
  if (args2.direction === "up") {
    return {
      row: args2.sourceBounds.startRow + (args2.sourceBounds.startRow - args2.destinationRow - 1) % args2.sourceBounds.rows,
      col: args2.destinationCol
    };
  }
  if (args2.direction === "right") {
    return {
      row: args2.destinationRow,
      col: args2.sourceBounds.startCol + (args2.destinationCol - sourceEndCol - 1) % args2.sourceBounds.cols
    };
  }
  return {
    row: args2.destinationRow,
    col: args2.sourceBounds.startCol + (args2.sourceBounds.startCol - args2.destinationCol - 1) % args2.sourceBounds.cols
  };
}

// node_modules/@oai/granola/dist/models/range.js
var RANGE_WORKSHEET = new WeakMap;
var isGranolaDataValidationAssignment = (value) => {
  if (!value || typeof value !== "object") {
    return false;
  }
  const prompt = value.prompt;
  return "rule" in value || "errorAlert" in value || "ignoreBlanks" in value || "inCellDropDown" in value || prompt !== undefined && typeof prompt === "object" && prompt !== null;
};
function serializeCellValue(value) {
  if (value instanceof Date) {
    return value.toISOString();
  }
  return value ?? null;
}
var EXCEL_EPOCH_MS = Date.UTC(1899, 11, 30);
var MS_PER_DAY = 24 * 60 * 60 * 1000;
var ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
function coerceExcelSerialToDate(value) {
  if (value instanceof Date) {
    return value;
  }
  if (typeof value === "string") {
    const parsed = Number(value);
    if (!Number.isFinite(parsed)) {
      return null;
    }
    return new Date(EXCEL_EPOCH_MS + parsed * MS_PER_DAY);
  }
  if (typeof value === "number" && Number.isFinite(value)) {
    return new Date(EXCEL_EPOCH_MS + value * MS_PER_DAY);
  }
  return null;
}

class Range {
  #address;
  #format;
  #formulas;
  #formulasR1C1;
  #values;
  #rawValues;
  #worksheet;
  #conditionalFormats;
  #dataValidation;
  #sparklinesProxy;
  constructor(options = {}) {
    this.#address = options.address;
    this.#format = options.format ?? new RangeFormat(this.#buildFormatContext());
    this.#worksheet = options.worksheet;
    RANGE_WORKSHEET.set(this, options.worksheet);
  }
  get address() {
    return this.#address ?? "";
  }
  getAddress() {
    return this.address;
  }
  write(value, options = {}) {
    const bounds = this.#bounds();
    const worksheet = this.#worksheet;
    if (!bounds || !worksheet) {
      throw new Error("Range.write requires a range attached to a worksheet.");
    }
    const resize = options.resize ?? "auto";
    const overwrite = options.overwrite ?? "allow";
    if (value !== null && typeof value === "object" && !Array.isArray(value)) {
      const payload = value;
      const keys2 = [
        payload.values !== undefined ? "values" : null,
        payload.formulas !== undefined ? "formulas" : null,
        payload.formulasR1C1 !== undefined ? "formulasR1C1" : null
      ].filter((k) => k !== null);
      if (keys2.length === 0) {
        throw new Error("Range.write(payload) expects one of: { values }, { formulas }, { formulasR1C1 }.");
      }
      if (keys2.length > 1) {
        throw new Error(`Range.write(payload) expects exactly one field; got ${keys2.join(", ")}.`);
      }
      const kind = keys2[0];
      if (kind === "values") {
        return this.write(payload.values ?? null, options);
      }
      const matrixLike = payload[kind];
      const normalizedInput2 = Array.isArray(matrixLike) && (matrixLike.length === 0 || !Array.isArray(matrixLike[0])) ? [matrixLike] : matrixLike;
      const rows2 = normalizedInput2.length;
      const cols2 = normalizedInput2.reduce((max4, row2) => Math.max(max4, Array.isArray(row2) ? row2.length : 0), 0);
      if (rows2 <= 0 || cols2 <= 0) {
        throw new Error("Range.write expects a non-empty 2D matrix.");
      }
      const target2 = resize === "none" ? this : worksheet.getRange(buildRangeRef({
        startRow: bounds.startRow,
        startCol: bounds.startCol,
        endRow: bounds.startRow + rows2 - 1,
        endCol: bounds.startCol + cols2 - 1
      }));
      if (options.clear) {
        target2.clear({ applyTo: options.clear });
      }
      if (overwrite === "error") {
        const overwriteSamples = target2.#collectOverwriteSamplesInTarget({
          worksheet,
          bounds: target2.#bounds()
        });
        if (overwriteSamples.length > 0) {
          const sheetPrefix = worksheet.name ? `${worksheet.name}!` : "";
          const sampleList = overwriteSamples.map((sample) => `${sheetPrefix}${sample}`).join(", ");
          throw new Error(`Range.write would overwrite existing values in ${sampleList}. ` + "Pass overwrite: 'allow' to proceed.");
        }
      }
      if (kind === "formulas") {
        target2.formulas = normalizedInput2;
      } else {
        target2.formulasR1C1 = normalizedInput2;
      }
      return target2;
    }
    if (value === null) {
      const applyTo = options.clear ?? "contents";
      if (resize === "none") {
        this.clear({ applyTo });
        return this;
      }
      this.clear({ applyTo });
      return this;
    }
    const normalizedInput = Array.isArray(value) && (value.length === 0 || !Array.isArray(value[0])) ? [value] : value;
    const rows = normalizedInput.length;
    const cols = normalizedInput.reduce((max4, row2) => Math.max(max4, Array.isArray(row2) ? row2.length : 0), 0);
    if (rows <= 0 || cols <= 0) {
      throw new Error("Range.write expects a non-empty 2D matrix.");
    }
    const target = resize === "none" ? this : worksheet.getRange(buildRangeRef({
      startRow: bounds.startRow,
      startCol: bounds.startCol,
      endRow: bounds.startRow + rows - 1,
      endCol: bounds.startCol + cols - 1
    }));
    if (options.clear) {
      target.clear({ applyTo: options.clear });
    }
    if (overwrite === "error") {
      const overwriteSamples = target.#collectOverwriteSamplesInTarget({
        worksheet,
        bounds: target.#bounds()
      });
      if (overwriteSamples.length > 0) {
        const sheetPrefix = worksheet.name ? `${worksheet.name}!` : "";
        const sampleList = overwriteSamples.map((sample) => `${sheetPrefix}${sample}`).join(", ");
        throw new Error(`Range.write would overwrite existing values in ${sampleList}. ` + "Pass overwrite: 'allow' to proceed.");
      }
    }
    target.values = normalizedInput;
    return target;
  }
  get rowCount() {
    const bounds = this.#bounds();
    if (!bounds) {
      throw new Error("Range is not attached to a worksheet.");
    }
    return bounds.rows;
  }
  getRowCount() {
    return this.rowCount;
  }
  get columnCount() {
    const bounds = this.#bounds();
    if (!bounds) {
      throw new Error("Range is not attached to a worksheet.");
    }
    return bounds.cols;
  }
  getColumnCount() {
    return this.columnCount;
  }
  get format() {
    return this.#format;
  }
  set format(value) {
    if (value instanceof RangeFormat) {
      return;
    }
    if (!value || typeof value !== "object") {
      throw new Error("Range.format setter requires a config object.");
    }
    const config = value;
    if ("fill" in config) {
      this.#format.fill = config.fill;
    }
    if ("font" in config && config.font) {
      this.#format.font = config.font;
    }
    if ("borders" in config && config.borders) {
      this.#format.borders = config.borders;
    }
    if ("numberFormat" in config && config.numberFormat !== undefined) {
      this.#format.numberFormat = config.numberFormat;
    }
    if ("wrapText" in config && config.wrapText !== undefined) {
      this.#format.wrapText = Boolean(config.wrapText);
    }
    if ("horizontalAlignment" in config && config.horizontalAlignment !== undefined) {
      this.#format.horizontalAlignment = config.horizontalAlignment;
    }
    if ("verticalAlignment" in config && config.verticalAlignment !== undefined) {
      this.#format.verticalAlignment = config.verticalAlignment;
    }
    if ("rowHeightPx" in config && config.rowHeightPx !== undefined) {
      this.#format.rowHeightPx = config.rowHeightPx;
    } else if ("rowHeight" in config && config.rowHeight !== undefined) {
      this.#format.rowHeight = config.rowHeight;
    }
    if ("columnWidthPx" in config && config.columnWidthPx !== undefined) {
      this.#format.columnWidthPx = config.columnWidthPx;
    } else if ("columnWidth" in config && config.columnWidth !== undefined) {
      this.#format.columnWidth = config.columnWidth;
    }
  }
  get rowIndex() {
    const bounds = this.#bounds();
    if (!bounds) {
      throw new Error("Range is not attached to a worksheet.");
    }
    return bounds.startRow;
  }
  get columnIndex() {
    const bounds = this.#bounds();
    if (!bounds) {
      throw new Error("Range is not attached to a worksheet.");
    }
    return bounds.startCol;
  }
  getRowIndex() {
    return this.rowIndex;
  }
  getColumnIndex() {
    return this.columnIndex;
  }
  getRange(address) {
    if (typeof address !== "string") {
      throw new Error("Range.getRange(address) requires an A1 string address.");
    }
    const worksheet = getRangeWorksheet(this);
    if (!worksheet) {
      throw new Error("Range is not attached to a worksheet.");
    }
    return worksheet.getRange(address);
  }
  setNumberFormat(formatCode) {
    this.format.numberFormat = formatCode;
  }
  get sparklines() {
    this.#sparklinesProxy ??= new RangeSparklinesProxy(this);
    return this.#sparklinesProxy;
  }
  get conditionalFormats() {
    if (!this.#conditionalFormats) {
      this.#conditionalFormats = new RangeConditionalFormats(this);
    }
    return this.#conditionalFormats;
  }
  get dataValidation() {
    if (!this.#dataValidation) {
      this.#dataValidation = new RangeDataValidation(this);
    }
    return this.#dataValidation;
  }
  set dataValidation(value) {
    if (value instanceof RangeDataValidation) {
      return;
    }
    if (value == null) {
      this.dataValidation.clear();
      return;
    }
    const validation = this.dataValidation;
    if (isGranolaDataValidationAssignment(value)) {
      if ("rule" in value && value.rule !== undefined) {
        validation.rule = value.rule;
      }
      if ("prompt" in value && value.prompt !== undefined) {
        validation.prompt = value.prompt;
      }
      if ("errorAlert" in value && value.errorAlert !== undefined) {
        validation.errorAlert = value.errorAlert;
      }
      if ("ignoreBlanks" in value && value.ignoreBlanks !== undefined) {
        validation.ignoreBlanks = value.ignoreBlanks;
      }
      if ("inCellDropDown" in value && value.inCellDropDown !== undefined) {
        validation.inCellDropDown = value.inCellDropDown;
      }
      return;
    }
    if (value.allowBlank !== undefined) {
      validation.ignoreBlanks = value.allowBlank;
    }
    if (value.list) {
      if (value.list.inCellDropDown !== undefined) {
        validation.inCellDropDown = value.list.inCellDropDown;
      }
      if (value.list.source !== undefined) {
        validation.rule = Array.isArray(value.list.source) ? { type: "list", values: value.list.source } : { type: "list", formula1: value.list.source };
      } else {
        validation.rule = { type: "list" };
      }
    }
    const hasPrompt2 = value.promptTitle !== undefined || value.prompt !== undefined || value.showInputMessage !== undefined;
    if (hasPrompt2) {
      validation.prompt = {
        title: value.promptTitle,
        message: value.prompt,
        show: value.showInputMessage
      };
    }
    const hasError = value.errorTitle !== undefined || value.errorMessage !== undefined || value.showErrorMessage !== undefined || value.errorStyle !== undefined;
    if (hasError) {
      validation.errorAlert = {
        title: value.errorTitle,
        message: value.errorMessage,
        show: value.showErrorMessage,
        style: value.errorStyle
      };
    }
  }
  getCell(row2, column2) {
    if (!Number.isFinite(row2) || !Number.isFinite(column2)) {
      throw new Error("Range.getCell(row, column) requires numeric arguments.");
    }
    if (!Number.isInteger(row2) || !Number.isInteger(column2)) {
      throw new Error("Range.getCell(row, column) requires integer arguments.");
    }
    if (row2 < 0 || column2 < 0) {
      throw new Error("Range.getCell(row, column) requires non-negative indexes.");
    }
    const worksheet = getRangeWorksheet(this);
    if (!worksheet) {
      throw new Error("Range is not attached to a worksheet.");
    }
    const bounds = this.#bounds();
    if (!bounds) {
      throw new Error("Range is not attached to a worksheet.");
    }
    const targetRow = bounds.startRow + row2;
    const targetCol = bounds.startCol + column2;
    const endRow = bounds.startRow + bounds.rows - 1;
    const endCol = bounds.startCol + bounds.cols - 1;
    if (targetRow > endRow || targetCol > endCol) {
      const address = this.address || "range";
      throw new Error(`Range.getCell(${row2}, ${column2}) is outside the bounds of ${address}.`);
    }
    return worksheet.getRangeByIndexes(targetRow, targetCol, 1, 1);
  }
  getRow(rowOffset) {
    if (!Number.isFinite(rowOffset)) {
      throw new Error("Range.getRow(rowOffset) requires a numeric argument.");
    }
    if (!Number.isInteger(rowOffset)) {
      throw new Error("Range.getRow(rowOffset) requires an integer offset.");
    }
    if (rowOffset < 0) {
      throw new Error("Range.getRow(rowOffset) requires a non-negative offset.");
    }
    const worksheet = getRangeWorksheet(this);
    if (!worksheet) {
      throw new Error("Range is not attached to a worksheet.");
    }
    const bounds = this.#bounds();
    if (!bounds) {
      throw new Error("Range is not attached to a worksheet.");
    }
    const targetRow = bounds.startRow + rowOffset;
    const endRow = bounds.startRow + bounds.rows - 1;
    if (targetRow > endRow) {
      const address2 = this.address || "range";
      throw new Error(`Range.getRow(${rowOffset}) is outside the bounds of ${address2}.`);
    }
    const address = buildRangeRef({
      startRow: targetRow,
      endRow: targetRow,
      startCol: bounds.startCol,
      endCol: bounds.startCol + bounds.cols - 1
    });
    return worksheet.getRange(address);
  }
  getColumn(columnOffset) {
    if (!Number.isFinite(columnOffset)) {
      throw new Error("Range.getColumn(columnOffset) requires a numeric argument.");
    }
    if (!Number.isInteger(columnOffset)) {
      throw new Error("Range.getColumn(columnOffset) requires an integer offset.");
    }
    if (columnOffset < 0) {
      throw new Error("Range.getColumn(columnOffset) requires a non-negative offset.");
    }
    const worksheet = getRangeWorksheet(this);
    if (!worksheet) {
      throw new Error("Range is not attached to a worksheet.");
    }
    const bounds = this.#bounds();
    if (!bounds) {
      throw new Error("Range is not attached to a worksheet.");
    }
    const targetCol = bounds.startCol + columnOffset;
    const endCol = bounds.startCol + bounds.cols - 1;
    if (targetCol > endCol) {
      const address2 = this.address || "range";
      throw new Error(`Range.getColumn(${columnOffset}) is outside the bounds of ${address2}.`);
    }
    const address = buildRangeRef({
      startRow: bounds.startRow,
      endRow: bounds.startRow + bounds.rows - 1,
      startCol: targetCol,
      endCol: targetCol
    });
    return worksheet.getRange(address);
  }
  getRangeByIndexes(rowOffset, columnOffset, rowCount, columnCount) {
    for (const [name, value] of [
      ["rowOffset", rowOffset],
      ["columnOffset", columnOffset],
      ["rowCount", rowCount],
      ["columnCount", columnCount]
    ]) {
      if (!Number.isFinite(value) || !Number.isInteger(value)) {
        throw new Error(`Range.getRangeByIndexes ${name} must be an integer.`);
      }
    }
    if (rowOffset < 0 || columnOffset < 0) {
      throw new Error("Range.getRangeByIndexes requires non-negative row and column offsets.");
    }
    if (rowCount <= 0 || columnCount <= 0) {
      throw new Error("Range.getRangeByIndexes requires positive row and column counts.");
    }
    const worksheet = getRangeWorksheet(this);
    if (!worksheet) {
      throw new Error("Range is not attached to a worksheet.");
    }
    const bounds = this.#bounds();
    if (!bounds) {
      throw new Error("Range is not attached to a worksheet.");
    }
    const startRow = bounds.startRow + rowOffset;
    const startCol = bounds.startCol + columnOffset;
    const endRow = startRow + rowCount - 1;
    const endCol = startCol + columnCount - 1;
    const maxRow = bounds.startRow + bounds.rows - 1;
    const maxCol = bounds.startCol + bounds.cols - 1;
    if (startRow > maxRow || startCol > maxCol || endRow > maxRow || endCol > maxCol) {
      const address2 = this.address || "range";
      throw new Error(`Range.getRangeByIndexes(${rowOffset}, ${columnOffset}, ${rowCount}, ${columnCount}) is outside the bounds of ${address2}.`);
    }
    const address = buildRangeRef({ startRow, startCol, endRow, endCol });
    return worksheet.getRange(address);
  }
  getOffsetRange(rowOffset, columnOffset, rowCount, columnCount) {
    for (const [name, value] of [
      ["rowOffset", rowOffset],
      ["columnOffset", columnOffset]
    ]) {
      if (!Number.isFinite(value) || !Number.isInteger(value)) {
        throw new Error(`Range.getOffsetRange ${name} must be an integer.`);
      }
    }
    if (rowCount !== undefined && (!Number.isFinite(rowCount) || !Number.isInteger(rowCount))) {
      throw new Error("Range.getOffsetRange rowCount must be an integer.");
    }
    if (columnCount !== undefined && (!Number.isFinite(columnCount) || !Number.isInteger(columnCount))) {
      throw new Error("Range.getOffsetRange columnCount must be an integer.");
    }
    const worksheet = getRangeWorksheet(this);
    if (!worksheet) {
      throw new Error("Range is not attached to a worksheet.");
    }
    const bounds = this.#bounds();
    if (!bounds) {
      throw new Error("Range is not attached to a worksheet.");
    }
    const effectiveRowCount = rowCount ?? bounds.rows;
    const effectiveColCount = columnCount ?? bounds.cols;
    if (effectiveRowCount <= 0 || effectiveColCount <= 0) {
      throw new Error("Range.getOffsetRange requires positive row/column counts.");
    }
    const startRow = bounds.startRow + rowOffset;
    const startCol = bounds.startCol + columnOffset;
    if (startRow < 0 || startCol < 0) {
      throw new Error("Range.getOffsetRange would start outside the worksheet.");
    }
    const endRow = startRow + effectiveRowCount - 1;
    const endCol = startCol + effectiveColCount - 1;
    const address = buildRangeRef({ startRow, startCol, endRow, endCol });
    return worksheet.getRange(address);
  }
  getResizedRange(deltaRows, deltaColumns) {
    for (const [name, value] of [
      ["deltaRows", deltaRows],
      ["deltaColumns", deltaColumns]
    ]) {
      if (!Number.isFinite(value) || !Number.isInteger(value)) {
        throw new Error(`Range.getResizedRange ${name} must be an integer.`);
      }
    }
    const bounds = this.#bounds();
    if (!bounds) {
      throw new Error("Range is not attached to a worksheet.");
    }
    const nextRowCount = bounds.rows + deltaRows;
    const nextColCount = bounds.cols + deltaColumns;
    if (nextRowCount <= 0 || nextColCount <= 0) {
      throw new Error("Range.getResizedRange requires resulting row/column counts to be positive.");
    }
    return this.getOffsetRange(0, 0, nextRowCount, nextColCount);
  }
  getResizeRange(rowCount, columnCount) {
    for (const [name, value] of [
      ["rowCount", rowCount],
      ["columnCount", columnCount]
    ]) {
      if (!Number.isFinite(value) || !Number.isInteger(value)) {
        throw new Error(`Range.getResizeRange ${name} must be an integer.`);
      }
    }
    if (rowCount <= 0 || columnCount <= 0) {
      throw new Error("Range.getResizeRange requires positive row/column counts.");
    }
    return this.getOffsetRange(0, 0, rowCount, columnCount);
  }
  offset(rowOffset, columnOffset, rowCount, columnCount) {
    return this.getOffsetRange(rowOffset, columnOffset, rowCount, columnCount);
  }
  resize(rowCount, columnCount) {
    return this.getResizeRange(rowCount, columnCount);
  }
  getCurrentRegion() {
    const worksheet = getRangeWorksheet(this);
    if (!worksheet) {
      throw new Error("Range is not attached to a worksheet.");
    }
    const bounds = this.#bounds();
    if (!bounds) {
      throw new Error("Range is not attached to a worksheet.");
    }
    const anchorRow = bounds.startRow;
    const anchorCol = bounds.startCol;
    if (!this.#cellHasContent(worksheet, anchorRow, anchorCol)) {
      return worksheet.getRangeByIndexes(anchorRow, anchorCol, 1, 1);
    }
    let minRow = anchorRow;
    let maxRow = anchorRow;
    let minCol = anchorCol;
    let maxCol = anchorCol;
    const rowHasContent = (rowIdx) => {
      for (let c = minCol;c <= maxCol; c += 1) {
        if (this.#cellHasContent(worksheet, rowIdx, c)) {
          return true;
        }
      }
      return false;
    };
    const colHasContent = (colIdx) => {
      for (let r = minRow;r <= maxRow; r += 1) {
        if (this.#cellHasContent(worksheet, r, colIdx)) {
          return true;
        }
      }
      return false;
    };
    while (true) {
      let changed = false;
      if (minRow > 0 && rowHasContent(minRow - 1)) {
        minRow -= 1;
        changed = true;
      }
      if (rowHasContent(maxRow + 1)) {
        maxRow += 1;
        changed = true;
      }
      if (minCol > 0 && colHasContent(minCol - 1)) {
        minCol -= 1;
        changed = true;
      }
      if (colHasContent(maxCol + 1)) {
        maxCol += 1;
        changed = true;
      }
      if (!changed) {
        break;
      }
    }
    const address = buildRangeRef({
      startRow: minRow,
      startCol: minCol,
      endRow: maxRow,
      endCol: maxCol
    });
    return worksheet.getRange(address);
  }
  __getWorksheet() {
    return this.#worksheet;
  }
  get formulas() {
    if (this.#worksheet) {
      const matrix = this.#readFormulasFromProto();
      this.#formulas = matrix;
      return matrix;
    }
    return this.#formulas ?? [];
  }
  get formulasR1C1() {
    const bounds = this.#bounds();
    const worksheet = this.#worksheet;
    if (bounds && worksheet) {
      const matrix = [];
      for (let r = 0;r < bounds.rows; r += 1) {
        const rowValues = [];
        for (let c = 0;c < bounds.cols; c += 1) {
          const cell = worksheet.__getCell(bounds.startRow + r, bounds.startCol + c);
          const a1 = cell?.formula ? `=${cell.formula}` : "";
          if (!a1) {
            rowValues.push("");
            continue;
          }
          rowValues.push(convertFormulaA1ToR1C1(a1, bounds.startRow + r + 1, bounds.startCol + c + 1));
        }
        matrix.push(rowValues);
      }
      this.#formulasR1C1 = matrix;
      return matrix;
    }
    return this.#formulasR1C1 ?? [];
  }
  set formulas(value) {
    const resolved = typeof value === "function" ? this.#resolveFormulasCallback(value) : value;
    const bounds = this.#bounds();
    const worksheet = this.#worksheet;
    if (bounds) {
      const normalizedInput = this.#normalizeMatrixInput(resolved, bounds, "formulas");
      const matrixShape = this.#getMatrixShape(normalizedInput, "formulas");
      const isScalarMatrix = !matrixShape.ragged && matrixShape.rows === 1 && matrixShape.cols === 1;
      if (worksheet && bounds.rows === 1 && bounds.cols === 1 && !matrixShape.ragged && (matrixShape.rows !== 1 || matrixShape.cols !== 1)) {
        const spillAddress = buildRangeRef({
          startRow: bounds.startRow,
          startCol: bounds.startCol,
          endRow: bounds.startRow + matrixShape.rows - 1,
          endCol: bounds.startCol + matrixShape.cols - 1
        });
        worksheet.getRange(spillAddress).formulas = normalizedInput;
        return;
      }
      if (worksheet && !isScalarMatrix && !matrixShape.ragged && (matrixShape.rows !== bounds.rows || matrixShape.cols !== bounds.cols)) {
        const wouldShrink = matrixShape.rows < bounds.rows || matrixShape.cols < bounds.cols;
        if (wouldShrink) {
          if (matrixShape.rows > 0 && matrixShape.cols > 0) {
            const shrinkAddress = this.#buildSpillRef(bounds, matrixShape.rows, matrixShape.cols);
            const sheetPrefix = worksheet.name ? `${worksheet.name}!` : "";
            console.warn(`Range.formulas shrank from ${sheetPrefix}${this.address} to ` + `${sheetPrefix}${shrinkAddress} (${bounds.rows}x${bounds.cols} -> ` + `${matrixShape.rows}x${matrixShape.cols}).`);
            worksheet.getRange(shrinkAddress).formulas = normalizedInput;
            return;
          }
        } else {
          const spillAddress = this.#buildSpillRef(bounds, matrixShape.rows, matrixShape.cols);
          const overwriteSamples = this.#collectSpillOverwriteSamples({
            worksheet,
            bounds,
            spillRows: matrixShape.rows,
            spillCols: matrixShape.cols
          });
          if (overwriteSamples.length === 0) {
            const sheetPrefix2 = worksheet.name ? `${worksheet.name}!` : "";
            console.warn(`Range.formulas spilled from ${sheetPrefix2}${this.address} to ` + `${sheetPrefix2}${spillAddress} (${bounds.rows}x${bounds.cols} -> ` + `${matrixShape.rows}x${matrixShape.cols}).`);
            worksheet.getRange(spillAddress).formulas = normalizedInput;
            return;
          }
          const anchor = this.#buildAnchorRef(bounds);
          const sheetPrefix = worksheet.name ? `${worksheet.name}!` : "";
          const sampleList = overwriteSamples.map((sample) => `${sheetPrefix}${sample}`).join(", ");
          throw new Error(`Range.formulas expects a ${bounds.rows}x${bounds.cols} matrix for ${this.address}, ` + `got ${matrixShape.rows}x${matrixShape.cols}. ` + `To write this ${matrixShape.rows}x${matrixShape.cols} matrix starting at ${anchor}, ` + `use ${spillAddress}. ` + `Writing to that spill range would overwrite existing values in ${sampleList}.`);
        }
      }
      if (!isScalarMatrix) {
        this.#assertMatrixShape(normalizedInput, bounds, "formulas");
      }
    }
    if (bounds && worksheet) {
      const inputMatrix = this.#normalizeMatrixInput(resolved, bounds, "formulas");
      const normalized2 = [];
      worksheet.workbook.batchCellInputWrites(() => {
        for (let r = 0;r < bounds.rows; r++) {
          const srcRow = inputMatrix[r] ?? [];
          const normalizedRow = [];
          for (let c = 0;c < bounds.cols; c++) {
            const entry = srcRow[c];
            const str = entry == null ? "" : String(entry);
            normalizedRow.push(str);
            const cell = worksheet.__getOrCreateCell(bounds.startRow + r, bounds.startCol + c);
            if (str.trim() === "") {
              cell.formula = undefined;
            } else {
              cell.formula = str.startsWith("=") ? str.slice(1) : str;
              cell.value = undefined;
              cell.dataType = 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
            }
            this.#worksheet?.__notifyCellFormulaChanged(cell.address, str);
            worksheet.__setRawValue(bounds.startRow + r, bounds.startCol + c, undefined);
            worksheet.writeCellInputToYjs(cell);
          }
          normalized2.push(normalizedRow);
        }
      });
      this.#formulas = normalized2;
      this.#formulasR1C1 = undefined;
      this.#values = undefined;
      this.#rawValues = undefined;
      const recorder = worksheet.workbook.getRecorder();
      const address = this.address;
      if (recorder && address && worksheet.name) {
        const op = {
          op: "range.formulas.set",
          target: { sheet: worksheet.name, range: address },
          formulas: normalized2.map((row2) => [...row2])
        };
        recorder.record(op);
      }
      return;
    }
    const normalized = Array.isArray(resolved) && !Array.isArray(resolved[0]) ? [resolved] : resolved;
    this.#formulas = normalized.map((row2) => row2.map((cell) => cell ?? ""));
    this.#formulasR1C1 = undefined;
    this.#values = undefined;
    this.#rawValues = undefined;
  }
  set formulasR1C1(value) {
    const bounds = this.#bounds();
    const worksheet = this.#worksheet;
    if (!bounds || !worksheet) {
      this.#formulasR1C1 = value.map((row2) => row2.map((cell) => cell ?? ""));
      this.#formulas = undefined;
      this.#values = undefined;
      this.#rawValues = undefined;
      return;
    }
    const converted = [];
    for (let r = 0;r < bounds.rows; r += 1) {
      const srcRow = value[r] ?? [];
      const nextRow = [];
      for (let c = 0;c < bounds.cols; c += 1) {
        const src = srcRow[c] ?? "";
        const trimmed = String(src);
        if (trimmed.trim() === "") {
          nextRow.push("");
          continue;
        }
        const hasEq = trimmed.startsWith("=");
        const body = hasEq ? trimmed.slice(1) : trimmed;
        const a1Body = convertFormulaR1C1ToA1(body, bounds.startRow + r + 1, bounds.startCol + c + 1);
        nextRow.push(hasEq ? `=${a1Body}` : a1Body);
      }
      converted.push(nextRow);
    }
    this.formulas = converted;
  }
  get values() {
    if (this.#worksheet) {
      const matrix = this.#readValuesFromProto();
      this.#values = matrix;
      return matrix;
    }
    return this.#values ?? [];
  }
  get displayFormula() {
    const matrix = this.displayFormulas;
    return matrix[0]?.[0] ?? "";
  }
  get displayFormulas() {
    const bounds = this.#bounds();
    if (!bounds || !this.#worksheet) {
      return [];
    }
    const matrix = [];
    for (let r = 0;r < bounds.rows; r += 1) {
      const rowValues = [];
      for (let c = 0;c < bounds.cols; c += 1) {
        rowValues.push(this.#worksheet.__getDisplayFormula(bounds.startRow + r, bounds.startCol + c) ?? "");
      }
      matrix.push(rowValues);
    }
    return matrix;
  }
  formulaInfo() {
    const infos = this.formulaInfos;
    return infos[0]?.[0];
  }
  get formulaInfos() {
    const bounds = this.#bounds();
    if (!bounds || !this.#worksheet) {
      return [];
    }
    const matrix = [];
    for (let r = 0;r < bounds.rows; r += 1) {
      const rowValues = [];
      for (let c = 0;c < bounds.cols; c += 1) {
        rowValues.push(this.#worksheet.__getFormulaPresence(bounds.startRow + r, bounds.startCol + c));
      }
      matrix.push(rowValues);
    }
    return matrix;
  }
  get rawValues() {
    if (this.#worksheet) {
      const matrix = this.#readRawValuesFromStore();
      this.#rawValues = matrix;
      return matrix;
    }
    return this.#rawValues ?? [];
  }
  set values(value) {
    this.writeValues(value);
  }
  writeValues(value, options = {}) {
    const shouldRecord = options.record ?? true;
    const resolved = typeof value === "function" ? this.#resolveValuesCallback(value) : value;
    const bounds = this.#bounds();
    const worksheet = this.#worksheet;
    let isScalarMatrix = false;
    if (bounds && resolved !== null) {
      const normalizedInput = this.#normalizeMatrixInput(resolved, bounds, "values");
      const matrixShape = this.#getMatrixShape(normalizedInput, "values");
      isScalarMatrix = !matrixShape.ragged && matrixShape.rows === 1 && matrixShape.cols === 1;
      if (worksheet && bounds.rows === 1 && bounds.cols === 1 && !matrixShape.ragged && (matrixShape.rows !== 1 || matrixShape.cols !== 1)) {
        const spillAddress = buildRangeRef({
          startRow: bounds.startRow,
          startCol: bounds.startCol,
          endRow: bounds.startRow + matrixShape.rows - 1,
          endCol: bounds.startCol + matrixShape.cols - 1
        });
        worksheet.getRange(spillAddress).values = normalizedInput;
        return;
      }
      if (worksheet && !isScalarMatrix && !matrixShape.ragged && (matrixShape.rows !== bounds.rows || matrixShape.cols !== bounds.cols)) {
        const wouldShrink = matrixShape.rows < bounds.rows || matrixShape.cols < bounds.cols;
        if (wouldShrink) {
          if (matrixShape.rows > 0 && matrixShape.cols > 0) {
            const shrinkAddress = this.#buildSpillRef(bounds, matrixShape.rows, matrixShape.cols);
            const sheetPrefix = worksheet.name ? `${worksheet.name}!` : "";
            console.warn(`Range.values shrank from ${sheetPrefix}${this.address} to ` + `${sheetPrefix}${shrinkAddress} (${bounds.rows}x${bounds.cols} -> ` + `${matrixShape.rows}x${matrixShape.cols}).`);
            worksheet.getRange(shrinkAddress).values = normalizedInput;
            return;
          }
        } else {
          const spillAddress = this.#buildSpillRef(bounds, matrixShape.rows, matrixShape.cols);
          const overwriteSamples = this.#collectSpillOverwriteSamples({
            worksheet,
            bounds,
            spillRows: matrixShape.rows,
            spillCols: matrixShape.cols
          });
          if (overwriteSamples.length === 0) {
            const sheetPrefix2 = worksheet.name ? `${worksheet.name}!` : "";
            console.warn(`Range.values spilled from ${sheetPrefix2}${this.address} to ` + `${sheetPrefix2}${spillAddress} (${bounds.rows}x${bounds.cols} -> ` + `${matrixShape.rows}x${matrixShape.cols}).`);
            worksheet.getRange(spillAddress).values = normalizedInput;
            return;
          }
          const anchor = this.#buildAnchorRef(bounds);
          const sheetPrefix = worksheet.name ? `${worksheet.name}!` : "";
          const sampleList = overwriteSamples.map((sample) => `${sheetPrefix}${sample}`).join(", ");
          throw new Error(`Range.values expects a ${bounds.rows}x${bounds.cols} matrix for ${this.address}, ` + `got ${matrixShape.rows}x${matrixShape.cols}. ` + `To write this ${matrixShape.rows}x${matrixShape.cols} matrix starting at ${anchor}, ` + `use ${spillAddress}. ` + `Writing to that spill range would overwrite existing values in ${sampleList}.`);
        }
      }
      if (!isScalarMatrix) {
        this.#assertMatrixShape(normalizedInput, bounds, "values");
      }
    }
    if (bounds && worksheet) {
      if (resolved === null) {
        worksheet.workbook.batchCellInputWrites(() => {
          for (let r = 0;r < bounds.rows; r++) {
            for (let c = 0;c < bounds.cols; c++) {
              const rowIdx = bounds.startRow + r;
              const colIdx = bounds.startCol + c;
              const cell = worksheet.__getCell(rowIdx, colIdx);
              if (!cell) {
                continue;
              }
              const hadFormula = Boolean(cell.formula?.trim());
              this.#applyCellValue(cell, null);
              this.#applyCheckboxStyle(cell, null, rowIdx, colIdx);
              if (hadFormula) {
                worksheet.__notifyCellFormulaChanged(cell.address, "");
              } else {
                worksheet.__notifyCellValueChanged(cell.address);
              }
              worksheet.__setRawValue(rowIdx, colIdx, null);
              worksheet.writeCellInputToYjs(cell);
            }
          }
        });
        const recorder2 = worksheet.workbook.getRecorder();
        const address2 = this.address;
        if (shouldRecord && recorder2 && address2 && worksheet.name) {
          const op = {
            op: "range.values.set",
            target: { sheet: worksheet.name, range: address2 },
            values: null
          };
          recorder2.record(op);
        }
        this.#values = undefined;
        this.#rawValues = undefined;
        this.#formulas = undefined;
        this.#formulasR1C1 = undefined;
        return;
      }
      const normalizedInput = this.#normalizeMatrixInput(resolved, bounds, "values");
      const scalarEntry = isScalarMatrix ? normalizedInput[0]?.[0] : undefined;
      const normalized = [];
      const recordValues = [];
      let hasFormulaWrites = false;
      worksheet.workbook.batchCellInputWrites(() => {
        for (let r = 0;r < bounds.rows; r++) {
          const srcRow = normalizedInput[r] ?? [];
          const normalizedRow = [];
          const recordRow = [];
          for (let c = 0;c < bounds.cols; c++) {
            const rawEntry = isScalarMatrix ? scalarEntry : srcRow[c];
            const entry = rawEntry ?? null;
            let valueEntry = entry;
            let formulaEntry = null;
            if (typeof entry === "string") {
              if (entry.startsWith("'=")) {
                valueEntry = entry.slice(1);
              } else if (entry.startsWith("=")) {
                formulaEntry = entry;
              } else if (ISO_DATE_PATTERN.test(entry)) {
                const timestamp = Date.parse(entry);
                if (!Number.isNaN(timestamp)) {
                  valueEntry = new Date(timestamp);
                }
              }
            }
            normalizedRow.push(formulaEntry ? null : valueEntry);
            recordRow.push(rawEntry ?? null);
            const cell = worksheet.__getOrCreateCell(bounds.startRow + r, bounds.startCol + c);
            if (formulaEntry) {
              const formulaText = formulaEntry.slice(1);
              cell.formula = formulaText;
              cell.value = undefined;
              cell.dataType = 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
              hasFormulaWrites = true;
              this.#worksheet?.__notifyCellFormulaChanged(cell.address, formulaEntry);
              worksheet.__setRawValue(bounds.startRow + r, bounds.startCol + c, undefined);
            } else {
              const hadFormula = Boolean(cell.formula?.trim());
              this.#applyCellValue(cell, valueEntry);
              this.#applyCheckboxStyle(cell, valueEntry, bounds.startRow + r, bounds.startCol + c);
              if (hadFormula) {
                worksheet.__notifyCellFormulaChanged(cell.address, "");
              } else {
                worksheet.__notifyCellValueChanged(cell.address);
              }
              worksheet.__setRawValue(bounds.startRow + r, bounds.startCol + c, valueEntry);
            }
            worksheet.writeCellInputToYjs(cell);
          }
          normalized.push(normalizedRow);
          recordValues.push(recordRow);
        }
      });
      this.#values = normalized;
      this.#rawValues = hasFormulaWrites ? undefined : normalized;
      this.#formulas = undefined;
      this.#formulasR1C1 = undefined;
      const recorder = worksheet.workbook.getRecorder();
      const address = this.address;
      if (shouldRecord && recorder && address && worksheet.name) {
        const op = {
          op: "range.values.set",
          target: { sheet: worksheet.name, range: address },
          values: recordValues.map((row2) => row2.map((cell) => serializeCellValue(cell)))
        };
        recorder.record(op);
      }
      return;
    }
    if (resolved === null) {
      this.#values = [];
      this.#rawValues = [];
      this.#formulas = undefined;
      this.#formulasR1C1 = undefined;
      return;
    }
    const detachedNormalized = Array.isArray(resolved) && !Array.isArray(resolved[0]) ? [resolved] : resolved;
    this.#values = detachedNormalized.map((row2) => row2.map((cell) => cell ?? null));
    this.#formulas = undefined;
    this.#formulasR1C1 = undefined;
    this.#rawValues = this.#values;
  }
  #resolveValuesCallback(callback) {
    const worksheet = getRangeWorksheet(this);
    if (!worksheet) {
      throw new Error("Range.values callback requires a range on a worksheet.");
    }
    const bounds = this.#bounds();
    if (!bounds) {
      throw new Error("Range.values callback requires a range with bounds.");
    }
    const current = this.values;
    const matrix = [];
    for (let r = 0;r < bounds.rows; r += 1) {
      const rowValues = [];
      for (let c = 0;c < bounds.cols; c += 1) {
        const cell = this.getCell(r, c);
        const cur = current[r]?.[c] ?? null;
        const next = callback(r, c, cell, cur);
        rowValues.push(next === undefined ? cur : next);
      }
      matrix.push(rowValues);
    }
    return matrix;
  }
  #resolveFormulasCallback(callback) {
    const worksheet = getRangeWorksheet(this);
    if (!worksheet) {
      throw new Error("Range.formulas callback requires a range on a worksheet.");
    }
    const bounds = this.#bounds();
    if (!bounds) {
      throw new Error("Range.formulas callback requires a range with bounds.");
    }
    const current = this.formulas;
    const matrix = [];
    for (let r = 0;r < bounds.rows; r += 1) {
      const rowValues = [];
      for (let c = 0;c < bounds.cols; c += 1) {
        const cell = this.getCell(r, c);
        const cur = current[r]?.[c] ?? "";
        const next = callback(r, c, cell, cur);
        rowValues.push((next === undefined ? cur : next) ?? "");
      }
      matrix.push(rowValues);
    }
    return matrix;
  }
  getLastRow() {
    const bounds = this.#bounds();
    if (!bounds) {
      return new Range({ worksheet: this.#worksheet });
    }
    const lastRow = bounds.startRow + bounds.rows - 1;
    const address = buildRangeRef({
      startRow: lastRow,
      endRow: lastRow,
      startCol: bounds.startCol,
      endCol: bounds.startCol + bounds.cols - 1
    });
    return new Range({
      address,
      worksheet: this.#worksheet
    });
  }
  load(properties) {
    return this;
  }
  calculate() {
    const worksheet = getRangeWorksheet(this);
    if (!worksheet) {
      throw new Error("Range is not attached to a worksheet.");
    }
    worksheet.workbook.recalculate();
  }
  clear(options) {
    const applyTo = options?.applyTo ?? "contents";
    if (applyTo !== "contents" && applyTo !== "formats" && applyTo !== "all") {
      throw new Error(`Range.clear applyTo must be "contents", "formats", or "all".`);
    }
    if (applyTo === "contents" || applyTo === "all") {
      this.values = null;
    }
    if (applyTo === "formats" || applyTo === "all") {
      this.#clearFormats();
      this.#format.reset();
      const worksheet = this.#worksheet;
      const recorder = worksheet?.workbook.getRecorder();
      const address = this.address;
      if (recorder && address && worksheet?.name) {
        const op = {
          op: "range.format.clear",
          target: { sheet: worksheet.name, range: address }
        };
        recorder.record(op);
      }
    }
  }
  merge(across = false) {
    const worksheet = this.#worksheet;
    if (!worksheet) {
      throw new Error("Range is not attached to a worksheet.");
    }
    const bounds = this.#bounds();
    if (!bounds) {
      throw new Error("Range has no address.");
    }
    const recorder = worksheet.workbook.getRecorder();
    const address = this.address;
    if (recorder && address && worksheet.name) {
      const op = {
        op: "range.merge",
        target: { sheet: worksheet.name, range: address },
        across: across ? true : undefined
      };
      recorder.record(op);
    }
    if (!across) {
      worksheet.mergeCells(this.address);
      return;
    }
    const endCol = bounds.startCol + bounds.cols - 1;
    for (let r = 0;r < bounds.rows; r += 1) {
      const rowIdx = bounds.startRow + r;
      worksheet.mergeCells(buildRangeRef({
        startRow: rowIdx,
        endRow: rowIdx,
        startCol: bounds.startCol,
        endCol
      }));
    }
  }
  unmerge() {
    const worksheet = this.#worksheet;
    if (!worksheet) {
      throw new Error("Range is not attached to a worksheet.");
    }
    const recorder = worksheet.workbook.getRecorder();
    const address = this.address;
    if (recorder && address && worksheet.name) {
      const op = {
        op: "range.unmerge",
        target: { sheet: worksheet.name, range: address }
      };
      recorder.record(op);
    }
    worksheet.unmergeCells(this.address);
  }
  fillDown() {
    const worksheet = this.#worksheet;
    if (!worksheet) {
      throw new Error("Range is not attached to a worksheet.");
    }
    const bounds = this.#bounds();
    if (!bounds) {
      throw new Error("Range is not attached to a worksheet.");
    }
    if (bounds.rows <= 1 || bounds.cols <= 0) {
      return;
    }
    worksheet.workbook.batchCellInputWrites(() => {
      for (let c = 0;c < bounds.cols; c += 1) {
        const srcCell = worksheet.__getCell(bounds.startRow, bounds.startCol + c);
        const srcFormula = srcCell?.formula;
        const srcValue = srcCell?.value;
        const srcDataType = srcCell?.dataType;
        for (let r = 1;r < bounds.rows; r += 1) {
          const rowIdx = bounds.startRow + r;
          const colIdx = bounds.startCol + c;
          const dst = worksheet.__getOrCreateCell(rowIdx, colIdx);
          if (srcFormula && srcFormula.trim()) {
            dst.formula = shiftFormulaRefs(srcFormula, r, 0);
            dst.value = undefined;
            dst.dataType = 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
            worksheet.__notifyCellFormulaChanged(dst.address, `=${dst.formula}`);
            worksheet.__setRawValue(rowIdx, colIdx, undefined);
          } else if (srcValue !== undefined) {
            dst.formula = undefined;
            dst.value = srcValue;
            dst.dataType = srcDataType ?? 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
            worksheet.__notifyCellValueChanged(dst.address);
            worksheet.__setRawValue(rowIdx, colIdx, coerceProtoCellRawValue({
              value: srcValue,
              dataType: dst.dataType
            }));
          } else {
            dst.formula = undefined;
            dst.value = undefined;
            dst.dataType = 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
            worksheet.__notifyCellValueChanged(dst.address);
            worksheet.__setRawValue(rowIdx, colIdx, null);
          }
          worksheet.writeCellInputToYjs(dst);
        }
      }
    });
  }
  fillRight() {
    const worksheet = this.#worksheet;
    if (!worksheet) {
      throw new Error("Range is not attached to a worksheet.");
    }
    const bounds = this.#bounds();
    if (!bounds) {
      throw new Error("Range is not attached to a worksheet.");
    }
    if (bounds.cols <= 1 || bounds.rows <= 0) {
      return;
    }
    worksheet.workbook.batchCellInputWrites(() => {
      for (let r = 0;r < bounds.rows; r += 1) {
        const rowIdx = bounds.startRow + r;
        const srcCell = worksheet.__getCell(rowIdx, bounds.startCol);
        const srcFormula = srcCell?.formula;
        const srcValue = srcCell?.value;
        const srcDataType = srcCell?.dataType;
        for (let c = 1;c < bounds.cols; c += 1) {
          const colIdx = bounds.startCol + c;
          const dst = worksheet.__getOrCreateCell(rowIdx, colIdx);
          if (srcFormula && srcFormula.trim()) {
            dst.formula = shiftFormulaRefs(srcFormula, 0, c);
            dst.value = undefined;
            dst.dataType = 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
            worksheet.__notifyCellFormulaChanged(dst.address, `=${dst.formula}`);
            worksheet.__setRawValue(rowIdx, colIdx, undefined);
          } else if (srcValue !== undefined) {
            dst.formula = undefined;
            dst.value = srcValue;
            dst.dataType = srcDataType ?? 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
            worksheet.__notifyCellValueChanged(dst.address);
            worksheet.__setRawValue(rowIdx, colIdx, coerceProtoCellRawValue({
              value: srcValue,
              dataType: dst.dataType
            }));
          } else {
            dst.formula = undefined;
            dst.value = undefined;
            dst.dataType = 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
            worksheet.__notifyCellValueChanged(dst.address);
            worksheet.__setRawValue(rowIdx, colIdx, null);
          }
          worksheet.writeCellInputToYjs(dst);
        }
      }
    });
  }
  fillFrom(sourceRange) {
    const destinationWorksheet = this.#worksheet;
    const sourceWorksheet = sourceRange.__getWorksheet();
    if (!destinationWorksheet || !sourceWorksheet) {
      throw new Error("Range.fillFrom requires both ranges to be attached to worksheets.");
    }
    if (destinationWorksheet !== sourceWorksheet) {
      throw new Error("Range.fillFrom requires source and destination to be on the same worksheet.");
    }
    const destBounds = this.#bounds();
    const srcBounds = sourceRange.getBoundingBox();
    if (!destBounds || !srcBounds) {
      throw new Error("Range.fillFrom requires both ranges to have bounds.");
    }
    const recorder = destinationWorksheet.workbook.getRecorder();
    const address = this.address;
    const shouldRecord = Boolean(recorder && address && destinationWorksheet.name);
    const valueMatrix = destinationWorksheet.workbook.batchCellInputWrites(() => fillRangeFrom({
      coerceCellValue: (cell) => this.#coerceCellValue(cell),
      destinationBounds: destBounds,
      destinationRangeAddress: this.address,
      readSourceCell: (row2, col) => sourceWorksheet.__getCell(row2, col),
      shouldCollectValues: shouldRecord,
      sourceBounds: srcBounds,
      sourceRangeAddress: sourceRange.address,
      shiftFormulaRefs,
      clearCell: (rowIdx, colIdx) => {
        const dst = destinationWorksheet.__getOrCreateCell(rowIdx, colIdx);
        dst.formula = undefined;
        dst.value = undefined;
        dst.dataType = 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
        destinationWorksheet.__notifyCellValueChanged(dst.address);
        destinationWorksheet.__setRawValue(rowIdx, colIdx, null);
        destinationWorksheet.writeCellInputToYjs(dst);
      },
      writeFormulaCell: (rowIdx, colIdx, formulaText) => {
        const dst = destinationWorksheet.__getOrCreateCell(rowIdx, colIdx);
        dst.formula = formulaText;
        dst.value = undefined;
        dst.dataType = 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
        destinationWorksheet.__notifyCellFormulaChanged(dst.address, `=${formulaText}`);
        destinationWorksheet.__setRawValue(rowIdx, colIdx, undefined);
        destinationWorksheet.writeCellInputToYjs(dst);
      },
      writeValueCell: (rowIdx, colIdx, sourceCell) => {
        const dst = destinationWorksheet.__getOrCreateCell(rowIdx, colIdx);
        dst.formula = undefined;
        dst.value = sourceCell.value;
        dst.dataType = sourceCell.dataType ?? 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
        destinationWorksheet.__notifyCellValueChanged(dst.address);
        destinationWorksheet.__setRawValue(rowIdx, colIdx, coerceProtoCellRawValue(sourceCell));
        destinationWorksheet.writeCellInputToYjs(dst);
      }
    }));
    if (recorder && address && destinationWorksheet.name && valueMatrix) {
      const op = {
        op: "range.values.set",
        target: { sheet: destinationWorksheet.name, range: address },
        values: valueMatrix.map((row2) => row2.map((cell) => serializeCellValue(cell)))
      };
      recorder.record(op);
    }
  }
  copyFrom(sourceRange, copyType, skipBlanks, transpose) {
    const destinationWorksheet = this.#worksheet;
    const sourceWorksheet = sourceRange.__getWorksheet();
    if (!destinationWorksheet || !sourceWorksheet) {
      throw new Error("Range.copyFrom requires both ranges to be attached to worksheets.");
    }
    const options = typeof copyType === "object" && copyType !== null ? copyType : { copyType, skipBlanks, transpose };
    if (options.skipBlanks) {
      throw new Error("Range.copyFrom skipBlanks is not supported yet.");
    }
    if (options.transpose) {
      throw new Error("Range.copyFrom transpose is not supported yet.");
    }
    const destBounds = this.#bounds();
    const srcBounds = sourceRange.getBoundingBox();
    if (!destBounds || !srcBounds) {
      throw new Error("Range.copyFrom requires both ranges to have bounds.");
    }
    const type = (options.copyType ?? "all").toLowerCase();
    const srcIsScalar = srcBounds.rows === 1 && srcBounds.cols === 1;
    const canTile = !srcIsScalar && srcBounds.rows > 0 && srcBounds.cols > 0 && destBounds.rows > 0 && destBounds.cols > 0 && destBounds.rows % srcBounds.rows === 0 && destBounds.cols % srcBounds.cols === 0;
    const shapeMatches = srcIsScalar || canTile || srcBounds.rows === destBounds.rows && srcBounds.cols === destBounds.cols;
    if (!shapeMatches) {
      throw new Error(`Range.copyFrom requires source and destination to match shape (or source to be 1x1). ` + `Source is ${srcBounds.rows}x${srcBounds.cols}, destination is ${destBounds.rows}x${destBounds.cols}. ` + `If you are filling down/right from a seed block, pass a source block whose size evenly tiles the destination.`);
    }
    if (type === "values") {
      const srcValues = sourceRange.values;
      if (srcIsScalar) {
        const scalar = srcValues[0]?.[0] ?? null;
        const matrix = Array.from({ length: destBounds.rows }, () => Array.from({ length: destBounds.cols }, () => scalar));
        this.values = matrix;
      } else if (canTile) {
        const matrix = [];
        for (let r = 0;r < destBounds.rows; r += 1) {
          const rowValues = [];
          const srcRow = srcValues[r % srcBounds.rows] ?? [];
          for (let c = 0;c < destBounds.cols; c += 1) {
            rowValues.push(srcRow[c % srcBounds.cols] ?? null);
          }
          matrix.push(rowValues);
        }
        this.values = matrix;
      } else {
        this.values = srcValues;
      }
      return;
    }
    const recorder = destinationWorksheet.workbook.getRecorder();
    const address = this.address;
    const shouldRecordFormulas = type === "formulas" && Boolean(recorder && address && destinationWorksheet.name);
    const shouldRecordAllValues = type === "all" && Boolean(recorder && address && destinationWorksheet.name);
    const formulaMatrix = [];
    const valueMatrix = [];
    destinationWorksheet.workbook.batchCellInputWrites(() => {
      for (let r = 0;r < destBounds.rows; r += 1) {
        const formulaRow = [];
        const valueRow = [];
        for (let c = 0;c < destBounds.cols; c += 1) {
          const srcRowOffset = srcIsScalar ? 0 : canTile ? r % srcBounds.rows : r;
          const srcColOffset = srcIsScalar ? 0 : canTile ? c % srcBounds.cols : c;
          const srcRow = srcBounds.startRow + srcRowOffset;
          const srcCol = srcBounds.startCol + srcColOffset;
          const dstRow = destBounds.startRow + r;
          const dstCol = destBounds.startCol + c;
          const srcCell = sourceWorksheet.__getCell(srcRow, srcCol);
          const dst = destinationWorksheet.__getOrCreateCell(dstRow, dstCol);
          const deltaRow = dstRow - srcRow;
          const deltaCol = dstCol - srcCol;
          const srcFormula = srcCell?.formula;
          if (type === "formulas" || type === "all") {
            if (srcFormula && srcFormula.trim()) {
              const shiftedFormula = shiftFormulaRefs(srcFormula, deltaRow, deltaCol);
              dst.formula = shiftedFormula;
              dst.value = undefined;
              dst.dataType = 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
              if (shouldRecordFormulas) {
                formulaRow.push(`=${shiftedFormula}`);
              }
              if (shouldRecordAllValues) {
                valueRow.push(`=${shiftedFormula}`);
              }
              destinationWorksheet.__notifyCellFormulaChanged(dst.address, `=${dst.formula}`);
              destinationWorksheet.__setRawValue(dstRow, dstCol, undefined);
              destinationWorksheet.writeCellInputToYjs(dst);
              continue;
            }
            if (type === "formulas") {
              dst.formula = undefined;
              if (shouldRecordFormulas) {
                formulaRow.push("");
              }
              destinationWorksheet.__notifyCellFormulaChanged(dst.address, "");
              destinationWorksheet.__setRawValue(dstRow, dstCol, undefined);
              destinationWorksheet.writeCellInputToYjs(dst);
              continue;
            }
          }
          if (srcCell?.value !== undefined) {
            dst.formula = undefined;
            dst.value = srcCell.value;
            dst.dataType = srcCell.dataType ?? 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
            if (shouldRecordAllValues) {
              valueRow.push(this.#coerceCellValue(srcCell));
            }
            destinationWorksheet.__notifyCellValueChanged(dst.address);
            destinationWorksheet.__setRawValue(dstRow, dstCol, coerceProtoCellRawValue(srcCell));
          } else {
            dst.formula = undefined;
            dst.value = undefined;
            dst.dataType = 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
            if (shouldRecordAllValues) {
              valueRow.push(null);
            }
            destinationWorksheet.__notifyCellValueChanged(dst.address);
            destinationWorksheet.__setRawValue(dstRow, dstCol, null);
          }
          destinationWorksheet.writeCellInputToYjs(dst);
        }
        if (shouldRecordFormulas) {
          formulaMatrix.push(formulaRow);
        }
        if (shouldRecordAllValues) {
          valueMatrix.push(valueRow);
        }
      }
    });
    if (recorder && address && destinationWorksheet.name) {
      if (shouldRecordFormulas) {
        const op = {
          op: "range.formulas.set",
          target: { sheet: destinationWorksheet.name, range: address },
          formulas: formulaMatrix.map((row2) => [...row2])
        };
        recorder.record(op);
      } else if (shouldRecordAllValues) {
        const op = {
          op: "range.values.set",
          target: { sheet: destinationWorksheet.name, range: address },
          values: valueMatrix.map((row2) => row2.map((cell) => serializeCellValue(cell)))
        };
        recorder.record(op);
      }
    }
  }
  copyTo(destinationRange, copyType, skipBlanks, transpose) {
    destinationRange.copyFrom(this, copyType, skipBlanks, transpose);
  }
  getBoundingBox() {
    return this.#bounds();
  }
  #bounds() {
    if (!this.#address)
      return null;
    const parsed = parseRangeAddress(this.#address);
    if (!parsed)
      return null;
    const size2 = boundsDimensions(parsed.bounds);
    return {
      startRow: parsed.bounds.startRow,
      startCol: parsed.bounds.startCol,
      rows: size2.rows,
      cols: size2.cols
    };
  }
  #getMatrixShape(matrix, label) {
    if (!Array.isArray(matrix)) {
      throw new Error(`Range.${label} expects a 2D array.`);
    }
    const colCounts = [];
    for (let r = 0;r < matrix.length; r += 1) {
      const row2 = matrix[r];
      if (!Array.isArray(row2)) {
        throw new Error(`Range.${label} expects a 2D array; row ${r + 1} is not an array.`);
      }
      colCounts.push(row2.length);
    }
    const rows = matrix.length;
    const cols = colCounts[0] ?? 0;
    const ragged = colCounts.some((count3) => count3 !== cols);
    return { rows, cols, ragged, colCounts };
  }
  #assertMatrixShape(matrix, bounds, label) {
    const { rows: actualRows, cols: actualCols, ragged, colCounts } = this.#getMatrixShape(matrix, label);
    const expectedRows = bounds.rows;
    const expectedCols = bounds.cols;
    if (actualRows !== expectedRows || ragged || actualCols !== expectedCols) {
      const address = this.address || "range";
      const raggedNote = ragged ? ` (ragged rows: ${colCounts.join(", ")})` : "";
      const looksTransposed = !ragged && actualRows === expectedCols && actualCols === expectedRows && (expectedRows === 1 || expectedCols === 1) && (actualRows === 1 || actualCols === 1);
      const transposeHint = looksTransposed ? " Input looks transposed; pass a row-shaped matrix like [[...]] or a 1D array for single-row/single-column ranges." : "";
      const spillHint = !ragged && actualRows > 0 && actualCols > 0 ? (() => {
        const anchor = this.#buildAnchorRef(bounds);
        const spillAddress = this.#buildSpillRef(bounds, actualRows, actualCols);
        if (!spillAddress || spillAddress === address) {
          return "";
        }
        return ` To write this ${actualRows}x${actualCols} matrix starting at ${anchor}, ` + `use ${spillAddress}.`;
      })() : "";
      throw new Error(`Range.${label} expects a ${expectedRows}x${expectedCols} matrix for ${address}, ` + `got ${actualRows}x${actualCols}${raggedNote}.${transposeHint}${spillHint}`);
    }
  }
  #buildAnchorRef(bounds) {
    return buildRangeRef({
      startRow: bounds.startRow,
      startCol: bounds.startCol,
      endRow: bounds.startRow,
      endCol: bounds.startCol
    });
  }
  #buildSpillRef(bounds, rows, cols) {
    return buildRangeRef({
      startRow: bounds.startRow,
      startCol: bounds.startCol,
      endRow: bounds.startRow + rows - 1,
      endCol: bounds.startCol + cols - 1
    });
  }
  #cellHasContent(worksheet, rowIdx, colIdx) {
    const cell = worksheet.__getCell(rowIdx, colIdx);
    const formula = cell?.formula ?? "";
    if (typeof formula === "string" && formula.trim() !== "") {
      return true;
    }
    const rawValue = worksheet.__getRawValue(rowIdx, colIdx);
    if (rawValue !== undefined) {
      if (rawValue === null) {
        return false;
      }
      return typeof rawValue === "string" ? rawValue !== "" : true;
    }
    const value = cell?.value;
    if (value == null) {
      return false;
    }
    return typeof value === "string" ? value !== "" : true;
  }
  #collectSpillOverwriteSamples(options) {
    const sampleLimit = Math.max(1, options.sampleLimit ?? 3);
    const { startRow, startCol, rows: expectedRows, cols: expectedCols } = options.bounds;
    const originalEndRow = startRow + expectedRows - 1;
    const originalEndCol = startCol + expectedCols - 1;
    const spillEndRow = startRow + options.spillRows - 1;
    const spillEndCol = startCol + options.spillCols - 1;
    const samples = [];
    for (let r = startRow;r <= spillEndRow; r += 1) {
      for (let c = startCol;c <= spillEndCol; c += 1) {
        if (r <= originalEndRow && c <= originalEndCol) {
          continue;
        }
        if (this.#cellHasContent(options.worksheet, r, c)) {
          samples.push(buildRangeRef({ startRow: r, startCol: c, endRow: r, endCol: c }));
          if (samples.length >= sampleLimit) {
            return samples;
          }
        }
      }
    }
    return samples;
  }
  #collectOverwriteSamplesInTarget(options) {
    const bounds = options.bounds;
    if (!bounds) {
      return [];
    }
    const sampleLimit = Math.max(1, options.sampleLimit ?? 3);
    const endRow = bounds.startRow + bounds.rows - 1;
    const endCol = bounds.startCol + bounds.cols - 1;
    const samples = [];
    for (let r = bounds.startRow;r <= endRow; r += 1) {
      for (let c = bounds.startCol;c <= endCol; c += 1) {
        if (this.#cellHasContent(options.worksheet, r, c)) {
          samples.push(buildRangeRef({ startRow: r, startCol: c, endRow: r, endCol: c }));
          if (samples.length >= sampleLimit) {
            return samples;
          }
        }
      }
    }
    return samples;
  }
  #normalizeMatrixInput(input, bounds, label) {
    if (!Array.isArray(input)) {
      throw new Error(`Range.${label} expects a 2D array.`);
    }
    const is1d = input.length === 0 || !Array.isArray(input[0]);
    if (is1d) {
      const vector = input;
      if (bounds.rows === 1 && bounds.cols === 1) {
        return [vector];
      }
      if (bounds.rows === 1) {
        return [vector];
      }
      if (bounds.cols === 1) {
        return vector.map((entry) => [entry]);
      }
      const address = this.address || "range";
      throw new Error(`Range.${label} expects a ${bounds.rows}x${bounds.cols} matrix for ${address}, ` + "but you passed a 1D array. Use a 2D array like [[...], ...].");
    }
    const matrix = input;
    const { rows, cols, ragged, colCounts } = this.#getMatrixShape(matrix, label);
    if (!ragged && rows === bounds.cols && cols === bounds.rows) {
      if ((bounds.rows === 1 || bounds.cols === 1) && (rows === 1 || cols === 1)) {
        const transposed = [];
        for (let c = 0;c < cols; c += 1) {
          const nextRow = [];
          for (let r = 0;r < rows; r += 1) {
            nextRow.push(matrix[r]?.[c]);
          }
          transposed.push(nextRow);
        }
        return transposed;
      }
    }
    if (ragged && rows === bounds.rows) {
      const maxCols = Math.max(0, ...colCounts);
      if (maxCols > bounds.cols) {
        const address = this.address || "range";
        throw new Error(`Range.${label} expects a ${bounds.rows}x${bounds.cols} matrix for ${address}, ` + `but one or more rows exceed the expected column count.`);
      }
      const padded = [];
      for (let r = 0;r < bounds.rows; r += 1) {
        const srcRow = matrix[r] ?? [];
        const nextRow = [];
        for (let c = 0;c < bounds.cols; c += 1) {
          nextRow.push(c < srcRow.length ? srcRow[c] : null);
        }
        padded.push(nextRow);
      }
      return padded;
    }
    return matrix;
  }
  #clearFormats() {
    const bounds = this.#bounds();
    const worksheet = this.#worksheet;
    if (!bounds || !worksheet) {
      return;
    }
    worksheet.workbook.runLocalCollabTransaction(() => {
      const defaultStyleIndex = 0;
      const defaultStyleId = worksheet.workbook.__getOrCreateStyleIdForStyleIndex(defaultStyleIndex);
      for (let r = 0;r < bounds.rows; r += 1) {
        for (let c = 0;c < bounds.cols; c += 1) {
          const rowIdx = bounds.startRow + r;
          const colIdx = bounds.startCol + c;
          const cell = worksheet.__getCell(rowIdx, colIdx);
          if (!cell) {
            continue;
          }
          cell.styleIndex = defaultStyleIndex;
          worksheet.__setLogicalStyleIndex(rowIdx, colIdx, defaultStyleIndex);
          worksheet.__setCellStyleRef(rowIdx, colIdx, defaultStyleId);
        }
      }
    });
  }
  #buildFormatContext() {
    return {
      getBounds: () => this.#bounds(),
      getWorkbook: () => this.#worksheet?.workbook,
      getWorksheet: () => this.#worksheet,
      getAddress: () => this.address,
      editCells: (create6, visitor) => this.#forEachCell(create6, visitor),
      getFirstCell: (create6) => this.#getFirstCell(create6),
      setLogicalStyleIndex: (row2, col, styleIndex) => this.#worksheet?.__setLogicalStyleIndex(row2, col, styleIndex),
      getLogicalStyleIndex: (row2, col) => this.#worksheet?.__getLogicalStyleIndex(row2, col),
      setCellStyleRef: (row2, col, styleId) => this.#worksheet?.__setCellStyleRef(row2, col, styleId)
    };
  }
  #getFirstCell(create6) {
    let first = null;
    this.#forEachCell(create6, (info) => {
      if (!first) {
        first = info;
      }
    });
    return first;
  }
  #forEachCell(create6, visitor) {
    const bounds = this.#bounds();
    const worksheet = this.#worksheet;
    if (!bounds || !worksheet) {
      return;
    }
    for (let r = 0;r < bounds.rows; r += 1) {
      for (let c = 0;c < bounds.cols; c += 1) {
        const rowIdx = bounds.startRow + r;
        const colIdx = bounds.startCol + c;
        const cell = create6 ? worksheet.__getOrCreateCell(rowIdx, colIdx) : worksheet.__getCell(rowIdx, colIdx);
        visitor({
          row: rowIdx,
          col: colIdx,
          cell,
          relativeRow: r,
          relativeCol: c
        });
      }
    }
  }
  #readFormulasFromProto() {
    const bounds = this.#bounds();
    if (!bounds || !this.#worksheet)
      return [];
    const worksheet = this.#worksheet;
    const matrix = [];
    for (let r = 0;r < bounds.rows; r++) {
      const rowValues = [];
      for (let c = 0;c < bounds.cols; c++) {
        const cell = worksheet.__getCell(bounds.startRow + r, bounds.startCol + c);
        rowValues.push(cell?.formula ? `=${cell.formula}` : "");
      }
      matrix.push(rowValues);
    }
    return matrix;
  }
  #coerceRawValueToCellValue(value) {
    if (value == null) {
      return null;
    }
    if (value instanceof Date) {
      return value;
    }
    if (typeof value === "number") {
      return Number.isFinite(value) ? value : "#NUM!";
    }
    if (typeof value === "string" || typeof value === "boolean") {
      return value;
    }
    if (isErrorValue(value)) {
      return value.code;
    }
    if (isArrayValue(value)) {
      return this.#coerceRawValueToCellValue(value.values[0]?.[0] ?? null);
    }
    if (value instanceof Error) {
      return value.message.startsWith("#") ? value.message : "#VALUE!";
    }
    return "#VALUE!";
  }
  #readValuesFromProto() {
    const bounds = this.#bounds();
    if (!bounds || !this.#worksheet)
      return [];
    const worksheet = this.#worksheet;
    const matrix = [];
    for (let r = 0;r < bounds.rows; r++) {
      const rowValues = [];
      for (let c = 0;c < bounds.cols; c++) {
        const raw = worksheet.__getRawValue(bounds.startRow + r, bounds.startCol + c);
        if (raw !== undefined) {
          rowValues.push(this.#coerceRawValueToCellValue(raw));
          continue;
        }
        const cell = worksheet.__getCell(bounds.startRow + r, bounds.startCol + c);
        rowValues.push(this.#coerceCellValue(cell));
      }
      matrix.push(rowValues);
    }
    return matrix;
  }
  #readRawValuesFromStore() {
    const bounds = this.#bounds();
    if (!bounds || !this.#worksheet)
      return [];
    const worksheet = this.#worksheet;
    const matrix = [];
    for (let r = 0;r < bounds.rows; r++) {
      const rowValues = [];
      for (let c = 0;c < bounds.cols; c++) {
        const raw = worksheet.__getRawValue(bounds.startRow + r, bounds.startCol + c);
        if (raw !== undefined) {
          rowValues.push(raw);
          continue;
        }
        const cell = worksheet.__getCell(bounds.startRow + r, bounds.startCol + c);
        rowValues.push(this.#coerceCellValue(cell));
      }
      matrix.push(rowValues);
    }
    return matrix;
  }
  #applyCellValue(cell, entry) {
    if (entry == null) {
      cell.value = undefined;
      cell.dataType = 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
      cell.formula = undefined;
      if (!cell.paragraphs)
        cell.paragraphs = [];
      return;
    }
    cell.formula = undefined;
    if (!cell.paragraphs)
      cell.paragraphs = [];
    switch (typeof entry) {
      case "number":
        if (Number.isNaN(entry)) {
          cell.value = undefined;
          cell.dataType = 6 /* CELL_DATA_TYPE_ERROR */;
        } else {
          cell.value = String(entry);
          cell.dataType = 5 /* CELL_DATA_TYPE_NUMBER */;
        }
        break;
      case "boolean":
        cell.value = entry ? "1" : "0";
        cell.dataType = 4 /* CELL_DATA_TYPE_BOOLEAN */;
        break;
      case "object":
        if (entry instanceof Date) {
          const workbook = this.#worksheet?.workbook;
          cell.value = workbook ? workbook.__formatRawValueForDisplay(entry).value : entry.toISOString();
          cell.dataType = 5 /* CELL_DATA_TYPE_NUMBER */;
        } else {
          cell.value = String(entry);
          cell.dataType = 3 /* CELL_DATA_TYPE_STRING */;
        }
        break;
      default:
        cell.value = String(entry);
        cell.dataType = 3 /* CELL_DATA_TYPE_STRING */;
        break;
    }
  }
  #applyCheckboxStyle(cell, entry, rowIdx, colIdx) {
    const worksheet = this.#worksheet;
    if (!worksheet) {
      return;
    }
    const workbook = worksheet.workbook;
    const currentStyleIndex = worksheet.__getLogicalStyleIndex(rowIdx, colIdx) ?? cell.styleIndex ?? 0;
    if (typeof entry === "boolean") {
      const nextStyleIndex2 = workbook.__resolveCheckboxStyleIndex(currentStyleIndex);
      if (nextStyleIndex2 !== currentStyleIndex) {
        cell.styleIndex = nextStyleIndex2;
        worksheet.__setLogicalStyleIndex(rowIdx, colIdx, nextStyleIndex2);
        const styleId = workbook.__getOrCreateStyleIdForStyleIndex(nextStyleIndex2);
        worksheet.__setCellStyleRef(rowIdx, colIdx, styleId);
      }
      return;
    }
    const nextStyleIndex = workbook.__removeCheckboxStyleIndex(currentStyleIndex);
    if (nextStyleIndex !== currentStyleIndex) {
      cell.styleIndex = nextStyleIndex;
      worksheet.__setLogicalStyleIndex(rowIdx, colIdx, nextStyleIndex);
      const styleId = workbook.__getOrCreateStyleIdForStyleIndex(nextStyleIndex);
      worksheet.__setCellStyleRef(rowIdx, colIdx, styleId);
    }
  }
  #coerceCellValue(cell) {
    if (!cell)
      return null;
    if (cell.value == null)
      return null;
    switch (cell.dataType) {
      case 5 /* CELL_DATA_TYPE_NUMBER */:
        return Number(cell.value);
      case 4 /* CELL_DATA_TYPE_BOOLEAN */:
        return cell.value === "TRUE" || cell.value === "1";
      case 7 /* CELL_DATA_TYPE_DATE */:
        return coerceExcelSerialToDate(cell.value) ?? new Date(cell.value);
      case 3 /* CELL_DATA_TYPE_STRING */:
      case 1 /* CELL_DATA_TYPE_SHARED_STRING */:
      case 2 /* CELL_DATA_TYPE_INLINE_STRING */:
        return cell.value;
      default:
        return cell.value;
    }
  }
}

class RangeSparklinesProxy {
  #range;
  constructor(range2) {
    this.#range = range2;
  }
  add(configOrType, sourceData, options) {
    const worksheet = this.#range.__getWorksheet();
    if (!worksheet) {
      throw new Error("Range.sparklines.add requires a range attached to a worksheet.");
    }
    if (typeof configOrType === "string") {
      if (!sourceData) {
        throw new Error("Range.sparklines.add(type, sourceData, options?) requires sourceData.");
      }
      return worksheet.sparklineGroups.add({
        type: configOrType,
        targetRange: this.#range,
        sourceData,
        ...options ?? {}
      });
    }
    const config = configOrType;
    if (config.targetRange && config.targetRange !== this.#range) {
      const requested = typeof config.targetRange === "string" ? config.targetRange : config.targetRange.address;
      console.warn(`Range.sparklines.add(config) ignores config.targetRange (${requested}) and uses ${this.#range.address}.`);
    }
    return worksheet.sparklineGroups.add({
      ...config,
      targetRange: this.#range
    });
  }
}
function getRangeWorksheet(range2) {
  return RANGE_WORKSHEET.get(range2);
}
var MAX_ROW_COUNT = 1048576;
var MAX_COL_COUNT = 16384;
function shiftFormulaRefs(formula, rowDelta, colDelta) {
  if (!formula)
    return formula;
  const refRegex = /(\$?)([A-Z]{1,3})(\$?)(\d{1,7})/g;
  return formula.replace(refRegex, (match, colAbs, colLabel, rowAbs, rowText) => {
    const col = columnLabelToNumber(colLabel);
    const row2 = Number(rowText);
    if (!col || !row2) {
      return match;
    }
    let nextCol = col;
    let nextRow = row2;
    if (!colAbs) {
      nextCol = col + colDelta;
    }
    if (!rowAbs) {
      nextRow = row2 + rowDelta;
    }
    if (nextCol < 1 || nextRow < 1 || nextCol > MAX_COL_COUNT || nextRow > MAX_ROW_COUNT) {
      return match;
    }
    const nextLabel = columnNumberToLabel(nextCol);
    return `${colAbs}${nextLabel}${rowAbs}${nextRow}`;
  });
}
function mapOutsideDoubleQuotes(formula, mapper) {
  if (!formula.includes('"')) {
    return mapper(formula);
  }
  let out = "";
  let idx = 0;
  while (idx < formula.length) {
    const quoteIdx = formula.indexOf('"', idx);
    if (quoteIdx < 0) {
      out += mapper(formula.slice(idx));
      break;
    }
    out += mapper(formula.slice(idx, quoteIdx));
    let j = quoteIdx + 1;
    while (j < formula.length) {
      if (formula[j] === '"') {
        if (formula[j + 1] === '"') {
          j += 2;
          continue;
        }
        j += 1;
        break;
      }
      j += 1;
    }
    out += formula.slice(quoteIdx, j);
    idx = j;
  }
  return out;
}
function isWordChar(ch) {
  if (!ch)
    return false;
  return /[A-Za-z0-9_]/.test(ch);
}
function convertFormulaR1C1ToA1(formula, baseRow1, baseCol1) {
  const convertSegment = (segment) => {
    const refRegex = /R(\[[-+]?\d+\]|\d+)?C(\[[-+]?\d+\]|\d+)?/gi;
    return segment.replace(refRegex, (match, rowToken, colToken, offset) => {
      const before = segment[offset - 1];
      const after = segment[offset + match.length];
      if (isWordChar(before) || isWordChar(after)) {
        return match;
      }
      const parseAxis = (token) => {
        if (!token) {
          return { absolute: false, value: 0 };
        }
        const trimmed = token.trim();
        if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
          const delta = Number(trimmed.slice(1, -1));
          if (!Number.isFinite(delta) || !Number.isInteger(delta)) {
            throw new Error(`Invalid R1C1 reference: ${match}`);
          }
          return { absolute: false, value: delta };
        }
        const abs3 = Number(trimmed);
        if (!Number.isFinite(abs3) || !Number.isInteger(abs3) || abs3 < 1) {
          throw new Error(`Invalid R1C1 reference: ${match}`);
        }
        return { absolute: true, value: abs3 };
      };
      const rowSpec = parseAxis(rowToken);
      const colSpec = parseAxis(colToken);
      const row1 = rowSpec.absolute ? rowSpec.value : baseRow1 + rowSpec.value;
      const col1 = colSpec.absolute ? colSpec.value : baseCol1 + colSpec.value;
      if (row1 < 1 || col1 < 1 || row1 > MAX_ROW_COUNT || col1 > MAX_COL_COUNT) {
        throw new Error(`R1C1 reference ${match} resolves outside worksheet bounds.`);
      }
      const colLabel = columnNumberToLabel(col1);
      const colPrefix = colSpec.absolute ? "$" : "";
      const rowPrefix = rowSpec.absolute ? "$" : "";
      return `${colPrefix}${colLabel}${rowPrefix}${row1}`;
    });
  };
  return mapOutsideDoubleQuotes(formula, convertSegment);
}
function convertFormulaA1ToR1C1(formula, baseRow1, baseCol1) {
  const convertSegment = (segment) => {
    const refRegex = /(\$?)([A-Z]{1,3})(\$?)(\d{1,7})/g;
    return segment.replace(refRegex, (match, colAbs, colLabel, rowAbs, rowText, offset) => {
      const before = segment[offset - 1];
      const after = segment[offset + match.length];
      if (isWordChar(before) || isWordChar(after)) {
        return match;
      }
      const col = columnLabelToNumber(colLabel);
      const row2 = Number(rowText);
      if (!col || !row2) {
        return match;
      }
      const rowPart = rowAbs ? `R${row2}` : (() => {
        const delta = row2 - baseRow1;
        if (delta === 0)
          return "R";
        return `R[${delta}]`;
      })();
      const colPart = colAbs ? `C${col}` : (() => {
        const delta = col - baseCol1;
        if (delta === 0)
          return "C";
        return `C[${delta}]`;
      })();
      return `${rowPart}${colPart}`;
    });
  };
  return mapOutsideDoubleQuotes(formula, convertSegment);
}
function coerceProtoCellRawValue(cell) {
  if (!cell)
    return null;
  if (cell.value == null)
    return null;
  switch (cell.dataType) {
    case 5 /* CELL_DATA_TYPE_NUMBER */:
      return Number(cell.value);
    case 4 /* CELL_DATA_TYPE_BOOLEAN */:
      return cell.value === "TRUE" || cell.value === "1";
    case 7 /* CELL_DATA_TYPE_DATE */:
      return new Date(cell.value);
    default:
      return cell.value;
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/apply/ops-utils.js
var SHAPE_GEOMETRY_FROM_PROTO2 = Object.entries(SHAPE_GEOMETRY_NAME_TO_PROTO).reduce((acc, [name, proto]) => {
  if (!(proto in acc)) {
    acc[proto] = name;
  }
  return acc;
}, {});
function buildThreadAddOp(input) {
  const { threadId, target, body, author, createdAt } = input;
  const normalizedTarget = normalizeSpreadsheetThreadTarget(target);
  if (!normalizedTarget) {
    return null;
  }
  return {
    op: "thread.add",
    id: threadId,
    target: normalizedTarget,
    body: typeof body === "string" ? body : body.plainText ?? "",
    author,
    createdAt
  };
}
function buildSpreadsheetThreadTargetRef(input) {
  const { threadId, target, rootBody, rootAuthorId, rootCreatedAt } = input;
  const normalizedTarget = normalizeSpreadsheetThreadTarget(target);
  if (!normalizedTarget) {
    return null;
  }
  const selector = {
    target: normalizedTarget
  };
  if (rootBody !== undefined) {
    selector.rootBody = rootBody;
  }
  if (rootAuthorId !== undefined) {
    selector.rootAuthorId = rootAuthorId;
  }
  if (rootCreatedAt !== undefined) {
    selector.rootCreatedAt = rootCreatedAt;
  }
  return {
    id: threadId,
    selector
  };
}
function normalizeSpreadsheetThreadTarget(input) {
  const cellTarget = input.spreadsheetCell;
  if (cellTarget?.sheetName && cellTarget.address) {
    return {
      cell: {
        sheet: cellTarget.sheetName,
        address: cellTarget.address
      }
    };
  }
  const rangeTarget = input.spreadsheetRange;
  const start = rangeTarget?.startAddress ?? rangeTarget?.endAddress;
  if (rangeTarget?.sheetName && start) {
    const end = rangeTarget.endAddress;
    return {
      range: {
        sheet: rangeTarget.sheetName,
        range: end && end !== start ? `${start}:${end}` : start
      }
    };
  }
  return null;
}
function buildChartAddOp(input) {
  const { sheet, chart: chart2, fallbackType, as } = input;
  const chartType = chart2.type ?? fallbackType;
  if (!chartType) {
    return null;
  }
  const op = {
    op: "chart.add",
    sheet,
    props: buildChartAddProps(chart2, chartType, { includeId: true })
  };
  if (as) {
    op.as = as;
  }
  return op;
}
function buildChartSetOp(input) {
  const { sheet, chart: chart2 } = input;
  const chartType = chart2.type;
  if (!chartType) {
    return null;
  }
  return {
    op: "chart.set",
    target: {
      sheet,
      selector: buildChartTargetSelector(chart2)
    },
    props: buildChartAddProps(chart2, chartType, { includeId: false })
  };
}
function buildChartAddProps(chart2, chartType, options) {
  const props = {
    chartType,
    anchor: buildChartAnchor(chart2.anchor)
  };
  if (options?.includeId) {
    props.id = chart2.id;
  }
  if (chart2.titleText !== undefined) {
    props.title = chart2.titleText;
  }
  const categories = chart2.categories;
  if (categories.length > 0) {
    props.categories = [...categories];
  }
  const series = buildChartSeries(chart2.series.items);
  if (series.length > 0) {
    props.series = series;
  }
  if (chart2.hasLegend !== undefined) {
    props.hasLegend = chart2.hasLegend;
  }
  const legendPosition = chart2.legend.position;
  if (legendPosition !== undefined) {
    props.legend = { position: legendPosition };
  }
  const dataLabels = buildChartDataLabels(chart2);
  if (dataLabels) {
    props.dataLabels = dataLabels;
  }
  if (chart2.displayBlanksAs !== undefined) {
    props.displayBlanksAs = chart2.displayBlanksAs;
  }
  const barOptions = buildChartBarOptions(chart2);
  if (barOptions) {
    props.barOptions = barOptions;
  }
  const pieOptions = buildChartPieOptions(chart2);
  if (pieOptions) {
    props.pieOptions = pieOptions;
  }
  const doughnutOptions = buildChartDoughnutOptions(chart2);
  if (doughnutOptions) {
    props.doughnutOptions = doughnutOptions;
  }
  const plotArea = buildChartAreaProps(chart2.plotAreaFill, chart2.plotAreaLine);
  if (plotArea) {
    props.plotArea = plotArea;
  }
  const chartArea = buildChartAreaProps(chart2.chartFill, chart2.chartLine);
  if (chartArea) {
    props.chartArea = chartArea;
  }
  return props;
}
function buildChartTargetSelector(chart2) {
  const seriesNames = chart2.series.items.map((series) => series.name);
  return {
    anchor: buildChartAnchor(chart2.anchor),
    chartType: chart2.type,
    title: chart2.titleText,
    ...seriesNames.length > 0 ? { seriesNames } : {}
  };
}
function buildChartAnchor(anchor) {
  const from2 = anchor.from;
  const to = anchor.to;
  const extent2 = anchor.extent;
  const snapshot = { from: { ...from2 } };
  if (to) {
    snapshot.to = { ...to };
  }
  if (extent2) {
    snapshot.extent = { ...extent2 };
  }
  return snapshot;
}
function buildChartSeries(items) {
  if (items.length === 0) {
    return [];
  }
  return items.map((series) => buildChartSeriesProps(series));
}
function buildChartSeriesProps(series) {
  const props = { name: series.name };
  const values = series.values;
  if (values !== undefined) {
    props.values = [...values];
  }
  const xValues = series.xValues;
  if (xValues !== undefined) {
    props.xValues = [...xValues];
  }
  const categories = series.categories;
  if (categories.length > 0) {
    props.categories = [...categories];
  }
  if (series.formula !== undefined) {
    props.formula = series.formula;
  }
  if (series.categoryFormula !== undefined) {
    props.categoryFormula = series.categoryFormula;
  }
  if (series.xFormula !== undefined) {
    props.xFormula = series.xFormula;
  }
  if (series.valuesFormatCode !== undefined) {
    props.valuesFormatCode = series.valuesFormatCode;
  }
  if (series.xValuesFormatCode !== undefined) {
    props.xValuesFormatCode = series.xValuesFormatCode;
  }
  const stroke = buildChartLine(series.stroke);
  if (stroke) {
    props.stroke = stroke;
  }
  const marker = buildChartMarker(series.marker);
  if (marker) {
    props.marker = marker;
  }
  const fill2 = toPatchFillConfig2(series.fill);
  if (fill2 !== undefined) {
    props.fill = fill2;
  }
  return props;
}
function buildChartLine(line) {
  return buildGenericChartLine(line);
}
function buildGenericChartLine(line) {
  const fill2 = toPatchFillConfig2(line.fill);
  const color2 = fill2 === undefined && typeof line.color === "string" ? line.color : undefined;
  const style = typeof line.style === "string" ? line.style : undefined;
  const width = typeof line.width === "number" ? line.width : undefined;
  if (fill2 === undefined && color2 === undefined && style === undefined && width === undefined) {
    return;
  }
  const props = {};
  if (fill2 !== undefined) {
    props.fill = fill2;
  }
  if (color2 !== undefined) {
    props.color = color2;
  }
  if (style !== undefined) {
    props.style = style;
  }
  if (width !== undefined) {
    props.width = width;
  }
  return props;
}
function buildChartMarker(marker) {
  const symbol2 = marker.symbol;
  const size2 = marker.size;
  if (symbol2 === undefined && size2 === undefined) {
    return;
  }
  const props = {};
  if (symbol2 !== undefined) {
    props.symbol = symbol2;
  }
  if (size2 !== undefined) {
    props.size = size2;
  }
  return props;
}
function buildChartDataLabels(chart2) {
  const labels = chart2.dataLabels;
  const props = {
    showValue: labels.showValue,
    showSeriesName: labels.showSeriesName,
    showCategoryName: labels.showCategoryName,
    showPercent: labels.showPercent,
    showLeaderLines: labels.showLeaderLines
  };
  const hasValues = Object.values(props).some((value) => value === true);
  return hasValues ? props : undefined;
}
function buildChartBarOptions(chart2) {
  const barOptions = chart2.barOptions;
  const props = {
    direction: barOptions.direction,
    grouping: barOptions.grouping,
    varyColors: barOptions.varyColors ? true : undefined,
    gapWidth: barOptions.gapWidth,
    gapDepth: barOptions.gapDepth,
    overlap: barOptions.overlap,
    bar3dShape: barOptions.bar3dShape
  };
  return Object.values(props).some((value) => value !== undefined) ? props : undefined;
}
function buildChartPieOptions(chart2) {
  const firstSliceAngle = chart2.pieOptions.firstSliceAngle;
  return firstSliceAngle !== undefined ? { firstSliceAngle } : undefined;
}
function buildChartDoughnutOptions(chart2) {
  const holeSize = chart2.doughnutOptions.holeSize;
  const firstSliceAngle = chart2.doughnutOptions.firstSliceAngle;
  return holeSize !== undefined || firstSliceAngle !== undefined ? {
    ...holeSize !== undefined ? { holeSize } : {},
    ...firstSliceAngle !== undefined ? { firstSliceAngle } : {}
  } : undefined;
}
function buildChartAreaProps(fill2, line) {
  const fillConfig = toPatchFillConfig2(fill2);
  const lineConfig = buildGenericChartLine(line);
  if (fillConfig === undefined && lineConfig === undefined) {
    return;
  }
  return {
    ...fillConfig !== undefined ? { fill: fillConfig } : {},
    ...lineConfig !== undefined ? { line: lineConfig } : {}
  };
}
function toPatchFillConfig2(fill2) {
  if (!fill2 || typeof fill2 !== "object" || !("toConfig" in fill2) || typeof fill2.toConfig !== "function") {
    return;
  }
  const raw = fill2.toConfig();
  if (!raw) {
    return;
  }
  if (typeof raw === "object" && raw !== null && "type" in raw) {
    if (raw.type === "proto") {
      return;
    }
  }
  return raw;
}
function cloneCfvoInput(entry) {
  if (typeof entry === "number" || typeof entry === "string") {
    return entry;
  }
  return { ...entry };
}
function toRecordedConditionalFormatRule(rule2) {
  switch (rule2.type) {
    case "aboveAverage":
      return {
        type: "aboveAverage",
        aboveAverage: rule2.aboveAverage,
        equalAverage: rule2.equalAverage,
        stdDev: rule2.stdDev,
        format: toRecordedDifferentialFormatConfig(rule2.format)
      };
    case "beginsWith":
    case "cellIs":
    case "containsText":
    case "endsWith":
    case "notContainsText":
      if (rule2.type !== "cellIs") {
        return {
          type: rule2.type,
          text: rule2.text,
          format: toRecordedDifferentialFormatConfig(rule2.format)
        };
      }
      return {
        type: "cellIs",
        operator: rule2.operator,
        formula: rule2.formula,
        format: toRecordedDifferentialFormatConfig(rule2.format)
      };
    case "colorScale":
      return {
        type: "colorScale",
        colors: (rule2.colors ?? []).map((color2) => toRecordedColorConfig(color2)).filter((color2) => color2 !== undefined),
        thresholds: rule2.thresholds?.map((entry) => cloneCfvoInput(entry))
      };
    case "dataBar":
      return {
        type: "dataBar",
        color: toRecordedColorConfig(rule2.color),
        thresholds: rule2.thresholds?.map((entry) => cloneCfvoInput(entry)),
        gradient: rule2.gradient
      };
    case "containsBlanks":
    case "containsErrors":
    case "duplicateValues":
    case "notContainsBlanks":
    case "notContainsErrors":
    case "uniqueValues":
      return {
        type: rule2.type,
        format: toRecordedDifferentialFormatConfig(rule2.format)
      };
    case "iconSet":
      return {
        type: "iconSet",
        iconSet: rule2.iconSet,
        showValue: rule2.showValue,
        reverse: rule2.reverse,
        custom: rule2.custom,
        percent: rule2.percent,
        thresholds: rule2.thresholds?.map((entry) => cloneCfvoInput(entry))
      };
    case "expression":
      return {
        type: "expression",
        formula: rule2.formula,
        format: toRecordedDifferentialFormatConfig(rule2.format)
      };
    case "timePeriod":
      return {
        type: "timePeriod",
        timePeriod: rule2.timePeriod,
        format: toRecordedDifferentialFormatConfig(rule2.format)
      };
    case "top10":
      return {
        type: "top10",
        rank: rule2.rank,
        percent: rule2.percent,
        bottom: rule2.bottom,
        format: toRecordedDifferentialFormatConfig(rule2.format)
      };
    default:
      return null;
  }
}
function buildConditionalFormatAddOp(input) {
  const { sheet, target, rule: rule2 } = input;
  const recordedRule = toRecordedConditionalFormatRule(rule2);
  if (!recordedRule) {
    return null;
  }
  const range2 = conditionalFormatTargetToRangeRef(target);
  if (!range2) {
    return null;
  }
  return {
    op: "conditionalformat.add",
    target: {
      sheet,
      range: range2
    },
    props: {
      rule: recordedRule
    }
  };
}
function conditionalFormatTargetToRangeRef(target) {
  const startAddress = target.startAddress;
  if (!startAddress) {
    return null;
  }
  const endAddress = target.endAddress;
  return endAddress && endAddress !== startAddress ? `${startAddress}:${endAddress}` : startAddress;
}
function toRecordedDifferentialFormatConfig(format2) {
  if (!format2) {
    return;
  }
  const fill2 = toRecordedFillConfig(format2.fill);
  const font = toRecordedDifferentialFontConfig(format2.font);
  const border = toRecordedDifferentialBorderConfig(format2.border);
  const normalized = {};
  if (fill2 !== undefined) {
    normalized.fill = fill2;
  }
  if (font !== undefined) {
    normalized.font = font;
  }
  if (border !== undefined) {
    normalized.border = border;
  }
  if (format2.numberFormat !== undefined) {
    normalized.numberFormat = format2.numberFormat;
  }
  return Object.keys(normalized).length > 0 ? normalized : undefined;
}
function toRecordedDifferentialFontConfig(font) {
  if (!font) {
    return;
  }
  const color2 = toRecordedColorConfig(font.color);
  const normalized = {};
  if (font.bold !== undefined) {
    normalized.bold = font.bold;
  }
  if (font.italic !== undefined) {
    normalized.italic = font.italic;
  }
  if (font.size !== undefined) {
    normalized.size = font.size;
  }
  if (font.name !== undefined) {
    normalized.name = font.name;
  }
  if (color2 !== undefined) {
    normalized.color = color2;
  }
  return Object.keys(normalized).length > 0 ? normalized : undefined;
}
function toRecordedDifferentialBorderConfig(border) {
  if (!border) {
    return;
  }
  const normalized = {};
  const top = toRecordedDifferentialBorderLineConfig(border.top);
  const bottom = toRecordedDifferentialBorderLineConfig(border.bottom);
  const left = toRecordedDifferentialBorderLineConfig(border.left);
  const right = toRecordedDifferentialBorderLineConfig(border.right);
  const diagonal = toRecordedDifferentialBorderLineConfig(border.diagonal);
  if (top !== undefined) {
    normalized.top = top;
  }
  if (bottom !== undefined) {
    normalized.bottom = bottom;
  }
  if (left !== undefined) {
    normalized.left = left;
  }
  if (right !== undefined) {
    normalized.right = right;
  }
  if (diagonal !== undefined) {
    normalized.diagonal = diagonal;
  }
  if (border.diagonalUp !== undefined) {
    normalized.diagonalUp = border.diagonalUp;
  }
  if (border.diagonalDown !== undefined) {
    normalized.diagonalDown = border.diagonalDown;
  }
  return Object.keys(normalized).length > 0 ? normalized : undefined;
}
function toRecordedDifferentialBorderLineConfig(line) {
  if (!line) {
    return;
  }
  const color2 = toRecordedColorConfig(line.color);
  const normalized = {};
  if (line.style !== undefined) {
    normalized.style = line.style;
  }
  if (line.weight !== undefined) {
    normalized.weight = line.weight;
  }
  if (color2 !== undefined) {
    normalized.color = color2;
  }
  return Object.keys(normalized).length > 0 ? normalized : undefined;
}
function toRecordedFillConfig(fill2) {
  if (!fill2) {
    return;
  }
  if (fill2 instanceof Fill2) {
    return toRecordedFillConfigFromConfig(fill2.toConfig()) ?? toRecordedFillConfigFromProto(fill2.toProto());
  }
  return toRecordedFillConfigFromConfig(fill2);
}
function toRecordedFillConfigFromConfig(fill2) {
  if (!fill2) {
    return;
  }
  if (typeof fill2 === "string") {
    return fill2;
  }
  switch (fill2.type) {
    case "none":
      return { type: "none" };
    case "solid": {
      const color2 = toRecordedColorConfig(fill2.color);
      if (!color2) {
        return;
      }
      const pattern = toRecordedPatternConfig(fill2.pattern);
      return pattern ? {
        type: "solid",
        color: color2,
        pattern
      } : {
        type: "solid",
        color: color2
      };
    }
    case "gradient":
      return {
        type: "gradient",
        stops: fill2.stops.map((stop) => {
          const color2 = toRecordedColorConfig(stop.color);
          if (!color2) {
            return;
          }
          return {
            offset: stop.offset,
            color: color2
          };
        }).filter((stop) => stop !== undefined),
        angleDeg: fill2.angleDeg,
        gradientKind: fill2.gradientKind
      };
    case "image":
      return {
        type: "image",
        imageReference: fill2.imageReference,
        alphaModFix: fill2.alphaModFix,
        stretchFillRect: fill2.stretchFillRect,
        fillRect: fill2.fillRect,
        pathType: fill2.pathType,
        srcRect: fill2.srcRect
      };
    case "proto":
      return toRecordedFillConfigFromProto(fill2.proto);
  }
}
function toRecordedFillConfigFromProto(proto) {
  if (!proto) {
    return;
  }
  const fill2 = new Fill2({ type: "proto", proto });
  if (fill2.type === 4 /* FILL_TYPE_PICTURE */ && fill2.imageReference) {
    return {
      type: "image",
      imageReference: fill2.imageReference,
      alphaModFix: fill2.alphaModFix,
      stretchFillRect: fill2.stretchFillRect,
      fillRect: fill2.fillRect,
      pathType: fill2.pathType,
      srcRect: fill2.srcRect
    };
  }
  if (fill2.type === 2 /* FILL_TYPE_GRADIENT */) {
    return {
      type: "gradient",
      stops: (fill2.gradientStops ?? []).map((stop) => {
        const offset = stop.position;
        const color3 = toRecordedColorConfig(stop.color ? { type: "proto", proto: stop.color } : undefined);
        if (offset === undefined || !color3) {
          return;
        }
        return {
          offset,
          color: color3
        };
      }).filter((stop) => stop !== undefined),
      angleDeg: fill2.angleDeg ?? undefined,
      gradientKind: fill2.gradientKind ?? undefined
    };
  }
  const color2 = toRecordedColorConfig(fill2.color);
  const pattern = fill2.pattern ? toRecordedPatternConfig(fill2.pattern.toConfig()) : undefined;
  if (color2) {
    return pattern ? {
      type: "solid",
      color: color2,
      pattern
    } : {
      type: "solid",
      color: color2
    };
  }
  if (pattern) {
    return {
      type: "solid",
      color: pattern.color,
      pattern
    };
  }
  return;
}
function toRecordedPatternConfig(pattern) {
  if (!pattern) {
    return;
  }
  const normalized = pattern.type === "proto" ? new Pattern({ type: "proto", proto: pattern.proto }).toConfig() : pattern;
  if (!normalized || normalized.type === "proto") {
    return;
  }
  const color2 = toRecordedColorConfig(normalized.color);
  if (!color2) {
    return;
  }
  return {
    type: normalized.type,
    color: color2
  };
}
function toRecordedColorConfig(color2) {
  if (!color2) {
    return;
  }
  const normalized = (color2 instanceof Color4 ? color2 : new Color4(color2)).toConfig();
  if (!normalized) {
    return;
  }
  if (typeof normalized === "string") {
    return normalized;
  }
  if (normalized.type === "rgb" || normalized.type === "theme") {
    return normalized;
  }
  if (!normalized.proto) {
    return;
  }
  return toRecordedColorConfig({ type: "proto", proto: normalized.proto });
}
function normalizeRecordedSparklineColor(color2) {
  if (color2 === undefined) {
    return;
  }
  const config = new Color4(color2).toConfig();
  if (!config) {
    return;
  }
  if (typeof config === "string") {
    return config;
  }
  return config.type === "proto" ? undefined : config;
}
function buildSparklineGroupSetOp(input) {
  const { group, sheetName, targetUid } = input;
  return {
    op: "sparkline.set",
    target: {
      sheet: sheetName,
      uid: targetUid ?? group.uid,
      selector: buildSparklineTargetSelector(group, sheetName)
    },
    props: buildSparklineGroupProps(group, sheetName, { includeUid: false })
  };
}
function buildSparklineGroupAddOp(input) {
  const { group, sheetName, as } = input;
  const op = {
    op: "sparkline.add",
    props: buildSparklineGroupProps(group, sheetName, { includeUid: true })
  };
  if (as) {
    op.as = as;
  }
  return op;
}
function buildSparklineTargetSelector(group, sheetName) {
  return {
    uid: group.uid,
    targetRange: sparklineRangeToRef(group.locationRange, sheetName),
    sourceData: sparklineRangeToRef(group.sourceData, sheetName)
  };
}
function buildSparklineGroupProps(group, sheetName, options) {
  const props = {
    type: group.type,
    targetRange: sparklineRangeToRef(group.locationRange, sheetName),
    sourceData: sparklineRangeToRef(group.sourceData, sheetName),
    lineWeight: group.lineWeight,
    displayEmptyCellsAs: group.displayEmptyCellsAs,
    displayHidden: group.displayHidden,
    axis: {
      ...group.axis.manualMin !== undefined ? { manualMin: group.axis.manualMin } : {},
      ...group.axis.manualMax !== undefined ? { manualMax: group.axis.manualMax } : {},
      minMode: group.axis.minMode,
      maxMode: group.axis.maxMode,
      showAxis: group.axis.showAxis,
      rightToLeft: group.axis.rightToLeft
    },
    markers: {
      show: group.markers.show,
      high: group.markers.high,
      low: group.markers.low,
      first: group.markers.first,
      last: group.markers.last,
      negative: group.markers.negative
    }
  };
  if (options?.includeUid) {
    props.uid = group.uid;
  }
  const dateAxisRange = group.dateAxisRange;
  if (dateAxisRange) {
    props.dateAxisRange = sparklineRangeToRef(dateAxisRange, sheetName);
  }
  const seriesColor = normalizeRecordedSparklineColor(group.seriesColor?.toConfig());
  if (seriesColor !== undefined) {
    props.seriesColor = seriesColor;
  }
  const negativeColor = normalizeRecordedSparklineColor(group.negativeColor?.toConfig());
  if (negativeColor !== undefined) {
    props.negativeColor = negativeColor;
  }
  const axisColor = normalizeRecordedSparklineColor(group.axisColor?.toConfig());
  if (axisColor !== undefined) {
    props.axisColor = axisColor;
  }
  const markersColor = normalizeRecordedSparklineColor(group.markersColor?.toConfig());
  if (markersColor !== undefined) {
    props.markersColor = markersColor;
  }
  const firstMarkerColor = normalizeRecordedSparklineColor(group.firstMarkerColor?.toConfig());
  if (firstMarkerColor !== undefined) {
    props.firstMarkerColor = firstMarkerColor;
  }
  const lastMarkerColor = normalizeRecordedSparklineColor(group.lastMarkerColor?.toConfig());
  if (lastMarkerColor !== undefined) {
    props.lastMarkerColor = lastMarkerColor;
  }
  const highMarkerColor = normalizeRecordedSparklineColor(group.highMarkerColor?.toConfig());
  if (highMarkerColor !== undefined) {
    props.highMarkerColor = highMarkerColor;
  }
  const lowMarkerColor = normalizeRecordedSparklineColor(group.lowMarkerColor?.toConfig());
  if (lowMarkerColor !== undefined) {
    props.lowMarkerColor = lowMarkerColor;
  }
  return props;
}
function sparklineRangeToRef(range2, fallbackSheetName) {
  const worksheet = getRangeWorksheet(range2);
  if (!worksheet) {
    throw new Error("Sparkline ranges must be attached to a worksheet.");
  }
  return {
    sheet: worksheet.name || fallbackSheetName,
    range: range2.address
  };
}
function buildDataValidationSetOp(input) {
  const { sheet, record } = input;
  if (!record.sqref) {
    return null;
  }
  const props = {
    rule: buildDataValidationRuleState(record)
  };
  const prompt = buildDataValidationPromptState(record);
  if (prompt) {
    props.prompt = prompt;
  }
  const errorAlert = buildDataValidationErrorAlertState(record);
  if (errorAlert) {
    props.errorAlert = errorAlert;
  }
  if (record.allowBlank !== undefined) {
    props.ignoreBlanks = record.allowBlank;
  }
  if (record.showDropDown !== undefined) {
    props.inCellDropDown = !record.showDropDown;
  }
  return {
    op: "datavalidation.set",
    target: {
      sheet,
      range: record.sqref
    },
    props
  };
}
function buildDataValidationRuleState(record) {
  const rule2 = {
    type: mapDataValidationRuleType(record.type)
  };
  const operator = mapDataValidationOperator(record.operator);
  if (operator !== undefined) {
    rule2.operator = operator;
  }
  const listValues = parseListValidationValues(record);
  if (listValues) {
    rule2.values = listValues;
    return rule2;
  }
  if (record.formula1 !== undefined) {
    rule2.formula1 = record.formula1;
  }
  if (record.formula2 !== undefined) {
    rule2.formula2 = record.formula2;
  }
  return rule2;
}
function buildDataValidationPromptState(record) {
  if (record.promptTitle === undefined && record.promptMessage === undefined && record.showInputMessage === undefined) {
    return;
  }
  const prompt = {};
  if (record.promptTitle !== undefined) {
    prompt.title = record.promptTitle;
  }
  if (record.promptMessage !== undefined) {
    prompt.message = record.promptMessage;
  }
  if (record.showInputMessage !== undefined) {
    prompt.show = record.showInputMessage;
  }
  return prompt;
}
function buildDataValidationErrorAlertState(record) {
  if (record.errorTitle === undefined && record.errorMessage === undefined && record.errorStyle === undefined && record.showErrorMessage === undefined) {
    return;
  }
  const errorAlert = {};
  if (record.errorTitle !== undefined) {
    errorAlert.title = record.errorTitle;
  }
  if (record.errorMessage !== undefined) {
    errorAlert.message = record.errorMessage;
  }
  const style = mapDataValidationErrorStyle(record.errorStyle);
  if (style !== undefined) {
    errorAlert.style = style;
  }
  if (record.showErrorMessage !== undefined) {
    errorAlert.show = record.showErrorMessage;
  }
  return errorAlert;
}
function parseListValidationValues(record) {
  if (mapDataValidationRuleType(record.type) !== "list") {
    return;
  }
  if (record.formula2 !== undefined) {
    return;
  }
  const formula1 = record.formula1?.trim();
  if (!formula1 || formula1.length < 2) {
    return;
  }
  if (!formula1.startsWith('"') || !formula1.endsWith('"')) {
    return;
  }
  const inner = formula1.slice(1, -1);
  return inner ? inner.split(",") : [];
}
function mapDataValidationRuleType(value) {
  switch (value) {
    case 2 /* DATA_VALIDATION_TYPE_WHOLE */:
      return "whole";
    case 3 /* DATA_VALIDATION_TYPE_DECIMAL */:
      return "decimal";
    case 4 /* DATA_VALIDATION_TYPE_LIST */:
      return "list";
    case 5 /* DATA_VALIDATION_TYPE_DATE */:
      return "date";
    case 6 /* DATA_VALIDATION_TYPE_TIME */:
      return "time";
    case 7 /* DATA_VALIDATION_TYPE_TEXT_LENGTH */:
      return "textLength";
    case 8 /* DATA_VALIDATION_TYPE_CUSTOM */:
      return "custom";
    case 1 /* DATA_VALIDATION_TYPE_NONE */:
    case 0 /* DATA_VALIDATION_TYPE_UNSPECIFIED */:
    case -1 /* UNRECOGNIZED */:
    default:
      return "none";
  }
}
function mapDataValidationOperator(value) {
  switch (value) {
    case 1 /* DATA_VALIDATION_OPERATOR_BETWEEN */:
      return "between";
    case 2 /* DATA_VALIDATION_OPERATOR_NOT_BETWEEN */:
      return "notBetween";
    case 3 /* DATA_VALIDATION_OPERATOR_EQUAL */:
      return "equal";
    case 4 /* DATA_VALIDATION_OPERATOR_NOT_EQUAL */:
      return "notEqual";
    case 5 /* DATA_VALIDATION_OPERATOR_LESS_THAN */:
      return "lessThan";
    case 6 /* DATA_VALIDATION_OPERATOR_LESS_THAN_OR_EQUAL */:
      return "lessThanOrEqual";
    case 7 /* DATA_VALIDATION_OPERATOR_GREATER_THAN */:
      return "greaterThan";
    case 8 /* DATA_VALIDATION_OPERATOR_GREATER_THAN_OR_EQUAL */:
      return "greaterThanOrEqual";
    default:
      return;
  }
}
function mapDataValidationErrorStyle(value) {
  switch (value) {
    case 1 /* DATA_VALIDATION_ERROR_STYLE_STOP */:
      return "stop";
    case 2 /* DATA_VALIDATION_ERROR_STYLE_WARNING */:
      return "warning";
    case 3 /* DATA_VALIDATION_ERROR_STYLE_INFORMATION */:
      return "information";
    default:
      return;
  }
}
function buildShapeAddOpFromShape(input) {
  const { sheet, shape: shape2, as } = input;
  const props = buildShapeAddPropsFromShape(shape2);
  if (!props) {
    return null;
  }
  const op = {
    op: "shape.add",
    sheet,
    props
  };
  if (as) {
    op.as = as;
  }
  return op;
}
function buildShapeSetOpFromShape(input) {
  const { sheet, shape: shape2 } = input;
  const props = buildShapeSetPropsFromShape(shape2);
  if (!Object.values(props).some((value) => value !== undefined)) {
    return null;
  }
  return {
    op: "shape.set",
    target: {
      sheet,
      selector: buildShapeTargetSelector(shape2)
    },
    props
  };
}
function buildShapeTargetSelector(shape2) {
  const geometryProto = shape2.toProto().shape?.geometry;
  const geometry = geometryProto ? SHAPE_GEOMETRY_FROM_PROTO2[geometryProto] : undefined;
  return {
    anchor: shape2.anchor.toConfig(),
    ...geometry ? { geometry } : {},
    ...shape2.name ? { name: shape2.name } : {}
  };
}
function buildShapeAddPropsFromShape(shape2) {
  const props = buildShapeSetPropsFromShape(shape2);
  const geometryProto = shape2.toProto().shape?.geometry;
  const geometry = geometryProto ? SHAPE_GEOMETRY_FROM_PROTO2[geometryProto] : undefined;
  const line = buildShapeAddLineFromShape(shape2.line);
  if (!geometry || geometry === "custom") {
    return null;
  }
  return {
    id: shape2.id,
    geometry,
    ...props.anchor ? { anchor: props.anchor } : {},
    ...props.fill ? { fill: props.fill } : {},
    ...line ? { line } : {}
  };
}
function buildShapeSetPropsFromShape(shape2) {
  const fill2 = toRecordedShapeFillConfig(shape2.fill);
  const line = buildShapeSetLine(shape2.line);
  return {
    name: shape2.name,
    zIndex: shape2.zIndex,
    placeholderType: shape2.placeholderType,
    placeholderIndex: shape2.placeholderIndex,
    position: shape2.position,
    anchor: shape2.anchor.toConfig(),
    ...fill2 !== undefined ? { fill: fill2 } : {},
    ...line !== undefined ? { line } : {}
  };
}
function buildShapeSetLine(line) {
  const fill2 = toRecordedShapeFillConfig(line.fill);
  const style = line.style;
  const width = line.width;
  if (fill2 === undefined && style === undefined && width === undefined) {
    return;
  }
  return {
    ...fill2 !== undefined ? { fill: fill2 } : {},
    style: style ?? "solid",
    ...width !== undefined ? { width } : {}
  };
}
function buildShapeAddLineFromShape(line) {
  const fill2 = toRecordedShapeFillConfig(line.fill);
  const style = line.style ?? "solid";
  const width = line.width;
  if (fill2 === undefined && style === undefined && width === undefined) {
    return;
  }
  return {
    style,
    ...fill2 !== undefined ? { fill: fill2 } : {},
    ...width !== undefined ? { width } : {}
  };
}
function toRecordedShapeFillConfig(fill2) {
  if (!fill2 || typeof fill2 !== "object" || !("toConfig" in fill2) || typeof fill2.toConfig !== "function") {
    return;
  }
  const raw = fill2.toConfig();
  if (!raw) {
    return;
  }
  if (typeof raw === "object" && raw !== null && "type" in raw) {
    if (raw.type === "proto") {
      return;
    }
  }
  return raw;
}
function buildImageAddOp(input) {
  const { sheet, source, anchor, as } = input;
  const props = buildImageAddProps(source, anchor);
  if (!props) {
    return null;
  }
  const op = {
    op: "image.add",
    sheet,
    props
  };
  if (as) {
    op.as = as;
  }
  return op;
}
function buildImageSetOp(input) {
  const { sheet, image: image2, previous, source, targetImageId } = input;
  return {
    op: "image.set",
    target: {
      ...previous,
      sheet,
      imageId: targetImageId ?? previous.imageId
    },
    props: {
      imageId: image2.imageId,
      anchor: image2.anchor.toConfig(),
      ...buildImageSetSourceProps(source)
    }
  };
}
function buildImageAddProps(source, anchor) {
  const recordable = toRecordableImageAddOptions(source);
  if ("path" in recordable) {
    const props = {
      path: recordable.path
    };
    if ("prompt" in recordable && recordable.prompt !== undefined) {
      props.prompt = recordable.prompt;
    }
    if (anchor) {
      props.anchor = anchor;
    }
    return props;
  }
  if ("dataUrl" in recordable) {
    const props = {
      dataUrl: recordable.dataUrl
    };
    if (recordable.contentType !== undefined) {
      props.contentType = recordable.contentType;
    }
    if ("prompt" in recordable && recordable.prompt !== undefined) {
      props.prompt = recordable.prompt;
    }
    if (anchor) {
      props.anchor = anchor;
    }
    return props;
  }
  if ("uri" in recordable) {
    const props = {
      uri: recordable.uri
    };
    if ("prompt" in recordable && recordable.prompt !== undefined) {
      props.prompt = recordable.prompt;
    }
    if (anchor) {
      props.anchor = anchor;
    }
    return props;
  }
  if ("prompt" in recordable) {
    return anchor ? { prompt: recordable.prompt, anchor } : { prompt: recordable.prompt };
  }
  return null;
}
function buildImageSetSourceProps(source) {
  if (!source) {
    return {};
  }
  const recordable = toRecordableImageAddOptions(source);
  if ("path" in recordable) {
    const props = {
      path: recordable.path
    };
    if ("prompt" in recordable && recordable.prompt !== undefined) {
      props.prompt = recordable.prompt;
    }
    return props;
  }
  if ("dataUrl" in recordable) {
    const props = {
      dataUrl: recordable.dataUrl
    };
    if (recordable.contentType !== undefined) {
      props.contentType = recordable.contentType;
    }
    if ("prompt" in recordable && recordable.prompt !== undefined) {
      props.prompt = recordable.prompt;
    }
    return props;
  }
  if ("uri" in recordable) {
    const props = {
      uri: recordable.uri
    };
    if ("prompt" in recordable && recordable.prompt !== undefined) {
      props.prompt = recordable.prompt;
    }
    return props;
  }
  if ("prompt" in recordable) {
    return { prompt: recordable.prompt };
  }
  return {};
}

// node_modules/@oai/granola/dist/models/comments/thread.js
class Thread2 {
  #context;
  #target;
  #comments;
  #id;
  #status;
  #resolvedBy;
  #resolvedAt;
  constructor(data, context) {
    this.#id = data.id;
    this.#target = data.target;
    this.#comments = data.comments;
    this.#status = data.status;
    this.#resolvedBy = data.resolvedBy;
    this.#resolvedAt = data.resolvedAt;
    this.#context = context;
  }
  static create(config, context) {
    const target = AnnotationTarget3.fromConfig(config.target);
    const authorId = context.resolveAuthorId(config.author);
    const commentContext = buildCommentContext(context);
    const root = Comment2.create({
      id: config.id,
      authorId,
      createdAt: config.createdAt,
      body: config.body,
      position: config.position
    }, commentContext);
    return new Thread2({
      id: config.id,
      target,
      comments: [root],
      status: config.status ?? 1 /* THREAD_STATUS_ACTIVE */
    }, context);
  }
  static fromProto(proto, context) {
    if (!proto.id) {
      throw new Error("Thread id is required.");
    }
    if (!proto.target) {
      throw new Error("Thread target is required.");
    }
    const commentContext = buildCommentContext(context);
    const comments = (proto.comments ?? []).map((comment) => Comment2.fromProto(comment, commentContext));
    return new Thread2({
      id: proto.id,
      target: AnnotationTarget3.fromProto(proto.target),
      comments,
      status: proto.status ?? 0 /* THREAD_STATUS_UNSPECIFIED */,
      resolvedBy: proto.resolvedBy,
      resolvedAt: proto.resolvedAt
    }, context);
  }
  get id() {
    return this.#id;
  }
  get target() {
    return this.#target;
  }
  get comments() {
    return [...this.#comments];
  }
  get status() {
    return this.#status;
  }
  get resolvedBy() {
    return this.#resolvedBy;
  }
  get resolvedAt() {
    return this.#resolvedAt;
  }
  toSnapshot() {
    return {
      aid: `th/${this.#id}`,
      kind: "thread",
      id: this.#id,
      status: this.#status,
      target: {
        slideId: this.#target.slideId,
        elementId: this.#target.elementId,
        spreadsheetCell: this.#target.spreadsheetCell,
        spreadsheetRange: this.#target.spreadsheetRange
      },
      comments: this.#comments.map((comment) => ({
        id: comment.id,
        text: comment.text,
        authorId: comment.authorId,
        createdAt: comment.createdAt
      }))
    };
  }
  addReply(text2, config = {}) {
    const root = this.#comments[0];
    if (!root) {
      throw new Error("Cannot reply to a thread without a root comment.");
    }
    const authorId = this.#context.resolveAuthorId(config.author);
    const commentContext = buildCommentContext(this.#context);
    const reply = Comment2.create({
      id: config.id ?? generateGuid(),
      parentId: root.id,
      authorId,
      createdAt: config.createdAt,
      body: text2,
      position: config.position
    }, commentContext);
    this.#comments.push(reply);
    this.#context.recordOp?.({
      op: "thread.reply",
      target: this.#recordTargetRef(),
      body: text2,
      author: config.author,
      createdAt: config.createdAt,
      position: config.position
    });
    return reply;
  }
  getComment(id2) {
    return this.#comments.find((comment) => comment.id === id2);
  }
  resolve(author, resolvedAt) {
    this.#status = 2 /* THREAD_STATUS_RESOLVED */;
    this.#resolvedBy = this.#context.resolveAuthorId(author);
    this.#resolvedAt = resolvedAt ?? this.#context.now();
    this.#context.recordOp?.({
      op: "thread.resolve",
      target: this.#recordTargetRef()
    });
  }
  reopen() {
    this.#status = 1 /* THREAD_STATUS_ACTIVE */;
    this.#resolvedBy = undefined;
    this.#resolvedAt = undefined;
    this.#context.recordOp?.({
      op: "thread.reopen",
      target: this.#recordTargetRef()
    });
  }
  delete() {
    this.#context.recordOp?.({
      op: "thread.remove",
      target: this.#recordTargetRef()
    });
    this.#context.removeThread(this);
  }
  toProto() {
    return {
      id: this.#id,
      target: this.#target.toProto(),
      comments: this.#comments.map((comment) => comment.toProto()),
      status: this.#status,
      resolvedBy: this.#resolvedBy,
      resolvedAt: this.#resolvedAt
    };
  }
  #recordTargetRef() {
    const root = this.#comments[0];
    const spreadsheetRef = buildSpreadsheetThreadTargetRef({
      threadId: this.#id,
      target: {
        spreadsheetCell: this.#target.spreadsheetCell,
        spreadsheetRange: this.#target.spreadsheetRange
      },
      rootBody: root?.text,
      rootAuthorId: root?.authorId,
      rootCreatedAt: root?.createdAt
    });
    if (spreadsheetRef) {
      return spreadsheetRef;
    }
    return `th/${this.#id}`;
  }
}
var buildCommentContext = (context) => {
  return {
    resolveAuthorId: context.resolveAuthorId,
    now: context.now
  };
};

// node_modules/@oai/granola/dist/models/comments/threads-collection.js
class ThreadsCollection {
  #items = [];
  #byId = new Map;
  #context;
  constructor(threads = [], context) {
    this.#context = context;
    threads.forEach((thread) => {
      this.#registerThread(Thread2.fromProto(thread, this.#threadContext()));
    });
  }
  get items() {
    return [...this.#items];
  }
  getById(id2) {
    return this.#byId.get(id2);
  }
  add(target, body, options = {}) {
    return this.#addThread(target, body, options);
  }
  __addForApply(target, body, options = {}) {
    return this.#addThread(target, body, options);
  }
  toProto() {
    return this.#items.map((thread) => thread.toProto());
  }
  replace(threads = []) {
    this.#items = [];
    this.#byId = new Map;
    threads.forEach((thread) => {
      this.#registerThread(Thread2.fromProto(thread, this.#threadContext()));
    });
  }
  #registerThread(thread) {
    this.#items.push(thread);
    this.#byId.set(thread.id, thread);
  }
  #removeThread(thread) {
    const index = this.#items.indexOf(thread);
    if (index >= 0) {
      this.#items.splice(index, 1);
    }
    this.#byId.delete(thread.id);
  }
  #addThread(target, body, options) {
    const id2 = options.id ?? generateAidSuffix();
    const position = options.position ?? resolveDefaultPosition(target);
    const thread = Thread2.create({
      id: id2,
      target,
      body,
      author: options.author,
      createdAt: options.createdAt,
      position,
      status: options.status
    }, this.#threadContext());
    this.#registerThread(thread);
    return thread;
  }
  #threadContext() {
    return {
      resolveAuthorId: this.#context.resolveAuthorId,
      now: this.#context.now,
      removeThread: (thread) => this.#removeThread(thread),
      recordOp: this.#context.recordOp
    };
  }
}
var resolveDefaultPosition = (target) => {
  if ("element" in target) {
    return positionFromElement(target.element);
  }
  if ("textRange" in target) {
    return positionFromElement(target.textRange.element);
  }
  if ("textMatch" in target) {
    return positionFromElement(target.textMatch.element);
  }
  if ("slide" in target) {
    return positionFromSlide(target.slide);
  }
  return;
};
var positionFromElement = (element) => {
  const frame = element.frame;
  if (!frame) {
    return { x: 0, y: 0 };
  }
  return {
    x: frame.left ?? 0,
    y: frame.top ?? 0
  };
};
var positionFromSlide = (slide) => {
  const frame = slide.frame;
  return {
    x: frame.width / 2,
    y: frame.height / 2
  };
};

// node_modules/@oai/granola/dist/models/comments/comments.js
class Comments {
  people;
  threads;
  #selfId;
  #recordOp;
  constructor(config = {}) {
    this.people = new PeopleCollection(config.people ?? []);
    this.#recordOp = config.recordOp;
    this.threads = new ThreadsCollection(config.threads ?? [], {
      resolveAuthorId: (author) => this.#resolveAuthorId(author),
      now: () => this.#now(),
      recordOp: (op) => this.#recordOp?.(op)
    });
  }
  get self() {
    if (!this.#selfId) {
      return;
    }
    return this.people.getById(this.#selfId);
  }
  setSelf(person) {
    const resolved = this.#resolvePerson(person);
    this.#selfId = resolved.id;
    this.#recordOp?.({
      op: "comments.self.set",
      person: resolved.toProto()
    });
    return resolved;
  }
  clearSelf() {
    this.#selfId = undefined;
  }
  addThread(target, body, options = {}) {
    const thread = this.threads.add(target, body, options);
    const rootComment = thread.comments[0];
    const rootAuthor = rootComment ? this.people.getById(rootComment.authorId)?.toProto() : undefined;
    const op = buildThreadAddOp({
      threadId: thread.id,
      target: {
        spreadsheetCell: thread.target.spreadsheetCell,
        spreadsheetRange: thread.target.spreadsheetRange
      },
      body,
      author: rootAuthor,
      createdAt: rootComment?.createdAt
    });
    if (op)
      this.#recordOp?.(op);
    return thread;
  }
  __addThreadForApply(target, body, options = {}) {
    return this.threads.__addForApply(target, body, options);
  }
  getThread(id2) {
    return this.threads.getById(id2);
  }
  toProto() {
    return {
      people: this.people.toProto(),
      threads: this.threads.toProto()
    };
  }
  replaceFromProto(config) {
    const selfId = this.#selfId;
    this.people.replace(config.people ?? []);
    this.threads.replace(config.threads ?? []);
    if (selfId && !this.people.getById(selfId)) {
      this.#selfId = undefined;
    }
  }
  #resolvePerson(input) {
    if (input instanceof Person2) {
      return this.people.register(input);
    }
    if (isPersonConfig(input)) {
      return this.people.add(input);
    }
    if (isPersonReference(input)) {
      const existing = this.people.getById(input.id);
      if (!existing) {
        throw new Error(`Person id not found: ${input.id}`);
      }
      return existing;
    }
    throw new Error("Unsupported person input.");
  }
  #resolveAuthorId(author) {
    if (!author) {
      if (!this.#selfId) {
        throw new Error("Comment author is required when self is not set. " + "Call comments.self.set(...) or pass an author.");
      }
      return this.#selfId;
    }
    return this.#resolvePerson(author).id;
  }
  #now() {
    return new Date().toISOString();
  }
}

// node_modules/@oai/granola/dist/models/presentation/presentation-inspect.js
var DEFAULT_KIND_TOKENS = [
  "deck",
  "slide",
  "textbox",
  "shape",
  "table",
  "chart",
  "image",
  "notes",
  "thread"
];
var KIND_ALIASES = {
  charts: "chart",
  comments: "thread",
  decks: "deck",
  images: "image",
  layout: "layout",
  layoutlist: "layout",
  layoutlists: "layout",
  layouts: "layout",
  shapes: "shape",
  slides: "slide",
  table: "table",
  tables: "table",
  text: "textbox",
  textboxes: "textbox",
  texts: "textbox",
  textranges: "textrange",
  threads: "thread"
};
var KIND_TOKEN_SET = new Set([
  ...DEFAULT_KIND_TOKENS,
  "layout",
  "notice",
  "textrange"
]);
var PROPERTY_ALIASES = {
  bboxunit: "bboxUnit",
  charttype: "chartType",
  colcount: "cols",
  columncount: "cols",
  columns: "cols",
  layoutid: "layoutId",
  placeholdertext: "textPreview",
  rowcount: "rows",
  textchars: "textChars",
  textlines: "textLines",
  textpreview: "textPreview",
  textshapes: "textShapes"
};
var PROPERTY_TOKEN_SET = new Set([
  "alt",
  "bbox",
  "bboxUnit",
  "chartType",
  "comments",
  "geometry",
  "id",
  "layoutId",
  "length",
  "message",
  "name",
  "placeholder",
  "placeholders",
  "preview",
  "rows",
  "cols",
  "slide",
  "status",
  "target",
  "text",
  "textChars",
  "textLines",
  "textPreview",
  "textShapes",
  "title",
  "type"
]);
var DEFAULT_KIND_PROPERTIES = {
  deck: ["id", "name"],
  slide: ["id", "slide", "title", "textShapes"],
  textbox: [
    "id",
    "slide",
    "name",
    "placeholder",
    "text",
    "textPreview",
    "textChars",
    "textLines",
    "bbox",
    "bboxUnit"
  ],
  shape: ["id", "slide", "name", "placeholder", "bbox", "bboxUnit"],
  table: ["id", "slide", "name", "rows", "cols", "preview", "bbox", "bboxUnit"],
  chart: ["id", "slide", "name", "chartType", "title", "bbox", "bboxUnit"],
  image: ["id", "slide", "name", "geometry", "alt", "bbox", "bboxUnit"],
  notes: ["id", "slide", "text"],
  thread: ["id", "slide", "target", "status", "comments"],
  textrange: ["id", "slide", "target", "length"],
  layout: ["layoutId", "name", "type", "placeholders"],
  notice: ["message"]
};
var DEFAULT_MAX_CHARS = 12000;
var TRUNCATED_TEXT_PREVIEW_LENGTH = 80;
async function inspectPresentation(presentation, options = {}) {
  const snapshot = presentation.toSnapshot();
  const kindInfo = parseKindTokens(options.kind);
  const includeInfo = parsePropertyTokens(options.include, "include");
  const excludeInfo = parsePropertyTokens(options.exclude, "exclude");
  const target = normalizeTarget(options.target, snapshot.aid);
  const metadata = {
    revision: generateAidSuffix(),
    target,
    kind: {
      requested: options.kind,
      tokens: kindInfo.tokens
    },
    include: {
      requested: options.include,
      tokens: includeInfo.tokens
    },
    exclude: {
      requested: options.exclude,
      tokens: excludeInfo.tokens
    },
    search: options.search,
    notices: [
      ...kindInfo.notices,
      ...includeInfo.notices,
      ...excludeInfo.notices
    ]
  };
  const slides = selectSlides(snapshot, target.id);
  const threadsBySlide = groupThreadsBySlide(snapshot, slides);
  const records = renderPresentationRecords(snapshot, slides, threadsBySlide, presentation.layouts.items, kindInfo);
  const projectedRecords = projectRecords(records, includeInfo, excludeInfo);
  const windowedRecords = applyTargetWindow(projectedRecords, target);
  const recordLines = windowedRecords.map((record) => JSON.stringify(record));
  const filteredLines = applySearchFilter(recordLines, options.search, metadata);
  const maxChars = typeof options.maxChars === "number" && Number.isFinite(options.maxChars) ? Math.max(0, Math.floor(options.maxChars)) : DEFAULT_MAX_CHARS;
  const { ndjson, truncated } = applyTruncation(filteredLines, maxChars);
  return {
    ndjson,
    truncated,
    metadata
  };
}
var parseKindTokens = (value) => {
  const raw = value ?? DEFAULT_KIND_TOKENS.join(",");
  const tokensRaw = raw.split(/[^A-Za-z0-9-]+/).map((token) => token.trim().toLowerCase()).filter(Boolean);
  const tokens = [];
  const tokenSet = new Set;
  const unknown = [];
  for (const token of tokensRaw) {
    const normalized = KIND_ALIASES[token] ?? token;
    if (!KIND_TOKEN_SET.has(normalized)) {
      if (!unknown.includes(token)) {
        unknown.push(token);
      }
      continue;
    }
    const canonical = normalized;
    if (!tokenSet.has(canonical)) {
      tokenSet.add(canonical);
      tokens.push(canonical);
    }
  }
  const notices = [];
  if (unknown.length > 0) {
    notices.push(`Unknown kind tokens: ${unknown.join(", ")}`);
  }
  return {
    tokens,
    tokenSet,
    notices
  };
};
var parsePropertyTokens = (value, label) => {
  if (!value) {
    return { tokens: [], tokenSet: new Set, notices: [] };
  }
  const tokensRaw = value.split(/[^A-Za-z0-9-]+/).map((token) => token.trim().toLowerCase()).filter(Boolean);
  const tokens = [];
  const tokenSet = new Set;
  const unknown = [];
  for (const token of tokensRaw) {
    const normalized = PROPERTY_ALIASES[token] ?? token;
    if (!PROPERTY_TOKEN_SET.has(normalized)) {
      if (!unknown.includes(token)) {
        unknown.push(token);
      }
      continue;
    }
    if (!tokenSet.has(normalized)) {
      tokenSet.add(normalized);
      tokens.push(normalized);
    }
  }
  const notices = [];
  if (unknown.length > 0) {
    notices.push(`Unknown ${label === "include" ? "include" : "exclude"} tokens: ${unknown.join(", ")}`);
  }
  return {
    tokens,
    tokenSet,
    notices
  };
};
var projectRecords = (records, includeInfo, excludeInfo) => {
  return records.map((record) => projectRecord(record, includeInfo, excludeInfo));
};
var projectRecord = (record, includeInfo, excludeInfo) => {
  const defaultProps = DEFAULT_KIND_PROPERTIES[record.kind] ?? [];
  const allowed = new Set(defaultProps);
  includeInfo.tokens.forEach((token) => allowed.add(token));
  excludeInfo.tokens.forEach((token) => allowed.delete(token));
  const projected = { kind: record.kind };
  for (const [key, value] of Object.entries(record)) {
    if (key === "kind") {
      continue;
    }
    if (!allowed.has(key)) {
      continue;
    }
    if (value === undefined) {
      continue;
    }
    projected[key] = value;
  }
  return projected;
};
var applySearchFilter = (lines, search, metadata) => {
  if (!search) {
    return lines;
  }
  let regex;
  try {
    regex = new RegExp(search, "i");
  } catch (error) {
    const message = error instanceof Error ? error.message : "Invalid regular expression";
    throw new Error(`Invalid search regex: ${message}`);
  }
  const filtered = lines.filter((line) => regex.test(line));
  if (filtered.length === 0) {
    metadata.notices ??= [];
    metadata.notices.push("Search matched 0 entries");
  }
  return filtered;
};
var normalizeTarget = (target, id2) => {
  if (!target) {
    return { id: id2 };
  }
  const normalized = { id: target.id };
  if (Number.isFinite(target.beforeLines)) {
    normalized.beforeLines = Math.max(0, Math.floor(target.beforeLines ?? 0));
  }
  if (Number.isFinite(target.afterLines)) {
    normalized.afterLines = Math.max(0, Math.floor(target.afterLines ?? 0));
  }
  return normalized;
};
var buildTruncationNoticeLine = (omittedLines) => JSON.stringify({
  kind: "notice",
  message: `Truncated: omitted ${omittedLines} lines. Increase maxChars or narrow target.`
});
var compactLineForTruncation = (line) => {
  try {
    const record = JSON.parse(line);
    const title = record["title"];
    if (record.kind === "slide" && typeof title === "string") {
      const compactRecord = { ...record };
      compactRecord["title"] = buildTextPreview2(title, TRUNCATED_TEXT_PREVIEW_LENGTH);
      return JSON.stringify(compactRecord);
    }
    const text2 = record["text"];
    if (record.kind === "textbox" && typeof text2 === "string") {
      const textChars = record["textChars"];
      const textLines = record["textLines"];
      const compactRecord = {
        kind: record.kind,
        id: record["id"],
        slide: record["slide"],
        textChars: typeof textChars === "number" ? textChars : text2.length,
        textLines: typeof textLines === "number" ? textLines : countTextLines(text2)
      };
      return JSON.stringify(compactRecord);
    }
    if (record.kind === "notes" && typeof text2 === "string") {
      const compactRecord = { ...record };
      compactRecord["text"] = buildTextPreview2(text2, TRUNCATED_TEXT_PREVIEW_LENGTH);
      return JSON.stringify(compactRecord);
    }
    return line;
  } catch {
    return line;
  }
};
var applyTruncation = (lines, maxChars) => {
  const baseNdjson = lines.join(`
`);
  if (maxChars <= 0 || baseNdjson.length <= maxChars) {
    return { ndjson: baseNdjson, truncated: false };
  }
  const compactLines = lines.map((line) => compactLineForTruncation(line));
  let omittedLines = lines.length;
  let noticeLine = buildTruncationNoticeLine(omittedLines);
  let truncatedLines = [];
  for (let pass = 0;pass < 3; pass += 1) {
    truncatedLines = [];
    let length2 = 0;
    for (const line of compactLines) {
      let lineToAppend = line;
      let lineLength = lineToAppend.length + (truncatedLines.length > 0 ? 1 : 0);
      const noticeLength = noticeLine.length + (truncatedLines.length > 0 ? 1 : 0);
      if (length2 + lineLength + noticeLength > maxChars) {
        const compactLine = compactLineForTruncation(line);
        const compactLineLength = compactLine.length + (truncatedLines.length > 0 ? 1 : 0);
        if (compactLine !== line && length2 + compactLineLength + noticeLength <= maxChars) {
          lineToAppend = compactLine;
          lineLength = compactLineLength;
        } else {
          break;
        }
      }
      truncatedLines.push(lineToAppend);
      length2 += lineLength;
    }
    const nextOmitted = compactLines.length - truncatedLines.length;
    if (nextOmitted === omittedLines) {
      break;
    }
    omittedLines = nextOmitted;
    noticeLine = buildTruncationNoticeLine(omittedLines);
  }
  const ndjson = truncatedLines.length > 0 ? `${truncatedLines.join(`
`)}
${noticeLine}` : noticeLine;
  return { ndjson, truncated: true };
};
var selectSlides = (snapshot, targetId) => {
  const { prefix, suffix } = splitId(targetId);
  if (prefix === "pr") {
    return snapshot.slides;
  }
  if (prefix === "sl") {
    return snapshot.slides.filter((slide) => slide.id === suffix);
  }
  if (prefix === "nt") {
    return snapshot.slides.filter((slide) => slide.id === suffix);
  }
  if (prefix === "sh" || prefix === "ch" || prefix === "im" || prefix === "tb") {
    const slideId = findSlideIdForElementAid(snapshot, `${prefix}/${suffix}`);
    if (!slideId) {
      return [];
    }
    return snapshot.slides.filter((slide) => slide.id === slideId);
  }
  if (prefix === "tr") {
    const match = /^([a-z]+)\/([^/]+)\//.exec(suffix);
    if (!match) {
      return [];
    }
    const elemPrefix = match[1];
    const elemSuffix = match[2];
    if (!elemPrefix || !elemSuffix) {
      return [];
    }
    if (elemPrefix === "sh" || elemPrefix === "ch" || elemPrefix === "im") {
      const slideId = findSlideIdForElementAid(snapshot, `${elemPrefix}/${elemSuffix}`);
      if (!slideId) {
        return [];
      }
      return snapshot.slides.filter((slide) => slide.id === slideId);
    }
    if (elemPrefix === "nt") {
      return snapshot.slides.filter((slide) => slide.id === elemSuffix);
    }
    return [];
  }
  if (prefix === "th") {
    const thread = snapshot.threads.find((entry) => entry.id === suffix);
    const slideId = thread?.target?.slideId;
    if (slideId) {
      return snapshot.slides.filter((slide) => slide.id === slideId);
    }
    return [];
  }
  return snapshot.slides;
};
var groupThreadsBySlide = (snapshot, slides) => {
  const slideIds = new Set(slides.map((slide) => slide.id));
  const bySlide = new Map;
  snapshot.threads.forEach((thread) => {
    const slideId = thread.target?.slideId;
    if (!slideId || !slideIds.has(slideId)) {
      return;
    }
    const list = bySlide.get(slideId) ?? [];
    list.push(thread);
    bySlide.set(slideId, list);
  });
  return bySlide;
};
var renderPresentationRecords = (snapshot, slides, threadsBySlide, layouts, kindInfo) => {
  const records = [];
  if (kindInfo.tokenSet.has("deck")) {
    const deckRecord = {
      kind: "deck",
      id: snapshot.aid,
      name: snapshot.title
    };
    records.push(deckRecord);
  }
  if (kindInfo.tokenSet.has("layout")) {
    records.push(...renderLayoutRecords(layouts));
  }
  for (const slide of slides) {
    const slideRecords = renderSlideRecords(slide, kindInfo, threadsBySlide.get(slide.id) ?? []);
    records.push(...slideRecords);
  }
  return records;
};
var renderLayoutRecords = (layouts) => {
  return layouts.map((layout) => {
    const placeholders = layout.placeholders.summary().map((entry) => {
      const record = {
        name: entry.name,
        type: entry.type
      };
      const textPreview = buildTextPreview2(entry.text);
      if (textPreview) {
        record.textPreview = textPreview;
      }
      return record;
    });
    const type = layout.type?.trim();
    return {
      kind: "layout",
      layoutId: layout.id,
      name: layout.name,
      type: type && type.length > 0 ? type : undefined,
      placeholders: placeholders.length > 0 ? placeholders : undefined
    };
  });
};
var renderSlideRecords = (slide, kindInfo, threads) => {
  const records = [];
  const slideNumber = slide.index + 1;
  const includeSlide = kindInfo.tokenSet.has("slide");
  const includeTextbox = kindInfo.tokenSet.has("textbox");
  const includeShape = kindInfo.tokenSet.has("shape");
  const includeTables = kindInfo.tokenSet.has("table");
  const includeCharts = kindInfo.tokenSet.has("chart");
  const includeImages = kindInfo.tokenSet.has("image");
  const includeNotes = kindInfo.tokenSet.has("notes");
  const includeThreads = kindInfo.tokenSet.has("thread");
  const includeTextranges = kindInfo.tokenSet.has("textrange");
  if (includeSlide) {
    const textShapes = slide.shapes.filter((shape2) => shape2.text.trim().length > 0).length;
    const slideRecord = {
      kind: "slide",
      id: slide.aid,
      slide: slideNumber,
      title: slide.title,
      textShapes
    };
    records.push(slideRecord);
  }
  slide.shapes.forEach((shape2) => {
    const rawText = shape2.text;
    const hasText = rawText.trim().length > 0;
    if (hasText && includeTextbox) {
      const shapeRecord = {
        kind: "textbox",
        id: shape2.aid,
        slide: slideNumber
      };
      if (shape2.name) {
        shapeRecord.name = shape2.name;
      }
      if (shape2.placeholderType) {
        shapeRecord.placeholder = shape2.placeholderType;
      }
      shapeRecord.text = rawText;
      shapeRecord.textPreview = buildTextPreview2(rawText);
      shapeRecord.textChars = rawText.length;
      shapeRecord.textLines = countTextLines(rawText);
      const { bbox, bboxUnit } = buildBbox2(shape2.frame);
      if (bbox) {
        shapeRecord.bbox = bbox;
      }
      if (bboxUnit) {
        shapeRecord.bboxUnit = bboxUnit;
      }
      records.push(shapeRecord);
    }
    if (!hasText && includeShape) {
      const shapeRecord = {
        kind: "shape",
        id: shape2.aid,
        slide: slideNumber
      };
      if (shape2.name) {
        shapeRecord.name = shape2.name;
      }
      if (shape2.placeholderType) {
        shapeRecord.placeholder = shape2.placeholderType;
      }
      const { bbox, bboxUnit } = buildBbox2(shape2.frame);
      if (bbox) {
        shapeRecord.bbox = bbox;
      }
      if (bboxUnit) {
        shapeRecord.bboxUnit = bboxUnit;
      }
      records.push(shapeRecord);
    }
    if (includeTextranges && hasText) {
      const textRangeAid = buildTextRangeAid(shape2.aid, shape2.text.length);
      if (textRangeAid) {
        const textRangeRecord = {
          kind: "textrange",
          id: textRangeAid,
          slide: slideNumber,
          target: shape2.aid,
          length: shape2.text.length
        };
        records.push(textRangeRecord);
      }
    }
  });
  if (includeCharts) {
    slide.charts.forEach((chart2) => {
      const chartRecord = {
        kind: "chart",
        id: chart2.aid,
        slide: slideNumber,
        name: chart2.name,
        chartType: chart2.chartType
      };
      if (chart2.title) {
        chartRecord.title = chart2.title;
      }
      const { bbox, bboxUnit } = buildBbox2(chart2.frame);
      if (bbox) {
        chartRecord.bbox = bbox;
      }
      if (bboxUnit) {
        chartRecord.bboxUnit = bboxUnit;
      }
      records.push(chartRecord);
    });
  }
  if (includeTables) {
    slide.tables.forEach((table2) => {
      const tableRecord = {
        kind: "table",
        id: table2.aid,
        slide: slideNumber,
        name: table2.name,
        rows: table2.rows,
        cols: table2.cols,
        preview: table2.preview
      };
      const { bbox, bboxUnit } = buildBbox2(table2.frame);
      if (bbox) {
        tableRecord.bbox = bbox;
      }
      if (bboxUnit) {
        tableRecord.bboxUnit = bboxUnit;
      }
      records.push(tableRecord);
    });
  }
  if (includeImages) {
    slide.images.forEach((image2) => {
      const imageRecord = {
        kind: "image",
        id: image2.aid,
        slide: slideNumber,
        name: image2.name,
        geometry: image2.geometry
      };
      if (image2.alt) {
        imageRecord.alt = image2.alt;
      }
      if (image2.prompt) {
        imageRecord.prompt = image2.prompt;
      }
      if (image2.isPlaceholder) {
        imageRecord.isPlaceholder = true;
      }
      const { bbox, bboxUnit } = buildBbox2(image2.frame);
      if (bbox) {
        imageRecord.bbox = bbox;
      }
      if (bboxUnit) {
        imageRecord.bboxUnit = bboxUnit;
      }
      records.push(imageRecord);
    });
  }
  if (includeNotes) {
    const notesRecord = {
      kind: "notes",
      id: slide.notes.aid,
      slide: slideNumber,
      text: slide.notes.text ?? ""
    };
    records.push(notesRecord);
  }
  if (includeThreads && threads.length > 0) {
    threads.forEach((thread) => {
      const targetAid = resolveThreadTargetAid(thread, slide);
      const comments = thread.comments.filter((comment) => comment.text).map((comment) => ({
        id: comment.id,
        text: comment.text,
        authorId: comment.authorId,
        createdAt: comment.createdAt
      }));
      const threadRecord = {
        kind: "thread",
        id: thread.aid,
        slide: slideNumber,
        target: targetAid,
        status: formatThreadStatus(thread.status),
        comments
      };
      records.push(threadRecord);
    });
  }
  return records;
};
var buildTextRangeAid = (elementId, length2) => {
  if (length2 <= 0) {
    return;
  }
  const { prefix, suffix } = splitId(elementId);
  if (!prefix || !suffix) {
    return;
  }
  return `tr/${prefix}/${suffix}/0/${length2}`;
};
var resolveThreadTargetAid = (thread, slide) => {
  if (thread.target?.elementId) {
    const elementId = thread.target.elementId;
    const match = slide.shapes.find((item) => item.id === elementId) ?? slide.charts.find((item) => item.id === elementId) ?? slide.images.find((item) => item.id === elementId);
    if (match) {
      return match.aid;
    }
  }
  if (thread.target?.slideId && thread.target.slideId === slide.id) {
    return slide.aid;
  }
  return;
};
var formatThreadStatus = (status) => {
  if (typeof status === "string") {
    return status.toLowerCase().replace("thread_status_", "");
  }
  return;
};
var buildBbox2 = (frame) => {
  if (!frame) {
    return {};
  }
  const left = formatNumber(frame.left);
  const top = formatNumber(frame.top);
  const width = formatNumber(frame.width);
  const height = formatNumber(frame.height);
  if (left === undefined || top === undefined || width === undefined || height === undefined) {
    return {};
  }
  return {
    bbox: [left, top, width, height],
    bboxUnit: frame.unit
  };
};
var formatNumber = (value) => {
  if (value === undefined || !Number.isFinite(value)) {
    return;
  }
  return Math.round(value * 100) / 100;
};
var splitLines = (value) => value.split(/\r?\n/);
var buildTextPreview2 = (value, maxLength = 140) => {
  const normalized = value.replace(/\r?\n/g, " | ").trim();
  if (!normalized) {
    return "";
  }
  if (normalized.length <= maxLength) {
    return normalized;
  }
  const sliceLength = Math.max(1, maxLength - 3);
  return `${normalized.slice(0, sliceLength)}...`;
};
var countTextLines = (value) => splitLines(value).length;
var applyTargetWindow = (records, target) => {
  const beforeLines = target.beforeLines ?? 0;
  const afterLines = target.afterLines ?? 0;
  if (beforeLines <= 0 && afterLines <= 0) {
    return records;
  }
  const recordLines = records.map((record) => JSON.stringify(record));
  const index = recordLines.findIndex((line) => line.includes(target.id));
  if (index === -1) {
    return records;
  }
  const start = Math.max(0, index - beforeLines);
  const end = Math.min(records.length, index + afterLines + 1);
  const windowRecords = records.slice(start, end);
  const keepRecords = records.filter((record) => record.kind === "deck" || record.kind === "slide" || record.kind === "layout");
  const combined = [];
  const seen = new Set;
  for (const record of keepRecords) {
    const line = JSON.stringify(record);
    if (!seen.has(line)) {
      seen.add(line);
      combined.push(record);
    }
  }
  for (const record of windowRecords) {
    const line = JSON.stringify(record);
    if (!seen.has(line)) {
      seen.add(line);
      combined.push(record);
    }
  }
  return combined;
};
var splitId = (id2) => {
  const slashIndex = id2.indexOf("/");
  if (slashIndex <= 0 || slashIndex === id2.length - 1) {
    return { prefix: "", suffix: "" };
  }
  return {
    prefix: id2.slice(0, slashIndex),
    suffix: id2.slice(slashIndex + 1)
  };
};
var findSlideIdForElementAid = (snapshot, aid) => {
  for (const slide of snapshot.slides) {
    if (slide.shapes.some((shape2) => shape2.aid === aid)) {
      return slide.id;
    }
    if (slide.charts.some((chart2) => chart2.aid === aid)) {
      return slide.id;
    }
    if (slide.images.some((image2) => image2.aid === aid)) {
      return slide.id;
    }
    if (slide.tables.some((table2) => table2.aid === aid)) {
      return slide.id;
    }
  }
  return;
};

// node_modules/@oai/granola/dist/models/presentation/presentation-resolve.util.js
function resolveElementByAid(presentation, kind, aid) {
  for (const slide of presentation.slides.items) {
    for (const element of slide.elements.items) {
      if (kind === "sh" && element.type !== "shape") {
        continue;
      }
      if (kind === "ch" && element.type !== "chart") {
        continue;
      }
      if (kind === "im" && element.type !== "image") {
        continue;
      }
      if (kind === "tb" && element.type !== "table") {
        continue;
      }
      if (buildElementAid(kind, slide.id, element.id) === aid) {
        return element;
      }
    }
  }
  throw new Error(`Unknown element aid: ${aid}`);
}
function normalizeAidPrefix(prefix) {
  const normalized = prefix.trim().toLowerCase();
  const aliasMap = {
    presentation: "pr",
    deck: "pr",
    slide: "sl",
    shape: "sh",
    chart: "ch",
    image: "im",
    table: "tb",
    notes: "nt",
    thread: "th",
    textrange: "tr"
  };
  return aliasMap[normalized] ?? normalized;
}

// node_modules/@oai/granola/dist/models/presentation/presentation-resolve.js
function resolvePresentation(presentation, aid) {
  if (!aid || typeof aid !== "string") {
    throw new Error("resolve requires a non-empty aid.");
  }
  const { prefix, suffix } = splitAid(aid);
  const kind = normalizeAidPrefix(prefix);
  if (kind === "tr") {
    return resolveTextRange(presentation, suffix);
  }
  if (kind === "pr") {
    if (suffix !== presentation.id) {
      throw new Error(`Unknown presentation aid: ${aid}`);
    }
    return presentation;
  }
  if (kind === "sl") {
    return resolveSlide(presentation, suffix);
  }
  if (kind === "nt") {
    return resolveSlide(presentation, suffix).speakerNotes;
  }
  if (kind === "th") {
    const thread = presentation.comments.threads.getById(suffix);
    if (!thread) {
      throw new Error(`Unknown thread aid: ${aid}`);
    }
    return thread;
  }
  if (kind === "sh" || kind === "ch" || kind === "im" || kind === "tb") {
    return resolveElementByAid(presentation, kind, `${kind}/${suffix}`);
  }
  throw new Error(`Unknown aid prefix: ${aid}`);
}
var resolveSlide = (presentation, slideId) => {
  const slide = presentation.slides.items.find((item) => item.id === slideId);
  if (!slide) {
    throw new Error(`Unknown slide aid: sl/${slideId}`);
  }
  return slide;
};
var resolveTextRange = (presentation, suffix) => {
  const match = /^([a-z]+)\/([^/]+)\/(\d+)\/(\d+)$/.exec(suffix);
  if (!match) {
    throw new Error(`Invalid text range aid: tr/${suffix}`);
  }
  const [, elemPrefix, elemSuffix, startRaw, lengthRaw] = match;
  const start = Number(startRaw);
  const length2 = Number(lengthRaw);
  if (!Number.isFinite(start) || !Number.isFinite(length2)) {
    throw new Error(`Invalid text range offsets: tr/${suffix}`);
  }
  const element = resolvePresentation(presentation, `${elemPrefix}/${elemSuffix}`);
  if (typeof element.text !== "object" || element === null) {
    throw new Error(`Text range target is not text-bearing: tr/${suffix}`);
  }
  const text2 = element.text;
  if (!text2 || typeof text2.getRange !== "function") {
    throw new Error(`Text range target does not support ranges: tr/${suffix}`);
  }
  return text2.getRange(start, length2);
};
var splitAid = (aid) => {
  const slashIndex = aid.indexOf("/");
  if (slashIndex <= 0 || slashIndex === aid.length - 1) {
    throw new Error(`Invalid aid: ${aid}`);
  }
  return {
    prefix: aid.slice(0, slashIndex),
    suffix: aid.slice(slashIndex + 1)
  };
};

// node_modules/@oai/granola/dist/models/presentation/apply/record.js
class PresentationRecorder {
  #ops = [];
  #aliases = new WeakMap;
  #idMap = {};
  #counts = {};
  constructor(_presentation) {}
  record(op) {
    this.#ops.push(op);
  }
  getPatch() {
    return [...this.#ops];
  }
  getIdMap() {
    return { ...this.#idMap };
  }
  assignAlias(target, anchor, prefix) {
    const existing = this.#aliases.get(target);
    if (existing) {
      return existing;
    }
    const alias = this.#nextAlias(prefix);
    this.#aliases.set(target, alias);
    this.#idMap[alias] = anchor;
    return alias;
  }
  targetRefForElement(target, anchor) {
    return this.#aliases.get(target) ?? anchor;
  }
  #nextAlias(prefix) {
    const count3 = (this.#counts[prefix] ?? 0) + 1;
    this.#counts[prefix] = count3;
    return `@${prefix}${count3}`;
  }
}

// node_modules/@oai/granola/dist/models/presentation/apply/apply.js
function applyPresentationPatch(presentation, patch) {
  const aliasTargets = new Map;
  const idMap = {};
  const warnings = [];
  const recordTodo = (op) => {
    warnings.push(`TODO: ${op} is not implemented yet.`);
  };
  const registerAlias = (alias, target) => {
    if (!alias) {
      return;
    }
    if (!isPatchAlias(alias)) {
      throw new Error(`Alias must start with "@": ${alias}`);
    }
    if (aliasTargets.has(alias)) {
      throw new Error(`Alias already defined: ${alias}`);
    }
    const anchor = anchorForTarget(target);
    if (!anchor) {
      throw new Error(`Cannot alias target without anchor: ${alias}`);
    }
    aliasTargets.set(alias, target);
    idMap[alias] = anchor;
  };
  const resolveTarget = (ref) => {
    if (isPatchAlias(ref)) {
      const target = aliasTargets.get(ref);
      if (!target) {
        throw new Error(`Unknown alias target: ${ref}`);
      }
      return target;
    }
    return presentation.resolve(ref);
  };
  for (const op of patch) {
    switch (op.op) {
      case "slide.add": {
        const slide = presentation.slides.add({
          layout: op.layout,
          layoutId: op.layoutId,
          width: op.width,
          height: op.height
        });
        registerAlias(op.as, slide);
        break;
      }
      case "slide.duplicate": {
        const slide = resolveSlide2(resolveTarget(op.target), op.op);
        const duplicate = slide.duplicate();
        registerAlias(op.as, duplicate);
        break;
      }
      case "slide.remove": {
        const slide = resolveSlide2(resolveTarget(op.target), op.op);
        slide.delete();
        break;
      }
      case "slide.background.set": {
        const slide = resolveSlide2(resolveTarget(op.target), op.op);
        if (op.fill !== undefined) {
          slide.background.fill = op.fill;
        }
        if (op.ref !== undefined) {
          slide.background.ref = parseBackgroundRef(op.ref);
        }
        break;
      }
      case "shape.add": {
        const slide = resolveSlide2(resolveTarget(op.slide), op.op);
        const shape2 = slide.shapes.add(buildShapeAddConfig(op.props, resolveTarget));
        applyShapeSetProps(shape2, {
          name: op.props.name,
          placeholderType: op.props.placeholderType,
          placeholderIndex: op.props.placeholderIndex
        }, resolveTarget);
        registerAlias(op.as, shape2);
        break;
      }
      case "shape.set": {
        const shape2 = resolveShape(resolveTarget(op.target), op.op);
        applyShapeSetProps(shape2, op.props, resolveTarget);
        break;
      }
      case "shape.remove": {
        const shape2 = resolveShape(resolveTarget(op.target), op.op);
        shape2.delete();
        break;
      }
      case "text.set": {
        const text2 = resolveText(resolveTarget(op.target), op.op);
        text2.set(op.value);
        break;
      }
      case "text.add": {
        recordTodo(op.op);
        break;
      }
      case "text.replace": {
        if (!op.find) {
          warnings.push("text.replace ignored empty find string");
          break;
        }
        const text2 = resolveText(resolveTarget(op.target), op.op);
        const replacement = toTextReplacement(op.value);
        text2.replace(op.find, replacement);
        break;
      }
      case "text.style.set": {
        const text2 = resolveText(resolveTarget(op.target), op.op);
        applyTextStylePatch(text2, op.props);
        break;
      }
      case "textrange.style.set": {
        const range2 = resolveTextRangeTarget(op.target, resolveTarget, presentation);
        applyTextRangeStylePatch(range2, op.props);
        break;
      }
      case "notes.set": {
        const notes = resolveNotes(resolveTarget(op.target), op.op);
        notes.text = op.value;
        break;
      }
      case "notes.append":
      case "notes.clear":
      case "notes.visibility.set": {
        recordTodo(op.op);
        break;
      }
      case "image.add": {
        const slide = resolveSlide2(resolveTarget(op.slide), op.op);
        const image2 = slide.images.add(op.props);
        registerAlias(op.as, image2);
        break;
      }
      case "image.set": {
        const image2 = resolveImage(resolveTarget(op.target), op.op);
        applyImageSetProps(image2, op.props);
        break;
      }
      case "image.replace": {
        const image2 = resolveImage(resolveTarget(op.target), op.op);
        image2.replace(op.props);
        break;
      }
      case "image.remove": {
        const image2 = resolveImage(resolveTarget(op.target), op.op);
        image2.delete();
        break;
      }
      case "table.add":
      case "table.set":
      case "table.remove":
      case "table.merge":
      case "table.values.set":
      case "table.cell.set":
      case "table.column.set":
      case "table.range.set": {
        recordTodo(op.op);
        break;
      }
      case "chart.add":
      case "chart.set":
      case "chart.remove": {
        recordTodo(op.op);
        break;
      }
      case "slide.insert":
      case "slide.move":
      case "slide.frame.set":
      case "slide.layout.set": {
        recordTodo(op.op);
        break;
      }
      case "shape.order": {
        recordTodo(op.op);
        break;
      }
      case "layout.add":
      case "layout.rename":
      case "layout.parent.set":
      case "layout.colorMap.set":
      case "layout.placeholder.add": {
        recordTodo(op.op);
        break;
      }
      case "theme.colorScheme.set": {
        recordTodo(op.op);
        break;
      }
      case "style.set": {
        recordTodo(op.op);
        break;
      }
      case "script.run": {
        recordTodo(op.op);
        break;
      }
      case "autolayout.apply": {
        recordTodo(op.op);
        break;
      }
      case "comments.self.set":
      case "thread.add":
      case "thread.resolve":
      case "thread.reopen":
      case "thread.reaction.toggle": {
        recordTodo(op.op);
        break;
      }
      case "thread.reply": {
        const thread = resolveThread(resolveTarget(op.target), op.op);
        thread.addReply(op.body, {
          author: op.author,
          createdAt: op.createdAt,
          position: op.position
        });
        break;
      }
      default: {
        const exhaustiveCheck = op;
        throw new Error(`Unsupported patch op: ${String(exhaustiveCheck)}`);
      }
    }
  }
  return {
    idMap,
    warnings
  };
}
function isPatchAlias(value) {
  return value.startsWith("@") && value.length > 1;
}
function resolveSlide2(target, op) {
  if (target instanceof Slide2) {
    return target;
  }
  throw new Error(`${op} requires a slide target.`);
}
function resolveShape(target, op) {
  if (target instanceof Shape2) {
    return target;
  }
  throw new Error(`${op} requires a shape target.`);
}
function resolveImage(target, op) {
  if (target instanceof ImageElement2) {
    return target;
  }
  throw new Error(`${op} requires an image target.`);
}
function resolveNotes(target, op) {
  if (target instanceof SpeakerNotes) {
    return target;
  }
  throw new Error(`${op} requires a notes target.`);
}
function resolveThread(target, op) {
  if (target instanceof Thread2) {
    return target;
  }
  throw new Error(`${op} requires a thread target.`);
}
function resolveTextRange2(target, op) {
  if (target instanceof TextRange) {
    return target;
  }
  throw new Error(`${op} requires a text range target.`);
}
function resolveTextRangeTarget(ref, resolveTarget, presentation) {
  const aliasRange = parseTextRangeAliasRef(ref);
  if (aliasRange) {
    const baseTarget = resolveTarget(aliasRange.alias);
    const baseAnchor = anchorForTarget(baseTarget);
    if (!baseAnchor) {
      throw new Error("textrange.style.set requires an element target.");
    }
    const rangeAnchor = buildTextRangeAnchor(baseAnchor, aliasRange.start, aliasRange.length);
    return resolveTextRange2(presentation.resolve(rangeAnchor), "textrange.style.set");
  }
  return resolveTextRange2(resolveTarget(ref), "textrange.style.set");
}
function parseTextRangeAliasRef(ref) {
  if (!ref.startsWith("tr/@")) {
    return;
  }
  const parts = ref.split("/");
  if (parts.length !== 4) {
    throw new Error(`Invalid text range alias target: ${ref}`);
  }
  const alias = parts[1];
  const start = Number(parts[2]);
  const length2 = Number(parts[3]);
  if (!Number.isFinite(start) || !Number.isFinite(length2)) {
    throw new Error(`Invalid text range offsets in target: ${ref}`);
  }
  return { alias, start, length: length2 };
}
function buildTextRangeAnchor(anchor, start, length2) {
  const slashIndex = anchor.indexOf("/");
  if (slashIndex <= 0 || slashIndex === anchor.length - 1) {
    throw new Error(`Invalid element anchor for text range: ${anchor}`);
  }
  const prefix = anchor.slice(0, slashIndex);
  const suffix = anchor.slice(slashIndex + 1);
  return `tr/${prefix}/${suffix}/${start}/${length2}`;
}
function resolveText(target, op) {
  if (target instanceof Shape2) {
    return target.text;
  }
  throw new Error(`${op} requires a shape text target.`);
}
function toTextReplacement(value) {
  if (typeof value === "string") {
    return value;
  }
  const text2 = Text.create();
  text2.set(value);
  return text2;
}
function applyShapeSetProps(shape2, props, resolveTarget) {
  if (props.className !== undefined) {
    shape2.className = props.className;
  }
  if (props.name !== undefined) {
    shape2.name = props.name;
  }
  if (props.zIndex !== undefined) {
    shape2.zIndex = props.zIndex;
  }
  if (props.placeholderType !== undefined) {
    shape2.placeholderType = props.placeholderType;
  }
  if (props.placeholderIndex !== undefined) {
    shape2.placeholderIndex = props.placeholderIndex;
  }
  if (props.position) {
    shape2.position = props.position;
  }
  if (props.from !== undefined || props.fromIdx !== undefined) {
    shape2.setConnectorFrom(props.from !== undefined ? resolveShape(resolveTarget(props.from), "shape.set") : undefined, props.fromIdx);
  }
  if (props.to !== undefined || props.toIdx !== undefined) {
    shape2.setConnectorTo(props.to !== undefined ? resolveShape(resolveTarget(props.to), "shape.set") : undefined, props.toIdx);
  }
  if (props.borderRadius !== undefined) {
    shape2.borderRadius = props.borderRadius;
  }
  if (props.shadow !== undefined) {
    shape2.shadow = props.shadow;
  }
  if (props.fill !== undefined) {
    shape2.fill = props.fill;
  }
  if (props.line) {
    applyShapeLinePatch(shape2, props.line);
  }
}
function applyShapeLinePatch(shape2, patch) {
  if (patch.style !== undefined) {
    shape2.line.style = patch.style;
  }
  if (patch.width !== undefined) {
    shape2.line.width = patch.width;
  }
  if (patch.fill !== undefined) {
    shape2.line.fill = patch.fill;
  }
}
function applyImageSetProps(image2, props) {
  if (props.alt !== undefined) {
    image2.alt = props.alt;
  }
  if (props.fit !== undefined) {
    image2.fit = props.fit;
  }
  if (props.geometry !== undefined) {
    image2.geometry = props.geometry;
  }
  if (props.lockAspectRatio !== undefined) {
    image2.lockAspectRatio = props.lockAspectRatio;
  }
  if (props.crop !== undefined) {
    image2.crop = props.crop;
  }
  if (props.position) {
    image2.position = props.position;
  }
  if (props.frame) {
    image2.frame = props.frame;
  }
  if (props.rotation !== undefined) {
    image2.rotation = props.rotation;
  }
  if (props.flipHorizontal !== undefined) {
    image2.flipHorizontal = props.flipHorizontal;
  }
  if (props.flipVertical !== undefined) {
    image2.flipVertical = props.flipVertical;
  }
  if (props.width !== undefined) {
    image2.width = props.width;
  }
  if (props.height !== undefined) {
    image2.height = props.height;
  }
}
function buildShapeAddConfig(props, resolveTarget) {
  if (props.geometry === "custom") {
    return {
      geometry: "custom",
      position: props.position,
      fill: props.fill,
      line: props.line,
      adjustmentList: props.adjustmentList,
      borderRadius: props.borderRadius,
      shadow: props.shadow,
      className: props.className,
      customPaths: props.customPaths ?? []
    };
  }
  if (props.geometry !== "connector") {
    return {
      geometry: props.geometry,
      position: props.position,
      fill: props.fill,
      line: props.line,
      adjustmentList: props.adjustmentList,
      borderRadius: props.borderRadius,
      shadow: props.shadow,
      className: props.className
    };
  }
  const from2 = props.from !== undefined ? resolveShape(resolveTarget(props.from), "shape.add") : undefined;
  const to = props.to !== undefined ? resolveShape(resolveTarget(props.to), "shape.add") : undefined;
  if (!from2 || !to) {
    throw new Error("shape.add connector requires from/to targets.");
  }
  return {
    geometry: "connector",
    position: props.position,
    fill: props.fill,
    line: props.line,
    adjustmentList: props.adjustmentList,
    borderRadius: props.borderRadius,
    shadow: props.shadow,
    className: props.className,
    from: from2,
    to,
    fromIdx: props.fromIdx ?? 0,
    toIdx: props.toIdx ?? 0,
    kind: props.kind,
    head: props.head,
    tail: props.tail,
    cap: props.cap,
    join: props.join
  };
}
function applyTextStylePatch(text2, props) {
  if (props.className !== undefined) {
    text2.className = props.className;
  }
  if (props.style !== undefined) {
    text2.style = props.style;
  }
  if (props.bold !== undefined) {
    text2.bold = props.bold;
  }
  if (props.italic !== undefined) {
    text2.italic = props.italic;
  }
  if (props.underline !== undefined) {
    text2.underline = props.underline;
  }
  const fontSize = resolveFontSizePx(props.fontSize, props.fontSizePt);
  if (fontSize !== undefined) {
    text2.fontSize = fontSize;
  }
  if (props.lineSpacing !== undefined) {
    text2.lineSpacing = props.lineSpacing;
  }
  if (props.color !== undefined) {
    text2.color = props.color;
  }
  if (props.alignment !== undefined) {
    text2.alignment = props.alignment;
  }
  if (props.verticalAlignment !== undefined) {
    text2.verticalAlignment = props.verticalAlignment;
  }
  if (props.autoFit !== undefined) {
    text2.autoFit = props.autoFit;
  }
  if (props.wrap !== undefined) {
    text2.wrap = props.wrap;
  }
  if (props.insets !== undefined) {
    text2.insets = props.insets;
  }
}
function applyTextRangeStylePatch(range2, props) {
  if (props.className !== undefined) {
    range2.className = props.className;
  }
  if (props.style !== undefined) {
    range2.style = props.style;
  }
  if (props.bold !== undefined) {
    range2.bold = props.bold;
  }
  if (props.italic !== undefined) {
    range2.italic = props.italic;
  }
  if (props.underline !== undefined) {
    range2.underline = props.underline;
  }
  const fontSize = resolveFontSizePx(props.fontSize, props.fontSizePt);
  if (fontSize !== undefined) {
    range2.fontSize = fontSize;
  }
  if (props.color !== undefined) {
    range2.color = props.color;
  }
  if (props.alignment !== undefined) {
    range2.alignment = props.alignment;
  }
  if (props.spacingBefore !== undefined) {
    range2.spacingBefore = props.spacingBefore;
  }
  if (props.spacingAfter !== undefined) {
    range2.spacingAfter = props.spacingAfter;
  }
  if (props.lineSpacing !== undefined) {
    range2.lineSpacing = props.lineSpacing;
  }
  if (props.indentLeft !== undefined) {
    range2.indentLeft = props.indentLeft;
  }
  if (props.indentFirstLine !== undefined) {
    range2.indentFirstLine = props.indentFirstLine;
  }
  if (props.link !== undefined) {
    range2.link = props.link ?? undefined;
  }
}
function resolveFontSizePx(fontSizePx, fontSizePt) {
  if (fontSizePx !== undefined) {
    return fontSizePx;
  }
  if (fontSizePt !== undefined) {
    return fontSizePt * 96 / 72;
  }
  return;
}
var BACKGROUND_REF_SEPARATOR2 = ":";
var DEFAULT_BACKGROUND_REF_INDEX = 1001;
var DEFAULT_BACKGROUND_REF_SCHEME = "bg1";
function parseBackgroundRef(value) {
  if (value === null || value === undefined) {
    return;
  }
  const trimmed = value.trim();
  if (!trimmed) {
    return;
  }
  const separatorIndex = trimmed.indexOf(BACKGROUND_REF_SEPARATOR2);
  if (separatorIndex > 0) {
    const indexPart = trimmed.slice(0, separatorIndex);
    const schemeColor = trimmed.slice(separatorIndex + 1).trim();
    const index = Number(indexPart);
    if (Number.isFinite(index)) {
      return {
        index,
        schemeColor: schemeColor || DEFAULT_BACKGROUND_REF_SCHEME
      };
    }
  }
  const numeric = Number(trimmed);
  if (Number.isFinite(numeric) && String(numeric) === trimmed) {
    return { index: numeric, schemeColor: DEFAULT_BACKGROUND_REF_SCHEME };
  }
  return { index: DEFAULT_BACKGROUND_REF_INDEX, schemeColor: trimmed };
}
function anchorForTarget(target) {
  if (target instanceof Slide2) {
    return `sl/${target.id}`;
  }
  if (target instanceof Shape2) {
    const slideId = target.slideId;
    if (!slideId) {
      return;
    }
    return buildElementAid("sh", slideId, target.id);
  }
  if (target instanceof ImageElement2) {
    const slideId = target.slideId;
    if (!slideId) {
      return;
    }
    return `im/${slideId}.${target.id}`;
  }
  if (target instanceof SpeakerNotes) {
    const slideId = target.slideId;
    if (!slideId) {
      return;
    }
    return `nt/${slideId}`;
  }
  if (target instanceof Thread2) {
    return `th/${target.id}`;
  }
  return;
}

// node_modules/zod/v4/classic/external.js
var exports_external = {};
__export(exports_external, {
  xor: () => xor,
  xid: () => xid2,
  void: () => _void2,
  uuidv7: () => uuidv7,
  uuidv6: () => uuidv6,
  uuidv4: () => uuidv42,
  uuid: () => uuid2,
  util: () => exports_util,
  url: () => url,
  uppercase: () => _uppercase,
  unknown: () => unknown,
  union: () => union,
  undefined: () => _undefined3,
  ulid: () => ulid2,
  uint64: () => uint64,
  uint32: () => uint322,
  tuple: () => tuple,
  trim: () => _trim,
  treeifyError: () => treeifyError,
  transform: () => transform,
  toUpperCase: () => _toUpperCase,
  toLowerCase: () => _toLowerCase,
  toJSONSchema: () => toJSONSchema,
  templateLiteral: () => templateLiteral,
  symbol: () => symbol2,
  superRefine: () => superRefine,
  success: () => success,
  stringbool: () => stringbool,
  stringFormat: () => stringFormat,
  string: () => string2,
  strictObject: () => strictObject,
  startsWith: () => _startsWith,
  slugify: () => _slugify,
  size: () => _size,
  setErrorMap: () => setErrorMap,
  set: () => set,
  safeParseAsync: () => safeParseAsync2,
  safeParse: () => safeParse2,
  safeEncodeAsync: () => safeEncodeAsync2,
  safeEncode: () => safeEncode2,
  safeDecodeAsync: () => safeDecodeAsync2,
  safeDecode: () => safeDecode2,
  registry: () => registry2,
  regexes: () => exports_regexes,
  regex: () => _regex,
  refine: () => refine,
  record: () => record,
  readonly: () => readonly,
  property: () => _property,
  promise: () => promise,
  prettifyError: () => prettifyError,
  preprocess: () => preprocess,
  prefault: () => prefault,
  positive: () => _positive,
  pipe: () => pipe,
  partialRecord: () => partialRecord,
  parseAsync: () => parseAsync2,
  parse: () => parse3,
  overwrite: () => _overwrite,
  optional: () => optional,
  object: () => object,
  number: () => number4,
  nullish: () => nullish2,
  nullable: () => nullable,
  null: () => _null3,
  normalize: () => _normalize,
  nonpositive: () => _nonpositive,
  nonoptional: () => nonoptional,
  nonnegative: () => _nonnegative,
  never: () => never,
  negative: () => _negative,
  nativeEnum: () => nativeEnum,
  nanoid: () => nanoid2,
  nan: () => nan,
  multipleOf: () => _multipleOf,
  minSize: () => _minSize,
  minLength: () => _minLength,
  mime: () => _mime,
  meta: () => meta2,
  maxSize: () => _maxSize,
  maxLength: () => _maxLength,
  map: () => map3,
  mac: () => mac2,
  lte: () => _lte,
  lt: () => _lt,
  lowercase: () => _lowercase,
  looseRecord: () => looseRecord,
  looseObject: () => looseObject,
  locales: () => exports_locales,
  literal: () => literal,
  length: () => _length,
  lazy: () => lazy,
  ksuid: () => ksuid2,
  keyof: () => keyof2,
  jwt: () => jwt,
  json: () => json,
  iso: () => exports_iso,
  ipv6: () => ipv62,
  ipv4: () => ipv42,
  intersection: () => intersection,
  int64: () => int64,
  int32: () => int32,
  int: () => int,
  instanceof: () => _instanceof,
  includes: () => _includes,
  httpUrl: () => httpUrl,
  hostname: () => hostname2,
  hex: () => hex3,
  hash: () => hash,
  guid: () => guid2,
  gte: () => _gte,
  gt: () => _gt,
  globalRegistry: () => globalRegistry,
  getErrorMap: () => getErrorMap,
  function: () => _function,
  fromJSONSchema: () => fromJSONSchema,
  formatError: () => formatError,
  float64: () => float64,
  float32: () => float32,
  flattenError: () => flattenError,
  file: () => file,
  exactOptional: () => exactOptional,
  enum: () => _enum2,
  endsWith: () => _endsWith,
  encodeAsync: () => encodeAsync2,
  encode: () => encode2,
  emoji: () => emoji2,
  email: () => email2,
  e164: () => e1642,
  discriminatedUnion: () => discriminatedUnion,
  describe: () => describe2,
  decodeAsync: () => decodeAsync2,
  decode: () => decode2,
  date: () => date3,
  custom: () => custom2,
  cuid2: () => cuid22,
  cuid: () => cuid3,
  core: () => exports_core2,
  config: () => config,
  coerce: () => exports_coerce,
  codec: () => codec,
  clone: () => clone,
  cidrv6: () => cidrv62,
  cidrv4: () => cidrv42,
  check: () => check,
  catch: () => _catch2,
  boolean: () => boolean2,
  bigint: () => bigint2,
  base64url: () => base64url2,
  base64: () => base642,
  array: () => array2,
  any: () => any2,
  _function: () => _function,
  _default: () => _default2,
  _ZodString: () => _ZodString,
  ZodXor: () => ZodXor,
  ZodXID: () => ZodXID,
  ZodVoid: () => ZodVoid,
  ZodUnknown: () => ZodUnknown,
  ZodUnion: () => ZodUnion,
  ZodUndefined: () => ZodUndefined,
  ZodUUID: () => ZodUUID,
  ZodURL: () => ZodURL,
  ZodULID: () => ZodULID,
  ZodType: () => ZodType,
  ZodTuple: () => ZodTuple,
  ZodTransform: () => ZodTransform,
  ZodTemplateLiteral: () => ZodTemplateLiteral,
  ZodSymbol: () => ZodSymbol,
  ZodSuccess: () => ZodSuccess,
  ZodStringFormat: () => ZodStringFormat,
  ZodString: () => ZodString,
  ZodSet: () => ZodSet,
  ZodRecord: () => ZodRecord,
  ZodRealError: () => ZodRealError,
  ZodReadonly: () => ZodReadonly,
  ZodPromise: () => ZodPromise,
  ZodPrefault: () => ZodPrefault,
  ZodPipe: () => ZodPipe,
  ZodOptional: () => ZodOptional,
  ZodObject: () => ZodObject,
  ZodNumberFormat: () => ZodNumberFormat,
  ZodNumber: () => ZodNumber,
  ZodNullable: () => ZodNullable,
  ZodNull: () => ZodNull,
  ZodNonOptional: () => ZodNonOptional,
  ZodNever: () => ZodNever,
  ZodNanoID: () => ZodNanoID,
  ZodNaN: () => ZodNaN,
  ZodMap: () => ZodMap,
  ZodMAC: () => ZodMAC,
  ZodLiteral: () => ZodLiteral,
  ZodLazy: () => ZodLazy,
  ZodKSUID: () => ZodKSUID,
  ZodJWT: () => ZodJWT,
  ZodIssueCode: () => ZodIssueCode,
  ZodIntersection: () => ZodIntersection,
  ZodISOTime: () => ZodISOTime,
  ZodISODuration: () => ZodISODuration,
  ZodISODateTime: () => ZodISODateTime,
  ZodISODate: () => ZodISODate,
  ZodIPv6: () => ZodIPv6,
  ZodIPv4: () => ZodIPv4,
  ZodGUID: () => ZodGUID,
  ZodFunction: () => ZodFunction,
  ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
  ZodFile: () => ZodFile,
  ZodExactOptional: () => ZodExactOptional,
  ZodError: () => ZodError,
  ZodEnum: () => ZodEnum,
  ZodEmoji: () => ZodEmoji,
  ZodEmail: () => ZodEmail,
  ZodE164: () => ZodE164,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
  ZodDefault: () => ZodDefault,
  ZodDate: () => ZodDate,
  ZodCustomStringFormat: () => ZodCustomStringFormat,
  ZodCustom: () => ZodCustom,
  ZodCodec: () => ZodCodec,
  ZodCatch: () => ZodCatch,
  ZodCUID2: () => ZodCUID2,
  ZodCUID: () => ZodCUID,
  ZodCIDRv6: () => ZodCIDRv6,
  ZodCIDRv4: () => ZodCIDRv4,
  ZodBoolean: () => ZodBoolean,
  ZodBigIntFormat: () => ZodBigIntFormat,
  ZodBigInt: () => ZodBigInt,
  ZodBase64URL: () => ZodBase64URL,
  ZodBase64: () => ZodBase64,
  ZodArray: () => ZodArray,
  ZodAny: () => ZodAny,
  TimePrecision: () => TimePrecision,
  NEVER: () => NEVER,
  $output: () => $output,
  $input: () => $input,
  $brand: () => $brand
});

// node_modules/zod/v4/core/index.js
var exports_core2 = {};
__export(exports_core2, {
  version: () => version,
  util: () => exports_util,
  treeifyError: () => treeifyError,
  toJSONSchema: () => toJSONSchema,
  toDotPath: () => toDotPath,
  safeParseAsync: () => safeParseAsync,
  safeParse: () => safeParse,
  safeEncodeAsync: () => safeEncodeAsync,
  safeEncode: () => safeEncode,
  safeDecodeAsync: () => safeDecodeAsync,
  safeDecode: () => safeDecode,
  registry: () => registry2,
  regexes: () => exports_regexes,
  process: () => process2,
  prettifyError: () => prettifyError,
  parseAsync: () => parseAsync,
  parse: () => parse,
  meta: () => meta,
  locales: () => exports_locales,
  isValidJWT: () => isValidJWT,
  isValidBase64URL: () => isValidBase64URL,
  isValidBase64: () => isValidBase64,
  initializeContext: () => initializeContext,
  globalRegistry: () => globalRegistry,
  globalConfig: () => globalConfig,
  formatError: () => formatError,
  flattenError: () => flattenError,
  finalize: () => finalize,
  extractDefs: () => extractDefs,
  encodeAsync: () => encodeAsync,
  encode: () => encode,
  describe: () => describe,
  decodeAsync: () => decodeAsync,
  decode: () => decode,
  createToJSONSchemaMethod: () => createToJSONSchemaMethod,
  createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod,
  config: () => config,
  clone: () => clone,
  _xor: () => _xor,
  _xid: () => _xid,
  _void: () => _void,
  _uuidv7: () => _uuidv7,
  _uuidv6: () => _uuidv6,
  _uuidv4: () => _uuidv4,
  _uuid: () => _uuid,
  _url: () => _url,
  _uppercase: () => _uppercase,
  _unknown: () => _unknown,
  _union: () => _union,
  _undefined: () => _undefined2,
  _ulid: () => _ulid,
  _uint64: () => _uint64,
  _uint32: () => _uint32,
  _tuple: () => _tuple,
  _trim: () => _trim,
  _transform: () => _transform,
  _toUpperCase: () => _toUpperCase,
  _toLowerCase: () => _toLowerCase,
  _templateLiteral: () => _templateLiteral,
  _symbol: () => _symbol,
  _superRefine: () => _superRefine,
  _success: () => _success,
  _stringbool: () => _stringbool,
  _stringFormat: () => _stringFormat,
  _string: () => _string,
  _startsWith: () => _startsWith,
  _slugify: () => _slugify,
  _size: () => _size,
  _set: () => _set,
  _safeParseAsync: () => _safeParseAsync,
  _safeParse: () => _safeParse,
  _safeEncodeAsync: () => _safeEncodeAsync,
  _safeEncode: () => _safeEncode,
  _safeDecodeAsync: () => _safeDecodeAsync,
  _safeDecode: () => _safeDecode,
  _regex: () => _regex,
  _refine: () => _refine,
  _record: () => _record,
  _readonly: () => _readonly,
  _property: () => _property,
  _promise: () => _promise,
  _positive: () => _positive,
  _pipe: () => _pipe,
  _parseAsync: () => _parseAsync,
  _parse: () => _parse,
  _overwrite: () => _overwrite,
  _optional: () => _optional,
  _number: () => _number,
  _nullable: () => _nullable,
  _null: () => _null2,
  _normalize: () => _normalize,
  _nonpositive: () => _nonpositive,
  _nonoptional: () => _nonoptional,
  _nonnegative: () => _nonnegative,
  _never: () => _never,
  _negative: () => _negative,
  _nativeEnum: () => _nativeEnum,
  _nanoid: () => _nanoid,
  _nan: () => _nan,
  _multipleOf: () => _multipleOf,
  _minSize: () => _minSize,
  _minLength: () => _minLength,
  _min: () => _gte,
  _mime: () => _mime,
  _maxSize: () => _maxSize,
  _maxLength: () => _maxLength,
  _max: () => _lte,
  _map: () => _map,
  _mac: () => _mac,
  _lte: () => _lte,
  _lt: () => _lt,
  _lowercase: () => _lowercase,
  _literal: () => _literal,
  _length: () => _length,
  _lazy: () => _lazy,
  _ksuid: () => _ksuid,
  _jwt: () => _jwt,
  _isoTime: () => _isoTime,
  _isoDuration: () => _isoDuration,
  _isoDateTime: () => _isoDateTime,
  _isoDate: () => _isoDate,
  _ipv6: () => _ipv6,
  _ipv4: () => _ipv4,
  _intersection: () => _intersection,
  _int64: () => _int64,
  _int32: () => _int32,
  _int: () => _int,
  _includes: () => _includes,
  _guid: () => _guid,
  _gte: () => _gte,
  _gt: () => _gt,
  _float64: () => _float64,
  _float32: () => _float32,
  _file: () => _file,
  _enum: () => _enum,
  _endsWith: () => _endsWith,
  _encodeAsync: () => _encodeAsync,
  _encode: () => _encode,
  _emoji: () => _emoji2,
  _email: () => _email,
  _e164: () => _e164,
  _discriminatedUnion: () => _discriminatedUnion,
  _default: () => _default,
  _decodeAsync: () => _decodeAsync,
  _decode: () => _decode,
  _date: () => _date,
  _custom: () => _custom,
  _cuid2: () => _cuid2,
  _cuid: () => _cuid,
  _coercedString: () => _coercedString,
  _coercedNumber: () => _coercedNumber,
  _coercedDate: () => _coercedDate,
  _coercedBoolean: () => _coercedBoolean,
  _coercedBigint: () => _coercedBigint,
  _cidrv6: () => _cidrv6,
  _cidrv4: () => _cidrv4,
  _check: () => _check,
  _catch: () => _catch,
  _boolean: () => _boolean,
  _bigint: () => _bigint,
  _base64url: () => _base64url,
  _base64: () => _base64,
  _array: () => _array,
  _any: () => _any,
  TimePrecision: () => TimePrecision,
  NEVER: () => NEVER,
  JSONSchemaGenerator: () => JSONSchemaGenerator,
  JSONSchema: () => exports_json_schema,
  Doc: () => Doc2,
  $output: () => $output,
  $input: () => $input,
  $constructor: () => $constructor,
  $brand: () => $brand,
  $ZodXor: () => $ZodXor,
  $ZodXID: () => $ZodXID,
  $ZodVoid: () => $ZodVoid,
  $ZodUnknown: () => $ZodUnknown,
  $ZodUnion: () => $ZodUnion,
  $ZodUndefined: () => $ZodUndefined,
  $ZodUUID: () => $ZodUUID,
  $ZodURL: () => $ZodURL,
  $ZodULID: () => $ZodULID,
  $ZodType: () => $ZodType,
  $ZodTuple: () => $ZodTuple,
  $ZodTransform: () => $ZodTransform,
  $ZodTemplateLiteral: () => $ZodTemplateLiteral,
  $ZodSymbol: () => $ZodSymbol,
  $ZodSuccess: () => $ZodSuccess,
  $ZodStringFormat: () => $ZodStringFormat,
  $ZodString: () => $ZodString,
  $ZodSet: () => $ZodSet,
  $ZodRegistry: () => $ZodRegistry,
  $ZodRecord: () => $ZodRecord,
  $ZodRealError: () => $ZodRealError,
  $ZodReadonly: () => $ZodReadonly,
  $ZodPromise: () => $ZodPromise,
  $ZodPrefault: () => $ZodPrefault,
  $ZodPipe: () => $ZodPipe,
  $ZodOptional: () => $ZodOptional,
  $ZodObjectJIT: () => $ZodObjectJIT,
  $ZodObject: () => $ZodObject,
  $ZodNumberFormat: () => $ZodNumberFormat,
  $ZodNumber: () => $ZodNumber,
  $ZodNullable: () => $ZodNullable,
  $ZodNull: () => $ZodNull,
  $ZodNonOptional: () => $ZodNonOptional,
  $ZodNever: () => $ZodNever,
  $ZodNanoID: () => $ZodNanoID,
  $ZodNaN: () => $ZodNaN,
  $ZodMap: () => $ZodMap,
  $ZodMAC: () => $ZodMAC,
  $ZodLiteral: () => $ZodLiteral,
  $ZodLazy: () => $ZodLazy,
  $ZodKSUID: () => $ZodKSUID,
  $ZodJWT: () => $ZodJWT,
  $ZodIntersection: () => $ZodIntersection,
  $ZodISOTime: () => $ZodISOTime,
  $ZodISODuration: () => $ZodISODuration,
  $ZodISODateTime: () => $ZodISODateTime,
  $ZodISODate: () => $ZodISODate,
  $ZodIPv6: () => $ZodIPv6,
  $ZodIPv4: () => $ZodIPv4,
  $ZodGUID: () => $ZodGUID,
  $ZodFunction: () => $ZodFunction,
  $ZodFile: () => $ZodFile,
  $ZodExactOptional: () => $ZodExactOptional,
  $ZodError: () => $ZodError,
  $ZodEnum: () => $ZodEnum,
  $ZodEncodeError: () => $ZodEncodeError,
  $ZodEmoji: () => $ZodEmoji,
  $ZodEmail: () => $ZodEmail,
  $ZodE164: () => $ZodE164,
  $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion,
  $ZodDefault: () => $ZodDefault,
  $ZodDate: () => $ZodDate,
  $ZodCustomStringFormat: () => $ZodCustomStringFormat,
  $ZodCustom: () => $ZodCustom,
  $ZodCodec: () => $ZodCodec,
  $ZodCheckUpperCase: () => $ZodCheckUpperCase,
  $ZodCheckStringFormat: () => $ZodCheckStringFormat,
  $ZodCheckStartsWith: () => $ZodCheckStartsWith,
  $ZodCheckSizeEquals: () => $ZodCheckSizeEquals,
  $ZodCheckRegex: () => $ZodCheckRegex,
  $ZodCheckProperty: () => $ZodCheckProperty,
  $ZodCheckOverwrite: () => $ZodCheckOverwrite,
  $ZodCheckNumberFormat: () => $ZodCheckNumberFormat,
  $ZodCheckMultipleOf: () => $ZodCheckMultipleOf,
  $ZodCheckMinSize: () => $ZodCheckMinSize,
  $ZodCheckMinLength: () => $ZodCheckMinLength,
  $ZodCheckMimeType: () => $ZodCheckMimeType,
  $ZodCheckMaxSize: () => $ZodCheckMaxSize,
  $ZodCheckMaxLength: () => $ZodCheckMaxLength,
  $ZodCheckLowerCase: () => $ZodCheckLowerCase,
  $ZodCheckLessThan: () => $ZodCheckLessThan,
  $ZodCheckLengthEquals: () => $ZodCheckLengthEquals,
  $ZodCheckIncludes: () => $ZodCheckIncludes,
  $ZodCheckGreaterThan: () => $ZodCheckGreaterThan,
  $ZodCheckEndsWith: () => $ZodCheckEndsWith,
  $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat,
  $ZodCheck: () => $ZodCheck,
  $ZodCatch: () => $ZodCatch,
  $ZodCUID2: () => $ZodCUID2,
  $ZodCUID: () => $ZodCUID,
  $ZodCIDRv6: () => $ZodCIDRv6,
  $ZodCIDRv4: () => $ZodCIDRv4,
  $ZodBoolean: () => $ZodBoolean,
  $ZodBigIntFormat: () => $ZodBigIntFormat,
  $ZodBigInt: () => $ZodBigInt,
  $ZodBase64URL: () => $ZodBase64URL,
  $ZodBase64: () => $ZodBase64,
  $ZodAsyncError: () => $ZodAsyncError,
  $ZodArray: () => $ZodArray,
  $ZodAny: () => $ZodAny
});

// node_modules/zod/v4/core/core.js
var NEVER = Object.freeze({
  status: "aborted"
});
function $constructor(name, initializer, params2) {
  function init(inst, def) {
    if (!inst._zod) {
      Object.defineProperty(inst, "_zod", {
        value: {
          def,
          constr: _,
          traits: new Set
        },
        enumerable: false
      });
    }
    if (inst._zod.traits.has(name)) {
      return;
    }
    inst._zod.traits.add(name);
    initializer(inst, def);
    const proto = _.prototype;
    const keys2 = Object.keys(proto);
    for (let i = 0;i < keys2.length; i++) {
      const k = keys2[i];
      if (!(k in inst)) {
        inst[k] = proto[k].bind(inst);
      }
    }
  }
  const Parent = params2?.Parent ?? Object;

  class Definition extends Parent {
  }
  Object.defineProperty(Definition, "name", { value: name });
  function _(def) {
    var _a;
    const inst = params2?.Parent ? new Definition : this;
    init(inst, def);
    (_a = inst._zod).deferred ?? (_a.deferred = []);
    for (const fn of inst._zod.deferred) {
      fn();
    }
    return inst;
  }
  Object.defineProperty(_, "init", { value: init });
  Object.defineProperty(_, Symbol.hasInstance, {
    value: (inst) => {
      if (params2?.Parent && inst instanceof params2.Parent)
        return true;
      return inst?._zod?.traits?.has(name);
    }
  });
  Object.defineProperty(_, "name", { value: name });
  return _;
}
var $brand = Symbol("zod_brand");

class $ZodAsyncError extends Error {
  constructor() {
    super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
  }
}

class $ZodEncodeError extends Error {
  constructor(name) {
    super(`Encountered unidirectional transform during encode: ${name}`);
    this.name = "ZodEncodeError";
  }
}
var globalConfig = {};
function config(newConfig) {
  if (newConfig)
    Object.assign(globalConfig, newConfig);
  return globalConfig;
}
// node_modules/zod/v4/core/util.js
var exports_util = {};
__export(exports_util, {
  unwrapMessage: () => unwrapMessage,
  uint8ArrayToHex: () => uint8ArrayToHex,
  uint8ArrayToBase64url: () => uint8ArrayToBase64url,
  uint8ArrayToBase64: () => uint8ArrayToBase64,
  stringifyPrimitive: () => stringifyPrimitive,
  slugify: () => slugify,
  shallowClone: () => shallowClone,
  safeExtend: () => safeExtend,
  required: () => required2,
  randomString: () => randomString,
  propertyKeyTypes: () => propertyKeyTypes,
  promiseAllObject: () => promiseAllObject,
  primitiveTypes: () => primitiveTypes,
  prefixIssues: () => prefixIssues,
  pick: () => pick,
  partial: () => partial,
  parsedType: () => parsedType,
  optionalKeys: () => optionalKeys,
  omit: () => omit,
  objectClone: () => objectClone,
  numKeys: () => numKeys,
  nullish: () => nullish,
  normalizeParams: () => normalizeParams,
  mergeDefs: () => mergeDefs,
  merge: () => merge,
  jsonStringifyReplacer: () => jsonStringifyReplacer,
  joinValues: () => joinValues,
  issue: () => issue,
  isPlainObject: () => isPlainObject2,
  isObject: () => isObject,
  hexToUint8Array: () => hexToUint8Array,
  getSizableOrigin: () => getSizableOrigin,
  getParsedType: () => getParsedType,
  getLengthableOrigin: () => getLengthableOrigin,
  getEnumValues: () => getEnumValues,
  getElementAtPath: () => getElementAtPath,
  floatSafeRemainder: () => floatSafeRemainder,
  finalizeIssue: () => finalizeIssue,
  extend: () => extend2,
  escapeRegex: () => escapeRegex,
  esc: () => esc,
  defineLazy: () => defineLazy,
  createTransparentProxy: () => createTransparentProxy,
  cloneDef: () => cloneDef,
  clone: () => clone,
  cleanRegex: () => cleanRegex,
  cleanEnum: () => cleanEnum,
  captureStackTrace: () => captureStackTrace,
  cached: () => cached,
  base64urlToUint8Array: () => base64urlToUint8Array,
  base64ToUint8Array: () => base64ToUint8Array,
  assignProp: () => assignProp,
  assertNotEqual: () => assertNotEqual,
  assertNever: () => assertNever,
  assertIs: () => assertIs,
  assertEqual: () => assertEqual,
  assert: () => assert,
  allowsEval: () => allowsEval,
  aborted: () => aborted,
  NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES,
  Class: () => Class,
  BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES
});
function assertEqual(val) {
  return val;
}
function assertNotEqual(val) {
  return val;
}
function assertIs(_arg) {}
function assertNever(_x2) {
  throw new Error("Unexpected value in exhaustive check");
}
function assert(_) {}
function getEnumValues(entries) {
  const numericValues = Object.values(entries).filter((v) => typeof v === "number");
  const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
  return values;
}
function joinValues(array2, separator = "|") {
  return array2.map((val) => stringifyPrimitive(val)).join(separator);
}
function jsonStringifyReplacer(_, value) {
  if (typeof value === "bigint")
    return value.toString();
  return value;
}
function cached(getter) {
  const set = false;
  return {
    get value() {
      if (!set) {
        const value = getter();
        Object.defineProperty(this, "value", { value });
        return value;
      }
      throw new Error("cached value already set");
    }
  };
}
function nullish(input) {
  return input === null || input === undefined;
}
function cleanRegex(source) {
  const start = source.startsWith("^") ? 1 : 0;
  const end = source.endsWith("$") ? source.length - 1 : source.length;
  return source.slice(start, end);
}
function floatSafeRemainder(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepString = step.toString();
  let stepDecCount = (stepString.split(".")[1] || "").length;
  if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) {
    const match = stepString.match(/\d?e-(\d?)/);
    if (match?.[1]) {
      stepDecCount = Number.parseInt(match[1]);
    }
  }
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / 10 ** decCount;
}
var EVALUATING = Symbol("evaluating");
function defineLazy(object, key, getter) {
  let value = undefined;
  Object.defineProperty(object, key, {
    get() {
      if (value === EVALUATING) {
        return;
      }
      if (value === undefined) {
        value = EVALUATING;
        value = getter();
      }
      return value;
    },
    set(v) {
      Object.defineProperty(object, key, {
        value: v
      });
    },
    configurable: true
  });
}
function objectClone(obj) {
  return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
}
function assignProp(target, prop, value) {
  Object.defineProperty(target, prop, {
    value,
    writable: true,
    enumerable: true,
    configurable: true
  });
}
function mergeDefs(...defs) {
  const mergedDescriptors = {};
  for (const def of defs) {
    const descriptors = Object.getOwnPropertyDescriptors(def);
    Object.assign(mergedDescriptors, descriptors);
  }
  return Object.defineProperties({}, mergedDescriptors);
}
function cloneDef(schema) {
  return mergeDefs(schema._zod.def);
}
function getElementAtPath(obj, path3) {
  if (!path3)
    return obj;
  return path3.reduce((acc, key) => acc?.[key], obj);
}
function promiseAllObject(promisesObj) {
  const keys2 = Object.keys(promisesObj);
  const promises = keys2.map((key) => promisesObj[key]);
  return Promise.all(promises).then((results) => {
    const resolvedObj = {};
    for (let i = 0;i < keys2.length; i++) {
      resolvedObj[keys2[i]] = results[i];
    }
    return resolvedObj;
  });
}
function randomString(length2 = 10) {
  const chars = "abcdefghijklmnopqrstuvwxyz";
  let str = "";
  for (let i = 0;i < length2; i++) {
    str += chars[Math.floor(Math.random() * chars.length)];
  }
  return str;
}
function esc(str) {
  return JSON.stringify(str);
}
function slugify(input) {
  return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
}
var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
function isObject(data) {
  return typeof data === "object" && data !== null && !Array.isArray(data);
}
var allowsEval = cached(() => {
  if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
    return false;
  }
  try {
    const F = Function;
    new F("");
    return true;
  } catch (_) {
    return false;
  }
});
function isPlainObject2(o) {
  if (isObject(o) === false)
    return false;
  const ctor = o.constructor;
  if (ctor === undefined)
    return true;
  if (typeof ctor !== "function")
    return true;
  const prot = ctor.prototype;
  if (isObject(prot) === false)
    return false;
  if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
    return false;
  }
  return true;
}
function shallowClone(o) {
  if (isPlainObject2(o))
    return { ...o };
  if (Array.isArray(o))
    return [...o];
  return o;
}
function numKeys(data) {
  let keyCount = 0;
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      keyCount++;
    }
  }
  return keyCount;
}
var getParsedType = (data) => {
  const t = typeof data;
  switch (t) {
    case "undefined":
      return "undefined";
    case "string":
      return "string";
    case "number":
      return Number.isNaN(data) ? "nan" : "number";
    case "boolean":
      return "boolean";
    case "function":
      return "function";
    case "bigint":
      return "bigint";
    case "symbol":
      return "symbol";
    case "object":
      if (Array.isArray(data)) {
        return "array";
      }
      if (data === null) {
        return "null";
      }
      if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
        return "promise";
      }
      if (typeof Map !== "undefined" && data instanceof Map) {
        return "map";
      }
      if (typeof Set !== "undefined" && data instanceof Set) {
        return "set";
      }
      if (typeof Date !== "undefined" && data instanceof Date) {
        return "date";
      }
      if (typeof File !== "undefined" && data instanceof File) {
        return "file";
      }
      return "object";
    default:
      throw new Error(`Unknown data type: ${t}`);
  }
};
var propertyKeyTypes = new Set(["string", "number", "symbol"]);
var primitiveTypes = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
function escapeRegex(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function clone(inst, def, params2) {
  const cl = new inst._zod.constr(def ?? inst._zod.def);
  if (!def || params2?.parent)
    cl._zod.parent = inst;
  return cl;
}
function normalizeParams(_params) {
  const params2 = _params;
  if (!params2)
    return {};
  if (typeof params2 === "string")
    return { error: () => params2 };
  if (params2?.message !== undefined) {
    if (params2?.error !== undefined)
      throw new Error("Cannot specify both `message` and `error` params");
    params2.error = params2.message;
  }
  delete params2.message;
  if (typeof params2.error === "string")
    return { ...params2, error: () => params2.error };
  return params2;
}
function createTransparentProxy(getter) {
  let target;
  return new Proxy({}, {
    get(_, prop, receiver) {
      target ?? (target = getter());
      return Reflect.get(target, prop, receiver);
    },
    set(_, prop, value, receiver) {
      target ?? (target = getter());
      return Reflect.set(target, prop, value, receiver);
    },
    has(_, prop) {
      target ?? (target = getter());
      return Reflect.has(target, prop);
    },
    deleteProperty(_, prop) {
      target ?? (target = getter());
      return Reflect.deleteProperty(target, prop);
    },
    ownKeys(_) {
      target ?? (target = getter());
      return Reflect.ownKeys(target);
    },
    getOwnPropertyDescriptor(_, prop) {
      target ?? (target = getter());
      return Reflect.getOwnPropertyDescriptor(target, prop);
    },
    defineProperty(_, prop, descriptor) {
      target ?? (target = getter());
      return Reflect.defineProperty(target, prop, descriptor);
    }
  });
}
function stringifyPrimitive(value) {
  if (typeof value === "bigint")
    return value.toString() + "n";
  if (typeof value === "string")
    return `"${value}"`;
  return `${value}`;
}
function optionalKeys(shape2) {
  return Object.keys(shape2).filter((k) => {
    return shape2[k]._zod.optin === "optional" && shape2[k]._zod.optout === "optional";
  });
}
var NUMBER_FORMAT_RANGES = {
  safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
  int32: [-2147483648, 2147483647],
  uint32: [0, 4294967295],
  float32: [-340282346638528860000000000000000000000, 340282346638528860000000000000000000000],
  float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
};
var BIGINT_FORMAT_RANGES = {
  int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],
  uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]
};
function pick(schema, mask) {
  const currDef = schema._zod.def;
  const checks = currDef.checks;
  const hasChecks = checks && checks.length > 0;
  if (hasChecks) {
    throw new Error(".pick() cannot be used on object schemas containing refinements");
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const newShape = {};
      for (const key in mask) {
        if (!(key in currDef.shape)) {
          throw new Error(`Unrecognized key: "${key}"`);
        }
        if (!mask[key])
          continue;
        newShape[key] = currDef.shape[key];
      }
      assignProp(this, "shape", newShape);
      return newShape;
    },
    checks: []
  });
  return clone(schema, def);
}
function omit(schema, mask) {
  const currDef = schema._zod.def;
  const checks = currDef.checks;
  const hasChecks = checks && checks.length > 0;
  if (hasChecks) {
    throw new Error(".omit() cannot be used on object schemas containing refinements");
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const newShape = { ...schema._zod.def.shape };
      for (const key in mask) {
        if (!(key in currDef.shape)) {
          throw new Error(`Unrecognized key: "${key}"`);
        }
        if (!mask[key])
          continue;
        delete newShape[key];
      }
      assignProp(this, "shape", newShape);
      return newShape;
    },
    checks: []
  });
  return clone(schema, def);
}
function extend2(schema, shape2) {
  if (!isPlainObject2(shape2)) {
    throw new Error("Invalid input to extend: expected a plain object");
  }
  const checks = schema._zod.def.checks;
  const hasChecks = checks && checks.length > 0;
  if (hasChecks) {
    throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const _shape = { ...schema._zod.def.shape, ...shape2 };
      assignProp(this, "shape", _shape);
      return _shape;
    },
    checks: []
  });
  return clone(schema, def);
}
function safeExtend(schema, shape2) {
  if (!isPlainObject2(shape2)) {
    throw new Error("Invalid input to safeExtend: expected a plain object");
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const _shape = { ...schema._zod.def.shape, ...shape2 };
      assignProp(this, "shape", _shape);
      return _shape;
    }
  });
  return clone(schema, def);
}
function merge(a, b) {
  const def = mergeDefs(a._zod.def, {
    get shape() {
      const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
      assignProp(this, "shape", _shape);
      return _shape;
    },
    get catchall() {
      return b._zod.def.catchall;
    },
    checks: []
  });
  return clone(a, def);
}
function partial(Class, schema, mask) {
  const currDef = schema._zod.def;
  const checks = currDef.checks;
  const hasChecks = checks && checks.length > 0;
  if (hasChecks) {
    throw new Error(".partial() cannot be used on object schemas containing refinements");
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const oldShape = schema._zod.def.shape;
      const shape2 = { ...oldShape };
      if (mask) {
        for (const key in mask) {
          if (!(key in oldShape)) {
            throw new Error(`Unrecognized key: "${key}"`);
          }
          if (!mask[key])
            continue;
          shape2[key] = Class ? new Class({
            type: "optional",
            innerType: oldShape[key]
          }) : oldShape[key];
        }
      } else {
        for (const key in oldShape) {
          shape2[key] = Class ? new Class({
            type: "optional",
            innerType: oldShape[key]
          }) : oldShape[key];
        }
      }
      assignProp(this, "shape", shape2);
      return shape2;
    },
    checks: []
  });
  return clone(schema, def);
}
function required2(Class, schema, mask) {
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const oldShape = schema._zod.def.shape;
      const shape2 = { ...oldShape };
      if (mask) {
        for (const key in mask) {
          if (!(key in shape2)) {
            throw new Error(`Unrecognized key: "${key}"`);
          }
          if (!mask[key])
            continue;
          shape2[key] = new Class({
            type: "nonoptional",
            innerType: oldShape[key]
          });
        }
      } else {
        for (const key in oldShape) {
          shape2[key] = new Class({
            type: "nonoptional",
            innerType: oldShape[key]
          });
        }
      }
      assignProp(this, "shape", shape2);
      return shape2;
    }
  });
  return clone(schema, def);
}
function aborted(x2, startIndex = 0) {
  if (x2.aborted === true)
    return true;
  for (let i = startIndex;i < x2.issues.length; i++) {
    if (x2.issues[i]?.continue !== true) {
      return true;
    }
  }
  return false;
}
function prefixIssues(path3, issues) {
  return issues.map((iss) => {
    var _a;
    (_a = iss).path ?? (_a.path = []);
    iss.path.unshift(path3);
    return iss;
  });
}
function unwrapMessage(message) {
  return typeof message === "string" ? message : message?.message;
}
function finalizeIssue(iss, ctx, config2) {
  const full = { ...iss, path: iss.path ?? [] };
  if (!iss.message) {
    const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
    full.message = message;
  }
  delete full.inst;
  delete full.continue;
  if (!ctx?.reportInput) {
    delete full.input;
  }
  return full;
}
function getSizableOrigin(input) {
  if (input instanceof Set)
    return "set";
  if (input instanceof Map)
    return "map";
  if (input instanceof File)
    return "file";
  return "unknown";
}
function getLengthableOrigin(input) {
  if (Array.isArray(input))
    return "array";
  if (typeof input === "string")
    return "string";
  return "unknown";
}
function parsedType(data) {
  const t = typeof data;
  switch (t) {
    case "number": {
      return Number.isNaN(data) ? "nan" : "number";
    }
    case "object": {
      if (data === null) {
        return "null";
      }
      if (Array.isArray(data)) {
        return "array";
      }
      const obj = data;
      if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) {
        return obj.constructor.name;
      }
    }
  }
  return t;
}
function issue(...args2) {
  const [iss, input, inst] = args2;
  if (typeof iss === "string") {
    return {
      message: iss,
      code: "custom",
      input,
      inst
    };
  }
  return { ...iss };
}
function cleanEnum(obj) {
  return Object.entries(obj).filter(([k, _]) => {
    return Number.isNaN(Number.parseInt(k, 10));
  }).map((el) => el[1]);
}
function base64ToUint8Array(base64) {
  const binaryString = atob(base64);
  const bytes = new Uint8Array(binaryString.length);
  for (let i = 0;i < binaryString.length; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  return bytes;
}
function uint8ArrayToBase64(bytes) {
  let binaryString = "";
  for (let i = 0;i < bytes.length; i++) {
    binaryString += String.fromCharCode(bytes[i]);
  }
  return btoa(binaryString);
}
function base64urlToUint8Array(base64url) {
  const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/");
  const padding = "=".repeat((4 - base64.length % 4) % 4);
  return base64ToUint8Array(base64 + padding);
}
function uint8ArrayToBase64url(bytes) {
  return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
function hexToUint8Array(hex2) {
  const cleanHex = hex2.replace(/^0x/, "");
  if (cleanHex.length % 2 !== 0) {
    throw new Error("Invalid hex string length");
  }
  const bytes = new Uint8Array(cleanHex.length / 2);
  for (let i = 0;i < cleanHex.length; i += 2) {
    bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);
  }
  return bytes;
}
function uint8ArrayToHex(bytes) {
  return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
}

class Class {
  constructor(..._args) {}
}

// node_modules/zod/v4/core/errors.js
var initializer = (inst, def) => {
  inst.name = "$ZodError";
  Object.defineProperty(inst, "_zod", {
    value: inst._zod,
    enumerable: false
  });
  Object.defineProperty(inst, "issues", {
    value: def,
    enumerable: false
  });
  inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
  Object.defineProperty(inst, "toString", {
    value: () => inst.message,
    enumerable: false
  });
};
var $ZodError = $constructor("$ZodError", initializer);
var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
function flattenError(error, mapper = (issue2) => issue2.message) {
  const fieldErrors = {};
  const formErrors = [];
  for (const sub of error.issues) {
    if (sub.path.length > 0) {
      fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
      fieldErrors[sub.path[0]].push(mapper(sub));
    } else {
      formErrors.push(mapper(sub));
    }
  }
  return { formErrors, fieldErrors };
}
function formatError(error, mapper = (issue2) => issue2.message) {
  const fieldErrors = { _errors: [] };
  const processError = (error2) => {
    for (const issue2 of error2.issues) {
      if (issue2.code === "invalid_union" && issue2.errors.length) {
        issue2.errors.map((issues) => processError({ issues }));
      } else if (issue2.code === "invalid_key") {
        processError({ issues: issue2.issues });
      } else if (issue2.code === "invalid_element") {
        processError({ issues: issue2.issues });
      } else if (issue2.path.length === 0) {
        fieldErrors._errors.push(mapper(issue2));
      } else {
        let curr = fieldErrors;
        let i = 0;
        while (i < issue2.path.length) {
          const el = issue2.path[i];
          const terminal = i === issue2.path.length - 1;
          if (!terminal) {
            curr[el] = curr[el] || { _errors: [] };
          } else {
            curr[el] = curr[el] || { _errors: [] };
            curr[el]._errors.push(mapper(issue2));
          }
          curr = curr[el];
          i++;
        }
      }
    }
  };
  processError(error);
  return fieldErrors;
}
function treeifyError(error, mapper = (issue2) => issue2.message) {
  const result = { errors: [] };
  const processError = (error2, path3 = []) => {
    var _a, _b;
    for (const issue2 of error2.issues) {
      if (issue2.code === "invalid_union" && issue2.errors.length) {
        issue2.errors.map((issues) => processError({ issues }, issue2.path));
      } else if (issue2.code === "invalid_key") {
        processError({ issues: issue2.issues }, issue2.path);
      } else if (issue2.code === "invalid_element") {
        processError({ issues: issue2.issues }, issue2.path);
      } else {
        const fullpath = [...path3, ...issue2.path];
        if (fullpath.length === 0) {
          result.errors.push(mapper(issue2));
          continue;
        }
        let curr = result;
        let i = 0;
        while (i < fullpath.length) {
          const el = fullpath[i];
          const terminal = i === fullpath.length - 1;
          if (typeof el === "string") {
            curr.properties ?? (curr.properties = {});
            (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });
            curr = curr.properties[el];
          } else {
            curr.items ?? (curr.items = []);
            (_b = curr.items)[el] ?? (_b[el] = { errors: [] });
            curr = curr.items[el];
          }
          if (terminal) {
            curr.errors.push(mapper(issue2));
          }
          i++;
        }
      }
    }
  };
  processError(error);
  return result;
}
function toDotPath(_path) {
  const segs = [];
  const path3 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
  for (const seg of path3) {
    if (typeof seg === "number")
      segs.push(`[${seg}]`);
    else if (typeof seg === "symbol")
      segs.push(`[${JSON.stringify(String(seg))}]`);
    else if (/[^\w$]/.test(seg))
      segs.push(`[${JSON.stringify(seg)}]`);
    else {
      if (segs.length)
        segs.push(".");
      segs.push(seg);
    }
  }
  return segs.join("");
}
function prettifyError(error) {
  const lines = [];
  const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);
  for (const issue2 of issues) {
    lines.push(`✖ ${issue2.message}`);
    if (issue2.path?.length)
      lines.push(`  → at ${toDotPath(issue2.path)}`);
  }
  return lines.join(`
`);
}

// node_modules/zod/v4/core/parse.js
var _parse = (_Err) => (schema, value, _ctx, _params) => {
  const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
  const result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise) {
    throw new $ZodAsyncError;
  }
  if (result.issues.length) {
    const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
    captureStackTrace(e, _params?.callee);
    throw e;
  }
  return result.value;
};
var parse = /* @__PURE__ */ _parse($ZodRealError);
var _parseAsync = (_Err) => async (schema, value, _ctx, params2) => {
  const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
  let result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise)
    result = await result;
  if (result.issues.length) {
    const e = new (params2?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
    captureStackTrace(e, params2?.callee);
    throw e;
  }
  return result.value;
};
var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError);
var _safeParse = (_Err) => (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
  const result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise) {
    throw new $ZodAsyncError;
  }
  return result.issues.length ? {
    success: false,
    error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
  } : { success: true, data: result.value };
};
var safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
var _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
  const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
  let result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise)
    result = await result;
  return result.issues.length ? {
    success: false,
    error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
  } : { success: true, data: result.value };
};
var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);
var _encode = (_Err) => (schema, value, _ctx) => {
  const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
  return _parse(_Err)(schema, value, ctx);
};
var encode = /* @__PURE__ */ _encode($ZodRealError);
var _decode = (_Err) => (schema, value, _ctx) => {
  return _parse(_Err)(schema, value, _ctx);
};
var decode = /* @__PURE__ */ _decode($ZodRealError);
var _encodeAsync = (_Err) => async (schema, value, _ctx) => {
  const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
  return _parseAsync(_Err)(schema, value, ctx);
};
var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError);
var _decodeAsync = (_Err) => async (schema, value, _ctx) => {
  return _parseAsync(_Err)(schema, value, _ctx);
};
var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError);
var _safeEncode = (_Err) => (schema, value, _ctx) => {
  const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
  return _safeParse(_Err)(schema, value, ctx);
};
var safeEncode = /* @__PURE__ */ _safeEncode($ZodRealError);
var _safeDecode = (_Err) => (schema, value, _ctx) => {
  return _safeParse(_Err)(schema, value, _ctx);
};
var safeDecode = /* @__PURE__ */ _safeDecode($ZodRealError);
var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
  const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
  return _safeParseAsync(_Err)(schema, value, ctx);
};
var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync($ZodRealError);
var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
  return _safeParseAsync(_Err)(schema, value, _ctx);
};
var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError);
// node_modules/zod/v4/core/regexes.js
var exports_regexes = {};
__export(exports_regexes, {
  xid: () => xid,
  uuid7: () => uuid7,
  uuid6: () => uuid6,
  uuid4: () => uuid4,
  uuid: () => uuid,
  uppercase: () => uppercase,
  unicodeEmail: () => unicodeEmail,
  undefined: () => _undefined,
  ulid: () => ulid,
  time: () => time,
  string: () => string,
  sha512_hex: () => sha512_hex,
  sha512_base64url: () => sha512_base64url,
  sha512_base64: () => sha512_base64,
  sha384_hex: () => sha384_hex,
  sha384_base64url: () => sha384_base64url,
  sha384_base64: () => sha384_base64,
  sha256_hex: () => sha256_hex,
  sha256_base64url: () => sha256_base64url,
  sha256_base64: () => sha256_base64,
  sha1_hex: () => sha1_hex,
  sha1_base64url: () => sha1_base64url,
  sha1_base64: () => sha1_base64,
  rfc5322Email: () => rfc5322Email,
  number: () => number3,
  null: () => _null,
  nanoid: () => nanoid,
  md5_hex: () => md5_hex,
  md5_base64url: () => md5_base64url,
  md5_base64: () => md5_base64,
  mac: () => mac,
  lowercase: () => lowercase,
  ksuid: () => ksuid,
  ipv6: () => ipv6,
  ipv4: () => ipv4,
  integer: () => integer,
  idnEmail: () => idnEmail,
  html5Email: () => html5Email,
  hostname: () => hostname,
  hex: () => hex2,
  guid: () => guid,
  extendedDuration: () => extendedDuration,
  emoji: () => emoji,
  email: () => email,
  e164: () => e164,
  duration: () => duration,
  domain: () => domain,
  datetime: () => datetime,
  date: () => date,
  cuid2: () => cuid2,
  cuid: () => cuid,
  cidrv6: () => cidrv6,
  cidrv4: () => cidrv4,
  browserEmail: () => browserEmail,
  boolean: () => boolean,
  bigint: () => bigint,
  base64url: () => base64url,
  base64: () => base64
});
var cuid = /^[cC][^\s-]{8,}$/;
var cuid2 = /^[0-9a-z]+$/;
var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
var xid = /^[0-9a-vA-V]{20}$/;
var ksuid = /^[A-Za-z0-9]{27}$/;
var nanoid = /^[a-zA-Z0-9_-]{21}$/;
var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
var uuid = (version) => {
  if (!version)
    return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
  return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
};
var uuid4 = /* @__PURE__ */ uuid(4);
var uuid6 = /* @__PURE__ */ uuid(6);
var uuid7 = /* @__PURE__ */ uuid(7);
var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u;
var idnEmail = unicodeEmail;
var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
function emoji() {
  return new RegExp(_emoji, "u");
}
var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
var mac = (delimiter) => {
  const escapedDelim = escapeRegex(delimiter ?? ":");
  return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
};
var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
var base64url = /^[A-Za-z0-9_-]*$/;
var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;
var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
var e164 = /^\+[1-9]\d{6,14}$/;
var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
function timeSource(args2) {
  const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
  const regex = typeof args2.precision === "number" ? args2.precision === -1 ? `${hhmm}` : args2.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args2.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
  return regex;
}
function time(args2) {
  return new RegExp(`^${timeSource(args2)}$`);
}
function datetime(args2) {
  const time2 = timeSource({ precision: args2.precision });
  const opts = ["Z"];
  if (args2.local)
    opts.push("");
  if (args2.offset)
    opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
  const timeRegex = `${time2}(?:${opts.join("|")})`;
  return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
}
var string = (params2) => {
  const regex = params2 ? `[\\s\\S]{${params2?.minimum ?? 0},${params2?.maximum ?? ""}}` : `[\\s\\S]*`;
  return new RegExp(`^${regex}$`);
};
var bigint = /^-?\d+n?$/;
var integer = /^-?\d+$/;
var number3 = /^-?\d+(?:\.\d+)?$/;
var boolean = /^(?:true|false)$/i;
var _null = /^null$/i;
var _undefined = /^undefined$/i;
var lowercase = /^[^A-Z]*$/;
var uppercase = /^[^a-z]*$/;
var hex2 = /^[0-9a-fA-F]*$/;
function fixedBase64(bodyLength, padding) {
  return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);
}
function fixedBase64url(length2) {
  return new RegExp(`^[A-Za-z0-9_-]{${length2}}$`);
}
var md5_hex = /^[0-9a-fA-F]{32}$/;
var md5_base64 = /* @__PURE__ */ fixedBase64(22, "==");
var md5_base64url = /* @__PURE__ */ fixedBase64url(22);
var sha1_hex = /^[0-9a-fA-F]{40}$/;
var sha1_base64 = /* @__PURE__ */ fixedBase64(27, "=");
var sha1_base64url = /* @__PURE__ */ fixedBase64url(27);
var sha256_hex = /^[0-9a-fA-F]{64}$/;
var sha256_base64 = /* @__PURE__ */ fixedBase64(43, "=");
var sha256_base64url = /* @__PURE__ */ fixedBase64url(43);
var sha384_hex = /^[0-9a-fA-F]{96}$/;
var sha384_base64 = /* @__PURE__ */ fixedBase64(64, "");
var sha384_base64url = /* @__PURE__ */ fixedBase64url(64);
var sha512_hex = /^[0-9a-fA-F]{128}$/;
var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "==");
var sha512_base64url = /* @__PURE__ */ fixedBase64url(86);

// node_modules/zod/v4/core/checks.js
var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
  var _a;
  inst._zod ?? (inst._zod = {});
  inst._zod.def = def;
  (_a = inst._zod).onattach ?? (_a.onattach = []);
});
var numericOriginMap = {
  number: "number",
  bigint: "bigint",
  object: "date"
};
var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
  $ZodCheck.init(inst, def);
  const origin = numericOriginMap[typeof def.value];
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
    if (def.value < curr) {
      if (def.inclusive)
        bag.maximum = def.value;
      else
        bag.exclusiveMaximum = def.value;
    }
  });
  inst._zod.check = (payload) => {
    if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
      return;
    }
    payload.issues.push({
      origin,
      code: "too_big",
      maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
      input: payload.value,
      inclusive: def.inclusive,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
  $ZodCheck.init(inst, def);
  const origin = numericOriginMap[typeof def.value];
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
    if (def.value > curr) {
      if (def.inclusive)
        bag.minimum = def.value;
      else
        bag.exclusiveMinimum = def.value;
    }
  });
  inst._zod.check = (payload) => {
    if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
      return;
    }
    payload.issues.push({
      origin,
      code: "too_small",
      minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
      input: payload.value,
      inclusive: def.inclusive,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
  $ZodCheck.init(inst, def);
  inst._zod.onattach.push((inst2) => {
    var _a;
    (_a = inst2._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
  });
  inst._zod.check = (payload) => {
    if (typeof payload.value !== typeof def.value)
      throw new Error("Cannot mix number and bigint in multiple_of check.");
    const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0;
    if (isMultiple)
      return;
    payload.issues.push({
      origin: typeof payload.value,
      code: "not_multiple_of",
      divisor: def.value,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
  $ZodCheck.init(inst, def);
  def.format = def.format || "float64";
  const isInt = def.format?.includes("int");
  const origin = isInt ? "int" : "number";
  const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.format = def.format;
    bag.minimum = minimum;
    bag.maximum = maximum;
    if (isInt)
      bag.pattern = integer;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    if (isInt) {
      if (!Number.isInteger(input)) {
        payload.issues.push({
          expected: origin,
          format: def.format,
          code: "invalid_type",
          continue: false,
          input,
          inst
        });
        return;
      }
      if (!Number.isSafeInteger(input)) {
        if (input > 0) {
          payload.issues.push({
            input,
            code: "too_big",
            maximum: Number.MAX_SAFE_INTEGER,
            note: "Integers must be within the safe integer range.",
            inst,
            origin,
            inclusive: true,
            continue: !def.abort
          });
        } else {
          payload.issues.push({
            input,
            code: "too_small",
            minimum: Number.MIN_SAFE_INTEGER,
            note: "Integers must be within the safe integer range.",
            inst,
            origin,
            inclusive: true,
            continue: !def.abort
          });
        }
        return;
      }
    }
    if (input < minimum) {
      payload.issues.push({
        origin: "number",
        input,
        code: "too_small",
        minimum,
        inclusive: true,
        inst,
        continue: !def.abort
      });
    }
    if (input > maximum) {
      payload.issues.push({
        origin: "number",
        input,
        code: "too_big",
        maximum,
        inclusive: true,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => {
  $ZodCheck.init(inst, def);
  const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format];
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.format = def.format;
    bag.minimum = minimum;
    bag.maximum = maximum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    if (input < minimum) {
      payload.issues.push({
        origin: "bigint",
        input,
        code: "too_small",
        minimum,
        inclusive: true,
        inst,
        continue: !def.abort
      });
    }
    if (input > maximum) {
      payload.issues.push({
        origin: "bigint",
        input,
        code: "too_big",
        maximum,
        inclusive: true,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => {
  var _a;
  $ZodCheck.init(inst, def);
  (_a = inst._zod.def).when ?? (_a.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.size !== undefined;
  });
  inst._zod.onattach.push((inst2) => {
    const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
    if (def.maximum < curr)
      inst2._zod.bag.maximum = def.maximum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const size2 = input.size;
    if (size2 <= def.maximum)
      return;
    payload.issues.push({
      origin: getSizableOrigin(input),
      code: "too_big",
      maximum: def.maximum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => {
  var _a;
  $ZodCheck.init(inst, def);
  (_a = inst._zod.def).when ?? (_a.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.size !== undefined;
  });
  inst._zod.onattach.push((inst2) => {
    const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
    if (def.minimum > curr)
      inst2._zod.bag.minimum = def.minimum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const size2 = input.size;
    if (size2 >= def.minimum)
      return;
    payload.issues.push({
      origin: getSizableOrigin(input),
      code: "too_small",
      minimum: def.minimum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => {
  var _a;
  $ZodCheck.init(inst, def);
  (_a = inst._zod.def).when ?? (_a.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.size !== undefined;
  });
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.minimum = def.size;
    bag.maximum = def.size;
    bag.size = def.size;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const size2 = input.size;
    if (size2 === def.size)
      return;
    const tooBig = size2 > def.size;
    payload.issues.push({
      origin: getSizableOrigin(input),
      ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size },
      inclusive: true,
      exact: true,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
  var _a;
  $ZodCheck.init(inst, def);
  (_a = inst._zod.def).when ?? (_a.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.length !== undefined;
  });
  inst._zod.onattach.push((inst2) => {
    const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
    if (def.maximum < curr)
      inst2._zod.bag.maximum = def.maximum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const length2 = input.length;
    if (length2 <= def.maximum)
      return;
    const origin = getLengthableOrigin(input);
    payload.issues.push({
      origin,
      code: "too_big",
      maximum: def.maximum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
  var _a;
  $ZodCheck.init(inst, def);
  (_a = inst._zod.def).when ?? (_a.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.length !== undefined;
  });
  inst._zod.onattach.push((inst2) => {
    const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
    if (def.minimum > curr)
      inst2._zod.bag.minimum = def.minimum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const length2 = input.length;
    if (length2 >= def.minimum)
      return;
    const origin = getLengthableOrigin(input);
    payload.issues.push({
      origin,
      code: "too_small",
      minimum: def.minimum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
  var _a;
  $ZodCheck.init(inst, def);
  (_a = inst._zod.def).when ?? (_a.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.length !== undefined;
  });
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.minimum = def.length;
    bag.maximum = def.length;
    bag.length = def.length;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const length2 = input.length;
    if (length2 === def.length)
      return;
    const origin = getLengthableOrigin(input);
    const tooBig = length2 > def.length;
    payload.issues.push({
      origin,
      ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length },
      inclusive: true,
      exact: true,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
  var _a, _b;
  $ZodCheck.init(inst, def);
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.format = def.format;
    if (def.pattern) {
      bag.patterns ?? (bag.patterns = new Set);
      bag.patterns.add(def.pattern);
    }
  });
  if (def.pattern)
    (_a = inst._zod).check ?? (_a.check = (payload) => {
      def.pattern.lastIndex = 0;
      if (def.pattern.test(payload.value))
        return;
      payload.issues.push({
        origin: "string",
        code: "invalid_format",
        format: def.format,
        input: payload.value,
        ...def.pattern ? { pattern: def.pattern.toString() } : {},
        inst,
        continue: !def.abort
      });
    });
  else
    (_b = inst._zod).check ?? (_b.check = () => {});
});
var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
  $ZodCheckStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    def.pattern.lastIndex = 0;
    if (def.pattern.test(payload.value))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "regex",
      input: payload.value,
      pattern: def.pattern.toString(),
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
  def.pattern ?? (def.pattern = lowercase);
  $ZodCheckStringFormat.init(inst, def);
});
var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
  def.pattern ?? (def.pattern = uppercase);
  $ZodCheckStringFormat.init(inst, def);
});
var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
  $ZodCheck.init(inst, def);
  const escapedRegex = escapeRegex(def.includes);
  const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
  def.pattern = pattern;
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.patterns ?? (bag.patterns = new Set);
    bag.patterns.add(pattern);
  });
  inst._zod.check = (payload) => {
    if (payload.value.includes(def.includes, def.position))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "includes",
      includes: def.includes,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
  $ZodCheck.init(inst, def);
  const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
  def.pattern ?? (def.pattern = pattern);
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.patterns ?? (bag.patterns = new Set);
    bag.patterns.add(pattern);
  });
  inst._zod.check = (payload) => {
    if (payload.value.startsWith(def.prefix))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "starts_with",
      prefix: def.prefix,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
  $ZodCheck.init(inst, def);
  const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
  def.pattern ?? (def.pattern = pattern);
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.patterns ?? (bag.patterns = new Set);
    bag.patterns.add(pattern);
  });
  inst._zod.check = (payload) => {
    if (payload.value.endsWith(def.suffix))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "ends_with",
      suffix: def.suffix,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
function handleCheckPropertyResult(result, payload, property) {
  if (result.issues.length) {
    payload.issues.push(...prefixIssues(property, result.issues));
  }
}
var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => {
  $ZodCheck.init(inst, def);
  inst._zod.check = (payload) => {
    const result = def.schema._zod.run({
      value: payload.value[def.property],
      issues: []
    }, {});
    if (result instanceof Promise) {
      return result.then((result2) => handleCheckPropertyResult(result2, payload, def.property));
    }
    handleCheckPropertyResult(result, payload, def.property);
    return;
  };
});
var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => {
  $ZodCheck.init(inst, def);
  const mimeSet = new Set(def.mime);
  inst._zod.onattach.push((inst2) => {
    inst2._zod.bag.mime = def.mime;
  });
  inst._zod.check = (payload) => {
    if (mimeSet.has(payload.value.type))
      return;
    payload.issues.push({
      code: "invalid_value",
      values: def.mime,
      input: payload.value.type,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
  $ZodCheck.init(inst, def);
  inst._zod.check = (payload) => {
    payload.value = def.tx(payload.value);
  };
});

// node_modules/zod/v4/core/doc.js
class Doc2 {
  constructor(args2 = []) {
    this.content = [];
    this.indent = 0;
    if (this)
      this.args = args2;
  }
  indented(fn) {
    this.indent += 1;
    fn(this);
    this.indent -= 1;
  }
  write(arg) {
    if (typeof arg === "function") {
      arg(this, { execution: "sync" });
      arg(this, { execution: "async" });
      return;
    }
    const content = arg;
    const lines = content.split(`
`).filter((x2) => x2);
    const minIndent = Math.min(...lines.map((x2) => x2.length - x2.trimStart().length));
    const dedented = lines.map((x2) => x2.slice(minIndent)).map((x2) => " ".repeat(this.indent * 2) + x2);
    for (const line of dedented) {
      this.content.push(line);
    }
  }
  compile() {
    const F = Function;
    const args2 = this?.args;
    const content = this?.content ?? [``];
    const lines = [...content.map((x2) => `  ${x2}`)];
    return new F(...args2, lines.join(`
`));
  }
}

// node_modules/zod/v4/core/versions.js
var version = {
  major: 4,
  minor: 3,
  patch: 0
};

// node_modules/zod/v4/core/schemas.js
var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
  var _a;
  inst ?? (inst = {});
  inst._zod.def = def;
  inst._zod.bag = inst._zod.bag || {};
  inst._zod.version = version;
  const checks = [...inst._zod.def.checks ?? []];
  if (inst._zod.traits.has("$ZodCheck")) {
    checks.unshift(inst);
  }
  for (const ch of checks) {
    for (const fn of ch._zod.onattach) {
      fn(inst);
    }
  }
  if (checks.length === 0) {
    (_a = inst._zod).deferred ?? (_a.deferred = []);
    inst._zod.deferred?.push(() => {
      inst._zod.run = inst._zod.parse;
    });
  } else {
    const runChecks = (payload, checks2, ctx) => {
      let isAborted = aborted(payload);
      let asyncResult;
      for (const ch of checks2) {
        if (ch._zod.def.when) {
          const shouldRun = ch._zod.def.when(payload);
          if (!shouldRun)
            continue;
        } else if (isAborted) {
          continue;
        }
        const currLen = payload.issues.length;
        const _ = ch._zod.check(payload);
        if (_ instanceof Promise && ctx?.async === false) {
          throw new $ZodAsyncError;
        }
        if (asyncResult || _ instanceof Promise) {
          asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
            await _;
            const nextLen = payload.issues.length;
            if (nextLen === currLen)
              return;
            if (!isAborted)
              isAborted = aborted(payload, currLen);
          });
        } else {
          const nextLen = payload.issues.length;
          if (nextLen === currLen)
            continue;
          if (!isAborted)
            isAborted = aborted(payload, currLen);
        }
      }
      if (asyncResult) {
        return asyncResult.then(() => {
          return payload;
        });
      }
      return payload;
    };
    const handleCanaryResult = (canary, payload, ctx) => {
      if (aborted(canary)) {
        canary.aborted = true;
        return canary;
      }
      const checkResult = runChecks(payload, checks, ctx);
      if (checkResult instanceof Promise) {
        if (ctx.async === false)
          throw new $ZodAsyncError;
        return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx));
      }
      return inst._zod.parse(checkResult, ctx);
    };
    inst._zod.run = (payload, ctx) => {
      if (ctx.skipChecks) {
        return inst._zod.parse(payload, ctx);
      }
      if (ctx.direction === "backward") {
        const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });
        if (canary instanceof Promise) {
          return canary.then((canary2) => {
            return handleCanaryResult(canary2, payload, ctx);
          });
        }
        return handleCanaryResult(canary, payload, ctx);
      }
      const result = inst._zod.parse(payload, ctx);
      if (result instanceof Promise) {
        if (ctx.async === false)
          throw new $ZodAsyncError;
        return result.then((result2) => runChecks(result2, checks, ctx));
      }
      return runChecks(result, checks, ctx);
    };
  }
  defineLazy(inst, "~standard", () => ({
    validate: (value) => {
      try {
        const r = safeParse(inst, value);
        return r.success ? { value: r.data } : { issues: r.error?.issues };
      } catch (_) {
        return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
      }
    },
    vendor: "zod",
    version: 1
  }));
});
var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag);
  inst._zod.parse = (payload, _) => {
    if (def.coerce)
      try {
        payload.value = String(payload.value);
      } catch (_2) {}
    if (typeof payload.value === "string")
      return payload;
    payload.issues.push({
      expected: "string",
      code: "invalid_type",
      input: payload.value,
      inst
    });
    return payload;
  };
});
var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {
  $ZodCheckStringFormat.init(inst, def);
  $ZodString.init(inst, def);
});
var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
  def.pattern ?? (def.pattern = guid);
  $ZodStringFormat.init(inst, def);
});
var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
  if (def.version) {
    const versionMap = {
      v1: 1,
      v2: 2,
      v3: 3,
      v4: 4,
      v5: 5,
      v6: 6,
      v7: 7,
      v8: 8
    };
    const v = versionMap[def.version];
    if (v === undefined)
      throw new Error(`Invalid UUID version: "${def.version}"`);
    def.pattern ?? (def.pattern = uuid(v));
  } else
    def.pattern ?? (def.pattern = uuid());
  $ZodStringFormat.init(inst, def);
});
var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
  def.pattern ?? (def.pattern = email);
  $ZodStringFormat.init(inst, def);
});
var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    try {
      const trimmed = payload.value.trim();
      const url = new URL(trimmed);
      if (def.hostname) {
        def.hostname.lastIndex = 0;
        if (!def.hostname.test(url.hostname)) {
          payload.issues.push({
            code: "invalid_format",
            format: "url",
            note: "Invalid hostname",
            pattern: def.hostname.source,
            input: payload.value,
            inst,
            continue: !def.abort
          });
        }
      }
      if (def.protocol) {
        def.protocol.lastIndex = 0;
        if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) {
          payload.issues.push({
            code: "invalid_format",
            format: "url",
            note: "Invalid protocol",
            pattern: def.protocol.source,
            input: payload.value,
            inst,
            continue: !def.abort
          });
        }
      }
      if (def.normalize) {
        payload.value = url.href;
      } else {
        payload.value = trimmed;
      }
      return;
    } catch (_) {
      payload.issues.push({
        code: "invalid_format",
        format: "url",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
  def.pattern ?? (def.pattern = emoji());
  $ZodStringFormat.init(inst, def);
});
var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
  def.pattern ?? (def.pattern = nanoid);
  $ZodStringFormat.init(inst, def);
});
var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
  def.pattern ?? (def.pattern = cuid);
  $ZodStringFormat.init(inst, def);
});
var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
  def.pattern ?? (def.pattern = cuid2);
  $ZodStringFormat.init(inst, def);
});
var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
  def.pattern ?? (def.pattern = ulid);
  $ZodStringFormat.init(inst, def);
});
var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
  def.pattern ?? (def.pattern = xid);
  $ZodStringFormat.init(inst, def);
});
var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
  def.pattern ?? (def.pattern = ksuid);
  $ZodStringFormat.init(inst, def);
});
var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
  def.pattern ?? (def.pattern = datetime(def));
  $ZodStringFormat.init(inst, def);
});
var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
  def.pattern ?? (def.pattern = date);
  $ZodStringFormat.init(inst, def);
});
var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
  def.pattern ?? (def.pattern = time(def));
  $ZodStringFormat.init(inst, def);
});
var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
  def.pattern ?? (def.pattern = duration);
  $ZodStringFormat.init(inst, def);
});
var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
  def.pattern ?? (def.pattern = ipv4);
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.format = `ipv4`;
});
var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
  def.pattern ?? (def.pattern = ipv6);
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.format = `ipv6`;
  inst._zod.check = (payload) => {
    try {
      new URL(`http://[${payload.value}]`);
    } catch {
      payload.issues.push({
        code: "invalid_format",
        format: "ipv6",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => {
  def.pattern ?? (def.pattern = mac(def.delimiter));
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.format = `mac`;
});
var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
  def.pattern ?? (def.pattern = cidrv4);
  $ZodStringFormat.init(inst, def);
});
var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
  def.pattern ?? (def.pattern = cidrv6);
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    const parts = payload.value.split("/");
    try {
      if (parts.length !== 2)
        throw new Error;
      const [address, prefix] = parts;
      if (!prefix)
        throw new Error;
      const prefixNum = Number(prefix);
      if (`${prefixNum}` !== prefix)
        throw new Error;
      if (prefixNum < 0 || prefixNum > 128)
        throw new Error;
      new URL(`http://[${address}]`);
    } catch {
      payload.issues.push({
        code: "invalid_format",
        format: "cidrv6",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
function isValidBase64(data) {
  if (data === "")
    return true;
  if (data.length % 4 !== 0)
    return false;
  try {
    atob(data);
    return true;
  } catch {
    return false;
  }
}
var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
  def.pattern ?? (def.pattern = base64);
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.contentEncoding = "base64";
  inst._zod.check = (payload) => {
    if (isValidBase64(payload.value))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "base64",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
function isValidBase64URL(data) {
  if (!base64url.test(data))
    return false;
  const base642 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
  const padded = base642.padEnd(Math.ceil(base642.length / 4) * 4, "=");
  return isValidBase64(padded);
}
var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
  def.pattern ?? (def.pattern = base64url);
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.contentEncoding = "base64url";
  inst._zod.check = (payload) => {
    if (isValidBase64URL(payload.value))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "base64url",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
  def.pattern ?? (def.pattern = e164);
  $ZodStringFormat.init(inst, def);
});
function isValidJWT(token, algorithm = null) {
  try {
    const tokensParts = token.split(".");
    if (tokensParts.length !== 3)
      return false;
    const [header] = tokensParts;
    if (!header)
      return false;
    const parsedHeader = JSON.parse(atob(header));
    if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
      return false;
    if (!parsedHeader.alg)
      return false;
    if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
      return false;
    return true;
  } catch {
    return false;
  }
}
var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    if (isValidJWT(payload.value, def.alg))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "jwt",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    if (def.fn(payload.value))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: def.format,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = inst._zod.bag.pattern ?? number3;
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce)
      try {
        payload.value = Number(payload.value);
      } catch (_) {}
    const input = payload.value;
    if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
      return payload;
    }
    const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : undefined : undefined;
    payload.issues.push({
      expected: "number",
      code: "invalid_type",
      input,
      inst,
      ...received ? { received } : {}
    });
    return payload;
  };
});
var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => {
  $ZodCheckNumberFormat.init(inst, def);
  $ZodNumber.init(inst, def);
});
var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = boolean;
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce)
      try {
        payload.value = Boolean(payload.value);
      } catch (_) {}
    const input = payload.value;
    if (typeof input === "boolean")
      return payload;
    payload.issues.push({
      expected: "boolean",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = bigint;
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce)
      try {
        payload.value = BigInt(payload.value);
      } catch (_) {}
    if (typeof payload.value === "bigint")
      return payload;
    payload.issues.push({
      expected: "bigint",
      code: "invalid_type",
      input: payload.value,
      inst
    });
    return payload;
  };
});
var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def) => {
  $ZodCheckBigIntFormat.init(inst, def);
  $ZodBigInt.init(inst, def);
});
var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (typeof input === "symbol")
      return payload;
    payload.issues.push({
      expected: "symbol",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = _undefined;
  inst._zod.values = new Set([undefined]);
  inst._zod.optin = "optional";
  inst._zod.optout = "optional";
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (typeof input === "undefined")
      return payload;
    payload.issues.push({
      expected: "undefined",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = _null;
  inst._zod.values = new Set([null]);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (input === null)
      return payload;
    payload.issues.push({
      expected: "null",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload) => payload;
});
var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload) => payload;
});
var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    payload.issues.push({
      expected: "never",
      code: "invalid_type",
      input: payload.value,
      inst
    });
    return payload;
  };
});
var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (typeof input === "undefined")
      return payload;
    payload.issues.push({
      expected: "void",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce) {
      try {
        payload.value = new Date(payload.value);
      } catch (_err) {}
    }
    const input = payload.value;
    const isDate = input instanceof Date;
    const isValidDate = isDate && !Number.isNaN(input.getTime());
    if (isValidDate)
      return payload;
    payload.issues.push({
      expected: "date",
      code: "invalid_type",
      input,
      ...isDate ? { received: "Invalid Date" } : {},
      inst
    });
    return payload;
  };
});
function handleArrayResult(result, final, index) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues(index, result.issues));
  }
  final.value[index] = result.value;
}
var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!Array.isArray(input)) {
      payload.issues.push({
        expected: "array",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    payload.value = Array(input.length);
    const proms = [];
    for (let i = 0;i < input.length; i++) {
      const item = input[i];
      const result = def.element._zod.run({
        value: item,
        issues: []
      }, ctx);
      if (result instanceof Promise) {
        proms.push(result.then((result2) => handleArrayResult(result2, payload, i)));
      } else {
        handleArrayResult(result, payload, i);
      }
    }
    if (proms.length) {
      return Promise.all(proms).then(() => payload);
    }
    return payload;
  };
});
function handlePropertyResult(result, final, key, input, isOptionalOut) {
  if (result.issues.length) {
    if (isOptionalOut && !(key in input)) {
      return;
    }
    final.issues.push(...prefixIssues(key, result.issues));
  }
  if (result.value === undefined) {
    if (key in input) {
      final.value[key] = undefined;
    }
  } else {
    final.value[key] = result.value;
  }
}
function normalizeDef(def) {
  const keys2 = Object.keys(def.shape);
  for (const k of keys2) {
    if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) {
      throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
    }
  }
  const okeys = optionalKeys(def.shape);
  return {
    ...def,
    keys: keys2,
    keySet: new Set(keys2),
    numKeys: keys2.length,
    optionalKeys: new Set(okeys)
  };
}
function handleCatchall(proms, input, payload, ctx, def, inst) {
  const unrecognized = [];
  const keySet = def.keySet;
  const _catchall = def.catchall._zod;
  const t = _catchall.def.type;
  const isOptionalOut = _catchall.optout === "optional";
  for (const key in input) {
    if (keySet.has(key))
      continue;
    if (t === "never") {
      unrecognized.push(key);
      continue;
    }
    const r = _catchall.run({ value: input[key], issues: [] }, ctx);
    if (r instanceof Promise) {
      proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalOut)));
    } else {
      handlePropertyResult(r, payload, key, input, isOptionalOut);
    }
  }
  if (unrecognized.length) {
    payload.issues.push({
      code: "unrecognized_keys",
      keys: unrecognized,
      input,
      inst
    });
  }
  if (!proms.length)
    return payload;
  return Promise.all(proms).then(() => {
    return payload;
  });
}
var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
  $ZodType.init(inst, def);
  const desc = Object.getOwnPropertyDescriptor(def, "shape");
  if (!desc?.get) {
    const sh = def.shape;
    Object.defineProperty(def, "shape", {
      get: () => {
        const newSh = { ...sh };
        Object.defineProperty(def, "shape", {
          value: newSh
        });
        return newSh;
      }
    });
  }
  const _normalized = cached(() => normalizeDef(def));
  defineLazy(inst._zod, "propValues", () => {
    const shape2 = def.shape;
    const propValues = {};
    for (const key in shape2) {
      const field = shape2[key]._zod;
      if (field.values) {
        propValues[key] ?? (propValues[key] = new Set);
        for (const v of field.values)
          propValues[key].add(v);
      }
    }
    return propValues;
  });
  const isObject2 = isObject;
  const catchall = def.catchall;
  let value;
  inst._zod.parse = (payload, ctx) => {
    value ?? (value = _normalized.value);
    const input = payload.value;
    if (!isObject2(input)) {
      payload.issues.push({
        expected: "object",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    payload.value = {};
    const proms = [];
    const shape2 = value.shape;
    for (const key of value.keys) {
      const el = shape2[key];
      const isOptionalOut = el._zod.optout === "optional";
      const r = el._zod.run({ value: input[key], issues: [] }, ctx);
      if (r instanceof Promise) {
        proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalOut)));
      } else {
        handlePropertyResult(r, payload, key, input, isOptionalOut);
      }
    }
    if (!catchall) {
      return proms.length ? Promise.all(proms).then(() => payload) : payload;
    }
    return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
  };
});
var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
  $ZodObject.init(inst, def);
  const superParse = inst._zod.parse;
  const _normalized = cached(() => normalizeDef(def));
  const generateFastpass = (shape2) => {
    const doc = new Doc2(["shape", "payload", "ctx"]);
    const normalized = _normalized.value;
    const parseStr = (key) => {
      const k = esc(key);
      return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
    };
    doc.write(`const input = payload.value;`);
    const ids = Object.create(null);
    let counter = 0;
    for (const key of normalized.keys) {
      ids[key] = `key_${counter++}`;
    }
    doc.write(`const newResult = {};`);
    for (const key of normalized.keys) {
      const id2 = ids[key];
      const k = esc(key);
      const schema = shape2[key];
      const isOptionalOut = schema?._zod?.optout === "optional";
      doc.write(`const ${id2} = ${parseStr(key)};`);
      if (isOptionalOut) {
        doc.write(`
        if (${id2}.issues.length) {
          if (${k} in input) {
            payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
              ...iss,
              path: iss.path ? [${k}, ...iss.path] : [${k}]
            })));
          }
        }
        
        if (${id2}.value === undefined) {
          if (${k} in input) {
            newResult[${k}] = undefined;
          }
        } else {
          newResult[${k}] = ${id2}.value;
        }
        
      `);
      } else {
        doc.write(`
        if (${id2}.issues.length) {
          payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
            ...iss,
            path: iss.path ? [${k}, ...iss.path] : [${k}]
          })));
        }
        
        if (${id2}.value === undefined) {
          if (${k} in input) {
            newResult[${k}] = undefined;
          }
        } else {
          newResult[${k}] = ${id2}.value;
        }
        
      `);
      }
    }
    doc.write(`payload.value = newResult;`);
    doc.write(`return payload;`);
    const fn = doc.compile();
    return (payload, ctx) => fn(shape2, payload, ctx);
  };
  let fastpass;
  const isObject2 = isObject;
  const jit = !globalConfig.jitless;
  const allowsEval2 = allowsEval;
  const fastEnabled = jit && allowsEval2.value;
  const catchall = def.catchall;
  let value;
  inst._zod.parse = (payload, ctx) => {
    value ?? (value = _normalized.value);
    const input = payload.value;
    if (!isObject2(input)) {
      payload.issues.push({
        expected: "object",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
      if (!fastpass)
        fastpass = generateFastpass(def.shape);
      payload = fastpass(payload, ctx);
      if (!catchall)
        return payload;
      return handleCatchall([], input, payload, ctx, value, inst);
    }
    return superParse(payload, ctx);
  };
});
function handleUnionResults(results, final, inst, ctx) {
  for (const result of results) {
    if (result.issues.length === 0) {
      final.value = result.value;
      return final;
    }
  }
  const nonaborted = results.filter((r) => !aborted(r));
  if (nonaborted.length === 1) {
    final.value = nonaborted[0].value;
    return nonaborted[0];
  }
  final.issues.push({
    code: "invalid_union",
    input: final.value,
    inst,
    errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
  });
  return final;
}
var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined);
  defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined);
  defineLazy(inst._zod, "values", () => {
    if (def.options.every((o) => o._zod.values)) {
      return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
    }
    return;
  });
  defineLazy(inst._zod, "pattern", () => {
    if (def.options.every((o) => o._zod.pattern)) {
      const patterns = def.options.map((o) => o._zod.pattern);
      return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
    }
    return;
  });
  const single = def.options.length === 1;
  const first = def.options[0]._zod.run;
  inst._zod.parse = (payload, ctx) => {
    if (single) {
      return first(payload, ctx);
    }
    let async = false;
    const results = [];
    for (const option of def.options) {
      const result = option._zod.run({
        value: payload.value,
        issues: []
      }, ctx);
      if (result instanceof Promise) {
        results.push(result);
        async = true;
      } else {
        if (result.issues.length === 0)
          return result;
        results.push(result);
      }
    }
    if (!async)
      return handleUnionResults(results, payload, inst, ctx);
    return Promise.all(results).then((results2) => {
      return handleUnionResults(results2, payload, inst, ctx);
    });
  };
});
function handleExclusiveUnionResults(results, final, inst, ctx) {
  const successes = results.filter((r) => r.issues.length === 0);
  if (successes.length === 1) {
    final.value = successes[0].value;
    return final;
  }
  if (successes.length === 0) {
    final.issues.push({
      code: "invalid_union",
      input: final.value,
      inst,
      errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
    });
  } else {
    final.issues.push({
      code: "invalid_union",
      input: final.value,
      inst,
      errors: [],
      inclusive: false
    });
  }
  return final;
}
var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => {
  $ZodUnion.init(inst, def);
  def.inclusive = false;
  const single = def.options.length === 1;
  const first = def.options[0]._zod.run;
  inst._zod.parse = (payload, ctx) => {
    if (single) {
      return first(payload, ctx);
    }
    let async = false;
    const results = [];
    for (const option of def.options) {
      const result = option._zod.run({
        value: payload.value,
        issues: []
      }, ctx);
      if (result instanceof Promise) {
        results.push(result);
        async = true;
      } else {
        results.push(result);
      }
    }
    if (!async)
      return handleExclusiveUnionResults(results, payload, inst, ctx);
    return Promise.all(results).then((results2) => {
      return handleExclusiveUnionResults(results2, payload, inst, ctx);
    });
  };
});
var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
  def.inclusive = false;
  $ZodUnion.init(inst, def);
  const _super = inst._zod.parse;
  defineLazy(inst._zod, "propValues", () => {
    const propValues = {};
    for (const option of def.options) {
      const pv = option._zod.propValues;
      if (!pv || Object.keys(pv).length === 0)
        throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
      for (const [k, v] of Object.entries(pv)) {
        if (!propValues[k])
          propValues[k] = new Set;
        for (const val of v) {
          propValues[k].add(val);
        }
      }
    }
    return propValues;
  });
  const disc = cached(() => {
    const opts = def.options;
    const map3 = new Map;
    for (const o of opts) {
      const values = o._zod.propValues?.[def.discriminator];
      if (!values || values.size === 0)
        throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
      for (const v of values) {
        if (map3.has(v)) {
          throw new Error(`Duplicate discriminator value "${String(v)}"`);
        }
        map3.set(v, o);
      }
    }
    return map3;
  });
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!isObject(input)) {
      payload.issues.push({
        code: "invalid_type",
        expected: "object",
        input,
        inst
      });
      return payload;
    }
    const opt = disc.value.get(input?.[def.discriminator]);
    if (opt) {
      return opt._zod.run(payload, ctx);
    }
    if (def.unionFallback) {
      return _super(payload, ctx);
    }
    payload.issues.push({
      code: "invalid_union",
      errors: [],
      note: "No matching discriminator",
      discriminator: def.discriminator,
      input,
      path: [def.discriminator],
      inst
    });
    return payload;
  };
});
var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    const left = def.left._zod.run({ value: input, issues: [] }, ctx);
    const right = def.right._zod.run({ value: input, issues: [] }, ctx);
    const async = left instanceof Promise || right instanceof Promise;
    if (async) {
      return Promise.all([left, right]).then(([left2, right2]) => {
        return handleIntersectionResults(payload, left2, right2);
      });
    }
    return handleIntersectionResults(payload, left, right);
  };
});
function mergeValues(a, b) {
  if (a === b) {
    return { valid: true, data: a };
  }
  if (a instanceof Date && b instanceof Date && +a === +b) {
    return { valid: true, data: a };
  }
  if (isPlainObject2(a) && isPlainObject2(b)) {
    const bKeys = Object.keys(b);
    const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a, ...b };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a[key], b[key]);
      if (!sharedValue.valid) {
        return {
          valid: false,
          mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
        };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  }
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) {
      return { valid: false, mergeErrorPath: [] };
    }
    const newArray = [];
    for (let index = 0;index < a.length; index++) {
      const itemA = a[index];
      const itemB = b[index];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return {
          valid: false,
          mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
        };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  }
  return { valid: false, mergeErrorPath: [] };
}
function handleIntersectionResults(result, left, right) {
  if (left.issues.length) {
    result.issues.push(...left.issues);
  }
  if (right.issues.length) {
    result.issues.push(...right.issues);
  }
  if (aborted(result))
    return result;
  const merged = mergeValues(left.value, right.value);
  if (!merged.valid) {
    throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);
  }
  result.value = merged.data;
  return result;
}
var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
  $ZodType.init(inst, def);
  const items = def.items;
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!Array.isArray(input)) {
      payload.issues.push({
        input,
        inst,
        expected: "tuple",
        code: "invalid_type"
      });
      return payload;
    }
    payload.value = [];
    const proms = [];
    const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== "optional");
    const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex;
    if (!def.rest) {
      const tooBig = input.length > items.length;
      const tooSmall = input.length < optStart - 1;
      if (tooBig || tooSmall) {
        payload.issues.push({
          ...tooBig ? { code: "too_big", maximum: items.length, inclusive: true } : { code: "too_small", minimum: items.length },
          input,
          inst,
          origin: "array"
        });
        return payload;
      }
    }
    let i = -1;
    for (const item of items) {
      i++;
      if (i >= input.length) {
        if (i >= optStart)
          continue;
      }
      const result = item._zod.run({
        value: input[i],
        issues: []
      }, ctx);
      if (result instanceof Promise) {
        proms.push(result.then((result2) => handleTupleResult(result2, payload, i)));
      } else {
        handleTupleResult(result, payload, i);
      }
    }
    if (def.rest) {
      const rest = input.slice(items.length);
      for (const el of rest) {
        i++;
        const result = def.rest._zod.run({
          value: el,
          issues: []
        }, ctx);
        if (result instanceof Promise) {
          proms.push(result.then((result2) => handleTupleResult(result2, payload, i)));
        } else {
          handleTupleResult(result, payload, i);
        }
      }
    }
    if (proms.length)
      return Promise.all(proms).then(() => payload);
    return payload;
  };
});
function handleTupleResult(result, final, index) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues(index, result.issues));
  }
  final.value[index] = result.value;
}
var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!isPlainObject2(input)) {
      payload.issues.push({
        expected: "record",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    const proms = [];
    const values = def.keyType._zod.values;
    if (values) {
      payload.value = {};
      const recordKeys = new Set;
      for (const key of values) {
        if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
          recordKeys.add(typeof key === "number" ? key.toString() : key);
          const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
          if (result instanceof Promise) {
            proms.push(result.then((result2) => {
              if (result2.issues.length) {
                payload.issues.push(...prefixIssues(key, result2.issues));
              }
              payload.value[key] = result2.value;
            }));
          } else {
            if (result.issues.length) {
              payload.issues.push(...prefixIssues(key, result.issues));
            }
            payload.value[key] = result.value;
          }
        }
      }
      let unrecognized;
      for (const key in input) {
        if (!recordKeys.has(key)) {
          unrecognized = unrecognized ?? [];
          unrecognized.push(key);
        }
      }
      if (unrecognized && unrecognized.length > 0) {
        payload.issues.push({
          code: "unrecognized_keys",
          input,
          inst,
          keys: unrecognized
        });
      }
    } else {
      payload.value = {};
      for (const key of Reflect.ownKeys(input)) {
        if (key === "__proto__")
          continue;
        let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
        if (keyResult instanceof Promise) {
          throw new Error("Async schemas not supported in object keys currently");
        }
        const checkNumericKey = typeof key === "string" && number3.test(key) && keyResult.issues.length && keyResult.issues.some((iss) => iss.code === "invalid_type" && iss.expected === "number");
        if (checkNumericKey) {
          const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);
          if (retryResult instanceof Promise) {
            throw new Error("Async schemas not supported in object keys currently");
          }
          if (retryResult.issues.length === 0) {
            keyResult = retryResult;
          }
        }
        if (keyResult.issues.length) {
          if (def.mode === "loose") {
            payload.value[key] = input[key];
          } else {
            payload.issues.push({
              code: "invalid_key",
              origin: "record",
              issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
              input: key,
              path: [key],
              inst
            });
          }
          continue;
        }
        const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
        if (result instanceof Promise) {
          proms.push(result.then((result2) => {
            if (result2.issues.length) {
              payload.issues.push(...prefixIssues(key, result2.issues));
            }
            payload.value[keyResult.value] = result2.value;
          }));
        } else {
          if (result.issues.length) {
            payload.issues.push(...prefixIssues(key, result.issues));
          }
          payload.value[keyResult.value] = result.value;
        }
      }
    }
    if (proms.length) {
      return Promise.all(proms).then(() => payload);
    }
    return payload;
  };
});
var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!(input instanceof Map)) {
      payload.issues.push({
        expected: "map",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    const proms = [];
    payload.value = new Map;
    for (const [key, value] of input) {
      const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
      const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx);
      if (keyResult instanceof Promise || valueResult instanceof Promise) {
        proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => {
          handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx);
        }));
      } else {
        handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);
      }
    }
    if (proms.length)
      return Promise.all(proms).then(() => payload);
    return payload;
  };
});
function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {
  if (keyResult.issues.length) {
    if (propertyKeyTypes.has(typeof key)) {
      final.issues.push(...prefixIssues(key, keyResult.issues));
    } else {
      final.issues.push({
        code: "invalid_key",
        origin: "map",
        input,
        inst,
        issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
      });
    }
  }
  if (valueResult.issues.length) {
    if (propertyKeyTypes.has(typeof key)) {
      final.issues.push(...prefixIssues(key, valueResult.issues));
    } else {
      final.issues.push({
        origin: "map",
        code: "invalid_element",
        input,
        inst,
        key,
        issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
      });
    }
  }
  final.value.set(keyResult.value, valueResult.value);
}
var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!(input instanceof Set)) {
      payload.issues.push({
        input,
        inst,
        expected: "set",
        code: "invalid_type"
      });
      return payload;
    }
    const proms = [];
    payload.value = new Set;
    for (const item of input) {
      const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);
      if (result instanceof Promise) {
        proms.push(result.then((result2) => handleSetResult(result2, payload)));
      } else
        handleSetResult(result, payload);
    }
    if (proms.length)
      return Promise.all(proms).then(() => payload);
    return payload;
  };
});
function handleSetResult(result, final) {
  if (result.issues.length) {
    final.issues.push(...result.issues);
  }
  final.value.add(result.value);
}
var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
  $ZodType.init(inst, def);
  const values = getEnumValues(def.entries);
  const valuesSet = new Set(values);
  inst._zod.values = valuesSet;
  inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (valuesSet.has(input)) {
      return payload;
    }
    payload.issues.push({
      code: "invalid_value",
      values,
      input,
      inst
    });
    return payload;
  };
});
var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
  $ZodType.init(inst, def);
  if (def.values.length === 0) {
    throw new Error("Cannot create literal schema with no valid values");
  }
  const values = new Set(def.values);
  inst._zod.values = values;
  inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (values.has(input)) {
      return payload;
    }
    payload.issues.push({
      code: "invalid_value",
      values: def.values,
      input,
      inst
    });
    return payload;
  };
});
var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (input instanceof File)
      return payload;
    payload.issues.push({
      expected: "file",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      throw new $ZodEncodeError(inst.constructor.name);
    }
    const _out = def.transform(payload.value, payload);
    if (ctx.async) {
      const output = _out instanceof Promise ? _out : Promise.resolve(_out);
      return output.then((output2) => {
        payload.value = output2;
        return payload;
      });
    }
    if (_out instanceof Promise) {
      throw new $ZodAsyncError;
    }
    payload.value = _out;
    return payload;
  };
});
function handleOptionalResult(result, input) {
  if (result.issues.length && input === undefined) {
    return { issues: [], value: undefined };
  }
  return result;
}
var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  inst._zod.optout = "optional";
  defineLazy(inst._zod, "values", () => {
    return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;
  });
  defineLazy(inst._zod, "pattern", () => {
    const pattern = def.innerType._zod.pattern;
    return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined;
  });
  inst._zod.parse = (payload, ctx) => {
    if (def.innerType._zod.optin === "optional") {
      const result = def.innerType._zod.run(payload, ctx);
      if (result instanceof Promise)
        return result.then((r) => handleOptionalResult(r, payload.value));
      return handleOptionalResult(result, payload.value);
    }
    if (payload.value === undefined) {
      return payload;
    }
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => {
  $ZodOptional.init(inst, def);
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern);
  inst._zod.parse = (payload, ctx) => {
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
  defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
  defineLazy(inst._zod, "pattern", () => {
    const pattern = def.innerType._zod.pattern;
    return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined;
  });
  defineLazy(inst._zod, "values", () => {
    return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;
  });
  inst._zod.parse = (payload, ctx) => {
    if (payload.value === null)
      return payload;
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      return def.innerType._zod.run(payload, ctx);
    }
    if (payload.value === undefined) {
      payload.value = def.defaultValue;
      return payload;
    }
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => handleDefaultResult(result2, def));
    }
    return handleDefaultResult(result, def);
  };
});
function handleDefaultResult(payload, def) {
  if (payload.value === undefined) {
    payload.value = def.defaultValue;
  }
  return payload;
}
var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      return def.innerType._zod.run(payload, ctx);
    }
    if (payload.value === undefined) {
      payload.value = def.defaultValue;
    }
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "values", () => {
    const v = def.innerType._zod.values;
    return v ? new Set([...v].filter((x2) => x2 !== undefined)) : undefined;
  });
  inst._zod.parse = (payload, ctx) => {
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => handleNonOptionalResult(result2, inst));
    }
    return handleNonOptionalResult(result, inst);
  };
});
function handleNonOptionalResult(payload, inst) {
  if (!payload.issues.length && payload.value === undefined) {
    payload.issues.push({
      code: "invalid_type",
      expected: "nonoptional",
      input: payload.value,
      inst
    });
  }
  return payload;
}
var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      throw new $ZodEncodeError("ZodSuccess");
    }
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => {
        payload.value = result2.issues.length === 0;
        return payload;
      });
    }
    payload.value = result.issues.length === 0;
    return payload;
  };
});
var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
  defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      return def.innerType._zod.run(payload, ctx);
    }
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => {
        payload.value = result2.value;
        if (result2.issues.length) {
          payload.value = def.catchValue({
            ...payload,
            error: {
              issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))
            },
            input: payload.value
          });
          payload.issues = [];
        }
        return payload;
      });
    }
    payload.value = result.value;
    if (result.issues.length) {
      payload.value = def.catchValue({
        ...payload,
        error: {
          issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
        },
        input: payload.value
      });
      payload.issues = [];
    }
    return payload;
  };
});
var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) {
      payload.issues.push({
        input: payload.value,
        inst,
        expected: "nan",
        code: "invalid_type"
      });
      return payload;
    }
    return payload;
  };
});
var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "values", () => def.in._zod.values);
  defineLazy(inst._zod, "optin", () => def.in._zod.optin);
  defineLazy(inst._zod, "optout", () => def.out._zod.optout);
  defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      const right = def.out._zod.run(payload, ctx);
      if (right instanceof Promise) {
        return right.then((right2) => handlePipeResult(right2, def.in, ctx));
      }
      return handlePipeResult(right, def.in, ctx);
    }
    const left = def.in._zod.run(payload, ctx);
    if (left instanceof Promise) {
      return left.then((left2) => handlePipeResult(left2, def.out, ctx));
    }
    return handlePipeResult(left, def.out, ctx);
  };
});
function handlePipeResult(left, next, ctx) {
  if (left.issues.length) {
    left.aborted = true;
    return left;
  }
  return next._zod.run({ value: left.value, issues: left.issues }, ctx);
}
var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "values", () => def.in._zod.values);
  defineLazy(inst._zod, "optin", () => def.in._zod.optin);
  defineLazy(inst._zod, "optout", () => def.out._zod.optout);
  defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
  inst._zod.parse = (payload, ctx) => {
    const direction = ctx.direction || "forward";
    if (direction === "forward") {
      const left = def.in._zod.run(payload, ctx);
      if (left instanceof Promise) {
        return left.then((left2) => handleCodecAResult(left2, def, ctx));
      }
      return handleCodecAResult(left, def, ctx);
    } else {
      const right = def.out._zod.run(payload, ctx);
      if (right instanceof Promise) {
        return right.then((right2) => handleCodecAResult(right2, def, ctx));
      }
      return handleCodecAResult(right, def, ctx);
    }
  };
});
function handleCodecAResult(result, def, ctx) {
  if (result.issues.length) {
    result.aborted = true;
    return result;
  }
  const direction = ctx.direction || "forward";
  if (direction === "forward") {
    const transformed = def.transform(result.value, result);
    if (transformed instanceof Promise) {
      return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));
    }
    return handleCodecTxResult(result, transformed, def.out, ctx);
  } else {
    const transformed = def.reverseTransform(result.value, result);
    if (transformed instanceof Promise) {
      return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));
    }
    return handleCodecTxResult(result, transformed, def.in, ctx);
  }
}
function handleCodecTxResult(left, value, nextSchema, ctx) {
  if (left.issues.length) {
    left.aborted = true;
    return left;
  }
  return nextSchema._zod.run({ value, issues: left.issues }, ctx);
}
var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
  defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      return def.innerType._zod.run(payload, ctx);
    }
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then(handleReadonlyResult);
    }
    return handleReadonlyResult(result);
  };
});
function handleReadonlyResult(payload) {
  payload.value = Object.freeze(payload.value);
  return payload;
}
var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => {
  $ZodType.init(inst, def);
  const regexParts = [];
  for (const part of def.parts) {
    if (typeof part === "object" && part !== null) {
      if (!part._zod.pattern) {
        throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);
      }
      const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;
      if (!source)
        throw new Error(`Invalid template literal part: ${part._zod.traits}`);
      const start = source.startsWith("^") ? 1 : 0;
      const end = source.endsWith("$") ? source.length - 1 : source.length;
      regexParts.push(source.slice(start, end));
    } else if (part === null || primitiveTypes.has(typeof part)) {
      regexParts.push(escapeRegex(`${part}`));
    } else {
      throw new Error(`Invalid template literal part: ${part}`);
    }
  }
  inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`);
  inst._zod.parse = (payload, _ctx) => {
    if (typeof payload.value !== "string") {
      payload.issues.push({
        input: payload.value,
        inst,
        expected: "string",
        code: "invalid_type"
      });
      return payload;
    }
    inst._zod.pattern.lastIndex = 0;
    if (!inst._zod.pattern.test(payload.value)) {
      payload.issues.push({
        input: payload.value,
        inst,
        code: "invalid_format",
        format: def.format ?? "template_literal",
        pattern: inst._zod.pattern.source
      });
      return payload;
    }
    return payload;
  };
});
var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => {
  $ZodType.init(inst, def);
  inst._def = def;
  inst._zod.def = def;
  inst.implement = (func) => {
    if (typeof func !== "function") {
      throw new Error("implement() must be called with a function");
    }
    return function(...args2) {
      const parsedArgs = inst._def.input ? parse(inst._def.input, args2) : args2;
      const result = Reflect.apply(func, this, parsedArgs);
      if (inst._def.output) {
        return parse(inst._def.output, result);
      }
      return result;
    };
  };
  inst.implementAsync = (func) => {
    if (typeof func !== "function") {
      throw new Error("implementAsync() must be called with a function");
    }
    return async function(...args2) {
      const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args2) : args2;
      const result = await Reflect.apply(func, this, parsedArgs);
      if (inst._def.output) {
        return await parseAsync(inst._def.output, result);
      }
      return result;
    };
  };
  inst._zod.parse = (payload, _ctx) => {
    if (typeof payload.value !== "function") {
      payload.issues.push({
        code: "invalid_type",
        expected: "function",
        input: payload.value,
        inst
      });
      return payload;
    }
    const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise";
    if (hasPromiseOutput) {
      payload.value = inst.implementAsync(payload.value);
    } else {
      payload.value = inst.implement(payload.value);
    }
    return payload;
  };
  inst.input = (...args2) => {
    const F = inst.constructor;
    if (Array.isArray(args2[0])) {
      return new F({
        type: "function",
        input: new $ZodTuple({
          type: "tuple",
          items: args2[0],
          rest: args2[1]
        }),
        output: inst._def.output
      });
    }
    return new F({
      type: "function",
      input: args2[0],
      output: inst._def.output
    });
  };
  inst.output = (output) => {
    const F = inst.constructor;
    return new F({
      type: "function",
      input: inst._def.input,
      output
    });
  };
  return inst;
});
var $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));
  };
});
var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "innerType", () => def.getter());
  defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern);
  defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues);
  defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? undefined);
  defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? undefined);
  inst._zod.parse = (payload, ctx) => {
    const inner = inst._zod.innerType;
    return inner._zod.run(payload, ctx);
  };
});
var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
  $ZodCheck.init(inst, def);
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _) => {
    return payload;
  };
  inst._zod.check = (payload) => {
    const input = payload.value;
    const r = def.fn(input);
    if (r instanceof Promise) {
      return r.then((r2) => handleRefineResult(r2, payload, input, inst));
    }
    handleRefineResult(r, payload, input, inst);
    return;
  };
});
function handleRefineResult(result, payload, input, inst) {
  if (!result) {
    const _iss = {
      code: "custom",
      input,
      inst,
      path: [...inst._zod.def.path ?? []],
      continue: !inst._zod.def.abort
    };
    if (inst._zod.def.params)
      _iss.params = inst._zod.def.params;
    payload.issues.push(issue(_iss));
  }
}
// node_modules/zod/v4/locales/index.js
var exports_locales = {};
__export(exports_locales, {
  zhTW: () => zh_TW_default,
  zhCN: () => zh_CN_default,
  yo: () => yo_default,
  vi: () => vi_default,
  uz: () => uz_default,
  ur: () => ur_default,
  uk: () => uk_default,
  ua: () => ua_default,
  tr: () => tr_default,
  th: () => th_default,
  ta: () => ta_default,
  sv: () => sv_default,
  sl: () => sl_default,
  ru: () => ru_default,
  pt: () => pt_default,
  ps: () => ps_default,
  pl: () => pl_default,
  ota: () => ota_default,
  no: () => no_default,
  nl: () => nl_default,
  ms: () => ms_default,
  mk: () => mk_default,
  lt: () => lt_default,
  ko: () => ko_default,
  km: () => km_default,
  kh: () => kh_default,
  ka: () => ka_default,
  ja: () => ja_default,
  it: () => it_default,
  is: () => is_default,
  id: () => id_default,
  hy: () => hy_default,
  hu: () => hu_default,
  he: () => he_default,
  frCA: () => fr_CA_default,
  fr: () => fr_default,
  fi: () => fi_default,
  fa: () => fa_default,
  es: () => es_default,
  eo: () => eo_default,
  en: () => en_default,
  de: () => de_default,
  da: () => da_default,
  cs: () => cs_default,
  ca: () => ca_default,
  bg: () => bg_default,
  be: () => be_default,
  az: () => az_default,
  ar: () => ar_default
});

// node_modules/zod/v4/locales/ar.js
var error = () => {
  const Sizable = {
    string: { unit: "حرف", verb: "أن يحوي" },
    file: { unit: "بايت", verb: "أن يحوي" },
    array: { unit: "عنصر", verb: "أن يحوي" },
    set: { unit: "عنصر", verb: "أن يحوي" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "مدخل",
    email: "بريد إلكتروني",
    url: "رابط",
    emoji: "إيموجي",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "تاريخ ووقت بمعيار ISO",
    date: "تاريخ بمعيار ISO",
    time: "وقت بمعيار ISO",
    duration: "مدة بمعيار ISO",
    ipv4: "عنوان IPv4",
    ipv6: "عنوان IPv6",
    cidrv4: "مدى عناوين بصيغة IPv4",
    cidrv6: "مدى عناوين بصيغة IPv6",
    base64: "نَص بترميز base64-encoded",
    base64url: "نَص بترميز base64url-encoded",
    json_string: "نَص على هيئة JSON",
    e164: "رقم هاتف بمعيار E.164",
    jwt: "JWT",
    template_literal: "مدخل"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `مدخلات غير مقبولة: يفترض إدخال instanceof ${issue2.expected}، ولكن تم إدخال ${received}`;
        }
        return `مدخلات غير مقبولة: يفترض إدخال ${expected}، ولكن تم إدخال ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `مدخلات غير مقبولة: يفترض إدخال ${stringifyPrimitive(issue2.values[0])}`;
        return `اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return ` أكبر من اللازم: يفترض أن تكون ${issue2.origin ?? "القيمة"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "عنصر"}`;
        return `أكبر من اللازم: يفترض أن تكون ${issue2.origin ?? "القيمة"} ${adj} ${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `أصغر من اللازم: يفترض لـ ${issue2.origin} أن يكون ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `أصغر من اللازم: يفترض لـ ${issue2.origin} أن يكون ${adj} ${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `نَص غير مقبول: يجب أن يبدأ بـ "${issue2.prefix}"`;
        if (_issue.format === "ends_with")
          return `نَص غير مقبول: يجب أن ينتهي بـ "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `نَص غير مقبول: يجب أن يتضمَّن "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `نَص غير مقبول: يجب أن يطابق النمط ${_issue.pattern}`;
        return `${FormatDictionary[_issue.format] ?? issue2.format} غير مقبول`;
      }
      case "not_multiple_of":
        return `رقم غير مقبول: يجب أن يكون من مضاعفات ${issue2.divisor}`;
      case "unrecognized_keys":
        return `معرف${issue2.keys.length > 1 ? "ات" : ""} غريب${issue2.keys.length > 1 ? "ة" : ""}: ${joinValues(issue2.keys, "، ")}`;
      case "invalid_key":
        return `معرف غير مقبول في ${issue2.origin}`;
      case "invalid_union":
        return "مدخل غير مقبول";
      case "invalid_element":
        return `مدخل غير مقبول في ${issue2.origin}`;
      default:
        return "مدخل غير مقبول";
    }
  };
};
function ar_default() {
  return {
    localeError: error()
  };
}
// node_modules/zod/v4/locales/az.js
var error2 = () => {
  const Sizable = {
    string: { unit: "simvol", verb: "olmalıdır" },
    file: { unit: "bayt", verb: "olmalıdır" },
    array: { unit: "element", verb: "olmalıdır" },
    set: { unit: "element", verb: "olmalıdır" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "email address",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO datetime",
    date: "ISO date",
    time: "ISO time",
    duration: "ISO duration",
    ipv4: "IPv4 address",
    ipv6: "IPv6 address",
    cidrv4: "IPv4 range",
    cidrv6: "IPv6 range",
    base64: "base64-encoded string",
    base64url: "base64url-encoded string",
    json_string: "JSON string",
    e164: "E.164 number",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Yanlış dəyər: gözlənilən instanceof ${issue2.expected}, daxil olan ${received}`;
        }
        return `Yanlış dəyər: gözlənilən ${expected}, daxil olan ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Yanlış dəyər: gözlənilən ${stringifyPrimitive(issue2.values[0])}`;
        return `Yanlış seçim: aşağıdakılardan biri olmalıdır: ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Çox böyük: gözlənilən ${issue2.origin ?? "dəyər"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`;
        return `Çox böyük: gözlənilən ${issue2.origin ?? "dəyər"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Çox kiçik: gözlənilən ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        return `Çox kiçik: gözlənilən ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Yanlış mətn: "${_issue.prefix}" ilə başlamalıdır`;
        if (_issue.format === "ends_with")
          return `Yanlış mətn: "${_issue.suffix}" ilə bitməlidir`;
        if (_issue.format === "includes")
          return `Yanlış mətn: "${_issue.includes}" daxil olmalıdır`;
        if (_issue.format === "regex")
          return `Yanlış mətn: ${_issue.pattern} şablonuna uyğun olmalıdır`;
        return `Yanlış ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Yanlış ədəd: ${issue2.divisor} ilə bölünə bilən olmalıdır`;
      case "unrecognized_keys":
        return `Tanınmayan açar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} daxilində yanlış açar`;
      case "invalid_union":
        return "Yanlış dəyər";
      case "invalid_element":
        return `${issue2.origin} daxilində yanlış dəyər`;
      default:
        return `Yanlış dəyər`;
    }
  };
};
function az_default() {
  return {
    localeError: error2()
  };
}
// node_modules/zod/v4/locales/be.js
function getBelarusianPlural(count3, one2, few, many) {
  const absCount = Math.abs(count3);
  const lastDigit = absCount % 10;
  const lastTwoDigits = absCount % 100;
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
    return many;
  }
  if (lastDigit === 1) {
    return one2;
  }
  if (lastDigit >= 2 && lastDigit <= 4) {
    return few;
  }
  return many;
}
var error3 = () => {
  const Sizable = {
    string: {
      unit: {
        one: "сімвал",
        few: "сімвалы",
        many: "сімвалаў"
      },
      verb: "мець"
    },
    array: {
      unit: {
        one: "элемент",
        few: "элементы",
        many: "элементаў"
      },
      verb: "мець"
    },
    set: {
      unit: {
        one: "элемент",
        few: "элементы",
        many: "элементаў"
      },
      verb: "мець"
    },
    file: {
      unit: {
        one: "байт",
        few: "байты",
        many: "байтаў"
      },
      verb: "мець"
    }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "увод",
    email: "email адрас",
    url: "URL",
    emoji: "эмодзі",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO дата і час",
    date: "ISO дата",
    time: "ISO час",
    duration: "ISO працягласць",
    ipv4: "IPv4 адрас",
    ipv6: "IPv6 адрас",
    cidrv4: "IPv4 дыяпазон",
    cidrv6: "IPv6 дыяпазон",
    base64: "радок у фармаце base64",
    base64url: "радок у фармаце base64url",
    json_string: "JSON радок",
    e164: "нумар E.164",
    jwt: "JWT",
    template_literal: "увод"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "лік",
    array: "масіў"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Няправільны ўвод: чакаўся instanceof ${issue2.expected}, атрымана ${received}`;
        }
        return `Няправільны ўвод: чакаўся ${expected}, атрымана ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Няправільны ўвод: чакалася ${stringifyPrimitive(issue2.values[0])}`;
        return `Няправільны варыянт: чакаўся адзін з ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const maxValue = Number(issue2.maximum);
          const unit2 = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
          return `Занадта вялікі: чакалася, што ${issue2.origin ?? "значэнне"} павінна ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit2}`;
        }
        return `Занадта вялікі: чакалася, што ${issue2.origin ?? "значэнне"} павінна быць ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const minValue = Number(issue2.minimum);
          const unit2 = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
          return `Занадта малы: чакалася, што ${issue2.origin} павінна ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit2}`;
        }
        return `Занадта малы: чакалася, што ${issue2.origin} павінна быць ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Няправільны радок: павінен пачынацца з "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Няправільны радок: павінен заканчвацца на "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Няправільны радок: павінен змяшчаць "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Няправільны радок: павінен адпавядаць шаблону ${_issue.pattern}`;
        return `Няправільны ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Няправільны лік: павінен быць кратным ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Нераспазнаны ${issue2.keys.length > 1 ? "ключы" : "ключ"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Няправільны ключ у ${issue2.origin}`;
      case "invalid_union":
        return "Няправільны ўвод";
      case "invalid_element":
        return `Няправільнае значэнне ў ${issue2.origin}`;
      default:
        return `Няправільны ўвод`;
    }
  };
};
function be_default() {
  return {
    localeError: error3()
  };
}
// node_modules/zod/v4/locales/bg.js
var error4 = () => {
  const Sizable = {
    string: { unit: "символа", verb: "да съдържа" },
    file: { unit: "байта", verb: "да съдържа" },
    array: { unit: "елемента", verb: "да съдържа" },
    set: { unit: "елемента", verb: "да съдържа" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "вход",
    email: "имейл адрес",
    url: "URL",
    emoji: "емоджи",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO време",
    date: "ISO дата",
    time: "ISO време",
    duration: "ISO продължителност",
    ipv4: "IPv4 адрес",
    ipv6: "IPv6 адрес",
    cidrv4: "IPv4 диапазон",
    cidrv6: "IPv6 диапазон",
    base64: "base64-кодиран низ",
    base64url: "base64url-кодиран низ",
    json_string: "JSON низ",
    e164: "E.164 номер",
    jwt: "JWT",
    template_literal: "вход"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "число",
    array: "масив"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Невалиден вход: очакван instanceof ${issue2.expected}, получен ${received}`;
        }
        return `Невалиден вход: очакван ${expected}, получен ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Невалиден вход: очакван ${stringifyPrimitive(issue2.values[0])}`;
        return `Невалидна опция: очаквано едно от ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Твърде голямо: очаква се ${issue2.origin ?? "стойност"} да съдържа ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "елемента"}`;
        return `Твърде голямо: очаква се ${issue2.origin ?? "стойност"} да бъде ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Твърде малко: очаква се ${issue2.origin} да съдържа ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Твърде малко: очаква се ${issue2.origin} да бъде ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Невалиден низ: трябва да започва с "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Невалиден низ: трябва да завършва с "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Невалиден низ: трябва да включва "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Невалиден низ: трябва да съвпада с ${_issue.pattern}`;
        let invalid_adj = "Невалиден";
        if (_issue.format === "emoji")
          invalid_adj = "Невалидно";
        if (_issue.format === "datetime")
          invalid_adj = "Невалидно";
        if (_issue.format === "date")
          invalid_adj = "Невалидна";
        if (_issue.format === "time")
          invalid_adj = "Невалидно";
        if (_issue.format === "duration")
          invalid_adj = "Невалидна";
        return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Невалидно число: трябва да бъде кратно на ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Неразпознат${issue2.keys.length > 1 ? "и" : ""} ключ${issue2.keys.length > 1 ? "ове" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Невалиден ключ в ${issue2.origin}`;
      case "invalid_union":
        return "Невалиден вход";
      case "invalid_element":
        return `Невалидна стойност в ${issue2.origin}`;
      default:
        return `Невалиден вход`;
    }
  };
};
function bg_default() {
  return {
    localeError: error4()
  };
}
// node_modules/zod/v4/locales/ca.js
var error5 = () => {
  const Sizable = {
    string: { unit: "caràcters", verb: "contenir" },
    file: { unit: "bytes", verb: "contenir" },
    array: { unit: "elements", verb: "contenir" },
    set: { unit: "elements", verb: "contenir" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "entrada",
    email: "adreça electrònica",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "data i hora ISO",
    date: "data ISO",
    time: "hora ISO",
    duration: "durada ISO",
    ipv4: "adreça IPv4",
    ipv6: "adreça IPv6",
    cidrv4: "rang IPv4",
    cidrv6: "rang IPv6",
    base64: "cadena codificada en base64",
    base64url: "cadena codificada en base64url",
    json_string: "cadena JSON",
    e164: "número E.164",
    jwt: "JWT",
    template_literal: "entrada"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Tipus invàlid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`;
        }
        return `Tipus invàlid: s'esperava ${expected}, s'ha rebut ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Valor invàlid: s'esperava ${stringifyPrimitive(issue2.values[0])}`;
        return `Opció invàlida: s'esperava una de ${joinValues(issue2.values, " o ")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "com a màxim" : "menys de";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} contingués ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;
        return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} fos ${adj} ${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? "com a mínim" : "més de";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Massa petit: s'esperava que ${issue2.origin} contingués ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Format invàlid: ha de començar amb "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Format invàlid: ha d'acabar amb "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Format invàlid: ha d'incloure "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Format invàlid: ha de coincidir amb el patró ${_issue.pattern}`;
        return `Format invàlid per a ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Número invàlid: ha de ser múltiple de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Clau invàlida a ${issue2.origin}`;
      case "invalid_union":
        return "Entrada invàlida";
      case "invalid_element":
        return `Element invàlid a ${issue2.origin}`;
      default:
        return `Entrada invàlida`;
    }
  };
};
function ca_default() {
  return {
    localeError: error5()
  };
}
// node_modules/zod/v4/locales/cs.js
var error6 = () => {
  const Sizable = {
    string: { unit: "znaků", verb: "mít" },
    file: { unit: "bajtů", verb: "mít" },
    array: { unit: "prvků", verb: "mít" },
    set: { unit: "prvků", verb: "mít" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "regulární výraz",
    email: "e-mailová adresa",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "datum a čas ve formátu ISO",
    date: "datum ve formátu ISO",
    time: "čas ve formátu ISO",
    duration: "doba trvání ISO",
    ipv4: "IPv4 adresa",
    ipv6: "IPv6 adresa",
    cidrv4: "rozsah IPv4",
    cidrv6: "rozsah IPv6",
    base64: "řetězec zakódovaný ve formátu base64",
    base64url: "řetězec zakódovaný ve formátu base64url",
    json_string: "řetězec ve formátu JSON",
    e164: "číslo E.164",
    jwt: "JWT",
    template_literal: "vstup"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "číslo",
    string: "řetězec",
    function: "funkce",
    array: "pole"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Neplatný vstup: očekáváno instanceof ${issue2.expected}, obdrženo ${received}`;
        }
        return `Neplatný vstup: očekáváno ${expected}, obdrženo ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Neplatný vstup: očekáváno ${stringifyPrimitive(issue2.values[0])}`;
        return `Neplatná možnost: očekávána jedna z hodnot ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Hodnota je příliš velká: ${issue2.origin ?? "hodnota"} musí mít ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvků"}`;
        }
        return `Hodnota je příliš velká: ${issue2.origin ?? "hodnota"} musí být ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Hodnota je příliš malá: ${issue2.origin ?? "hodnota"} musí mít ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvků"}`;
        }
        return `Hodnota je příliš malá: ${issue2.origin ?? "hodnota"} musí být ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Neplatný řetězec: musí začínat na "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Neplatný řetězec: musí končit na "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Neplatný řetězec: musí obsahovat "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Neplatný řetězec: musí odpovídat vzoru ${_issue.pattern}`;
        return `Neplatný formát ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Neplatné číslo: musí být násobkem ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Neznámé klíče: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Neplatný klíč v ${issue2.origin}`;
      case "invalid_union":
        return "Neplatný vstup";
      case "invalid_element":
        return `Neplatná hodnota v ${issue2.origin}`;
      default:
        return `Neplatný vstup`;
    }
  };
};
function cs_default() {
  return {
    localeError: error6()
  };
}
// node_modules/zod/v4/locales/da.js
var error7 = () => {
  const Sizable = {
    string: { unit: "tegn", verb: "havde" },
    file: { unit: "bytes", verb: "havde" },
    array: { unit: "elementer", verb: "indeholdt" },
    set: { unit: "elementer", verb: "indeholdt" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "e-mailadresse",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO dato- og klokkeslæt",
    date: "ISO-dato",
    time: "ISO-klokkeslæt",
    duration: "ISO-varighed",
    ipv4: "IPv4-område",
    ipv6: "IPv6-område",
    cidrv4: "IPv4-spektrum",
    cidrv6: "IPv6-spektrum",
    base64: "base64-kodet streng",
    base64url: "base64url-kodet streng",
    json_string: "JSON-streng",
    e164: "E.164-nummer",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN",
    string: "streng",
    number: "tal",
    boolean: "boolean",
    array: "liste",
    object: "objekt",
    set: "sæt",
    file: "fil"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`;
        }
        return `Ugyldigt input: forventede ${expected}, fik ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ugyldig værdi: forventede ${stringifyPrimitive(issue2.values[0])}`;
        return `Ugyldigt valg: forventede en af følgende ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        if (sizing)
          return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`;
        return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        if (sizing) {
          return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Ugyldig streng: skal starte med "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Ugyldig streng: skal ende med "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Ugyldig streng: skal indeholde "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Ugyldig streng: skal matche mønsteret ${_issue.pattern}`;
        return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Ugyldigt tal: skal være deleligt med ${issue2.divisor}`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "Ukendte nøgler" : "Ukendt nøgle"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Ugyldig nøgle i ${issue2.origin}`;
      case "invalid_union":
        return "Ugyldigt input: matcher ingen af de tilladte typer";
      case "invalid_element":
        return `Ugyldig værdi i ${issue2.origin}`;
      default:
        return `Ugyldigt input`;
    }
  };
};
function da_default() {
  return {
    localeError: error7()
  };
}
// node_modules/zod/v4/locales/de.js
var error8 = () => {
  const Sizable = {
    string: { unit: "Zeichen", verb: "zu haben" },
    file: { unit: "Bytes", verb: "zu haben" },
    array: { unit: "Elemente", verb: "zu haben" },
    set: { unit: "Elemente", verb: "zu haben" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "Eingabe",
    email: "E-Mail-Adresse",
    url: "URL",
    emoji: "Emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO-Datum und -Uhrzeit",
    date: "ISO-Datum",
    time: "ISO-Uhrzeit",
    duration: "ISO-Dauer",
    ipv4: "IPv4-Adresse",
    ipv6: "IPv6-Adresse",
    cidrv4: "IPv4-Bereich",
    cidrv6: "IPv6-Bereich",
    base64: "Base64-codierter String",
    base64url: "Base64-URL-codierter String",
    json_string: "JSON-String",
    e164: "E.164-Nummer",
    jwt: "JWT",
    template_literal: "Eingabe"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "Zahl",
    array: "Array"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ungültige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`;
        }
        return `Ungültige Eingabe: erwartet ${expected}, erhalten ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ungültige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`;
        return `Ungültige Option: erwartet eine von ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Zu groß: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`;
        return `Zu groß: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ist`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`;
        }
        return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Ungültiger String: muss mit "${_issue.prefix}" beginnen`;
        if (_issue.format === "ends_with")
          return `Ungültiger String: muss mit "${_issue.suffix}" enden`;
        if (_issue.format === "includes")
          return `Ungültiger String: muss "${_issue.includes}" enthalten`;
        if (_issue.format === "regex")
          return `Ungültiger String: muss dem Muster ${_issue.pattern} entsprechen`;
        return `Ungültig: ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Ungültige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "Unbekannte Schlüssel" : "Unbekannter Schlüssel"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Ungültiger Schlüssel in ${issue2.origin}`;
      case "invalid_union":
        return "Ungültige Eingabe";
      case "invalid_element":
        return `Ungültiger Wert in ${issue2.origin}`;
      default:
        return `Ungültige Eingabe`;
    }
  };
};
function de_default() {
  return {
    localeError: error8()
  };
}
// node_modules/zod/v4/locales/en.js
var error9 = () => {
  const Sizable = {
    string: { unit: "characters", verb: "to have" },
    file: { unit: "bytes", verb: "to have" },
    array: { unit: "items", verb: "to have" },
    set: { unit: "items", verb: "to have" },
    map: { unit: "entries", verb: "to have" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "email address",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO datetime",
    date: "ISO date",
    time: "ISO time",
    duration: "ISO duration",
    ipv4: "IPv4 address",
    ipv6: "IPv6 address",
    mac: "MAC address",
    cidrv4: "IPv4 range",
    cidrv6: "IPv6 range",
    base64: "base64-encoded string",
    base64url: "base64url-encoded string",
    json_string: "JSON string",
    e164: "E.164 number",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        return `Invalid input: expected ${expected}, received ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
        return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;
        return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Invalid string: must start with "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Invalid string: must end with "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Invalid string: must include "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Invalid string: must match pattern ${_issue.pattern}`;
        return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Invalid number: must be a multiple of ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Invalid key in ${issue2.origin}`;
      case "invalid_union":
        return "Invalid input";
      case "invalid_element":
        return `Invalid value in ${issue2.origin}`;
      default:
        return `Invalid input`;
    }
  };
};
function en_default() {
  return {
    localeError: error9()
  };
}
// node_modules/zod/v4/locales/eo.js
var error10 = () => {
  const Sizable = {
    string: { unit: "karaktrojn", verb: "havi" },
    file: { unit: "bajtojn", verb: "havi" },
    array: { unit: "elementojn", verb: "havi" },
    set: { unit: "elementojn", verb: "havi" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "enigo",
    email: "retadreso",
    url: "URL",
    emoji: "emoĝio",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO-datotempo",
    date: "ISO-dato",
    time: "ISO-tempo",
    duration: "ISO-daŭro",
    ipv4: "IPv4-adreso",
    ipv6: "IPv6-adreso",
    cidrv4: "IPv4-rango",
    cidrv6: "IPv6-rango",
    base64: "64-ume kodita karaktraro",
    base64url: "URL-64-ume kodita karaktraro",
    json_string: "JSON-karaktraro",
    e164: "E.164-nombro",
    jwt: "JWT",
    template_literal: "enigo"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "nombro",
    array: "tabelo",
    null: "senvalora"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Nevalida enigo: atendiĝis instanceof ${issue2.expected}, riceviĝis ${received}`;
        }
        return `Nevalida enigo: atendiĝis ${expected}, riceviĝis ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Nevalida enigo: atendiĝis ${stringifyPrimitive(issue2.values[0])}`;
        return `Nevalida opcio: atendiĝis unu el ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Tro granda: atendiĝis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementojn"}`;
        return `Tro granda: atendiĝis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Tro malgranda: atendiĝis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Tro malgranda: atendiĝis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Nevalida karaktraro: devas komenciĝi per "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Nevalida karaktraro: devas finiĝi per "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`;
        return `Nevalida ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Nekonata${issue2.keys.length > 1 ? "j" : ""} ŝlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Nevalida ŝlosilo en ${issue2.origin}`;
      case "invalid_union":
        return "Nevalida enigo";
      case "invalid_element":
        return `Nevalida valoro en ${issue2.origin}`;
      default:
        return `Nevalida enigo`;
    }
  };
};
function eo_default() {
  return {
    localeError: error10()
  };
}
// node_modules/zod/v4/locales/es.js
var error11 = () => {
  const Sizable = {
    string: { unit: "caracteres", verb: "tener" },
    file: { unit: "bytes", verb: "tener" },
    array: { unit: "elementos", verb: "tener" },
    set: { unit: "elementos", verb: "tener" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "entrada",
    email: "dirección de correo electrónico",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "fecha y hora ISO",
    date: "fecha ISO",
    time: "hora ISO",
    duration: "duración ISO",
    ipv4: "dirección IPv4",
    ipv6: "dirección IPv6",
    cidrv4: "rango IPv4",
    cidrv6: "rango IPv6",
    base64: "cadena codificada en base64",
    base64url: "URL codificada en base64",
    json_string: "cadena JSON",
    e164: "número E.164",
    jwt: "JWT",
    template_literal: "entrada"
  };
  const TypeDictionary = {
    nan: "NaN",
    string: "texto",
    number: "número",
    boolean: "booleano",
    array: "arreglo",
    object: "objeto",
    set: "conjunto",
    file: "archivo",
    date: "fecha",
    bigint: "número grande",
    symbol: "símbolo",
    undefined: "indefinido",
    null: "nulo",
    function: "función",
    map: "mapa",
    record: "registro",
    tuple: "tupla",
    enum: "enumeración",
    union: "unión",
    literal: "literal",
    promise: "promesa",
    void: "vacío",
    never: "nunca",
    unknown: "desconocido",
    any: "cualquiera"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Entrada inválida: se esperaba instanceof ${issue2.expected}, recibido ${received}`;
        }
        return `Entrada inválida: se esperaba ${expected}, recibido ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Entrada inválida: se esperaba ${stringifyPrimitive(issue2.values[0])}`;
        return `Opción inválida: se esperaba una de ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        if (sizing)
          return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`;
        return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        if (sizing) {
          return `Demasiado pequeño: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Demasiado pequeño: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Cadena inválida: debe comenzar con "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Cadena inválida: debe terminar en "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Cadena inválida: debe incluir "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Cadena inválida: debe coincidir con el patrón ${_issue.pattern}`;
        return `Inválido ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Número inválido: debe ser múltiplo de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Llave inválida en ${TypeDictionary[issue2.origin] ?? issue2.origin}`;
      case "invalid_union":
        return "Entrada inválida";
      case "invalid_element":
        return `Valor inválido en ${TypeDictionary[issue2.origin] ?? issue2.origin}`;
      default:
        return `Entrada inválida`;
    }
  };
};
function es_default() {
  return {
    localeError: error11()
  };
}
// node_modules/zod/v4/locales/fa.js
var error12 = () => {
  const Sizable = {
    string: { unit: "کاراکتر", verb: "داشته باشد" },
    file: { unit: "بایت", verb: "داشته باشد" },
    array: { unit: "آیتم", verb: "داشته باشد" },
    set: { unit: "آیتم", verb: "داشته باشد" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "ورودی",
    email: "آدرس ایمیل",
    url: "URL",
    emoji: "ایموجی",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "تاریخ و زمان ایزو",
    date: "تاریخ ایزو",
    time: "زمان ایزو",
    duration: "مدت زمان ایزو",
    ipv4: "IPv4 آدرس",
    ipv6: "IPv6 آدرس",
    cidrv4: "IPv4 دامنه",
    cidrv6: "IPv6 دامنه",
    base64: "base64-encoded رشته",
    base64url: "base64url-encoded رشته",
    json_string: "JSON رشته",
    e164: "E.164 عدد",
    jwt: "JWT",
    template_literal: "ورودی"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "عدد",
    array: "آرایه"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `ورودی نامعتبر: می‌بایست instanceof ${issue2.expected} می‌بود، ${received} دریافت شد`;
        }
        return `ورودی نامعتبر: می‌بایست ${expected} می‌بود، ${received} دریافت شد`;
      }
      case "invalid_value":
        if (issue2.values.length === 1) {
          return `ورودی نامعتبر: می‌بایست ${stringifyPrimitive(issue2.values[0])} می‌بود`;
        }
        return `گزینه نامعتبر: می‌بایست یکی از ${joinValues(issue2.values, "|")} می‌بود`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `خیلی بزرگ: ${issue2.origin ?? "مقدار"} باید ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "عنصر"} باشد`;
        }
        return `خیلی بزرگ: ${issue2.origin ?? "مقدار"} باید ${adj}${issue2.maximum.toString()} باشد`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `خیلی کوچک: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} ${sizing.unit} باشد`;
        }
        return `خیلی کوچک: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} باشد`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `رشته نامعتبر: باید با "${_issue.prefix}" شروع شود`;
        }
        if (_issue.format === "ends_with") {
          return `رشته نامعتبر: باید با "${_issue.suffix}" تمام شود`;
        }
        if (_issue.format === "includes") {
          return `رشته نامعتبر: باید شامل "${_issue.includes}" باشد`;
        }
        if (_issue.format === "regex") {
          return `رشته نامعتبر: باید با الگوی ${_issue.pattern} مطابقت داشته باشد`;
        }
        return `${FormatDictionary[_issue.format] ?? issue2.format} نامعتبر`;
      }
      case "not_multiple_of":
        return `عدد نامعتبر: باید مضرب ${issue2.divisor} باشد`;
      case "unrecognized_keys":
        return `کلید${issue2.keys.length > 1 ? "های" : ""} ناشناس: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `کلید ناشناس در ${issue2.origin}`;
      case "invalid_union":
        return `ورودی نامعتبر`;
      case "invalid_element":
        return `مقدار نامعتبر در ${issue2.origin}`;
      default:
        return `ورودی نامعتبر`;
    }
  };
};
function fa_default() {
  return {
    localeError: error12()
  };
}
// node_modules/zod/v4/locales/fi.js
var error13 = () => {
  const Sizable = {
    string: { unit: "merkkiä", subject: "merkkijonon" },
    file: { unit: "tavua", subject: "tiedoston" },
    array: { unit: "alkiota", subject: "listan" },
    set: { unit: "alkiota", subject: "joukon" },
    number: { unit: "", subject: "luvun" },
    bigint: { unit: "", subject: "suuren kokonaisluvun" },
    int: { unit: "", subject: "kokonaisluvun" },
    date: { unit: "", subject: "päivämäärän" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "säännöllinen lauseke",
    email: "sähköpostiosoite",
    url: "URL-osoite",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO-aikaleima",
    date: "ISO-päivämäärä",
    time: "ISO-aika",
    duration: "ISO-kesto",
    ipv4: "IPv4-osoite",
    ipv6: "IPv6-osoite",
    cidrv4: "IPv4-alue",
    cidrv6: "IPv6-alue",
    base64: "base64-koodattu merkkijono",
    base64url: "base64url-koodattu merkkijono",
    json_string: "JSON-merkkijono",
    e164: "E.164-luku",
    jwt: "JWT",
    template_literal: "templaattimerkkijono"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`;
        }
        return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Virheellinen syöte: täytyy olla ${stringifyPrimitive(issue2.values[0])}`;
        return `Virheellinen valinta: täytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Liian suuri: ${sizing.subject} täytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim();
        }
        return `Liian suuri: arvon täytyy olla ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Liian pieni: ${sizing.subject} täytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim();
        }
        return `Liian pieni: arvon täytyy olla ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Virheellinen syöte: täytyy alkaa "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Virheellinen syöte: täytyy loppua "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Virheellinen syöte: täytyy sisältää "${_issue.includes}"`;
        if (_issue.format === "regex") {
          return `Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${_issue.pattern}`;
        }
        return `Virheellinen ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Virheellinen luku: täytyy olla luvun ${issue2.divisor} monikerta`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return "Virheellinen avain tietueessa";
      case "invalid_union":
        return "Virheellinen unioni";
      case "invalid_element":
        return "Virheellinen arvo joukossa";
      default:
        return `Virheellinen syöte`;
    }
  };
};
function fi_default() {
  return {
    localeError: error13()
  };
}
// node_modules/zod/v4/locales/fr.js
var error14 = () => {
  const Sizable = {
    string: { unit: "caractères", verb: "avoir" },
    file: { unit: "octets", verb: "avoir" },
    array: { unit: "éléments", verb: "avoir" },
    set: { unit: "éléments", verb: "avoir" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "entrée",
    email: "adresse e-mail",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "date et heure ISO",
    date: "date ISO",
    time: "heure ISO",
    duration: "durée ISO",
    ipv4: "adresse IPv4",
    ipv6: "adresse IPv6",
    cidrv4: "plage IPv4",
    cidrv6: "plage IPv6",
    base64: "chaîne encodée en base64",
    base64url: "chaîne encodée en base64url",
    json_string: "chaîne JSON",
    e164: "numéro E.164",
    jwt: "JWT",
    template_literal: "entrée"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "nombre",
    array: "tableau"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Entrée invalide : instanceof ${issue2.expected} attendu, ${received} reçu`;
        }
        return `Entrée invalide : ${expected} attendu, ${received} reçu`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Entrée invalide : ${stringifyPrimitive(issue2.values[0])} attendu`;
        return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Trop grand : ${issue2.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "élément(s)"}`;
        return `Trop grand : ${issue2.origin ?? "valeur"} doit être ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Trop petit : ${issue2.origin} doit être ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Chaîne invalide : doit commencer par "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Chaîne invalide : doit inclure "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Chaîne invalide : doit correspondre au modèle ${_issue.pattern}`;
        return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`;
      }
      case "not_multiple_of":
        return `Nombre invalide : doit être un multiple de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Clé${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Clé invalide dans ${issue2.origin}`;
      case "invalid_union":
        return "Entrée invalide";
      case "invalid_element":
        return `Valeur invalide dans ${issue2.origin}`;
      default:
        return `Entrée invalide`;
    }
  };
};
function fr_default() {
  return {
    localeError: error14()
  };
}
// node_modules/zod/v4/locales/fr-CA.js
var error15 = () => {
  const Sizable = {
    string: { unit: "caractères", verb: "avoir" },
    file: { unit: "octets", verb: "avoir" },
    array: { unit: "éléments", verb: "avoir" },
    set: { unit: "éléments", verb: "avoir" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "entrée",
    email: "adresse courriel",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "date-heure ISO",
    date: "date ISO",
    time: "heure ISO",
    duration: "durée ISO",
    ipv4: "adresse IPv4",
    ipv6: "adresse IPv6",
    cidrv4: "plage IPv4",
    cidrv6: "plage IPv6",
    base64: "chaîne encodée en base64",
    base64url: "chaîne encodée en base64url",
    json_string: "chaîne JSON",
    e164: "numéro E.164",
    jwt: "JWT",
    template_literal: "entrée"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Entrée invalide : attendu instanceof ${issue2.expected}, reçu ${received}`;
        }
        return `Entrée invalide : attendu ${expected}, reçu ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Entrée invalide : attendu ${stringifyPrimitive(issue2.values[0])}`;
        return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "≤" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
        return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} soit ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? "≥" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Chaîne invalide : doit commencer par "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Chaîne invalide : doit inclure "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Chaîne invalide : doit correspondre au motif ${_issue.pattern}`;
        return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`;
      }
      case "not_multiple_of":
        return `Nombre invalide : doit être un multiple de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Clé${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Clé invalide dans ${issue2.origin}`;
      case "invalid_union":
        return "Entrée invalide";
      case "invalid_element":
        return `Valeur invalide dans ${issue2.origin}`;
      default:
        return `Entrée invalide`;
    }
  };
};
function fr_CA_default() {
  return {
    localeError: error15()
  };
}
// node_modules/zod/v4/locales/he.js
var error16 = () => {
  const TypeNames = {
    string: { label: "מחרוזת", gender: "f" },
    number: { label: "מספר", gender: "m" },
    boolean: { label: "ערך בוליאני", gender: "m" },
    bigint: { label: "BigInt", gender: "m" },
    date: { label: "תאריך", gender: "m" },
    array: { label: "מערך", gender: "m" },
    object: { label: "אובייקט", gender: "m" },
    null: { label: "ערך ריק (null)", gender: "m" },
    undefined: { label: "ערך לא מוגדר (undefined)", gender: "m" },
    symbol: { label: "סימבול (Symbol)", gender: "m" },
    function: { label: "פונקציה", gender: "f" },
    map: { label: "מפה (Map)", gender: "f" },
    set: { label: "קבוצה (Set)", gender: "f" },
    file: { label: "קובץ", gender: "m" },
    promise: { label: "Promise", gender: "m" },
    NaN: { label: "NaN", gender: "m" },
    unknown: { label: "ערך לא ידוע", gender: "m" },
    value: { label: "ערך", gender: "m" }
  };
  const Sizable = {
    string: { unit: "תווים", shortLabel: "קצר", longLabel: "ארוך" },
    file: { unit: "בייטים", shortLabel: "קטן", longLabel: "גדול" },
    array: { unit: "פריטים", shortLabel: "קטן", longLabel: "גדול" },
    set: { unit: "פריטים", shortLabel: "קטן", longLabel: "גדול" },
    number: { unit: "", shortLabel: "קטן", longLabel: "גדול" }
  };
  const typeEntry = (t) => t ? TypeNames[t] : undefined;
  const typeLabel = (t) => {
    const e = typeEntry(t);
    if (e)
      return e.label;
    return t ?? TypeNames.unknown.label;
  };
  const withDefinite = (t) => `ה${typeLabel(t)}`;
  const verbFor = (t) => {
    const e = typeEntry(t);
    const gender = e?.gender ?? "m";
    return gender === "f" ? "צריכה להיות" : "צריך להיות";
  };
  const getSizing = (origin) => {
    if (!origin)
      return null;
    return Sizable[origin] ?? null;
  };
  const FormatDictionary = {
    regex: { label: "קלט", gender: "m" },
    email: { label: "כתובת אימייל", gender: "f" },
    url: { label: "כתובת רשת", gender: "f" },
    emoji: { label: "אימוג'י", gender: "m" },
    uuid: { label: "UUID", gender: "m" },
    nanoid: { label: "nanoid", gender: "m" },
    guid: { label: "GUID", gender: "m" },
    cuid: { label: "cuid", gender: "m" },
    cuid2: { label: "cuid2", gender: "m" },
    ulid: { label: "ULID", gender: "m" },
    xid: { label: "XID", gender: "m" },
    ksuid: { label: "KSUID", gender: "m" },
    datetime: { label: "תאריך וזמן ISO", gender: "m" },
    date: { label: "תאריך ISO", gender: "m" },
    time: { label: "זמן ISO", gender: "m" },
    duration: { label: "משך זמן ISO", gender: "m" },
    ipv4: { label: "כתובת IPv4", gender: "f" },
    ipv6: { label: "כתובת IPv6", gender: "f" },
    cidrv4: { label: "טווח IPv4", gender: "m" },
    cidrv6: { label: "טווח IPv6", gender: "m" },
    base64: { label: "מחרוזת בבסיס 64", gender: "f" },
    base64url: { label: "מחרוזת בבסיס 64 לכתובות רשת", gender: "f" },
    json_string: { label: "מחרוזת JSON", gender: "f" },
    e164: { label: "מספר E.164", gender: "m" },
    jwt: { label: "JWT", gender: "m" },
    ends_with: { label: "קלט", gender: "m" },
    includes: { label: "קלט", gender: "m" },
    lowercase: { label: "קלט", gender: "m" },
    starts_with: { label: "קלט", gender: "m" },
    uppercase: { label: "קלט", gender: "m" }
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expectedKey = issue2.expected;
        const expected = TypeDictionary[expectedKey ?? ""] ?? typeLabel(expectedKey);
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `קלט לא תקין: צריך להיות instanceof ${issue2.expected}, התקבל ${received}`;
        }
        return `קלט לא תקין: צריך להיות ${expected}, התקבל ${received}`;
      }
      case "invalid_value": {
        if (issue2.values.length === 1) {
          return `ערך לא תקין: הערך חייב להיות ${stringifyPrimitive(issue2.values[0])}`;
        }
        const stringified = issue2.values.map((v) => stringifyPrimitive(v));
        if (issue2.values.length === 2) {
          return `ערך לא תקין: האפשרויות המתאימות הן ${stringified[0]} או ${stringified[1]}`;
        }
        const lastValue = stringified[stringified.length - 1];
        const restValues = stringified.slice(0, -1).join(", ");
        return `ערך לא תקין: האפשרויות המתאימות הן ${restValues} או ${lastValue}`;
      }
      case "too_big": {
        const sizing = getSizing(issue2.origin);
        const subject = withDefinite(issue2.origin ?? "value");
        if (issue2.origin === "string") {
          return `${sizing?.longLabel ?? "ארוך"} מדי: ${subject} צריכה להכיל ${issue2.maximum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "או פחות" : "לכל היותר"}`.trim();
        }
        if (issue2.origin === "number") {
          const comparison = issue2.inclusive ? `קטן או שווה ל-${issue2.maximum}` : `קטן מ-${issue2.maximum}`;
          return `גדול מדי: ${subject} צריך להיות ${comparison}`;
        }
        if (issue2.origin === "array" || issue2.origin === "set") {
          const verb = issue2.origin === "set" ? "צריכה" : "צריך";
          const comparison = issue2.inclusive ? `${issue2.maximum} ${sizing?.unit ?? ""} או פחות` : `פחות מ-${issue2.maximum} ${sizing?.unit ?? ""}`;
          return `גדול מדי: ${subject} ${verb} להכיל ${comparison}`.trim();
        }
        const adj = issue2.inclusive ? "<=" : "<";
        const be = verbFor(issue2.origin ?? "value");
        if (sizing?.unit) {
          return `${sizing.longLabel} מדי: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
        }
        return `${sizing?.longLabel ?? "גדול"} מדי: ${subject} ${be} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const sizing = getSizing(issue2.origin);
        const subject = withDefinite(issue2.origin ?? "value");
        if (issue2.origin === "string") {
          return `${sizing?.shortLabel ?? "קצר"} מדי: ${subject} צריכה להכיל ${issue2.minimum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "או יותר" : "לפחות"}`.trim();
        }
        if (issue2.origin === "number") {
          const comparison = issue2.inclusive ? `גדול או שווה ל-${issue2.minimum}` : `גדול מ-${issue2.minimum}`;
          return `קטן מדי: ${subject} צריך להיות ${comparison}`;
        }
        if (issue2.origin === "array" || issue2.origin === "set") {
          const verb = issue2.origin === "set" ? "צריכה" : "צריך";
          if (issue2.minimum === 1 && issue2.inclusive) {
            const singularPhrase = issue2.origin === "set" ? "לפחות פריט אחד" : "לפחות פריט אחד";
            return `קטן מדי: ${subject} ${verb} להכיל ${singularPhrase}`;
          }
          const comparison = issue2.inclusive ? `${issue2.minimum} ${sizing?.unit ?? ""} או יותר` : `יותר מ-${issue2.minimum} ${sizing?.unit ?? ""}`;
          return `קטן מדי: ${subject} ${verb} להכיל ${comparison}`.trim();
        }
        const adj = issue2.inclusive ? ">=" : ">";
        const be = verbFor(issue2.origin ?? "value");
        if (sizing?.unit) {
          return `${sizing.shortLabel} מדי: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `${sizing?.shortLabel ?? "קטן"} מדי: ${subject} ${be} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `המחרוזת חייבת להתחיל ב "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `המחרוזת חייבת להסתיים ב "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `המחרוזת חייבת לכלול "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `המחרוזת חייבת להתאים לתבנית ${_issue.pattern}`;
        const nounEntry = FormatDictionary[_issue.format];
        const noun = nounEntry?.label ?? _issue.format;
        const gender = nounEntry?.gender ?? "m";
        const adjective = gender === "f" ? "תקינה" : "תקין";
        return `${noun} לא ${adjective}`;
      }
      case "not_multiple_of":
        return `מספר לא תקין: חייב להיות מכפלה של ${issue2.divisor}`;
      case "unrecognized_keys":
        return `מפתח${issue2.keys.length > 1 ? "ות" : ""} לא מזוה${issue2.keys.length > 1 ? "ים" : "ה"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key": {
        return `שדה לא תקין באובייקט`;
      }
      case "invalid_union":
        return "קלט לא תקין";
      case "invalid_element": {
        const place = withDefinite(issue2.origin ?? "array");
        return `ערך לא תקין ב${place}`;
      }
      default:
        return `קלט לא תקין`;
    }
  };
};
function he_default() {
  return {
    localeError: error16()
  };
}
// node_modules/zod/v4/locales/hu.js
var error17 = () => {
  const Sizable = {
    string: { unit: "karakter", verb: "legyen" },
    file: { unit: "byte", verb: "legyen" },
    array: { unit: "elem", verb: "legyen" },
    set: { unit: "elem", verb: "legyen" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "bemenet",
    email: "email cím",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO időbélyeg",
    date: "ISO dátum",
    time: "ISO idő",
    duration: "ISO időintervallum",
    ipv4: "IPv4 cím",
    ipv6: "IPv6 cím",
    cidrv4: "IPv4 tartomány",
    cidrv6: "IPv6 tartomány",
    base64: "base64-kódolt string",
    base64url: "base64url-kódolt string",
    json_string: "JSON string",
    e164: "E.164 szám",
    jwt: "JWT",
    template_literal: "bemenet"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "szám",
    array: "tömb"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Érvénytelen bemenet: a várt érték instanceof ${issue2.expected}, a kapott érték ${received}`;
        }
        return `Érvénytelen bemenet: a várt érték ${expected}, a kapott érték ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Érvénytelen bemenet: a várt érték ${stringifyPrimitive(issue2.values[0])}`;
        return `Érvénytelen opció: valamelyik érték várt ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Túl nagy: ${issue2.origin ?? "érték"} mérete túl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elem"}`;
        return `Túl nagy: a bemeneti érték ${issue2.origin ?? "érték"} túl nagy: ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Túl kicsi: a bemeneti érték ${issue2.origin} mérete túl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Túl kicsi: a bemeneti érték ${issue2.origin} túl kicsi ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Érvénytelen string: "${_issue.prefix}" értékkel kell kezdődnie`;
        if (_issue.format === "ends_with")
          return `Érvénytelen string: "${_issue.suffix}" értékkel kell végződnie`;
        if (_issue.format === "includes")
          return `Érvénytelen string: "${_issue.includes}" értéket kell tartalmaznia`;
        if (_issue.format === "regex")
          return `Érvénytelen string: ${_issue.pattern} mintának kell megfelelnie`;
        return `Érvénytelen ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Érvénytelen szám: ${issue2.divisor} többszörösének kell lennie`;
      case "unrecognized_keys":
        return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Érvénytelen kulcs ${issue2.origin}`;
      case "invalid_union":
        return "Érvénytelen bemenet";
      case "invalid_element":
        return `Érvénytelen érték: ${issue2.origin}`;
      default:
        return `Érvénytelen bemenet`;
    }
  };
};
function hu_default() {
  return {
    localeError: error17()
  };
}
// node_modules/zod/v4/locales/hy.js
function getArmenianPlural(count3, one2, many) {
  return Math.abs(count3) === 1 ? one2 : many;
}
function withDefiniteArticle(word) {
  if (!word)
    return "";
  const vowels = ["ա", "ե", "ը", "ի", "ո", "ու", "օ"];
  const lastChar = word[word.length - 1];
  return word + (vowels.includes(lastChar) ? "ն" : "ը");
}
var error18 = () => {
  const Sizable = {
    string: {
      unit: {
        one: "նշան",
        many: "նշաններ"
      },
      verb: "ունենալ"
    },
    file: {
      unit: {
        one: "բայթ",
        many: "բայթեր"
      },
      verb: "ունենալ"
    },
    array: {
      unit: {
        one: "տարր",
        many: "տարրեր"
      },
      verb: "ունենալ"
    },
    set: {
      unit: {
        one: "տարր",
        many: "տարրեր"
      },
      verb: "ունենալ"
    }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "մուտք",
    email: "էլ. հասցե",
    url: "URL",
    emoji: "էմոջի",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO ամսաթիվ և ժամ",
    date: "ISO ամսաթիվ",
    time: "ISO ժամ",
    duration: "ISO տևողություն",
    ipv4: "IPv4 հասցե",
    ipv6: "IPv6 հասցե",
    cidrv4: "IPv4 միջակայք",
    cidrv6: "IPv6 միջակայք",
    base64: "base64 ձևաչափով տող",
    base64url: "base64url ձևաչափով տող",
    json_string: "JSON տող",
    e164: "E.164 համար",
    jwt: "JWT",
    template_literal: "մուտք"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "թիվ",
    array: "զանգված"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Սխալ մուտքագրում․ սպասվում էր instanceof ${issue2.expected}, ստացվել է ${received}`;
        }
        return `Սխալ մուտքագրում․ սպասվում էր ${expected}, ստացվել է ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Սխալ մուտքագրում․ սպասվում էր ${stringifyPrimitive(issue2.values[1])}`;
        return `Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const maxValue = Number(issue2.maximum);
          const unit2 = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many);
          return `Չափազանց մեծ արժեք․ սպասվում է, որ ${withDefiniteArticle(issue2.origin ?? "արժեք")} կունենա ${adj}${issue2.maximum.toString()} ${unit2}`;
        }
        return `Չափազանց մեծ արժեք․ սպասվում է, որ ${withDefiniteArticle(issue2.origin ?? "արժեք")} լինի ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const minValue = Number(issue2.minimum);
          const unit2 = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many);
          return `Չափազանց փոքր արժեք․ սպասվում է, որ ${withDefiniteArticle(issue2.origin)} կունենա ${adj}${issue2.minimum.toString()} ${unit2}`;
        }
        return `Չափազանց փոքր արժեք․ սպասվում է, որ ${withDefiniteArticle(issue2.origin)} լինի ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Սխալ տող․ պետք է սկսվի "${_issue.prefix}"-ով`;
        if (_issue.format === "ends_with")
          return `Սխալ տող․ պետք է ավարտվի "${_issue.suffix}"-ով`;
        if (_issue.format === "includes")
          return `Սխալ տող․ պետք է պարունակի "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Սխալ տող․ պետք է համապատասխանի ${_issue.pattern} ձևաչափին`;
        return `Սխալ ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Սխալ թիվ․ պետք է բազմապատիկ լինի ${issue2.divisor}-ի`;
      case "unrecognized_keys":
        return `Չճանաչված բանալի${issue2.keys.length > 1 ? "ներ" : ""}. ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Սխալ բանալի ${withDefiniteArticle(issue2.origin)}-ում`;
      case "invalid_union":
        return "Սխալ մուտքագրում";
      case "invalid_element":
        return `Սխալ արժեք ${withDefiniteArticle(issue2.origin)}-ում`;
      default:
        return `Սխալ մուտքագրում`;
    }
  };
};
function hy_default() {
  return {
    localeError: error18()
  };
}
// node_modules/zod/v4/locales/id.js
var error19 = () => {
  const Sizable = {
    string: { unit: "karakter", verb: "memiliki" },
    file: { unit: "byte", verb: "memiliki" },
    array: { unit: "item", verb: "memiliki" },
    set: { unit: "item", verb: "memiliki" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "alamat email",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "tanggal dan waktu format ISO",
    date: "tanggal format ISO",
    time: "jam format ISO",
    duration: "durasi format ISO",
    ipv4: "alamat IPv4",
    ipv6: "alamat IPv6",
    cidrv4: "rentang alamat IPv4",
    cidrv6: "rentang alamat IPv6",
    base64: "string dengan enkode base64",
    base64url: "string dengan enkode base64url",
    json_string: "string JSON",
    e164: "angka E.164",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`;
        }
        return `Input tidak valid: diharapkan ${expected}, diterima ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`;
        return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`;
        return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} menjadi ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `String tidak valid: harus menyertakan "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `String tidak valid: harus sesuai pola ${_issue.pattern}`;
        return `${FormatDictionary[_issue.format] ?? issue2.format} tidak valid`;
      }
      case "not_multiple_of":
        return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Kunci tidak valid di ${issue2.origin}`;
      case "invalid_union":
        return "Input tidak valid";
      case "invalid_element":
        return `Nilai tidak valid di ${issue2.origin}`;
      default:
        return `Input tidak valid`;
    }
  };
};
function id_default() {
  return {
    localeError: error19()
  };
}
// node_modules/zod/v4/locales/is.js
var error20 = () => {
  const Sizable = {
    string: { unit: "stafi", verb: "að hafa" },
    file: { unit: "bæti", verb: "að hafa" },
    array: { unit: "hluti", verb: "að hafa" },
    set: { unit: "hluti", verb: "að hafa" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "gildi",
    email: "netfang",
    url: "vefslóð",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO dagsetning og tími",
    date: "ISO dagsetning",
    time: "ISO tími",
    duration: "ISO tímalengd",
    ipv4: "IPv4 address",
    ipv6: "IPv6 address",
    cidrv4: "IPv4 range",
    cidrv6: "IPv6 range",
    base64: "base64-encoded strengur",
    base64url: "base64url-encoded strengur",
    json_string: "JSON strengur",
    e164: "E.164 tölugildi",
    jwt: "JWT",
    template_literal: "gildi"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "númer",
    array: "fylki"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Rangt gildi: Þú slóst inn ${received} þar sem á að vera instanceof ${issue2.expected}`;
        }
        return `Rangt gildi: Þú slóst inn ${received} þar sem á að vera ${expected}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Rangt gildi: gert ráð fyrir ${stringifyPrimitive(issue2.values[0])}`;
        return `Ógilt val: má vera eitt af eftirfarandi ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Of stórt: gert er ráð fyrir að ${issue2.origin ?? "gildi"} hafi ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "hluti"}`;
        return `Of stórt: gert er ráð fyrir að ${issue2.origin ?? "gildi"} sé ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Of lítið: gert er ráð fyrir að ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Of lítið: gert er ráð fyrir að ${issue2.origin} sé ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Ógildur strengur: verður að byrja á "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Ógildur strengur: verður að enda á "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Ógildur strengur: verður að innihalda "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Ógildur strengur: verður að fylgja mynstri ${_issue.pattern}`;
        return `Rangt ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Röng tala: verður að vera margfeldi af ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Óþekkt ${issue2.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Rangur lykill í ${issue2.origin}`;
      case "invalid_union":
        return "Rangt gildi";
      case "invalid_element":
        return `Rangt gildi í ${issue2.origin}`;
      default:
        return `Rangt gildi`;
    }
  };
};
function is_default() {
  return {
    localeError: error20()
  };
}
// node_modules/zod/v4/locales/it.js
var error21 = () => {
  const Sizable = {
    string: { unit: "caratteri", verb: "avere" },
    file: { unit: "byte", verb: "avere" },
    array: { unit: "elementi", verb: "avere" },
    set: { unit: "elementi", verb: "avere" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "indirizzo email",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "data e ora ISO",
    date: "data ISO",
    time: "ora ISO",
    duration: "durata ISO",
    ipv4: "indirizzo IPv4",
    ipv6: "indirizzo IPv6",
    cidrv4: "intervallo IPv4",
    cidrv6: "intervallo IPv6",
    base64: "stringa codificata in base64",
    base64url: "URL codificata in base64",
    json_string: "stringa JSON",
    e164: "numero E.164",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "numero",
    array: "vettore"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`;
        }
        return `Input non valido: atteso ${expected}, ricevuto ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`;
        return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Troppo grande: ${issue2.origin ?? "valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementi"}`;
        return `Troppo grande: ${issue2.origin ?? "valore"} deve essere ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Stringa non valida: deve iniziare con "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Stringa non valida: deve terminare con "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Stringa non valida: deve includere "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;
        return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Chiave non valida in ${issue2.origin}`;
      case "invalid_union":
        return "Input non valido";
      case "invalid_element":
        return `Valore non valido in ${issue2.origin}`;
      default:
        return `Input non valido`;
    }
  };
};
function it_default() {
  return {
    localeError: error21()
  };
}
// node_modules/zod/v4/locales/ja.js
var error22 = () => {
  const Sizable = {
    string: { unit: "文字", verb: "である" },
    file: { unit: "バイト", verb: "である" },
    array: { unit: "要素", verb: "である" },
    set: { unit: "要素", verb: "である" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "入力値",
    email: "メールアドレス",
    url: "URL",
    emoji: "絵文字",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO日時",
    date: "ISO日付",
    time: "ISO時刻",
    duration: "ISO期間",
    ipv4: "IPv4アドレス",
    ipv6: "IPv6アドレス",
    cidrv4: "IPv4範囲",
    cidrv6: "IPv6範囲",
    base64: "base64エンコード文字列",
    base64url: "base64urlエンコード文字列",
    json_string: "JSON文字列",
    e164: "E.164番号",
    jwt: "JWT",
    template_literal: "入力値"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "数値",
    array: "配列"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `無効な入力: instanceof ${issue2.expected}が期待されましたが、${received}が入力されました`;
        }
        return `無効な入力: ${expected}が期待されましたが、${received}が入力されました`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `無効な入力: ${stringifyPrimitive(issue2.values[0])}が期待されました`;
        return `無効な選択: ${joinValues(issue2.values, "、")}のいずれかである必要があります`;
      case "too_big": {
        const adj = issue2.inclusive ? "以下である" : "より小さい";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `大きすぎる値: ${issue2.origin ?? "値"}は${issue2.maximum.toString()}${sizing.unit ?? "要素"}${adj}必要があります`;
        return `大きすぎる値: ${issue2.origin ?? "値"}は${issue2.maximum.toString()}${adj}必要があります`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? "以上である" : "より大きい";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `小さすぎる値: ${issue2.origin}は${issue2.minimum.toString()}${sizing.unit}${adj}必要があります`;
        return `小さすぎる値: ${issue2.origin}は${issue2.minimum.toString()}${adj}必要があります`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `無効な文字列: "${_issue.prefix}"で始まる必要があります`;
        if (_issue.format === "ends_with")
          return `無効な文字列: "${_issue.suffix}"で終わる必要があります`;
        if (_issue.format === "includes")
          return `無効な文字列: "${_issue.includes}"を含む必要があります`;
        if (_issue.format === "regex")
          return `無効な文字列: パターン${_issue.pattern}に一致する必要があります`;
        return `無効な${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `無効な数値: ${issue2.divisor}の倍数である必要があります`;
      case "unrecognized_keys":
        return `認識されていないキー${issue2.keys.length > 1 ? "群" : ""}: ${joinValues(issue2.keys, "、")}`;
      case "invalid_key":
        return `${issue2.origin}内の無効なキー`;
      case "invalid_union":
        return "無効な入力";
      case "invalid_element":
        return `${issue2.origin}内の無効な値`;
      default:
        return `無効な入力`;
    }
  };
};
function ja_default() {
  return {
    localeError: error22()
  };
}
// node_modules/zod/v4/locales/ka.js
var error23 = () => {
  const Sizable = {
    string: { unit: "სიმბოლო", verb: "უნდა შეიცავდეს" },
    file: { unit: "ბაიტი", verb: "უნდა შეიცავდეს" },
    array: { unit: "ელემენტი", verb: "უნდა შეიცავდეს" },
    set: { unit: "ელემენტი", verb: "უნდა შეიცავდეს" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "შეყვანა",
    email: "ელ-ფოსტის მისამართი",
    url: "URL",
    emoji: "ემოჯი",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "თარიღი-დრო",
    date: "თარიღი",
    time: "დრო",
    duration: "ხანგრძლივობა",
    ipv4: "IPv4 მისამართი",
    ipv6: "IPv6 მისამართი",
    cidrv4: "IPv4 დიაპაზონი",
    cidrv6: "IPv6 დიაპაზონი",
    base64: "base64-კოდირებული სტრინგი",
    base64url: "base64url-კოდირებული სტრინგი",
    json_string: "JSON სტრინგი",
    e164: "E.164 ნომერი",
    jwt: "JWT",
    template_literal: "შეყვანა"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "რიცხვი",
    string: "სტრინგი",
    boolean: "ბულეანი",
    function: "ფუნქცია",
    array: "მასივი"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `არასწორი შეყვანა: მოსალოდნელი instanceof ${issue2.expected}, მიღებული ${received}`;
        }
        return `არასწორი შეყვანა: მოსალოდნელი ${expected}, მიღებული ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `არასწორი შეყვანა: მოსალოდნელი ${stringifyPrimitive(issue2.values[0])}`;
        return `არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${joinValues(issue2.values, "|")}-დან`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `ზედმეტად დიდი: მოსალოდნელი ${issue2.origin ?? "მნიშვნელობა"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
        return `ზედმეტად დიდი: მოსალოდნელი ${issue2.origin ?? "მნიშვნელობა"} იყოს ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `ზედმეტად პატარა: მოსალოდნელი ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `ზედმეტად პატარა: მოსალოდნელი ${issue2.origin} იყოს ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `არასწორი სტრინგი: უნდა იწყებოდეს "${_issue.prefix}"-ით`;
        }
        if (_issue.format === "ends_with")
          return `არასწორი სტრინგი: უნდა მთავრდებოდეს "${_issue.suffix}"-ით`;
        if (_issue.format === "includes")
          return `არასწორი სტრინგი: უნდა შეიცავდეს "${_issue.includes}"-ს`;
        if (_issue.format === "regex")
          return `არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${_issue.pattern}`;
        return `არასწორი ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `არასწორი რიცხვი: უნდა იყოს ${issue2.divisor}-ის ჯერადი`;
      case "unrecognized_keys":
        return `უცნობი გასაღებ${issue2.keys.length > 1 ? "ები" : "ი"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `არასწორი გასაღები ${issue2.origin}-ში`;
      case "invalid_union":
        return "არასწორი შეყვანა";
      case "invalid_element":
        return `არასწორი მნიშვნელობა ${issue2.origin}-ში`;
      default:
        return `არასწორი შეყვანა`;
    }
  };
};
function ka_default() {
  return {
    localeError: error23()
  };
}
// node_modules/zod/v4/locales/km.js
var error24 = () => {
  const Sizable = {
    string: { unit: "តួអក្សរ", verb: "គួរមាន" },
    file: { unit: "បៃ", verb: "គួរមាន" },
    array: { unit: "ធាតុ", verb: "គួរមាន" },
    set: { unit: "ធាតុ", verb: "គួរមាន" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "ទិន្នន័យបញ្ចូល",
    email: "អាសយដ្ឋានអ៊ីមែល",
    url: "URL",
    emoji: "សញ្ញាអារម្មណ៍",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "កាលបរិច្ឆេទ និងម៉ោង ISO",
    date: "កាលបរិច្ឆេទ ISO",
    time: "ម៉ោង ISO",
    duration: "រយៈពេល ISO",
    ipv4: "អាសយដ្ឋាន IPv4",
    ipv6: "អាសយដ្ឋាន IPv6",
    cidrv4: "ដែនអាសយដ្ឋាន IPv4",
    cidrv6: "ដែនអាសយដ្ឋាន IPv6",
    base64: "ខ្សែអក្សរអ៊ិកូដ base64",
    base64url: "ខ្សែអក្សរអ៊ិកូដ base64url",
    json_string: "ខ្សែអក្សរ JSON",
    e164: "លេខ E.164",
    jwt: "JWT",
    template_literal: "ទិន្នន័យបញ្ចូល"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "លេខ",
    array: "អារេ (Array)",
    null: "គ្មានតម្លៃ (null)"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${issue2.expected} ប៉ុន្តែទទួលបាន ${received}`;
        }
        return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${expected} ប៉ុន្តែទទួលបាន ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${stringifyPrimitive(issue2.values[0])}`;
        return `ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `ធំពេក៖ ត្រូវការ ${issue2.origin ?? "តម្លៃ"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "ធាតុ"}`;
        return `ធំពេក៖ ត្រូវការ ${issue2.origin ?? "តម្លៃ"} ${adj} ${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `តូចពេក៖ ត្រូវការ ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `តូចពេក៖ ត្រូវការ ${issue2.origin} ${adj} ${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${_issue.pattern}`;
        return `មិនត្រឹមត្រូវ៖ ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${issue2.divisor}`;
      case "unrecognized_keys":
        return `រកឃើញសោមិនស្គាល់៖ ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `សោមិនត្រឹមត្រូវនៅក្នុង ${issue2.origin}`;
      case "invalid_union":
        return `ទិន្នន័យមិនត្រឹមត្រូវ`;
      case "invalid_element":
        return `ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${issue2.origin}`;
      default:
        return `ទិន្នន័យមិនត្រឹមត្រូវ`;
    }
  };
};
function km_default() {
  return {
    localeError: error24()
  };
}

// node_modules/zod/v4/locales/kh.js
function kh_default() {
  return km_default();
}
// node_modules/zod/v4/locales/ko.js
var error25 = () => {
  const Sizable = {
    string: { unit: "문자", verb: "to have" },
    file: { unit: "바이트", verb: "to have" },
    array: { unit: "개", verb: "to have" },
    set: { unit: "개", verb: "to have" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "입력",
    email: "이메일 주소",
    url: "URL",
    emoji: "이모지",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO 날짜시간",
    date: "ISO 날짜",
    time: "ISO 시간",
    duration: "ISO 기간",
    ipv4: "IPv4 주소",
    ipv6: "IPv6 주소",
    cidrv4: "IPv4 범위",
    cidrv6: "IPv6 범위",
    base64: "base64 인코딩 문자열",
    base64url: "base64url 인코딩 문자열",
    json_string: "JSON 문자열",
    e164: "E.164 번호",
    jwt: "JWT",
    template_literal: "입력"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `잘못된 입력: 예상 타입은 instanceof ${issue2.expected}, 받은 타입은 ${received}입니다`;
        }
        return `잘못된 입력: 예상 타입은 ${expected}, 받은 타입은 ${received}입니다`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `잘못된 입력: 값은 ${stringifyPrimitive(issue2.values[0])} 이어야 합니다`;
        return `잘못된 옵션: ${joinValues(issue2.values, "또는 ")} 중 하나여야 합니다`;
      case "too_big": {
        const adj = issue2.inclusive ? "이하" : "미만";
        const suffix = adj === "미만" ? "이어야 합니다" : "여야 합니다";
        const sizing = getSizing(issue2.origin);
        const unit2 = sizing?.unit ?? "요소";
        if (sizing)
          return `${issue2.origin ?? "값"}이 너무 큽니다: ${issue2.maximum.toString()}${unit2} ${adj}${suffix}`;
        return `${issue2.origin ?? "값"}이 너무 큽니다: ${issue2.maximum.toString()} ${adj}${suffix}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? "이상" : "초과";
        const suffix = adj === "이상" ? "이어야 합니다" : "여야 합니다";
        const sizing = getSizing(issue2.origin);
        const unit2 = sizing?.unit ?? "요소";
        if (sizing) {
          return `${issue2.origin ?? "값"}이 너무 작습니다: ${issue2.minimum.toString()}${unit2} ${adj}${suffix}`;
        }
        return `${issue2.origin ?? "값"}이 너무 작습니다: ${issue2.minimum.toString()} ${adj}${suffix}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `잘못된 문자열: "${_issue.prefix}"(으)로 시작해야 합니다`;
        }
        if (_issue.format === "ends_with")
          return `잘못된 문자열: "${_issue.suffix}"(으)로 끝나야 합니다`;
        if (_issue.format === "includes")
          return `잘못된 문자열: "${_issue.includes}"을(를) 포함해야 합니다`;
        if (_issue.format === "regex")
          return `잘못된 문자열: 정규식 ${_issue.pattern} 패턴과 일치해야 합니다`;
        return `잘못된 ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `잘못된 숫자: ${issue2.divisor}의 배수여야 합니다`;
      case "unrecognized_keys":
        return `인식할 수 없는 키: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `잘못된 키: ${issue2.origin}`;
      case "invalid_union":
        return `잘못된 입력`;
      case "invalid_element":
        return `잘못된 값: ${issue2.origin}`;
      default:
        return `잘못된 입력`;
    }
  };
};
function ko_default() {
  return {
    localeError: error25()
  };
}
// node_modules/zod/v4/locales/lt.js
var capitalizeFirstCharacter = (text2) => {
  return text2.charAt(0).toUpperCase() + text2.slice(1);
};
function getUnitTypeFromNumber(number4) {
  const abs3 = Math.abs(number4);
  const last2 = abs3 % 10;
  const last22 = abs3 % 100;
  if (last22 >= 11 && last22 <= 19 || last2 === 0)
    return "many";
  if (last2 === 1)
    return "one";
  return "few";
}
var error26 = () => {
  const Sizable = {
    string: {
      unit: {
        one: "simbolis",
        few: "simboliai",
        many: "simbolių"
      },
      verb: {
        smaller: {
          inclusive: "turi būti ne ilgesnė kaip",
          notInclusive: "turi būti trumpesnė kaip"
        },
        bigger: {
          inclusive: "turi būti ne trumpesnė kaip",
          notInclusive: "turi būti ilgesnė kaip"
        }
      }
    },
    file: {
      unit: {
        one: "baitas",
        few: "baitai",
        many: "baitų"
      },
      verb: {
        smaller: {
          inclusive: "turi būti ne didesnis kaip",
          notInclusive: "turi būti mažesnis kaip"
        },
        bigger: {
          inclusive: "turi būti ne mažesnis kaip",
          notInclusive: "turi būti didesnis kaip"
        }
      }
    },
    array: {
      unit: {
        one: "elementą",
        few: "elementus",
        many: "elementų"
      },
      verb: {
        smaller: {
          inclusive: "turi turėti ne daugiau kaip",
          notInclusive: "turi turėti mažiau kaip"
        },
        bigger: {
          inclusive: "turi turėti ne mažiau kaip",
          notInclusive: "turi turėti daugiau kaip"
        }
      }
    },
    set: {
      unit: {
        one: "elementą",
        few: "elementus",
        many: "elementų"
      },
      verb: {
        smaller: {
          inclusive: "turi turėti ne daugiau kaip",
          notInclusive: "turi turėti mažiau kaip"
        },
        bigger: {
          inclusive: "turi turėti ne mažiau kaip",
          notInclusive: "turi turėti daugiau kaip"
        }
      }
    }
  };
  function getSizing(origin, unitType, inclusive, targetShouldBe) {
    const result = Sizable[origin] ?? null;
    if (result === null)
      return result;
    return {
      unit: result.unit[unitType],
      verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"]
    };
  }
  const FormatDictionary = {
    regex: "įvestis",
    email: "el. pašto adresas",
    url: "URL",
    emoji: "jaustukas",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO data ir laikas",
    date: "ISO data",
    time: "ISO laikas",
    duration: "ISO trukmė",
    ipv4: "IPv4 adresas",
    ipv6: "IPv6 adresas",
    cidrv4: "IPv4 tinklo prefiksas (CIDR)",
    cidrv6: "IPv6 tinklo prefiksas (CIDR)",
    base64: "base64 užkoduota eilutė",
    base64url: "base64url užkoduota eilutė",
    json_string: "JSON eilutė",
    e164: "E.164 numeris",
    jwt: "JWT",
    template_literal: "įvestis"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "skaičius",
    bigint: "sveikasis skaičius",
    string: "eilutė",
    boolean: "loginė reikšmė",
    undefined: "neapibrėžta reikšmė",
    function: "funkcija",
    symbol: "simbolis",
    array: "masyvas",
    object: "objektas",
    null: "nulinė reikšmė"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Gautas tipas ${received}, o tikėtasi - instanceof ${issue2.expected}`;
        }
        return `Gautas tipas ${received}, o tikėtasi - ${expected}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Privalo būti ${stringifyPrimitive(issue2.values[0])}`;
        return `Privalo būti vienas iš ${joinValues(issue2.values, "|")} pasirinkimų`;
      case "too_big": {
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.maximum)), issue2.inclusive ?? false, "smaller");
        if (sizing?.verb)
          return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reikšmė")} ${sizing.verb} ${issue2.maximum.toString()} ${sizing.unit ?? "elementų"}`;
        const adj = issue2.inclusive ? "ne didesnis kaip" : "mažesnis kaip";
        return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reikšmė")} turi būti ${adj} ${issue2.maximum.toString()} ${sizing?.unit}`;
      }
      case "too_small": {
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.minimum)), issue2.inclusive ?? false, "bigger");
        if (sizing?.verb)
          return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reikšmė")} ${sizing.verb} ${issue2.minimum.toString()} ${sizing.unit ?? "elementų"}`;
        const adj = issue2.inclusive ? "ne mažesnis kaip" : "didesnis kaip";
        return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reikšmė")} turi būti ${adj} ${issue2.minimum.toString()} ${sizing?.unit}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Eilutė privalo prasidėti "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Eilutė privalo pasibaigti "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Eilutė privalo įtraukti "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Eilutė privalo atitikti ${_issue.pattern}`;
        return `Neteisingas ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Skaičius privalo būti ${issue2.divisor} kartotinis.`;
      case "unrecognized_keys":
        return `Neatpažint${issue2.keys.length > 1 ? "i" : "as"} rakt${issue2.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return "Rastas klaidingas raktas";
      case "invalid_union":
        return "Klaidinga įvestis";
      case "invalid_element": {
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reikšmė")} turi klaidingą įvestį`;
      }
      default:
        return "Klaidinga įvestis";
    }
  };
};
function lt_default() {
  return {
    localeError: error26()
  };
}
// node_modules/zod/v4/locales/mk.js
var error27 = () => {
  const Sizable = {
    string: { unit: "знаци", verb: "да имаат" },
    file: { unit: "бајти", verb: "да имаат" },
    array: { unit: "ставки", verb: "да имаат" },
    set: { unit: "ставки", verb: "да имаат" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "внес",
    email: "адреса на е-пошта",
    url: "URL",
    emoji: "емоџи",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO датум и време",
    date: "ISO датум",
    time: "ISO време",
    duration: "ISO времетраење",
    ipv4: "IPv4 адреса",
    ipv6: "IPv6 адреса",
    cidrv4: "IPv4 опсег",
    cidrv6: "IPv6 опсег",
    base64: "base64-енкодирана низа",
    base64url: "base64url-енкодирана низа",
    json_string: "JSON низа",
    e164: "E.164 број",
    jwt: "JWT",
    template_literal: "внес"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "број",
    array: "низа"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Грешен внес: се очекува instanceof ${issue2.expected}, примено ${received}`;
        }
        return `Грешен внес: се очекува ${expected}, примено ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
        return `Грешана опција: се очекува една ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Премногу голем: се очекува ${issue2.origin ?? "вредноста"} да има ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "елементи"}`;
        return `Премногу голем: се очекува ${issue2.origin ?? "вредноста"} да биде ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Премногу мал: се очекува ${issue2.origin} да има ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Премногу мал: се очекува ${issue2.origin} да биде ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Неважечка низа: мора да започнува со "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Неважечка низа: мора да завршува со "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Неважечка низа: мора да вклучува "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Неважечка низа: мора да одгоара на патернот ${_issue.pattern}`;
        return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Грешен број: мора да биде делив со ${issue2.divisor}`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "Непрепознаени клучеви" : "Непрепознаен клуч"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Грешен клуч во ${issue2.origin}`;
      case "invalid_union":
        return "Грешен внес";
      case "invalid_element":
        return `Грешна вредност во ${issue2.origin}`;
      default:
        return `Грешен внес`;
    }
  };
};
function mk_default() {
  return {
    localeError: error27()
  };
}
// node_modules/zod/v4/locales/ms.js
var error28 = () => {
  const Sizable = {
    string: { unit: "aksara", verb: "mempunyai" },
    file: { unit: "bait", verb: "mempunyai" },
    array: { unit: "elemen", verb: "mempunyai" },
    set: { unit: "elemen", verb: "mempunyai" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "alamat e-mel",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "tarikh masa ISO",
    date: "tarikh ISO",
    time: "masa ISO",
    duration: "tempoh ISO",
    ipv4: "alamat IPv4",
    ipv6: "alamat IPv6",
    cidrv4: "julat IPv4",
    cidrv6: "julat IPv6",
    base64: "string dikodkan base64",
    base64url: "string dikodkan base64url",
    json_string: "string JSON",
    e164: "nombor E.164",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "nombor"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`;
        }
        return `Input tidak sah: dijangka ${expected}, diterima ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`;
        return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`;
        return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} adalah ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `String tidak sah: mesti mengandungi "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`;
        return `${FormatDictionary[_issue.format] ?? issue2.format} tidak sah`;
      }
      case "not_multiple_of":
        return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Kunci tidak sah dalam ${issue2.origin}`;
      case "invalid_union":
        return "Input tidak sah";
      case "invalid_element":
        return `Nilai tidak sah dalam ${issue2.origin}`;
      default:
        return `Input tidak sah`;
    }
  };
};
function ms_default() {
  return {
    localeError: error28()
  };
}
// node_modules/zod/v4/locales/nl.js
var error29 = () => {
  const Sizable = {
    string: { unit: "tekens", verb: "heeft" },
    file: { unit: "bytes", verb: "heeft" },
    array: { unit: "elementen", verb: "heeft" },
    set: { unit: "elementen", verb: "heeft" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "invoer",
    email: "emailadres",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO datum en tijd",
    date: "ISO datum",
    time: "ISO tijd",
    duration: "ISO duur",
    ipv4: "IPv4-adres",
    ipv6: "IPv6-adres",
    cidrv4: "IPv4-bereik",
    cidrv6: "IPv6-bereik",
    base64: "base64-gecodeerde tekst",
    base64url: "base64 URL-gecodeerde tekst",
    json_string: "JSON string",
    e164: "E.164-nummer",
    jwt: "JWT",
    template_literal: "invoer"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "getal"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`;
        }
        return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`;
        return `Ongeldige optie: verwacht één van ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        const longName = issue2.origin === "date" ? "laat" : issue2.origin === "string" ? "lang" : "groot";
        if (sizing)
          return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementen"} ${sizing.verb}`;
        return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} is`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        const shortName = issue2.origin === "date" ? "vroeg" : issue2.origin === "string" ? "kort" : "klein";
        if (sizing) {
          return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
        }
        return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`;
        }
        if (_issue.format === "ends_with")
          return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`;
        if (_issue.format === "includes")
          return `Ongeldige tekst: moet "${_issue.includes}" bevatten`;
        if (_issue.format === "regex")
          return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;
        return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`;
      case "unrecognized_keys":
        return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Ongeldige key in ${issue2.origin}`;
      case "invalid_union":
        return "Ongeldige invoer";
      case "invalid_element":
        return `Ongeldige waarde in ${issue2.origin}`;
      default:
        return `Ongeldige invoer`;
    }
  };
};
function nl_default() {
  return {
    localeError: error29()
  };
}
// node_modules/zod/v4/locales/no.js
var error30 = () => {
  const Sizable = {
    string: { unit: "tegn", verb: "å ha" },
    file: { unit: "bytes", verb: "å ha" },
    array: { unit: "elementer", verb: "å inneholde" },
    set: { unit: "elementer", verb: "å inneholde" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "e-postadresse",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO dato- og klokkeslett",
    date: "ISO-dato",
    time: "ISO-klokkeslett",
    duration: "ISO-varighet",
    ipv4: "IPv4-område",
    ipv6: "IPv6-område",
    cidrv4: "IPv4-spekter",
    cidrv6: "IPv6-spekter",
    base64: "base64-enkodet streng",
    base64url: "base64url-enkodet streng",
    json_string: "JSON-streng",
    e164: "E.164-nummer",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "tall",
    array: "liste"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`;
        }
        return `Ugyldig input: forventet ${expected}, fikk ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`;
        return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `For stor(t): forventet ${issue2.origin ?? "value"} til å ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`;
        return `For stor(t): forventet ${issue2.origin ?? "value"} til å ha ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `For lite(n): forventet ${issue2.origin} til å ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `For lite(n): forventet ${issue2.origin} til å ha ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Ugyldig streng: må starte med "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Ugyldig streng: må ende med "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Ugyldig streng: må inneholde "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Ugyldig streng: må matche mønsteret ${_issue.pattern}`;
        return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Ugyldig tall: må være et multiplum av ${issue2.divisor}`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "Ukjente nøkler" : "Ukjent nøkkel"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Ugyldig nøkkel i ${issue2.origin}`;
      case "invalid_union":
        return "Ugyldig input";
      case "invalid_element":
        return `Ugyldig verdi i ${issue2.origin}`;
      default:
        return `Ugyldig input`;
    }
  };
};
function no_default() {
  return {
    localeError: error30()
  };
}
// node_modules/zod/v4/locales/ota.js
var error31 = () => {
  const Sizable = {
    string: { unit: "harf", verb: "olmalıdır" },
    file: { unit: "bayt", verb: "olmalıdır" },
    array: { unit: "unsur", verb: "olmalıdır" },
    set: { unit: "unsur", verb: "olmalıdır" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "giren",
    email: "epostagâh",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO hengâmı",
    date: "ISO tarihi",
    time: "ISO zamanı",
    duration: "ISO müddeti",
    ipv4: "IPv4 nişânı",
    ipv6: "IPv6 nişânı",
    cidrv4: "IPv4 menzili",
    cidrv6: "IPv6 menzili",
    base64: "base64-şifreli metin",
    base64url: "base64url-şifreli metin",
    json_string: "JSON metin",
    e164: "E.164 sayısı",
    jwt: "JWT",
    template_literal: "giren"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "numara",
    array: "saf",
    null: "gayb"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Fâsit giren: umulan instanceof ${issue2.expected}, alınan ${received}`;
        }
        return `Fâsit giren: umulan ${expected}, alınan ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Fâsit giren: umulan ${stringifyPrimitive(issue2.values[0])}`;
        return `Fâsit tercih: mûteberler ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Fazla büyük: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmalıydı.`;
        return `Fazla büyük: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} olmalıydı.`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Fazla küçük: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmalıydı.`;
        }
        return `Fazla küçük: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmalıydı.`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Fâsit metin: "${_issue.prefix}" ile başlamalı.`;
        if (_issue.format === "ends_with")
          return `Fâsit metin: "${_issue.suffix}" ile bitmeli.`;
        if (_issue.format === "includes")
          return `Fâsit metin: "${_issue.includes}" ihtivâ etmeli.`;
        if (_issue.format === "regex")
          return `Fâsit metin: ${_issue.pattern} nakşına uymalı.`;
        return `Fâsit ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Fâsit sayı: ${issue2.divisor} katı olmalıydı.`;
      case "unrecognized_keys":
        return `Tanınmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} için tanınmayan anahtar var.`;
      case "invalid_union":
        return "Giren tanınamadı.";
      case "invalid_element":
        return `${issue2.origin} için tanınmayan kıymet var.`;
      default:
        return `Kıymet tanınamadı.`;
    }
  };
};
function ota_default() {
  return {
    localeError: error31()
  };
}
// node_modules/zod/v4/locales/ps.js
var error32 = () => {
  const Sizable = {
    string: { unit: "توکي", verb: "ولري" },
    file: { unit: "بایټس", verb: "ولري" },
    array: { unit: "توکي", verb: "ولري" },
    set: { unit: "توکي", verb: "ولري" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "ورودي",
    email: "بریښنالیک",
    url: "یو آر ال",
    emoji: "ایموجي",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "نیټه او وخت",
    date: "نېټه",
    time: "وخت",
    duration: "موده",
    ipv4: "د IPv4 پته",
    ipv6: "د IPv6 پته",
    cidrv4: "د IPv4 ساحه",
    cidrv6: "د IPv6 ساحه",
    base64: "base64-encoded متن",
    base64url: "base64url-encoded متن",
    json_string: "JSON متن",
    e164: "د E.164 شمېره",
    jwt: "JWT",
    template_literal: "ورودي"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "عدد",
    array: "ارې"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `ناسم ورودي: باید instanceof ${issue2.expected} وای, مګر ${received} ترلاسه شو`;
        }
        return `ناسم ورودي: باید ${expected} وای, مګر ${received} ترلاسه شو`;
      }
      case "invalid_value":
        if (issue2.values.length === 1) {
          return `ناسم ورودي: باید ${stringifyPrimitive(issue2.values[0])} وای`;
        }
        return `ناسم انتخاب: باید یو له ${joinValues(issue2.values, "|")} څخه وای`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `ډیر لوی: ${issue2.origin ?? "ارزښت"} باید ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "عنصرونه"} ولري`;
        }
        return `ډیر لوی: ${issue2.origin ?? "ارزښت"} باید ${adj}${issue2.maximum.toString()} وي`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `ډیر کوچنی: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} ${sizing.unit} ولري`;
        }
        return `ډیر کوچنی: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} وي`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `ناسم متن: باید د "${_issue.prefix}" سره پیل شي`;
        }
        if (_issue.format === "ends_with") {
          return `ناسم متن: باید د "${_issue.suffix}" سره پای ته ورسيږي`;
        }
        if (_issue.format === "includes") {
          return `ناسم متن: باید "${_issue.includes}" ولري`;
        }
        if (_issue.format === "regex") {
          return `ناسم متن: باید د ${_issue.pattern} سره مطابقت ولري`;
        }
        return `${FormatDictionary[_issue.format] ?? issue2.format} ناسم دی`;
      }
      case "not_multiple_of":
        return `ناسم عدد: باید د ${issue2.divisor} مضرب وي`;
      case "unrecognized_keys":
        return `ناسم ${issue2.keys.length > 1 ? "کلیډونه" : "کلیډ"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `ناسم کلیډ په ${issue2.origin} کې`;
      case "invalid_union":
        return `ناسمه ورودي`;
      case "invalid_element":
        return `ناسم عنصر په ${issue2.origin} کې`;
      default:
        return `ناسمه ورودي`;
    }
  };
};
function ps_default() {
  return {
    localeError: error32()
  };
}
// node_modules/zod/v4/locales/pl.js
var error33 = () => {
  const Sizable = {
    string: { unit: "znaków", verb: "mieć" },
    file: { unit: "bajtów", verb: "mieć" },
    array: { unit: "elementów", verb: "mieć" },
    set: { unit: "elementów", verb: "mieć" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "wyrażenie",
    email: "adres email",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "data i godzina w formacie ISO",
    date: "data w formacie ISO",
    time: "godzina w formacie ISO",
    duration: "czas trwania ISO",
    ipv4: "adres IPv4",
    ipv6: "adres IPv6",
    cidrv4: "zakres IPv4",
    cidrv6: "zakres IPv6",
    base64: "ciąg znaków zakodowany w formacie base64",
    base64url: "ciąg znaków zakodowany w formacie base64url",
    json_string: "ciąg znaków w formacie JSON",
    e164: "liczba E.164",
    jwt: "JWT",
    template_literal: "wejście"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "liczba",
    array: "tablica"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Nieprawidłowe dane wejściowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`;
        }
        return `Nieprawidłowe dane wejściowe: oczekiwano ${expected}, otrzymano ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Nieprawidłowe dane wejściowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`;
        return `Nieprawidłowa opcja: oczekiwano jednej z wartości ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Za duża wartość: oczekiwano, że ${issue2.origin ?? "wartość"} będzie mieć ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementów"}`;
        }
        return `Zbyt duż(y/a/e): oczekiwano, że ${issue2.origin ?? "wartość"} będzie wynosić ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Za mała wartość: oczekiwano, że ${issue2.origin ?? "wartość"} będzie mieć ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "elementów"}`;
        }
        return `Zbyt mał(y/a/e): oczekiwano, że ${issue2.origin ?? "wartość"} będzie wynosić ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Nieprawidłowy ciąg znaków: musi zaczynać się od "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Nieprawidłowy ciąg znaków: musi kończyć się na "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Nieprawidłowy ciąg znaków: musi zawierać "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${_issue.pattern}`;
        return `Nieprawidłow(y/a/e) ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Nieprawidłowa liczba: musi być wielokrotnością ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Nieprawidłowy klucz w ${issue2.origin}`;
      case "invalid_union":
        return "Nieprawidłowe dane wejściowe";
      case "invalid_element":
        return `Nieprawidłowa wartość w ${issue2.origin}`;
      default:
        return `Nieprawidłowe dane wejściowe`;
    }
  };
};
function pl_default() {
  return {
    localeError: error33()
  };
}
// node_modules/zod/v4/locales/pt.js
var error34 = () => {
  const Sizable = {
    string: { unit: "caracteres", verb: "ter" },
    file: { unit: "bytes", verb: "ter" },
    array: { unit: "itens", verb: "ter" },
    set: { unit: "itens", verb: "ter" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "padrão",
    email: "endereço de e-mail",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "data e hora ISO",
    date: "data ISO",
    time: "hora ISO",
    duration: "duração ISO",
    ipv4: "endereço IPv4",
    ipv6: "endereço IPv6",
    cidrv4: "faixa de IPv4",
    cidrv6: "faixa de IPv6",
    base64: "texto codificado em base64",
    base64url: "URL codificada em base64",
    json_string: "texto JSON",
    e164: "número E.164",
    jwt: "JWT",
    template_literal: "entrada"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "número",
    null: "nulo"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Tipo inválido: esperado instanceof ${issue2.expected}, recebido ${received}`;
        }
        return `Tipo inválido: esperado ${expected}, recebido ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Entrada inválida: esperado ${stringifyPrimitive(issue2.values[0])}`;
        return `Opção inválida: esperada uma das ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`;
        return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Texto inválido: deve começar com "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Texto inválido: deve terminar com "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Texto inválido: deve incluir "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Texto inválido: deve corresponder ao padrão ${_issue.pattern}`;
        return `${FormatDictionary[_issue.format] ?? issue2.format} inválido`;
      }
      case "not_multiple_of":
        return `Número inválido: deve ser múltiplo de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Chave inválida em ${issue2.origin}`;
      case "invalid_union":
        return "Entrada inválida";
      case "invalid_element":
        return `Valor inválido em ${issue2.origin}`;
      default:
        return `Campo inválido`;
    }
  };
};
function pt_default() {
  return {
    localeError: error34()
  };
}
// node_modules/zod/v4/locales/ru.js
function getRussianPlural(count3, one2, few, many) {
  const absCount = Math.abs(count3);
  const lastDigit = absCount % 10;
  const lastTwoDigits = absCount % 100;
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
    return many;
  }
  if (lastDigit === 1) {
    return one2;
  }
  if (lastDigit >= 2 && lastDigit <= 4) {
    return few;
  }
  return many;
}
var error35 = () => {
  const Sizable = {
    string: {
      unit: {
        one: "символ",
        few: "символа",
        many: "символов"
      },
      verb: "иметь"
    },
    file: {
      unit: {
        one: "байт",
        few: "байта",
        many: "байт"
      },
      verb: "иметь"
    },
    array: {
      unit: {
        one: "элемент",
        few: "элемента",
        many: "элементов"
      },
      verb: "иметь"
    },
    set: {
      unit: {
        one: "элемент",
        few: "элемента",
        many: "элементов"
      },
      verb: "иметь"
    }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "ввод",
    email: "email адрес",
    url: "URL",
    emoji: "эмодзи",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO дата и время",
    date: "ISO дата",
    time: "ISO время",
    duration: "ISO длительность",
    ipv4: "IPv4 адрес",
    ipv6: "IPv6 адрес",
    cidrv4: "IPv4 диапазон",
    cidrv6: "IPv6 диапазон",
    base64: "строка в формате base64",
    base64url: "строка в формате base64url",
    json_string: "JSON строка",
    e164: "номер E.164",
    jwt: "JWT",
    template_literal: "ввод"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "число",
    array: "массив"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Неверный ввод: ожидалось instanceof ${issue2.expected}, получено ${received}`;
        }
        return `Неверный ввод: ожидалось ${expected}, получено ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Неверный ввод: ожидалось ${stringifyPrimitive(issue2.values[0])}`;
        return `Неверный вариант: ожидалось одно из ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const maxValue = Number(issue2.maximum);
          const unit2 = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
          return `Слишком большое значение: ожидалось, что ${issue2.origin ?? "значение"} будет иметь ${adj}${issue2.maximum.toString()} ${unit2}`;
        }
        return `Слишком большое значение: ожидалось, что ${issue2.origin ?? "значение"} будет ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const minValue = Number(issue2.minimum);
          const unit2 = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
          return `Слишком маленькое значение: ожидалось, что ${issue2.origin} будет иметь ${adj}${issue2.minimum.toString()} ${unit2}`;
        }
        return `Слишком маленькое значение: ожидалось, что ${issue2.origin} будет ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Неверная строка: должна начинаться с "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Неверная строка: должна заканчиваться на "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Неверная строка: должна содержать "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Неверная строка: должна соответствовать шаблону ${_issue.pattern}`;
        return `Неверный ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Неверное число: должно быть кратным ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Нераспознанн${issue2.keys.length > 1 ? "ые" : "ый"} ключ${issue2.keys.length > 1 ? "и" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Неверный ключ в ${issue2.origin}`;
      case "invalid_union":
        return "Неверные входные данные";
      case "invalid_element":
        return `Неверное значение в ${issue2.origin}`;
      default:
        return `Неверные входные данные`;
    }
  };
};
function ru_default() {
  return {
    localeError: error35()
  };
}
// node_modules/zod/v4/locales/sl.js
var error36 = () => {
  const Sizable = {
    string: { unit: "znakov", verb: "imeti" },
    file: { unit: "bajtov", verb: "imeti" },
    array: { unit: "elementov", verb: "imeti" },
    set: { unit: "elementov", verb: "imeti" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "vnos",
    email: "e-poštni naslov",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO datum in čas",
    date: "ISO datum",
    time: "ISO čas",
    duration: "ISO trajanje",
    ipv4: "IPv4 naslov",
    ipv6: "IPv6 naslov",
    cidrv4: "obseg IPv4",
    cidrv6: "obseg IPv6",
    base64: "base64 kodiran niz",
    base64url: "base64url kodiran niz",
    json_string: "JSON niz",
    e164: "E.164 številka",
    jwt: "JWT",
    template_literal: "vnos"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "število",
    array: "tabela"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Neveljaven vnos: pričakovano instanceof ${issue2.expected}, prejeto ${received}`;
        }
        return `Neveljaven vnos: pričakovano ${expected}, prejeto ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Neveljaven vnos: pričakovano ${stringifyPrimitive(issue2.values[0])}`;
        return `Neveljavna možnost: pričakovano eno izmed ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Preveliko: pričakovano, da bo ${issue2.origin ?? "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementov"}`;
        return `Preveliko: pričakovano, da bo ${issue2.origin ?? "vrednost"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Premajhno: pričakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Premajhno: pričakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Neveljaven niz: mora se začeti z "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Neveljaven niz: mora se končati z "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Neveljaven niz: mora vsebovati "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`;
        return `Neveljaven ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Neveljavno število: mora biti večkratnik ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Neprepoznan${issue2.keys.length > 1 ? "i ključi" : " ključ"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Neveljaven ključ v ${issue2.origin}`;
      case "invalid_union":
        return "Neveljaven vnos";
      case "invalid_element":
        return `Neveljavna vrednost v ${issue2.origin}`;
      default:
        return "Neveljaven vnos";
    }
  };
};
function sl_default() {
  return {
    localeError: error36()
  };
}
// node_modules/zod/v4/locales/sv.js
var error37 = () => {
  const Sizable = {
    string: { unit: "tecken", verb: "att ha" },
    file: { unit: "bytes", verb: "att ha" },
    array: { unit: "objekt", verb: "att innehålla" },
    set: { unit: "objekt", verb: "att innehålla" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "reguljärt uttryck",
    email: "e-postadress",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO-datum och tid",
    date: "ISO-datum",
    time: "ISO-tid",
    duration: "ISO-varaktighet",
    ipv4: "IPv4-intervall",
    ipv6: "IPv6-intervall",
    cidrv4: "IPv4-spektrum",
    cidrv6: "IPv6-spektrum",
    base64: "base64-kodad sträng",
    base64url: "base64url-kodad sträng",
    json_string: "JSON-sträng",
    e164: "E.164-nummer",
    jwt: "JWT",
    template_literal: "mall-literal"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "antal",
    array: "lista"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ogiltig inmatning: förväntat instanceof ${issue2.expected}, fick ${received}`;
        }
        return `Ogiltig inmatning: förväntat ${expected}, fick ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ogiltig inmatning: förväntat ${stringifyPrimitive(issue2.values[0])}`;
        return `Ogiltigt val: förväntade en av ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `För stor(t): förväntade ${issue2.origin ?? "värdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`;
        }
        return `För stor(t): förväntat ${issue2.origin ?? "värdet"} att ha ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `För lite(t): förväntade ${issue2.origin ?? "värdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `För lite(t): förväntade ${issue2.origin ?? "värdet"} att ha ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Ogiltig sträng: måste börja med "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Ogiltig sträng: måste sluta med "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Ogiltig sträng: måste innehålla "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Ogiltig sträng: måste matcha mönstret "${_issue.pattern}"`;
        return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Ogiltigt tal: måste vara en multipel av ${issue2.divisor}`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "Okända nycklar" : "Okänd nyckel"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Ogiltig nyckel i ${issue2.origin ?? "värdet"}`;
      case "invalid_union":
        return "Ogiltig input";
      case "invalid_element":
        return `Ogiltigt värde i ${issue2.origin ?? "värdet"}`;
      default:
        return `Ogiltig input`;
    }
  };
};
function sv_default() {
  return {
    localeError: error37()
  };
}
// node_modules/zod/v4/locales/ta.js
var error38 = () => {
  const Sizable = {
    string: { unit: "எழுத்துக்கள்", verb: "கொண்டிருக்க வேண்டும்" },
    file: { unit: "பைட்டுகள்", verb: "கொண்டிருக்க வேண்டும்" },
    array: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" },
    set: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "உள்ளீடு",
    email: "மின்னஞ்சல் முகவரி",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO தேதி நேரம்",
    date: "ISO தேதி",
    time: "ISO நேரம்",
    duration: "ISO கால அளவு",
    ipv4: "IPv4 முகவரி",
    ipv6: "IPv6 முகவரி",
    cidrv4: "IPv4 வரம்பு",
    cidrv6: "IPv6 வரம்பு",
    base64: "base64-encoded சரம்",
    base64url: "base64url-encoded சரம்",
    json_string: "JSON சரம்",
    e164: "E.164 எண்",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "எண்",
    array: "அணி",
    null: "வெறுமை"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${issue2.expected}, பெறப்பட்டது ${received}`;
        }
        return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${expected}, பெறப்பட்டது ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${stringifyPrimitive(issue2.values[0])}`;
        return `தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${joinValues(issue2.values, "|")} இல் ஒன்று`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue2.origin ?? "மதிப்பு"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "உறுப்புகள்"} ஆக இருக்க வேண்டும்`;
        }
        return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue2.origin ?? "மதிப்பு"} ${adj}${issue2.maximum.toString()} ஆக இருக்க வேண்டும்`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ஆக இருக்க வேண்டும்`;
        }
        return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue2.origin} ${adj}${issue2.minimum.toString()} ஆக இருக்க வேண்டும்`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `தவறான சரம்: "${_issue.prefix}" இல் தொடங்க வேண்டும்`;
        if (_issue.format === "ends_with")
          return `தவறான சரம்: "${_issue.suffix}" இல் முடிவடைய வேண்டும்`;
        if (_issue.format === "includes")
          return `தவறான சரம்: "${_issue.includes}" ஐ உள்ளடக்க வேண்டும்`;
        if (_issue.format === "regex")
          return `தவறான சரம்: ${_issue.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;
        return `தவறான ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `தவறான எண்: ${issue2.divisor} இன் பலமாக இருக்க வேண்டும்`;
      case "unrecognized_keys":
        return `அடையாளம் தெரியாத விசை${issue2.keys.length > 1 ? "கள்" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} இல் தவறான விசை`;
      case "invalid_union":
        return "தவறான உள்ளீடு";
      case "invalid_element":
        return `${issue2.origin} இல் தவறான மதிப்பு`;
      default:
        return `தவறான உள்ளீடு`;
    }
  };
};
function ta_default() {
  return {
    localeError: error38()
  };
}
// node_modules/zod/v4/locales/th.js
var error39 = () => {
  const Sizable = {
    string: { unit: "ตัวอักษร", verb: "ควรมี" },
    file: { unit: "ไบต์", verb: "ควรมี" },
    array: { unit: "รายการ", verb: "ควรมี" },
    set: { unit: "รายการ", verb: "ควรมี" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "ข้อมูลที่ป้อน",
    email: "ที่อยู่อีเมล",
    url: "URL",
    emoji: "อิโมจิ",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "วันที่เวลาแบบ ISO",
    date: "วันที่แบบ ISO",
    time: "เวลาแบบ ISO",
    duration: "ช่วงเวลาแบบ ISO",
    ipv4: "ที่อยู่ IPv4",
    ipv6: "ที่อยู่ IPv6",
    cidrv4: "ช่วง IP แบบ IPv4",
    cidrv6: "ช่วง IP แบบ IPv6",
    base64: "ข้อความแบบ Base64",
    base64url: "ข้อความแบบ Base64 สำหรับ URL",
    json_string: "ข้อความแบบ JSON",
    e164: "เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",
    jwt: "โทเคน JWT",
    template_literal: "ข้อมูลที่ป้อน"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "ตัวเลข",
    array: "อาร์เรย์ (Array)",
    null: "ไม่มีค่า (null)"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${issue2.expected} แต่ได้รับ ${received}`;
        }
        return `ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${expected} แต่ได้รับ ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `ค่าไม่ถูกต้อง: ควรเป็น ${stringifyPrimitive(issue2.values[0])}`;
        return `ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "ไม่เกิน" : "น้อยกว่า";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `เกินกำหนด: ${issue2.origin ?? "ค่า"} ควรมี${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "รายการ"}`;
        return `เกินกำหนด: ${issue2.origin ?? "ค่า"} ควรมี${adj} ${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? "อย่างน้อย" : "มากกว่า";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `น้อยกว่ากำหนด: ${issue2.origin} ควรมี${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `น้อยกว่ากำหนด: ${issue2.origin} ควรมี${adj} ${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${_issue.includes}" อยู่ในข้อความ`;
        if (_issue.format === "regex")
          return `รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${_issue.pattern}`;
        return `รูปแบบไม่ถูกต้อง: ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${issue2.divisor} ได้ลงตัว`;
      case "unrecognized_keys":
        return `พบคีย์ที่ไม่รู้จัก: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `คีย์ไม่ถูกต้องใน ${issue2.origin}`;
      case "invalid_union":
        return "ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";
      case "invalid_element":
        return `ข้อมูลไม่ถูกต้องใน ${issue2.origin}`;
      default:
        return `ข้อมูลไม่ถูกต้อง`;
    }
  };
};
function th_default() {
  return {
    localeError: error39()
  };
}
// node_modules/zod/v4/locales/tr.js
var error40 = () => {
  const Sizable = {
    string: { unit: "karakter", verb: "olmalı" },
    file: { unit: "bayt", verb: "olmalı" },
    array: { unit: "öğe", verb: "olmalı" },
    set: { unit: "öğe", verb: "olmalı" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "girdi",
    email: "e-posta adresi",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO tarih ve saat",
    date: "ISO tarih",
    time: "ISO saat",
    duration: "ISO süre",
    ipv4: "IPv4 adresi",
    ipv6: "IPv6 adresi",
    cidrv4: "IPv4 aralığı",
    cidrv6: "IPv6 aralığı",
    base64: "base64 ile şifrelenmiş metin",
    base64url: "base64url ile şifrelenmiş metin",
    json_string: "JSON dizesi",
    e164: "E.164 sayısı",
    jwt: "JWT",
    template_literal: "Şablon dizesi"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Geçersiz değer: beklenen instanceof ${issue2.expected}, alınan ${received}`;
        }
        return `Geçersiz değer: beklenen ${expected}, alınan ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Geçersiz değer: beklenen ${stringifyPrimitive(issue2.values[0])}`;
        return `Geçersiz seçenek: aşağıdakilerden biri olmalı: ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Çok büyük: beklenen ${issue2.origin ?? "değer"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "öğe"}`;
        return `Çok büyük: beklenen ${issue2.origin ?? "değer"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Çok küçük: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        return `Çok küçük: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Geçersiz metin: "${_issue.prefix}" ile başlamalı`;
        if (_issue.format === "ends_with")
          return `Geçersiz metin: "${_issue.suffix}" ile bitmeli`;
        if (_issue.format === "includes")
          return `Geçersiz metin: "${_issue.includes}" içermeli`;
        if (_issue.format === "regex")
          return `Geçersiz metin: ${_issue.pattern} desenine uymalı`;
        return `Geçersiz ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Geçersiz sayı: ${issue2.divisor} ile tam bölünebilmeli`;
      case "unrecognized_keys":
        return `Tanınmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} içinde geçersiz anahtar`;
      case "invalid_union":
        return "Geçersiz değer";
      case "invalid_element":
        return `${issue2.origin} içinde geçersiz değer`;
      default:
        return `Geçersiz değer`;
    }
  };
};
function tr_default() {
  return {
    localeError: error40()
  };
}
// node_modules/zod/v4/locales/uk.js
var error41 = () => {
  const Sizable = {
    string: { unit: "символів", verb: "матиме" },
    file: { unit: "байтів", verb: "матиме" },
    array: { unit: "елементів", verb: "матиме" },
    set: { unit: "елементів", verb: "матиме" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "вхідні дані",
    email: "адреса електронної пошти",
    url: "URL",
    emoji: "емодзі",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "дата та час ISO",
    date: "дата ISO",
    time: "час ISO",
    duration: "тривалість ISO",
    ipv4: "адреса IPv4",
    ipv6: "адреса IPv6",
    cidrv4: "діапазон IPv4",
    cidrv6: "діапазон IPv6",
    base64: "рядок у кодуванні base64",
    base64url: "рядок у кодуванні base64url",
    json_string: "рядок JSON",
    e164: "номер E.164",
    jwt: "JWT",
    template_literal: "вхідні дані"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "число",
    array: "масив"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Неправильні вхідні дані: очікується instanceof ${issue2.expected}, отримано ${received}`;
        }
        return `Неправильні вхідні дані: очікується ${expected}, отримано ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Неправильні вхідні дані: очікується ${stringifyPrimitive(issue2.values[0])}`;
        return `Неправильна опція: очікується одне з ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Занадто велике: очікується, що ${issue2.origin ?? "значення"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "елементів"}`;
        return `Занадто велике: очікується, що ${issue2.origin ?? "значення"} буде ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Занадто мале: очікується, що ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Занадто мале: очікується, що ${issue2.origin} буде ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Неправильний рядок: повинен починатися з "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Неправильний рядок: повинен закінчуватися на "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Неправильний рядок: повинен містити "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Неправильний рядок: повинен відповідати шаблону ${_issue.pattern}`;
        return `Неправильний ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Неправильне число: повинно бути кратним ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Нерозпізнаний ключ${issue2.keys.length > 1 ? "і" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Неправильний ключ у ${issue2.origin}`;
      case "invalid_union":
        return "Неправильні вхідні дані";
      case "invalid_element":
        return `Неправильне значення у ${issue2.origin}`;
      default:
        return `Неправильні вхідні дані`;
    }
  };
};
function uk_default() {
  return {
    localeError: error41()
  };
}

// node_modules/zod/v4/locales/ua.js
function ua_default() {
  return uk_default();
}
// node_modules/zod/v4/locales/ur.js
var error42 = () => {
  const Sizable = {
    string: { unit: "حروف", verb: "ہونا" },
    file: { unit: "بائٹس", verb: "ہونا" },
    array: { unit: "آئٹمز", verb: "ہونا" },
    set: { unit: "آئٹمز", verb: "ہونا" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "ان پٹ",
    email: "ای میل ایڈریس",
    url: "یو آر ایل",
    emoji: "ایموجی",
    uuid: "یو یو آئی ڈی",
    uuidv4: "یو یو آئی ڈی وی 4",
    uuidv6: "یو یو آئی ڈی وی 6",
    nanoid: "نینو آئی ڈی",
    guid: "جی یو آئی ڈی",
    cuid: "سی یو آئی ڈی",
    cuid2: "سی یو آئی ڈی 2",
    ulid: "یو ایل آئی ڈی",
    xid: "ایکس آئی ڈی",
    ksuid: "کے ایس یو آئی ڈی",
    datetime: "آئی ایس او ڈیٹ ٹائم",
    date: "آئی ایس او تاریخ",
    time: "آئی ایس او وقت",
    duration: "آئی ایس او مدت",
    ipv4: "آئی پی وی 4 ایڈریس",
    ipv6: "آئی پی وی 6 ایڈریس",
    cidrv4: "آئی پی وی 4 رینج",
    cidrv6: "آئی پی وی 6 رینج",
    base64: "بیس 64 ان کوڈڈ سٹرنگ",
    base64url: "بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",
    json_string: "جے ایس او این سٹرنگ",
    e164: "ای 164 نمبر",
    jwt: "جے ڈبلیو ٹی",
    template_literal: "ان پٹ"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "نمبر",
    array: "آرے",
    null: "نل"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `غلط ان پٹ: instanceof ${issue2.expected} متوقع تھا، ${received} موصول ہوا`;
        }
        return `غلط ان پٹ: ${expected} متوقع تھا، ${received} موصول ہوا`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `غلط ان پٹ: ${stringifyPrimitive(issue2.values[0])} متوقع تھا`;
        return `غلط آپشن: ${joinValues(issue2.values, "|")} میں سے ایک متوقع تھا`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `بہت بڑا: ${issue2.origin ?? "ویلیو"} کے ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "عناصر"} ہونے متوقع تھے`;
        return `بہت بڑا: ${issue2.origin ?? "ویلیو"} کا ${adj}${issue2.maximum.toString()} ہونا متوقع تھا`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `بہت چھوٹا: ${issue2.origin} کے ${adj}${issue2.minimum.toString()} ${sizing.unit} ہونے متوقع تھے`;
        }
        return `بہت چھوٹا: ${issue2.origin} کا ${adj}${issue2.minimum.toString()} ہونا متوقع تھا`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `غلط سٹرنگ: "${_issue.prefix}" سے شروع ہونا چاہیے`;
        }
        if (_issue.format === "ends_with")
          return `غلط سٹرنگ: "${_issue.suffix}" پر ختم ہونا چاہیے`;
        if (_issue.format === "includes")
          return `غلط سٹرنگ: "${_issue.includes}" شامل ہونا چاہیے`;
        if (_issue.format === "regex")
          return `غلط سٹرنگ: پیٹرن ${_issue.pattern} سے میچ ہونا چاہیے`;
        return `غلط ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `غلط نمبر: ${issue2.divisor} کا مضاعف ہونا چاہیے`;
      case "unrecognized_keys":
        return `غیر تسلیم شدہ کی${issue2.keys.length > 1 ? "ز" : ""}: ${joinValues(issue2.keys, "، ")}`;
      case "invalid_key":
        return `${issue2.origin} میں غلط کی`;
      case "invalid_union":
        return "غلط ان پٹ";
      case "invalid_element":
        return `${issue2.origin} میں غلط ویلیو`;
      default:
        return `غلط ان پٹ`;
    }
  };
};
function ur_default() {
  return {
    localeError: error42()
  };
}
// node_modules/zod/v4/locales/uz.js
var error43 = () => {
  const Sizable = {
    string: { unit: "belgi", verb: "bo‘lishi kerak" },
    file: { unit: "bayt", verb: "bo‘lishi kerak" },
    array: { unit: "element", verb: "bo‘lishi kerak" },
    set: { unit: "element", verb: "bo‘lishi kerak" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "kirish",
    email: "elektron pochta manzili",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO sana va vaqti",
    date: "ISO sana",
    time: "ISO vaqt",
    duration: "ISO davomiylik",
    ipv4: "IPv4 manzil",
    ipv6: "IPv6 manzil",
    mac: "MAC manzil",
    cidrv4: "IPv4 diapazon",
    cidrv6: "IPv6 diapazon",
    base64: "base64 kodlangan satr",
    base64url: "base64url kodlangan satr",
    json_string: "JSON satr",
    e164: "E.164 raqam",
    jwt: "JWT",
    template_literal: "kirish"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "raqam",
    array: "massiv"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Noto‘g‘ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`;
        }
        return `Noto‘g‘ri kirish: kutilgan ${expected}, qabul qilingan ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Noto‘g‘ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`;
        return `Noto‘g‘ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`;
        return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
        }
        return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Noto‘g‘ri satr: "${_issue.prefix}" bilan boshlanishi kerak`;
        if (_issue.format === "ends_with")
          return `Noto‘g‘ri satr: "${_issue.suffix}" bilan tugashi kerak`;
        if (_issue.format === "includes")
          return `Noto‘g‘ri satr: "${_issue.includes}" ni o‘z ichiga olishi kerak`;
        if (_issue.format === "regex")
          return `Noto‘g‘ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`;
        return `Noto‘g‘ri ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Noto‘g‘ri raqam: ${issue2.divisor} ning karralisi bo‘lishi kerak`;
      case "unrecognized_keys":
        return `Noma’lum kalit${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} dagi kalit noto‘g‘ri`;
      case "invalid_union":
        return "Noto‘g‘ri kirish";
      case "invalid_element":
        return `${issue2.origin} da noto‘g‘ri qiymat`;
      default:
        return `Noto‘g‘ri kirish`;
    }
  };
};
function uz_default() {
  return {
    localeError: error43()
  };
}
// node_modules/zod/v4/locales/vi.js
var error44 = () => {
  const Sizable = {
    string: { unit: "ký tự", verb: "có" },
    file: { unit: "byte", verb: "có" },
    array: { unit: "phần tử", verb: "có" },
    set: { unit: "phần tử", verb: "có" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "đầu vào",
    email: "địa chỉ email",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ngày giờ ISO",
    date: "ngày ISO",
    time: "giờ ISO",
    duration: "khoảng thời gian ISO",
    ipv4: "địa chỉ IPv4",
    ipv6: "địa chỉ IPv6",
    cidrv4: "dải IPv4",
    cidrv6: "dải IPv6",
    base64: "chuỗi mã hóa base64",
    base64url: "chuỗi mã hóa base64url",
    json_string: "chuỗi JSON",
    e164: "số E.164",
    jwt: "JWT",
    template_literal: "đầu vào"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "số",
    array: "mảng"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Đầu vào không hợp lệ: mong đợi instanceof ${issue2.expected}, nhận được ${received}`;
        }
        return `Đầu vào không hợp lệ: mong đợi ${expected}, nhận được ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Đầu vào không hợp lệ: mong đợi ${stringifyPrimitive(issue2.values[0])}`;
        return `Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Quá lớn: mong đợi ${issue2.origin ?? "giá trị"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "phần tử"}`;
        return `Quá lớn: mong đợi ${issue2.origin ?? "giá trị"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Quá nhỏ: mong đợi ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Quá nhỏ: mong đợi ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Chuỗi không hợp lệ: phải bắt đầu bằng "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Chuỗi không hợp lệ: phải kết thúc bằng "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Chuỗi không hợp lệ: phải bao gồm "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Chuỗi không hợp lệ: phải khớp với mẫu ${_issue.pattern}`;
        return `${FormatDictionary[_issue.format] ?? issue2.format} không hợp lệ`;
      }
      case "not_multiple_of":
        return `Số không hợp lệ: phải là bội số của ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Khóa không được nhận dạng: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Khóa không hợp lệ trong ${issue2.origin}`;
      case "invalid_union":
        return "Đầu vào không hợp lệ";
      case "invalid_element":
        return `Giá trị không hợp lệ trong ${issue2.origin}`;
      default:
        return `Đầu vào không hợp lệ`;
    }
  };
};
function vi_default() {
  return {
    localeError: error44()
  };
}
// node_modules/zod/v4/locales/zh-CN.js
var error45 = () => {
  const Sizable = {
    string: { unit: "字符", verb: "包含" },
    file: { unit: "字节", verb: "包含" },
    array: { unit: "项", verb: "包含" },
    set: { unit: "项", verb: "包含" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "输入",
    email: "电子邮件",
    url: "URL",
    emoji: "表情符号",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO日期时间",
    date: "ISO日期",
    time: "ISO时间",
    duration: "ISO时长",
    ipv4: "IPv4地址",
    ipv6: "IPv6地址",
    cidrv4: "IPv4网段",
    cidrv6: "IPv6网段",
    base64: "base64编码字符串",
    base64url: "base64url编码字符串",
    json_string: "JSON字符串",
    e164: "E.164号码",
    jwt: "JWT",
    template_literal: "输入"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "数字",
    array: "数组",
    null: "空值(null)"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `无效输入：期望 instanceof ${issue2.expected}，实际接收 ${received}`;
        }
        return `无效输入：期望 ${expected}，实际接收 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `无效输入：期望 ${stringifyPrimitive(issue2.values[0])}`;
        return `无效选项：期望以下之一 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `数值过大：期望 ${issue2.origin ?? "值"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "个元素"}`;
        return `数值过大：期望 ${issue2.origin ?? "值"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `数值过小：期望 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `数值过小：期望 ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `无效字符串：必须以 "${_issue.prefix}" 开头`;
        if (_issue.format === "ends_with")
          return `无效字符串：必须以 "${_issue.suffix}" 结尾`;
        if (_issue.format === "includes")
          return `无效字符串：必须包含 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `无效字符串：必须满足正则表达式 ${_issue.pattern}`;
        return `无效${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `无效数字：必须是 ${issue2.divisor} 的倍数`;
      case "unrecognized_keys":
        return `出现未知的键(key): ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} 中的键(key)无效`;
      case "invalid_union":
        return "无效输入";
      case "invalid_element":
        return `${issue2.origin} 中包含无效值(value)`;
      default:
        return `无效输入`;
    }
  };
};
function zh_CN_default() {
  return {
    localeError: error45()
  };
}
// node_modules/zod/v4/locales/zh-TW.js
var error46 = () => {
  const Sizable = {
    string: { unit: "字元", verb: "擁有" },
    file: { unit: "位元組", verb: "擁有" },
    array: { unit: "項目", verb: "擁有" },
    set: { unit: "項目", verb: "擁有" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "輸入",
    email: "郵件地址",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO 日期時間",
    date: "ISO 日期",
    time: "ISO 時間",
    duration: "ISO 期間",
    ipv4: "IPv4 位址",
    ipv6: "IPv6 位址",
    cidrv4: "IPv4 範圍",
    cidrv6: "IPv6 範圍",
    base64: "base64 編碼字串",
    base64url: "base64url 編碼字串",
    json_string: "JSON 字串",
    e164: "E.164 數值",
    jwt: "JWT",
    template_literal: "輸入"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `無效的輸入值：預期為 instanceof ${issue2.expected}，但收到 ${received}`;
        }
        return `無效的輸入值：預期為 ${expected}，但收到 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `無效的輸入值：預期為 ${stringifyPrimitive(issue2.values[0])}`;
        return `無效的選項：預期為以下其中之一 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `數值過大：預期 ${issue2.origin ?? "值"} 應為 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "個元素"}`;
        return `數值過大：預期 ${issue2.origin ?? "值"} 應為 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `數值過小：預期 ${issue2.origin} 應為 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `數值過小：預期 ${issue2.origin} 應為 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `無效的字串：必須以 "${_issue.prefix}" 開頭`;
        }
        if (_issue.format === "ends_with")
          return `無效的字串：必須以 "${_issue.suffix}" 結尾`;
        if (_issue.format === "includes")
          return `無效的字串：必須包含 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `無效的字串：必須符合格式 ${_issue.pattern}`;
        return `無效的 ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `無效的數字：必須為 ${issue2.divisor} 的倍數`;
      case "unrecognized_keys":
        return `無法識別的鍵值${issue2.keys.length > 1 ? "們" : ""}：${joinValues(issue2.keys, "、")}`;
      case "invalid_key":
        return `${issue2.origin} 中有無效的鍵值`;
      case "invalid_union":
        return "無效的輸入值";
      case "invalid_element":
        return `${issue2.origin} 中有無效的值`;
      default:
        return `無效的輸入值`;
    }
  };
};
function zh_TW_default() {
  return {
    localeError: error46()
  };
}
// node_modules/zod/v4/locales/yo.js
var error47 = () => {
  const Sizable = {
    string: { unit: "àmi", verb: "ní" },
    file: { unit: "bytes", verb: "ní" },
    array: { unit: "nkan", verb: "ní" },
    set: { unit: "nkan", verb: "ní" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "ẹ̀rọ ìbáwọlé",
    email: "àdírẹ́sì ìmẹ́lì",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "àkókò ISO",
    date: "ọjọ́ ISO",
    time: "àkókò ISO",
    duration: "àkókò tó pé ISO",
    ipv4: "àdírẹ́sì IPv4",
    ipv6: "àdírẹ́sì IPv6",
    cidrv4: "àgbègbè IPv4",
    cidrv6: "àgbègbè IPv6",
    base64: "ọ̀rọ̀ tí a kọ́ ní base64",
    base64url: "ọ̀rọ̀ base64url",
    json_string: "ọ̀rọ̀ JSON",
    e164: "nọ́mbà E.164",
    jwt: "JWT",
    template_literal: "ẹ̀rọ ìbáwọlé"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "nọ́mbà",
    array: "akopọ"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${issue2.expected}, àmọ̀ a rí ${received}`;
        }
        return `Ìbáwọlé aṣìṣe: a ní láti fi ${expected}, àmọ̀ a rí ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ìbáwọlé aṣìṣe: a ní láti fi ${stringifyPrimitive(issue2.values[0])}`;
        return `Àṣàyàn aṣìṣe: yan ọ̀kan lára ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Tó pọ̀ jù: a ní láti jẹ́ pé ${issue2.origin ?? "iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`;
        return `Tó pọ̀ jù: a ní láti jẹ́ ${adj}${issue2.maximum}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Kéré ju: a ní láti jẹ́ pé ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`;
        return `Kéré ju: a ní láti jẹ́ ${adj}${issue2.minimum}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${_issue.pattern}`;
        return `Aṣìṣe: ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Bọtìnì àìmọ̀: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Bọtìnì aṣìṣe nínú ${issue2.origin}`;
      case "invalid_union":
        return "Ìbáwọlé aṣìṣe";
      case "invalid_element":
        return `Iye aṣìṣe nínú ${issue2.origin}`;
      default:
        return "Ìbáwọlé aṣìṣe";
    }
  };
};
function yo_default() {
  return {
    localeError: error47()
  };
}
// node_modules/zod/v4/core/registries.js
var _a;
var $output = Symbol("ZodOutput");
var $input = Symbol("ZodInput");

class $ZodRegistry {
  constructor() {
    this._map = new WeakMap;
    this._idmap = new Map;
  }
  add(schema, ..._meta) {
    const meta = _meta[0];
    this._map.set(schema, meta);
    if (meta && typeof meta === "object" && "id" in meta) {
      this._idmap.set(meta.id, schema);
    }
    return this;
  }
  clear() {
    this._map = new WeakMap;
    this._idmap = new Map;
    return this;
  }
  remove(schema) {
    const meta = this._map.get(schema);
    if (meta && typeof meta === "object" && "id" in meta) {
      this._idmap.delete(meta.id);
    }
    this._map.delete(schema);
    return this;
  }
  get(schema) {
    const p = schema._zod.parent;
    if (p) {
      const pm = { ...this.get(p) ?? {} };
      delete pm.id;
      const f = { ...pm, ...this._map.get(schema) };
      return Object.keys(f).length ? f : undefined;
    }
    return this._map.get(schema);
  }
  has(schema) {
    return this._map.has(schema);
  }
}
function registry2() {
  return new $ZodRegistry;
}
(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry2());
var globalRegistry = globalThis.__zod_globalRegistry;
// node_modules/zod/v4/core/api.js
function _string(Class2, params2) {
  return new Class2({
    type: "string",
    ...normalizeParams(params2)
  });
}
function _coercedString(Class2, params2) {
  return new Class2({
    type: "string",
    coerce: true,
    ...normalizeParams(params2)
  });
}
function _email(Class2, params2) {
  return new Class2({
    type: "string",
    format: "email",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _guid(Class2, params2) {
  return new Class2({
    type: "string",
    format: "guid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _uuid(Class2, params2) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _uuidv4(Class2, params2) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v4",
    ...normalizeParams(params2)
  });
}
function _uuidv6(Class2, params2) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v6",
    ...normalizeParams(params2)
  });
}
function _uuidv7(Class2, params2) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v7",
    ...normalizeParams(params2)
  });
}
function _url(Class2, params2) {
  return new Class2({
    type: "string",
    format: "url",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _emoji2(Class2, params2) {
  return new Class2({
    type: "string",
    format: "emoji",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _nanoid(Class2, params2) {
  return new Class2({
    type: "string",
    format: "nanoid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _cuid(Class2, params2) {
  return new Class2({
    type: "string",
    format: "cuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _cuid2(Class2, params2) {
  return new Class2({
    type: "string",
    format: "cuid2",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _ulid(Class2, params2) {
  return new Class2({
    type: "string",
    format: "ulid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _xid(Class2, params2) {
  return new Class2({
    type: "string",
    format: "xid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _ksuid(Class2, params2) {
  return new Class2({
    type: "string",
    format: "ksuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _ipv4(Class2, params2) {
  return new Class2({
    type: "string",
    format: "ipv4",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _ipv6(Class2, params2) {
  return new Class2({
    type: "string",
    format: "ipv6",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _mac(Class2, params2) {
  return new Class2({
    type: "string",
    format: "mac",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _cidrv4(Class2, params2) {
  return new Class2({
    type: "string",
    format: "cidrv4",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _cidrv6(Class2, params2) {
  return new Class2({
    type: "string",
    format: "cidrv6",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _base64(Class2, params2) {
  return new Class2({
    type: "string",
    format: "base64",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _base64url(Class2, params2) {
  return new Class2({
    type: "string",
    format: "base64url",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _e164(Class2, params2) {
  return new Class2({
    type: "string",
    format: "e164",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
function _jwt(Class2, params2) {
  return new Class2({
    type: "string",
    format: "jwt",
    check: "string_format",
    abort: false,
    ...normalizeParams(params2)
  });
}
var TimePrecision = {
  Any: null,
  Minute: -1,
  Second: 0,
  Millisecond: 3,
  Microsecond: 6
};
function _isoDateTime(Class2, params2) {
  return new Class2({
    type: "string",
    format: "datetime",
    check: "string_format",
    offset: false,
    local: false,
    precision: null,
    ...normalizeParams(params2)
  });
}
function _isoDate(Class2, params2) {
  return new Class2({
    type: "string",
    format: "date",
    check: "string_format",
    ...normalizeParams(params2)
  });
}
function _isoTime(Class2, params2) {
  return new Class2({
    type: "string",
    format: "time",
    check: "string_format",
    precision: null,
    ...normalizeParams(params2)
  });
}
function _isoDuration(Class2, params2) {
  return new Class2({
    type: "string",
    format: "duration",
    check: "string_format",
    ...normalizeParams(params2)
  });
}
function _number(Class2, params2) {
  return new Class2({
    type: "number",
    checks: [],
    ...normalizeParams(params2)
  });
}
function _coercedNumber(Class2, params2) {
  return new Class2({
    type: "number",
    coerce: true,
    checks: [],
    ...normalizeParams(params2)
  });
}
function _int(Class2, params2) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "safeint",
    ...normalizeParams(params2)
  });
}
function _float32(Class2, params2) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "float32",
    ...normalizeParams(params2)
  });
}
function _float64(Class2, params2) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "float64",
    ...normalizeParams(params2)
  });
}
function _int32(Class2, params2) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "int32",
    ...normalizeParams(params2)
  });
}
function _uint32(Class2, params2) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "uint32",
    ...normalizeParams(params2)
  });
}
function _boolean(Class2, params2) {
  return new Class2({
    type: "boolean",
    ...normalizeParams(params2)
  });
}
function _coercedBoolean(Class2, params2) {
  return new Class2({
    type: "boolean",
    coerce: true,
    ...normalizeParams(params2)
  });
}
function _bigint(Class2, params2) {
  return new Class2({
    type: "bigint",
    ...normalizeParams(params2)
  });
}
function _coercedBigint(Class2, params2) {
  return new Class2({
    type: "bigint",
    coerce: true,
    ...normalizeParams(params2)
  });
}
function _int64(Class2, params2) {
  return new Class2({
    type: "bigint",
    check: "bigint_format",
    abort: false,
    format: "int64",
    ...normalizeParams(params2)
  });
}
function _uint64(Class2, params2) {
  return new Class2({
    type: "bigint",
    check: "bigint_format",
    abort: false,
    format: "uint64",
    ...normalizeParams(params2)
  });
}
function _symbol(Class2, params2) {
  return new Class2({
    type: "symbol",
    ...normalizeParams(params2)
  });
}
function _undefined2(Class2, params2) {
  return new Class2({
    type: "undefined",
    ...normalizeParams(params2)
  });
}
function _null2(Class2, params2) {
  return new Class2({
    type: "null",
    ...normalizeParams(params2)
  });
}
function _any(Class2) {
  return new Class2({
    type: "any"
  });
}
function _unknown(Class2) {
  return new Class2({
    type: "unknown"
  });
}
function _never(Class2, params2) {
  return new Class2({
    type: "never",
    ...normalizeParams(params2)
  });
}
function _void(Class2, params2) {
  return new Class2({
    type: "void",
    ...normalizeParams(params2)
  });
}
function _date(Class2, params2) {
  return new Class2({
    type: "date",
    ...normalizeParams(params2)
  });
}
function _coercedDate(Class2, params2) {
  return new Class2({
    type: "date",
    coerce: true,
    ...normalizeParams(params2)
  });
}
function _nan(Class2, params2) {
  return new Class2({
    type: "nan",
    ...normalizeParams(params2)
  });
}
function _lt(value, params2) {
  return new $ZodCheckLessThan({
    check: "less_than",
    ...normalizeParams(params2),
    value,
    inclusive: false
  });
}
function _lte(value, params2) {
  return new $ZodCheckLessThan({
    check: "less_than",
    ...normalizeParams(params2),
    value,
    inclusive: true
  });
}
function _gt(value, params2) {
  return new $ZodCheckGreaterThan({
    check: "greater_than",
    ...normalizeParams(params2),
    value,
    inclusive: false
  });
}
function _gte(value, params2) {
  return new $ZodCheckGreaterThan({
    check: "greater_than",
    ...normalizeParams(params2),
    value,
    inclusive: true
  });
}
function _positive(params2) {
  return _gt(0, params2);
}
function _negative(params2) {
  return _lt(0, params2);
}
function _nonpositive(params2) {
  return _lte(0, params2);
}
function _nonnegative(params2) {
  return _gte(0, params2);
}
function _multipleOf(value, params2) {
  return new $ZodCheckMultipleOf({
    check: "multiple_of",
    ...normalizeParams(params2),
    value
  });
}
function _maxSize(maximum, params2) {
  return new $ZodCheckMaxSize({
    check: "max_size",
    ...normalizeParams(params2),
    maximum
  });
}
function _minSize(minimum, params2) {
  return new $ZodCheckMinSize({
    check: "min_size",
    ...normalizeParams(params2),
    minimum
  });
}
function _size(size2, params2) {
  return new $ZodCheckSizeEquals({
    check: "size_equals",
    ...normalizeParams(params2),
    size: size2
  });
}
function _maxLength(maximum, params2) {
  const ch = new $ZodCheckMaxLength({
    check: "max_length",
    ...normalizeParams(params2),
    maximum
  });
  return ch;
}
function _minLength(minimum, params2) {
  return new $ZodCheckMinLength({
    check: "min_length",
    ...normalizeParams(params2),
    minimum
  });
}
function _length(length2, params2) {
  return new $ZodCheckLengthEquals({
    check: "length_equals",
    ...normalizeParams(params2),
    length: length2
  });
}
function _regex(pattern, params2) {
  return new $ZodCheckRegex({
    check: "string_format",
    format: "regex",
    ...normalizeParams(params2),
    pattern
  });
}
function _lowercase(params2) {
  return new $ZodCheckLowerCase({
    check: "string_format",
    format: "lowercase",
    ...normalizeParams(params2)
  });
}
function _uppercase(params2) {
  return new $ZodCheckUpperCase({
    check: "string_format",
    format: "uppercase",
    ...normalizeParams(params2)
  });
}
function _includes(includes, params2) {
  return new $ZodCheckIncludes({
    check: "string_format",
    format: "includes",
    ...normalizeParams(params2),
    includes
  });
}
function _startsWith(prefix, params2) {
  return new $ZodCheckStartsWith({
    check: "string_format",
    format: "starts_with",
    ...normalizeParams(params2),
    prefix
  });
}
function _endsWith(suffix, params2) {
  return new $ZodCheckEndsWith({
    check: "string_format",
    format: "ends_with",
    ...normalizeParams(params2),
    suffix
  });
}
function _property(property, schema, params2) {
  return new $ZodCheckProperty({
    check: "property",
    property,
    schema,
    ...normalizeParams(params2)
  });
}
function _mime(types, params2) {
  return new $ZodCheckMimeType({
    check: "mime_type",
    mime: types,
    ...normalizeParams(params2)
  });
}
function _overwrite(tx) {
  return new $ZodCheckOverwrite({
    check: "overwrite",
    tx
  });
}
function _normalize(form) {
  return _overwrite((input) => input.normalize(form));
}
function _trim() {
  return _overwrite((input) => input.trim());
}
function _toLowerCase() {
  return _overwrite((input) => input.toLowerCase());
}
function _toUpperCase() {
  return _overwrite((input) => input.toUpperCase());
}
function _slugify() {
  return _overwrite((input) => slugify(input));
}
function _array(Class2, element, params2) {
  return new Class2({
    type: "array",
    element,
    ...normalizeParams(params2)
  });
}
function _union(Class2, options, params2) {
  return new Class2({
    type: "union",
    options,
    ...normalizeParams(params2)
  });
}
function _xor(Class2, options, params2) {
  return new Class2({
    type: "union",
    options,
    inclusive: false,
    ...normalizeParams(params2)
  });
}
function _discriminatedUnion(Class2, discriminator, options, params2) {
  return new Class2({
    type: "union",
    options,
    discriminator,
    ...normalizeParams(params2)
  });
}
function _intersection(Class2, left, right) {
  return new Class2({
    type: "intersection",
    left,
    right
  });
}
function _tuple(Class2, items, _paramsOrRest, _params) {
  const hasRest = _paramsOrRest instanceof $ZodType;
  const params2 = hasRest ? _params : _paramsOrRest;
  const rest = hasRest ? _paramsOrRest : null;
  return new Class2({
    type: "tuple",
    items,
    rest,
    ...normalizeParams(params2)
  });
}
function _record(Class2, keyType, valueType, params2) {
  return new Class2({
    type: "record",
    keyType,
    valueType,
    ...normalizeParams(params2)
  });
}
function _map(Class2, keyType, valueType, params2) {
  return new Class2({
    type: "map",
    keyType,
    valueType,
    ...normalizeParams(params2)
  });
}
function _set(Class2, valueType, params2) {
  return new Class2({
    type: "set",
    valueType,
    ...normalizeParams(params2)
  });
}
function _enum(Class2, values, params2) {
  const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
  return new Class2({
    type: "enum",
    entries,
    ...normalizeParams(params2)
  });
}
function _nativeEnum(Class2, entries, params2) {
  return new Class2({
    type: "enum",
    entries,
    ...normalizeParams(params2)
  });
}
function _literal(Class2, value, params2) {
  return new Class2({
    type: "literal",
    values: Array.isArray(value) ? value : [value],
    ...normalizeParams(params2)
  });
}
function _file(Class2, params2) {
  return new Class2({
    type: "file",
    ...normalizeParams(params2)
  });
}
function _transform(Class2, fn) {
  return new Class2({
    type: "transform",
    transform: fn
  });
}
function _optional(Class2, innerType) {
  return new Class2({
    type: "optional",
    innerType
  });
}
function _nullable(Class2, innerType) {
  return new Class2({
    type: "nullable",
    innerType
  });
}
function _default(Class2, innerType, defaultValue) {
  return new Class2({
    type: "default",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
    }
  });
}
function _nonoptional(Class2, innerType, params2) {
  return new Class2({
    type: "nonoptional",
    innerType,
    ...normalizeParams(params2)
  });
}
function _success(Class2, innerType) {
  return new Class2({
    type: "success",
    innerType
  });
}
function _catch(Class2, innerType, catchValue) {
  return new Class2({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
function _pipe(Class2, in_, out) {
  return new Class2({
    type: "pipe",
    in: in_,
    out
  });
}
function _readonly(Class2, innerType) {
  return new Class2({
    type: "readonly",
    innerType
  });
}
function _templateLiteral(Class2, parts, params2) {
  return new Class2({
    type: "template_literal",
    parts,
    ...normalizeParams(params2)
  });
}
function _lazy(Class2, getter) {
  return new Class2({
    type: "lazy",
    getter
  });
}
function _promise(Class2, innerType) {
  return new Class2({
    type: "promise",
    innerType
  });
}
function _custom(Class2, fn, _params) {
  const norm = normalizeParams(_params);
  norm.abort ?? (norm.abort = true);
  const schema = new Class2({
    type: "custom",
    check: "custom",
    fn,
    ...norm
  });
  return schema;
}
function _refine(Class2, fn, _params) {
  const schema = new Class2({
    type: "custom",
    check: "custom",
    fn,
    ...normalizeParams(_params)
  });
  return schema;
}
function _superRefine(fn) {
  const ch = _check((payload) => {
    payload.addIssue = (issue2) => {
      if (typeof issue2 === "string") {
        payload.issues.push(issue(issue2, payload.value, ch._zod.def));
      } else {
        const _issue = issue2;
        if (_issue.fatal)
          _issue.continue = false;
        _issue.code ?? (_issue.code = "custom");
        _issue.input ?? (_issue.input = payload.value);
        _issue.inst ?? (_issue.inst = ch);
        _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
        payload.issues.push(issue(_issue));
      }
    };
    return fn(payload.value, payload);
  });
  return ch;
}
function _check(fn, params2) {
  const ch = new $ZodCheck({
    check: "custom",
    ...normalizeParams(params2)
  });
  ch._zod.check = fn;
  return ch;
}
function describe(description) {
  const ch = new $ZodCheck({ check: "describe" });
  ch._zod.onattach = [
    (inst) => {
      const existing = globalRegistry.get(inst) ?? {};
      globalRegistry.add(inst, { ...existing, description });
    }
  ];
  ch._zod.check = () => {};
  return ch;
}
function meta(metadata) {
  const ch = new $ZodCheck({ check: "meta" });
  ch._zod.onattach = [
    (inst) => {
      const existing = globalRegistry.get(inst) ?? {};
      globalRegistry.add(inst, { ...existing, ...metadata });
    }
  ];
  ch._zod.check = () => {};
  return ch;
}
function _stringbool(Classes, _params) {
  const params2 = normalizeParams(_params);
  let truthyArray = params2.truthy ?? ["true", "1", "yes", "on", "y", "enabled"];
  let falsyArray = params2.falsy ?? ["false", "0", "no", "off", "n", "disabled"];
  if (params2.case !== "sensitive") {
    truthyArray = truthyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v);
    falsyArray = falsyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v);
  }
  const truthySet = new Set(truthyArray);
  const falsySet = new Set(falsyArray);
  const _Codec = Classes.Codec ?? $ZodCodec;
  const _Boolean = Classes.Boolean ?? $ZodBoolean;
  const _String = Classes.String ?? $ZodString;
  const stringSchema = new _String({ type: "string", error: params2.error });
  const booleanSchema = new _Boolean({ type: "boolean", error: params2.error });
  const codec = new _Codec({
    type: "pipe",
    in: stringSchema,
    out: booleanSchema,
    transform: (input, payload) => {
      let data = input;
      if (params2.case !== "sensitive")
        data = data.toLowerCase();
      if (truthySet.has(data)) {
        return true;
      } else if (falsySet.has(data)) {
        return false;
      } else {
        payload.issues.push({
          code: "invalid_value",
          expected: "stringbool",
          values: [...truthySet, ...falsySet],
          input: payload.value,
          inst: codec,
          continue: false
        });
        return {};
      }
    },
    reverseTransform: (input, _payload) => {
      if (input === true) {
        return truthyArray[0] || "true";
      } else {
        return falsyArray[0] || "false";
      }
    },
    error: params2.error
  });
  return codec;
}
function _stringFormat(Class2, format2, fnOrRegex, _params = {}) {
  const params2 = normalizeParams(_params);
  const def = {
    ...normalizeParams(_params),
    check: "string_format",
    type: "string",
    format: format2,
    fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val),
    ...params2
  };
  if (fnOrRegex instanceof RegExp) {
    def.pattern = fnOrRegex;
  }
  const inst = new Class2(def);
  return inst;
}
// node_modules/zod/v4/core/to-json-schema.js
function initializeContext(params2) {
  let target = params2?.target ?? "draft-2020-12";
  if (target === "draft-4")
    target = "draft-04";
  if (target === "draft-7")
    target = "draft-07";
  return {
    processors: params2.processors ?? {},
    metadataRegistry: params2?.metadata ?? globalRegistry,
    target,
    unrepresentable: params2?.unrepresentable ?? "throw",
    override: params2?.override ?? (() => {}),
    io: params2?.io ?? "output",
    counter: 0,
    seen: new Map,
    cycles: params2?.cycles ?? "ref",
    reused: params2?.reused ?? "inline",
    external: params2?.external ?? undefined
  };
}
function process2(schema, ctx, _params = { path: [], schemaPath: [] }) {
  var _a2;
  const def = schema._zod.def;
  const seen = ctx.seen.get(schema);
  if (seen) {
    seen.count++;
    const isCycle = _params.schemaPath.includes(schema);
    if (isCycle) {
      seen.cycle = _params.path;
    }
    return seen.schema;
  }
  const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };
  ctx.seen.set(schema, result);
  const overrideSchema = schema._zod.toJSONSchema?.();
  if (overrideSchema) {
    result.schema = overrideSchema;
  } else {
    const params2 = {
      ..._params,
      schemaPath: [..._params.schemaPath, schema],
      path: _params.path
    };
    if (schema._zod.processJSONSchema) {
      schema._zod.processJSONSchema(ctx, result.schema, params2);
    } else {
      const _json = result.schema;
      const processor = ctx.processors[def.type];
      if (!processor) {
        throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
      }
      processor(schema, ctx, _json, params2);
    }
    const parent = schema._zod.parent;
    if (parent) {
      if (!result.ref)
        result.ref = parent;
      process2(parent, ctx, params2);
      ctx.seen.get(parent).isParent = true;
    }
  }
  const meta2 = ctx.metadataRegistry.get(schema);
  if (meta2)
    Object.assign(result.schema, meta2);
  if (ctx.io === "input" && isTransforming(schema)) {
    delete result.schema.examples;
    delete result.schema.default;
  }
  if (ctx.io === "input" && result.schema._prefault)
    (_a2 = result.schema).default ?? (_a2.default = result.schema._prefault);
  delete result.schema._prefault;
  const _result = ctx.seen.get(schema);
  return _result.schema;
}
function extractDefs(ctx, schema) {
  const root = ctx.seen.get(schema);
  if (!root)
    throw new Error("Unprocessed schema. This is a bug in Zod.");
  const idToSchema = new Map;
  for (const entry of ctx.seen.entries()) {
    const id2 = ctx.metadataRegistry.get(entry[0])?.id;
    if (id2) {
      const existing = idToSchema.get(id2);
      if (existing && existing !== entry[0]) {
        throw new Error(`Duplicate schema id "${id2}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
      }
      idToSchema.set(id2, entry[0]);
    }
  }
  const makeURI = (entry) => {
    const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
    if (ctx.external) {
      const externalId = ctx.external.registry.get(entry[0])?.id;
      const uriGenerator = ctx.external.uri ?? ((id3) => id3);
      if (externalId) {
        return { ref: uriGenerator(externalId) };
      }
      const id2 = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
      entry[1].defId = id2;
      return { defId: id2, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id2}` };
    }
    if (entry[1] === root) {
      return { ref: "#" };
    }
    const uriPrefix = `#`;
    const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
    const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
    return { defId, ref: defUriPrefix + defId };
  };
  const extractToDef = (entry) => {
    if (entry[1].schema.$ref) {
      return;
    }
    const seen = entry[1];
    const { ref, defId } = makeURI(entry);
    seen.def = { ...seen.schema };
    if (defId)
      seen.defId = defId;
    const schema2 = seen.schema;
    for (const key in schema2) {
      delete schema2[key];
    }
    schema2.$ref = ref;
  };
  if (ctx.cycles === "throw") {
    for (const entry of ctx.seen.entries()) {
      const seen = entry[1];
      if (seen.cycle) {
        throw new Error("Cycle detected: " + `#/${seen.cycle?.join("/")}/<root>` + '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.');
      }
    }
  }
  for (const entry of ctx.seen.entries()) {
    const seen = entry[1];
    if (schema === entry[0]) {
      extractToDef(entry);
      continue;
    }
    if (ctx.external) {
      const ext = ctx.external.registry.get(entry[0])?.id;
      if (schema !== entry[0] && ext) {
        extractToDef(entry);
        continue;
      }
    }
    const id2 = ctx.metadataRegistry.get(entry[0])?.id;
    if (id2) {
      extractToDef(entry);
      continue;
    }
    if (seen.cycle) {
      extractToDef(entry);
      continue;
    }
    if (seen.count > 1) {
      if (ctx.reused === "ref") {
        extractToDef(entry);
        continue;
      }
    }
  }
}
function finalize(ctx, schema) {
  const root = ctx.seen.get(schema);
  if (!root)
    throw new Error("Unprocessed schema. This is a bug in Zod.");
  const flattenRef = (zodSchema) => {
    const seen = ctx.seen.get(zodSchema);
    if (seen.ref === null)
      return;
    const schema2 = seen.def ?? seen.schema;
    const _cached = { ...schema2 };
    const ref = seen.ref;
    seen.ref = null;
    if (ref) {
      flattenRef(ref);
      const refSeen = ctx.seen.get(ref);
      const refSchema = refSeen.schema;
      if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
        schema2.allOf = schema2.allOf ?? [];
        schema2.allOf.push(refSchema);
      } else {
        Object.assign(schema2, refSchema);
      }
      Object.assign(schema2, _cached);
      const isParentRef = zodSchema._zod.parent === ref;
      if (isParentRef) {
        for (const key in schema2) {
          if (key === "$ref" || key === "allOf")
            continue;
          if (!(key in _cached)) {
            delete schema2[key];
          }
        }
      }
      if (refSchema.$ref) {
        for (const key in schema2) {
          if (key === "$ref" || key === "allOf")
            continue;
          if (key in refSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(refSeen.def[key])) {
            delete schema2[key];
          }
        }
      }
    }
    const parent = zodSchema._zod.parent;
    if (parent && parent !== ref) {
      flattenRef(parent);
      const parentSeen = ctx.seen.get(parent);
      if (parentSeen?.schema.$ref) {
        schema2.$ref = parentSeen.schema.$ref;
        if (parentSeen.def) {
          for (const key in schema2) {
            if (key === "$ref" || key === "allOf")
              continue;
            if (key in parentSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(parentSeen.def[key])) {
              delete schema2[key];
            }
          }
        }
      }
    }
    ctx.override({
      zodSchema,
      jsonSchema: schema2,
      path: seen.path ?? []
    });
  };
  for (const entry of [...ctx.seen.entries()].reverse()) {
    flattenRef(entry[0]);
  }
  const result = {};
  if (ctx.target === "draft-2020-12") {
    result.$schema = "https://json-schema.org/draft/2020-12/schema";
  } else if (ctx.target === "draft-07") {
    result.$schema = "http://json-schema.org/draft-07/schema#";
  } else if (ctx.target === "draft-04") {
    result.$schema = "http://json-schema.org/draft-04/schema#";
  } else if (ctx.target === "openapi-3.0") {} else {}
  if (ctx.external?.uri) {
    const id2 = ctx.external.registry.get(schema)?.id;
    if (!id2)
      throw new Error("Schema is missing an `id` property");
    result.$id = ctx.external.uri(id2);
  }
  Object.assign(result, root.def ?? root.schema);
  const defs = ctx.external?.defs ?? {};
  for (const entry of ctx.seen.entries()) {
    const seen = entry[1];
    if (seen.def && seen.defId) {
      defs[seen.defId] = seen.def;
    }
  }
  if (ctx.external) {} else {
    if (Object.keys(defs).length > 0) {
      if (ctx.target === "draft-2020-12") {
        result.$defs = defs;
      } else {
        result.definitions = defs;
      }
    }
  }
  try {
    const finalized = JSON.parse(JSON.stringify(result));
    Object.defineProperty(finalized, "~standard", {
      value: {
        ...schema["~standard"],
        jsonSchema: {
          input: createStandardJSONSchemaMethod(schema, "input", ctx.processors),
          output: createStandardJSONSchemaMethod(schema, "output", ctx.processors)
        }
      },
      enumerable: false,
      writable: false
    });
    return finalized;
  } catch (_err) {
    throw new Error("Error converting schema to JSON.");
  }
}
function isTransforming(_schema, _ctx) {
  const ctx = _ctx ?? { seen: new Set };
  if (ctx.seen.has(_schema))
    return false;
  ctx.seen.add(_schema);
  const def = _schema._zod.def;
  if (def.type === "transform")
    return true;
  if (def.type === "array")
    return isTransforming(def.element, ctx);
  if (def.type === "set")
    return isTransforming(def.valueType, ctx);
  if (def.type === "lazy")
    return isTransforming(def.getter(), ctx);
  if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") {
    return isTransforming(def.innerType, ctx);
  }
  if (def.type === "intersection") {
    return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
  }
  if (def.type === "record" || def.type === "map") {
    return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
  }
  if (def.type === "pipe") {
    return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
  }
  if (def.type === "object") {
    for (const key in def.shape) {
      if (isTransforming(def.shape[key], ctx))
        return true;
    }
    return false;
  }
  if (def.type === "union") {
    for (const option of def.options) {
      if (isTransforming(option, ctx))
        return true;
    }
    return false;
  }
  if (def.type === "tuple") {
    for (const item of def.items) {
      if (isTransforming(item, ctx))
        return true;
    }
    if (def.rest && isTransforming(def.rest, ctx))
      return true;
    return false;
  }
  return false;
}
var createToJSONSchemaMethod = (schema, processors = {}) => (params2) => {
  const ctx = initializeContext({ ...params2, processors });
  process2(schema, ctx);
  extractDefs(ctx, schema);
  return finalize(ctx, schema);
};
var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params2) => {
  const { libraryOptions, target } = params2 ?? {};
  const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors });
  process2(schema, ctx);
  extractDefs(ctx, schema);
  return finalize(ctx, schema);
};
// node_modules/zod/v4/core/json-schema-processors.js
var formatMap = {
  guid: "uuid",
  url: "uri",
  datetime: "date-time",
  json_string: "json-string",
  regex: ""
};
var stringProcessor = (schema, ctx, _json, _params) => {
  const json = _json;
  json.type = "string";
  const { minimum, maximum, format: format2, patterns, contentEncoding } = schema._zod.bag;
  if (typeof minimum === "number")
    json.minLength = minimum;
  if (typeof maximum === "number")
    json.maxLength = maximum;
  if (format2) {
    json.format = formatMap[format2] ?? format2;
    if (json.format === "")
      delete json.format;
    if (format2 === "time") {
      delete json.format;
    }
  }
  if (contentEncoding)
    json.contentEncoding = contentEncoding;
  if (patterns && patterns.size > 0) {
    const regexes = [...patterns];
    if (regexes.length === 1)
      json.pattern = regexes[0].source;
    else if (regexes.length > 1) {
      json.allOf = [
        ...regexes.map((regex) => ({
          ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
          pattern: regex.source
        }))
      ];
    }
  }
};
var numberProcessor = (schema, ctx, _json, _params) => {
  const json = _json;
  const { minimum, maximum, format: format2, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
  if (typeof format2 === "string" && format2.includes("int"))
    json.type = "integer";
  else
    json.type = "number";
  if (typeof exclusiveMinimum === "number") {
    if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
      json.minimum = exclusiveMinimum;
      json.exclusiveMinimum = true;
    } else {
      json.exclusiveMinimum = exclusiveMinimum;
    }
  }
  if (typeof minimum === "number") {
    json.minimum = minimum;
    if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") {
      if (exclusiveMinimum >= minimum)
        delete json.minimum;
      else
        delete json.exclusiveMinimum;
    }
  }
  if (typeof exclusiveMaximum === "number") {
    if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
      json.maximum = exclusiveMaximum;
      json.exclusiveMaximum = true;
    } else {
      json.exclusiveMaximum = exclusiveMaximum;
    }
  }
  if (typeof maximum === "number") {
    json.maximum = maximum;
    if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") {
      if (exclusiveMaximum <= maximum)
        delete json.maximum;
      else
        delete json.exclusiveMaximum;
    }
  }
  if (typeof multipleOf === "number")
    json.multipleOf = multipleOf;
};
var booleanProcessor = (_schema, _ctx, json, _params) => {
  json.type = "boolean";
};
var bigintProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("BigInt cannot be represented in JSON Schema");
  }
};
var symbolProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Symbols cannot be represented in JSON Schema");
  }
};
var nullProcessor = (_schema, ctx, json, _params) => {
  if (ctx.target === "openapi-3.0") {
    json.type = "string";
    json.nullable = true;
    json.enum = [null];
  } else {
    json.type = "null";
  }
};
var undefinedProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Undefined cannot be represented in JSON Schema");
  }
};
var voidProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Void cannot be represented in JSON Schema");
  }
};
var neverProcessor = (_schema, _ctx, json, _params) => {
  json.not = {};
};
var anyProcessor = (_schema, _ctx, _json, _params) => {};
var unknownProcessor = (_schema, _ctx, _json, _params) => {};
var dateProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Date cannot be represented in JSON Schema");
  }
};
var enumProcessor = (schema, _ctx, json, _params) => {
  const def = schema._zod.def;
  const values = getEnumValues(def.entries);
  if (values.every((v) => typeof v === "number"))
    json.type = "number";
  if (values.every((v) => typeof v === "string"))
    json.type = "string";
  json.enum = values;
};
var literalProcessor = (schema, ctx, json, _params) => {
  const def = schema._zod.def;
  const vals = [];
  for (const val of def.values) {
    if (val === undefined) {
      if (ctx.unrepresentable === "throw") {
        throw new Error("Literal `undefined` cannot be represented in JSON Schema");
      } else {}
    } else if (typeof val === "bigint") {
      if (ctx.unrepresentable === "throw") {
        throw new Error("BigInt literals cannot be represented in JSON Schema");
      } else {
        vals.push(Number(val));
      }
    } else {
      vals.push(val);
    }
  }
  if (vals.length === 0) {} else if (vals.length === 1) {
    const val = vals[0];
    json.type = val === null ? "null" : typeof val;
    if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
      json.enum = [val];
    } else {
      json.const = val;
    }
  } else {
    if (vals.every((v) => typeof v === "number"))
      json.type = "number";
    if (vals.every((v) => typeof v === "string"))
      json.type = "string";
    if (vals.every((v) => typeof v === "boolean"))
      json.type = "boolean";
    if (vals.every((v) => v === null))
      json.type = "null";
    json.enum = vals;
  }
};
var nanProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("NaN cannot be represented in JSON Schema");
  }
};
var templateLiteralProcessor = (schema, _ctx, json, _params) => {
  const _json = json;
  const pattern = schema._zod.pattern;
  if (!pattern)
    throw new Error("Pattern not found in template literal");
  _json.type = "string";
  _json.pattern = pattern.source;
};
var fileProcessor = (schema, _ctx, json, _params) => {
  const _json = json;
  const file = {
    type: "string",
    format: "binary",
    contentEncoding: "binary"
  };
  const { minimum, maximum, mime } = schema._zod.bag;
  if (minimum !== undefined)
    file.minLength = minimum;
  if (maximum !== undefined)
    file.maxLength = maximum;
  if (mime) {
    if (mime.length === 1) {
      file.contentMediaType = mime[0];
      Object.assign(_json, file);
    } else {
      Object.assign(_json, file);
      _json.anyOf = mime.map((m) => ({ contentMediaType: m }));
    }
  } else {
    Object.assign(_json, file);
  }
};
var successProcessor = (_schema, _ctx, json, _params) => {
  json.type = "boolean";
};
var customProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Custom types cannot be represented in JSON Schema");
  }
};
var functionProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Function types cannot be represented in JSON Schema");
  }
};
var transformProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Transforms cannot be represented in JSON Schema");
  }
};
var mapProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Map cannot be represented in JSON Schema");
  }
};
var setProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Set cannot be represented in JSON Schema");
  }
};
var arrayProcessor = (schema, ctx, _json, params2) => {
  const json = _json;
  const def = schema._zod.def;
  const { minimum, maximum } = schema._zod.bag;
  if (typeof minimum === "number")
    json.minItems = minimum;
  if (typeof maximum === "number")
    json.maxItems = maximum;
  json.type = "array";
  json.items = process2(def.element, ctx, { ...params2, path: [...params2.path, "items"] });
};
var objectProcessor = (schema, ctx, _json, params2) => {
  const json = _json;
  const def = schema._zod.def;
  json.type = "object";
  json.properties = {};
  const shape2 = def.shape;
  for (const key in shape2) {
    json.properties[key] = process2(shape2[key], ctx, {
      ...params2,
      path: [...params2.path, "properties", key]
    });
  }
  const allKeys = new Set(Object.keys(shape2));
  const requiredKeys = new Set([...allKeys].filter((key) => {
    const v = def.shape[key]._zod;
    if (ctx.io === "input") {
      return v.optin === undefined;
    } else {
      return v.optout === undefined;
    }
  }));
  if (requiredKeys.size > 0) {
    json.required = Array.from(requiredKeys);
  }
  if (def.catchall?._zod.def.type === "never") {
    json.additionalProperties = false;
  } else if (!def.catchall) {
    if (ctx.io === "output")
      json.additionalProperties = false;
  } else if (def.catchall) {
    json.additionalProperties = process2(def.catchall, ctx, {
      ...params2,
      path: [...params2.path, "additionalProperties"]
    });
  }
};
var unionProcessor = (schema, ctx, json, params2) => {
  const def = schema._zod.def;
  const isExclusive = def.inclusive === false;
  const options = def.options.map((x2, i) => process2(x2, ctx, {
    ...params2,
    path: [...params2.path, isExclusive ? "oneOf" : "anyOf", i]
  }));
  if (isExclusive) {
    json.oneOf = options;
  } else {
    json.anyOf = options;
  }
};
var intersectionProcessor = (schema, ctx, json, params2) => {
  const def = schema._zod.def;
  const a = process2(def.left, ctx, {
    ...params2,
    path: [...params2.path, "allOf", 0]
  });
  const b = process2(def.right, ctx, {
    ...params2,
    path: [...params2.path, "allOf", 1]
  });
  const isSimpleIntersection = (val) => ("allOf" in val) && Object.keys(val).length === 1;
  const allOf = [
    ...isSimpleIntersection(a) ? a.allOf : [a],
    ...isSimpleIntersection(b) ? b.allOf : [b]
  ];
  json.allOf = allOf;
};
var tupleProcessor = (schema, ctx, _json, params2) => {
  const json = _json;
  const def = schema._zod.def;
  json.type = "array";
  const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items";
  const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems";
  const prefixItems = def.items.map((x2, i) => process2(x2, ctx, {
    ...params2,
    path: [...params2.path, prefixPath, i]
  }));
  const rest = def.rest ? process2(def.rest, ctx, {
    ...params2,
    path: [...params2.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []]
  }) : null;
  if (ctx.target === "draft-2020-12") {
    json.prefixItems = prefixItems;
    if (rest) {
      json.items = rest;
    }
  } else if (ctx.target === "openapi-3.0") {
    json.items = {
      anyOf: prefixItems
    };
    if (rest) {
      json.items.anyOf.push(rest);
    }
    json.minItems = prefixItems.length;
    if (!rest) {
      json.maxItems = prefixItems.length;
    }
  } else {
    json.items = prefixItems;
    if (rest) {
      json.additionalItems = rest;
    }
  }
  const { minimum, maximum } = schema._zod.bag;
  if (typeof minimum === "number")
    json.minItems = minimum;
  if (typeof maximum === "number")
    json.maxItems = maximum;
};
var recordProcessor = (schema, ctx, _json, params2) => {
  const json = _json;
  const def = schema._zod.def;
  json.type = "object";
  if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
    json.propertyNames = process2(def.keyType, ctx, {
      ...params2,
      path: [...params2.path, "propertyNames"]
    });
  }
  json.additionalProperties = process2(def.valueType, ctx, {
    ...params2,
    path: [...params2.path, "additionalProperties"]
  });
  const keyDef = def.keyType._zod.def;
  if (keyDef.type === "enum") {
    const enumValues = getEnumValues(keyDef.entries);
    const validEnumValues = enumValues.filter((v) => typeof v === "string" || typeof v === "number");
    if (validEnumValues.length > 0) {
      json.required = validEnumValues;
    }
  }
};
var nullableProcessor = (schema, ctx, json, params2) => {
  const def = schema._zod.def;
  const inner = process2(def.innerType, ctx, params2);
  const seen = ctx.seen.get(schema);
  if (ctx.target === "openapi-3.0") {
    seen.ref = def.innerType;
    json.nullable = true;
  } else {
    json.anyOf = [inner, { type: "null" }];
  }
};
var nonoptionalProcessor = (schema, ctx, _json, params2) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params2);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
};
var defaultProcessor = (schema, ctx, json, params2) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params2);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  json.default = JSON.parse(JSON.stringify(def.defaultValue));
};
var prefaultProcessor = (schema, ctx, json, params2) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params2);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  if (ctx.io === "input")
    json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
};
var catchProcessor = (schema, ctx, json, params2) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params2);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  let catchValue;
  try {
    catchValue = def.catchValue(undefined);
  } catch {
    throw new Error("Dynamic catch values are not supported in JSON Schema");
  }
  json.default = catchValue;
};
var pipeProcessor = (schema, ctx, _json, params2) => {
  const def = schema._zod.def;
  const innerType = ctx.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out;
  process2(innerType, ctx, params2);
  const seen = ctx.seen.get(schema);
  seen.ref = innerType;
};
var readonlyProcessor = (schema, ctx, json, params2) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params2);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  json.readOnly = true;
};
var promiseProcessor = (schema, ctx, _json, params2) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params2);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
};
var optionalProcessor = (schema, ctx, _json, params2) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params2);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
};
var lazyProcessor = (schema, ctx, _json, params2) => {
  const innerType = schema._zod.innerType;
  process2(innerType, ctx, params2);
  const seen = ctx.seen.get(schema);
  seen.ref = innerType;
};
var allProcessors = {
  string: stringProcessor,
  number: numberProcessor,
  boolean: booleanProcessor,
  bigint: bigintProcessor,
  symbol: symbolProcessor,
  null: nullProcessor,
  undefined: undefinedProcessor,
  void: voidProcessor,
  never: neverProcessor,
  any: anyProcessor,
  unknown: unknownProcessor,
  date: dateProcessor,
  enum: enumProcessor,
  literal: literalProcessor,
  nan: nanProcessor,
  template_literal: templateLiteralProcessor,
  file: fileProcessor,
  success: successProcessor,
  custom: customProcessor,
  function: functionProcessor,
  transform: transformProcessor,
  map: mapProcessor,
  set: setProcessor,
  array: arrayProcessor,
  object: objectProcessor,
  union: unionProcessor,
  intersection: intersectionProcessor,
  tuple: tupleProcessor,
  record: recordProcessor,
  nullable: nullableProcessor,
  nonoptional: nonoptionalProcessor,
  default: defaultProcessor,
  prefault: prefaultProcessor,
  catch: catchProcessor,
  pipe: pipeProcessor,
  readonly: readonlyProcessor,
  promise: promiseProcessor,
  optional: optionalProcessor,
  lazy: lazyProcessor
};
function toJSONSchema(input, params2) {
  if ("_idmap" in input) {
    const registry3 = input;
    const ctx2 = initializeContext({ ...params2, processors: allProcessors });
    const defs = {};
    for (const entry of registry3._idmap.entries()) {
      const [_, schema] = entry;
      process2(schema, ctx2);
    }
    const schemas = {};
    const external = {
      registry: registry3,
      uri: params2?.uri,
      defs
    };
    ctx2.external = external;
    for (const entry of registry3._idmap.entries()) {
      const [key, schema] = entry;
      extractDefs(ctx2, schema);
      schemas[key] = finalize(ctx2, schema);
    }
    if (Object.keys(defs).length > 0) {
      const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions";
      schemas.__shared = {
        [defsSegment]: defs
      };
    }
    return { schemas };
  }
  const ctx = initializeContext({ ...params2, processors: allProcessors });
  process2(input, ctx);
  extractDefs(ctx, input);
  return finalize(ctx, input);
}
// node_modules/zod/v4/core/json-schema-generator.js
class JSONSchemaGenerator {
  get metadataRegistry() {
    return this.ctx.metadataRegistry;
  }
  get target() {
    return this.ctx.target;
  }
  get unrepresentable() {
    return this.ctx.unrepresentable;
  }
  get override() {
    return this.ctx.override;
  }
  get io() {
    return this.ctx.io;
  }
  get counter() {
    return this.ctx.counter;
  }
  set counter(value) {
    this.ctx.counter = value;
  }
  get seen() {
    return this.ctx.seen;
  }
  constructor(params2) {
    let normalizedTarget = params2?.target ?? "draft-2020-12";
    if (normalizedTarget === "draft-4")
      normalizedTarget = "draft-04";
    if (normalizedTarget === "draft-7")
      normalizedTarget = "draft-07";
    this.ctx = initializeContext({
      processors: allProcessors,
      target: normalizedTarget,
      ...params2?.metadata && { metadata: params2.metadata },
      ...params2?.unrepresentable && { unrepresentable: params2.unrepresentable },
      ...params2?.override && { override: params2.override },
      ...params2?.io && { io: params2.io }
    });
  }
  process(schema, _params = { path: [], schemaPath: [] }) {
    return process2(schema, this.ctx, _params);
  }
  emit(schema, _params) {
    if (_params) {
      if (_params.cycles)
        this.ctx.cycles = _params.cycles;
      if (_params.reused)
        this.ctx.reused = _params.reused;
      if (_params.external)
        this.ctx.external = _params.external;
    }
    extractDefs(this.ctx, schema);
    const result = finalize(this.ctx, schema);
    const { "~standard": _, ...plainResult } = result;
    return plainResult;
  }
}
// node_modules/zod/v4/core/json-schema.js
var exports_json_schema = {};
// node_modules/zod/v4/classic/schemas.js
var exports_schemas2 = {};
__export(exports_schemas2, {
  xor: () => xor,
  xid: () => xid2,
  void: () => _void2,
  uuidv7: () => uuidv7,
  uuidv6: () => uuidv6,
  uuidv4: () => uuidv42,
  uuid: () => uuid2,
  url: () => url,
  unknown: () => unknown,
  union: () => union,
  undefined: () => _undefined3,
  ulid: () => ulid2,
  uint64: () => uint64,
  uint32: () => uint322,
  tuple: () => tuple,
  transform: () => transform,
  templateLiteral: () => templateLiteral,
  symbol: () => symbol2,
  superRefine: () => superRefine,
  success: () => success,
  stringbool: () => stringbool,
  stringFormat: () => stringFormat,
  string: () => string2,
  strictObject: () => strictObject,
  set: () => set,
  refine: () => refine,
  record: () => record,
  readonly: () => readonly,
  promise: () => promise,
  preprocess: () => preprocess,
  prefault: () => prefault,
  pipe: () => pipe,
  partialRecord: () => partialRecord,
  optional: () => optional,
  object: () => object,
  number: () => number4,
  nullish: () => nullish2,
  nullable: () => nullable,
  null: () => _null3,
  nonoptional: () => nonoptional,
  never: () => never,
  nativeEnum: () => nativeEnum,
  nanoid: () => nanoid2,
  nan: () => nan,
  meta: () => meta2,
  map: () => map3,
  mac: () => mac2,
  looseRecord: () => looseRecord,
  looseObject: () => looseObject,
  literal: () => literal,
  lazy: () => lazy,
  ksuid: () => ksuid2,
  keyof: () => keyof2,
  jwt: () => jwt,
  json: () => json,
  ipv6: () => ipv62,
  ipv4: () => ipv42,
  intersection: () => intersection,
  int64: () => int64,
  int32: () => int32,
  int: () => int,
  instanceof: () => _instanceof,
  httpUrl: () => httpUrl,
  hostname: () => hostname2,
  hex: () => hex3,
  hash: () => hash,
  guid: () => guid2,
  function: () => _function,
  float64: () => float64,
  float32: () => float32,
  file: () => file,
  exactOptional: () => exactOptional,
  enum: () => _enum2,
  emoji: () => emoji2,
  email: () => email2,
  e164: () => e1642,
  discriminatedUnion: () => discriminatedUnion,
  describe: () => describe2,
  date: () => date3,
  custom: () => custom2,
  cuid2: () => cuid22,
  cuid: () => cuid3,
  codec: () => codec,
  cidrv6: () => cidrv62,
  cidrv4: () => cidrv42,
  check: () => check,
  catch: () => _catch2,
  boolean: () => boolean2,
  bigint: () => bigint2,
  base64url: () => base64url2,
  base64: () => base642,
  array: () => array2,
  any: () => any2,
  _function: () => _function,
  _default: () => _default2,
  _ZodString: () => _ZodString,
  ZodXor: () => ZodXor,
  ZodXID: () => ZodXID,
  ZodVoid: () => ZodVoid,
  ZodUnknown: () => ZodUnknown,
  ZodUnion: () => ZodUnion,
  ZodUndefined: () => ZodUndefined,
  ZodUUID: () => ZodUUID,
  ZodURL: () => ZodURL,
  ZodULID: () => ZodULID,
  ZodType: () => ZodType,
  ZodTuple: () => ZodTuple,
  ZodTransform: () => ZodTransform,
  ZodTemplateLiteral: () => ZodTemplateLiteral,
  ZodSymbol: () => ZodSymbol,
  ZodSuccess: () => ZodSuccess,
  ZodStringFormat: () => ZodStringFormat,
  ZodString: () => ZodString,
  ZodSet: () => ZodSet,
  ZodRecord: () => ZodRecord,
  ZodReadonly: () => ZodReadonly,
  ZodPromise: () => ZodPromise,
  ZodPrefault: () => ZodPrefault,
  ZodPipe: () => ZodPipe,
  ZodOptional: () => ZodOptional,
  ZodObject: () => ZodObject,
  ZodNumberFormat: () => ZodNumberFormat,
  ZodNumber: () => ZodNumber,
  ZodNullable: () => ZodNullable,
  ZodNull: () => ZodNull,
  ZodNonOptional: () => ZodNonOptional,
  ZodNever: () => ZodNever,
  ZodNanoID: () => ZodNanoID,
  ZodNaN: () => ZodNaN,
  ZodMap: () => ZodMap,
  ZodMAC: () => ZodMAC,
  ZodLiteral: () => ZodLiteral,
  ZodLazy: () => ZodLazy,
  ZodKSUID: () => ZodKSUID,
  ZodJWT: () => ZodJWT,
  ZodIntersection: () => ZodIntersection,
  ZodIPv6: () => ZodIPv6,
  ZodIPv4: () => ZodIPv4,
  ZodGUID: () => ZodGUID,
  ZodFunction: () => ZodFunction,
  ZodFile: () => ZodFile,
  ZodExactOptional: () => ZodExactOptional,
  ZodEnum: () => ZodEnum,
  ZodEmoji: () => ZodEmoji,
  ZodEmail: () => ZodEmail,
  ZodE164: () => ZodE164,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
  ZodDefault: () => ZodDefault,
  ZodDate: () => ZodDate,
  ZodCustomStringFormat: () => ZodCustomStringFormat,
  ZodCustom: () => ZodCustom,
  ZodCodec: () => ZodCodec,
  ZodCatch: () => ZodCatch,
  ZodCUID2: () => ZodCUID2,
  ZodCUID: () => ZodCUID,
  ZodCIDRv6: () => ZodCIDRv6,
  ZodCIDRv4: () => ZodCIDRv4,
  ZodBoolean: () => ZodBoolean,
  ZodBigIntFormat: () => ZodBigIntFormat,
  ZodBigInt: () => ZodBigInt,
  ZodBase64URL: () => ZodBase64URL,
  ZodBase64: () => ZodBase64,
  ZodArray: () => ZodArray,
  ZodAny: () => ZodAny
});

// node_modules/zod/v4/classic/checks.js
var exports_checks2 = {};
__export(exports_checks2, {
  uppercase: () => _uppercase,
  trim: () => _trim,
  toUpperCase: () => _toUpperCase,
  toLowerCase: () => _toLowerCase,
  startsWith: () => _startsWith,
  slugify: () => _slugify,
  size: () => _size,
  regex: () => _regex,
  property: () => _property,
  positive: () => _positive,
  overwrite: () => _overwrite,
  normalize: () => _normalize,
  nonpositive: () => _nonpositive,
  nonnegative: () => _nonnegative,
  negative: () => _negative,
  multipleOf: () => _multipleOf,
  minSize: () => _minSize,
  minLength: () => _minLength,
  mime: () => _mime,
  maxSize: () => _maxSize,
  maxLength: () => _maxLength,
  lte: () => _lte,
  lt: () => _lt,
  lowercase: () => _lowercase,
  length: () => _length,
  includes: () => _includes,
  gte: () => _gte,
  gt: () => _gt,
  endsWith: () => _endsWith
});

// node_modules/zod/v4/classic/iso.js
var exports_iso = {};
__export(exports_iso, {
  time: () => time2,
  duration: () => duration2,
  datetime: () => datetime2,
  date: () => date2,
  ZodISOTime: () => ZodISOTime,
  ZodISODuration: () => ZodISODuration,
  ZodISODateTime: () => ZodISODateTime,
  ZodISODate: () => ZodISODate
});
var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
  $ZodISODateTime.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function datetime2(params2) {
  return _isoDateTime(ZodISODateTime, params2);
}
var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
  $ZodISODate.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function date2(params2) {
  return _isoDate(ZodISODate, params2);
}
var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
  $ZodISOTime.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function time2(params2) {
  return _isoTime(ZodISOTime, params2);
}
var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
  $ZodISODuration.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function duration2(params2) {
  return _isoDuration(ZodISODuration, params2);
}

// node_modules/zod/v4/classic/errors.js
var initializer2 = (inst, issues) => {
  $ZodError.init(inst, issues);
  inst.name = "ZodError";
  Object.defineProperties(inst, {
    format: {
      value: (mapper) => formatError(inst, mapper)
    },
    flatten: {
      value: (mapper) => flattenError(inst, mapper)
    },
    addIssue: {
      value: (issue2) => {
        inst.issues.push(issue2);
        inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
      }
    },
    addIssues: {
      value: (issues2) => {
        inst.issues.push(...issues2);
        inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
      }
    },
    isEmpty: {
      get() {
        return inst.issues.length === 0;
      }
    }
  });
};
var ZodError = $constructor("ZodError", initializer2);
var ZodRealError = $constructor("ZodError", initializer2, {
  Parent: Error
});

// node_modules/zod/v4/classic/parse.js
var parse3 = /* @__PURE__ */ _parse(ZodRealError);
var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError);
var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
var encode2 = /* @__PURE__ */ _encode(ZodRealError);
var decode2 = /* @__PURE__ */ _decode(ZodRealError);
var encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError);
var decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError);
var safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError);
var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError);
var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);

// node_modules/zod/v4/classic/schemas.js
var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
  $ZodType.init(inst, def);
  Object.assign(inst["~standard"], {
    jsonSchema: {
      input: createStandardJSONSchemaMethod(inst, "input"),
      output: createStandardJSONSchemaMethod(inst, "output")
    }
  });
  inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
  inst.def = def;
  inst.type = def.type;
  Object.defineProperty(inst, "_def", { value: def });
  inst.check = (...checks2) => {
    return inst.clone(exports_util.mergeDefs(def, {
      checks: [
        ...def.checks ?? [],
        ...checks2.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
      ]
    }), {
      parent: true
    });
  };
  inst.with = inst.check;
  inst.clone = (def2, params2) => clone(inst, def2, params2);
  inst.brand = () => inst;
  inst.register = (reg, meta2) => {
    reg.add(inst, meta2);
    return inst;
  };
  inst.parse = (data, params2) => parse3(inst, data, params2, { callee: inst.parse });
  inst.safeParse = (data, params2) => safeParse2(inst, data, params2);
  inst.parseAsync = async (data, params2) => parseAsync2(inst, data, params2, { callee: inst.parseAsync });
  inst.safeParseAsync = async (data, params2) => safeParseAsync2(inst, data, params2);
  inst.spa = inst.safeParseAsync;
  inst.encode = (data, params2) => encode2(inst, data, params2);
  inst.decode = (data, params2) => decode2(inst, data, params2);
  inst.encodeAsync = async (data, params2) => encodeAsync2(inst, data, params2);
  inst.decodeAsync = async (data, params2) => decodeAsync2(inst, data, params2);
  inst.safeEncode = (data, params2) => safeEncode2(inst, data, params2);
  inst.safeDecode = (data, params2) => safeDecode2(inst, data, params2);
  inst.safeEncodeAsync = async (data, params2) => safeEncodeAsync2(inst, data, params2);
  inst.safeDecodeAsync = async (data, params2) => safeDecodeAsync2(inst, data, params2);
  inst.refine = (check, params2) => inst.check(refine(check, params2));
  inst.superRefine = (refinement) => inst.check(superRefine(refinement));
  inst.overwrite = (fn) => inst.check(_overwrite(fn));
  inst.optional = () => optional(inst);
  inst.exactOptional = () => exactOptional(inst);
  inst.nullable = () => nullable(inst);
  inst.nullish = () => optional(nullable(inst));
  inst.nonoptional = (params2) => nonoptional(inst, params2);
  inst.array = () => array2(inst);
  inst.or = (arg) => union([inst, arg]);
  inst.and = (arg) => intersection(inst, arg);
  inst.transform = (tx) => pipe(inst, transform(tx));
  inst.default = (def2) => _default2(inst, def2);
  inst.prefault = (def2) => prefault(inst, def2);
  inst.catch = (params2) => _catch2(inst, params2);
  inst.pipe = (target) => pipe(inst, target);
  inst.readonly = () => readonly(inst);
  inst.describe = (description) => {
    const cl = inst.clone();
    globalRegistry.add(cl, { description });
    return cl;
  };
  Object.defineProperty(inst, "description", {
    get() {
      return globalRegistry.get(inst)?.description;
    },
    configurable: true
  });
  inst.meta = (...args2) => {
    if (args2.length === 0) {
      return globalRegistry.get(inst);
    }
    const cl = inst.clone();
    globalRegistry.add(cl, args2[0]);
    return cl;
  };
  inst.isOptional = () => inst.safeParse(undefined).success;
  inst.isNullable = () => inst.safeParse(null).success;
  inst.apply = (fn) => fn(inst);
  return inst;
});
var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
  $ZodString.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => stringProcessor(inst, ctx, json, params2);
  const bag = inst._zod.bag;
  inst.format = bag.format ?? null;
  inst.minLength = bag.minimum ?? null;
  inst.maxLength = bag.maximum ?? null;
  inst.regex = (...args2) => inst.check(_regex(...args2));
  inst.includes = (...args2) => inst.check(_includes(...args2));
  inst.startsWith = (...args2) => inst.check(_startsWith(...args2));
  inst.endsWith = (...args2) => inst.check(_endsWith(...args2));
  inst.min = (...args2) => inst.check(_minLength(...args2));
  inst.max = (...args2) => inst.check(_maxLength(...args2));
  inst.length = (...args2) => inst.check(_length(...args2));
  inst.nonempty = (...args2) => inst.check(_minLength(1, ...args2));
  inst.lowercase = (params2) => inst.check(_lowercase(params2));
  inst.uppercase = (params2) => inst.check(_uppercase(params2));
  inst.trim = () => inst.check(_trim());
  inst.normalize = (...args2) => inst.check(_normalize(...args2));
  inst.toLowerCase = () => inst.check(_toLowerCase());
  inst.toUpperCase = () => inst.check(_toUpperCase());
  inst.slugify = () => inst.check(_slugify());
});
var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
  $ZodString.init(inst, def);
  _ZodString.init(inst, def);
  inst.email = (params2) => inst.check(_email(ZodEmail, params2));
  inst.url = (params2) => inst.check(_url(ZodURL, params2));
  inst.jwt = (params2) => inst.check(_jwt(ZodJWT, params2));
  inst.emoji = (params2) => inst.check(_emoji2(ZodEmoji, params2));
  inst.guid = (params2) => inst.check(_guid(ZodGUID, params2));
  inst.uuid = (params2) => inst.check(_uuid(ZodUUID, params2));
  inst.uuidv4 = (params2) => inst.check(_uuidv4(ZodUUID, params2));
  inst.uuidv6 = (params2) => inst.check(_uuidv6(ZodUUID, params2));
  inst.uuidv7 = (params2) => inst.check(_uuidv7(ZodUUID, params2));
  inst.nanoid = (params2) => inst.check(_nanoid(ZodNanoID, params2));
  inst.guid = (params2) => inst.check(_guid(ZodGUID, params2));
  inst.cuid = (params2) => inst.check(_cuid(ZodCUID, params2));
  inst.cuid2 = (params2) => inst.check(_cuid2(ZodCUID2, params2));
  inst.ulid = (params2) => inst.check(_ulid(ZodULID, params2));
  inst.base64 = (params2) => inst.check(_base64(ZodBase64, params2));
  inst.base64url = (params2) => inst.check(_base64url(ZodBase64URL, params2));
  inst.xid = (params2) => inst.check(_xid(ZodXID, params2));
  inst.ksuid = (params2) => inst.check(_ksuid(ZodKSUID, params2));
  inst.ipv4 = (params2) => inst.check(_ipv4(ZodIPv4, params2));
  inst.ipv6 = (params2) => inst.check(_ipv6(ZodIPv6, params2));
  inst.cidrv4 = (params2) => inst.check(_cidrv4(ZodCIDRv4, params2));
  inst.cidrv6 = (params2) => inst.check(_cidrv6(ZodCIDRv6, params2));
  inst.e164 = (params2) => inst.check(_e164(ZodE164, params2));
  inst.datetime = (params2) => inst.check(datetime2(params2));
  inst.date = (params2) => inst.check(date2(params2));
  inst.time = (params2) => inst.check(time2(params2));
  inst.duration = (params2) => inst.check(duration2(params2));
});
function string2(params2) {
  return _string(ZodString, params2);
}
var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  _ZodString.init(inst, def);
});
var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
  $ZodEmail.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function email2(params2) {
  return _email(ZodEmail, params2);
}
var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
  $ZodGUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function guid2(params2) {
  return _guid(ZodGUID, params2);
}
var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
  $ZodUUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function uuid2(params2) {
  return _uuid(ZodUUID, params2);
}
function uuidv42(params2) {
  return _uuidv4(ZodUUID, params2);
}
function uuidv6(params2) {
  return _uuidv6(ZodUUID, params2);
}
function uuidv7(params2) {
  return _uuidv7(ZodUUID, params2);
}
var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
  $ZodURL.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function url(params2) {
  return _url(ZodURL, params2);
}
function httpUrl(params2) {
  return _url(ZodURL, {
    protocol: /^https?$/,
    hostname: exports_regexes.domain,
    ...exports_util.normalizeParams(params2)
  });
}
var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
  $ZodEmoji.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function emoji2(params2) {
  return _emoji2(ZodEmoji, params2);
}
var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
  $ZodNanoID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function nanoid2(params2) {
  return _nanoid(ZodNanoID, params2);
}
var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
  $ZodCUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function cuid3(params2) {
  return _cuid(ZodCUID, params2);
}
var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
  $ZodCUID2.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function cuid22(params2) {
  return _cuid2(ZodCUID2, params2);
}
var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
  $ZodULID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function ulid2(params2) {
  return _ulid(ZodULID, params2);
}
var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
  $ZodXID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function xid2(params2) {
  return _xid(ZodXID, params2);
}
var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
  $ZodKSUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function ksuid2(params2) {
  return _ksuid(ZodKSUID, params2);
}
var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
  $ZodIPv4.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function ipv42(params2) {
  return _ipv4(ZodIPv4, params2);
}
var ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def) => {
  $ZodMAC.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function mac2(params2) {
  return _mac(ZodMAC, params2);
}
var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
  $ZodIPv6.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function ipv62(params2) {
  return _ipv6(ZodIPv6, params2);
}
var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
  $ZodCIDRv4.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function cidrv42(params2) {
  return _cidrv4(ZodCIDRv4, params2);
}
var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
  $ZodCIDRv6.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function cidrv62(params2) {
  return _cidrv6(ZodCIDRv6, params2);
}
var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
  $ZodBase64.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function base642(params2) {
  return _base64(ZodBase64, params2);
}
var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
  $ZodBase64URL.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function base64url2(params2) {
  return _base64url(ZodBase64URL, params2);
}
var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
  $ZodE164.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function e1642(params2) {
  return _e164(ZodE164, params2);
}
var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
  $ZodJWT.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function jwt(params2) {
  return _jwt(ZodJWT, params2);
}
var ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => {
  $ZodCustomStringFormat.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function stringFormat(format2, fnOrRegex, _params = {}) {
  return _stringFormat(ZodCustomStringFormat, format2, fnOrRegex, _params);
}
function hostname2(_params) {
  return _stringFormat(ZodCustomStringFormat, "hostname", exports_regexes.hostname, _params);
}
function hex3(_params) {
  return _stringFormat(ZodCustomStringFormat, "hex", exports_regexes.hex, _params);
}
function hash(alg, params2) {
  const enc = params2?.enc ?? "hex";
  const format2 = `${alg}_${enc}`;
  const regex = exports_regexes[format2];
  if (!regex)
    throw new Error(`Unrecognized hash format: ${format2}`);
  return _stringFormat(ZodCustomStringFormat, format2, regex, params2);
}
var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
  $ZodNumber.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => numberProcessor(inst, ctx, json, params2);
  inst.gt = (value, params2) => inst.check(_gt(value, params2));
  inst.gte = (value, params2) => inst.check(_gte(value, params2));
  inst.min = (value, params2) => inst.check(_gte(value, params2));
  inst.lt = (value, params2) => inst.check(_lt(value, params2));
  inst.lte = (value, params2) => inst.check(_lte(value, params2));
  inst.max = (value, params2) => inst.check(_lte(value, params2));
  inst.int = (params2) => inst.check(int(params2));
  inst.safe = (params2) => inst.check(int(params2));
  inst.positive = (params2) => inst.check(_gt(0, params2));
  inst.nonnegative = (params2) => inst.check(_gte(0, params2));
  inst.negative = (params2) => inst.check(_lt(0, params2));
  inst.nonpositive = (params2) => inst.check(_lte(0, params2));
  inst.multipleOf = (value, params2) => inst.check(_multipleOf(value, params2));
  inst.step = (value, params2) => inst.check(_multipleOf(value, params2));
  inst.finite = () => inst;
  const bag = inst._zod.bag;
  inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
  inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
  inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);
  inst.isFinite = true;
  inst.format = bag.format ?? null;
});
function number4(params2) {
  return _number(ZodNumber, params2);
}
var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
  $ZodNumberFormat.init(inst, def);
  ZodNumber.init(inst, def);
});
function int(params2) {
  return _int(ZodNumberFormat, params2);
}
function float32(params2) {
  return _float32(ZodNumberFormat, params2);
}
function float64(params2) {
  return _float64(ZodNumberFormat, params2);
}
function int32(params2) {
  return _int32(ZodNumberFormat, params2);
}
function uint322(params2) {
  return _uint32(ZodNumberFormat, params2);
}
var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {
  $ZodBoolean.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => booleanProcessor(inst, ctx, json, params2);
});
function boolean2(params2) {
  return _boolean(ZodBoolean, params2);
}
var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => {
  $ZodBigInt.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => bigintProcessor(inst, ctx, json, params2);
  inst.gte = (value, params2) => inst.check(_gte(value, params2));
  inst.min = (value, params2) => inst.check(_gte(value, params2));
  inst.gt = (value, params2) => inst.check(_gt(value, params2));
  inst.gte = (value, params2) => inst.check(_gte(value, params2));
  inst.min = (value, params2) => inst.check(_gte(value, params2));
  inst.lt = (value, params2) => inst.check(_lt(value, params2));
  inst.lte = (value, params2) => inst.check(_lte(value, params2));
  inst.max = (value, params2) => inst.check(_lte(value, params2));
  inst.positive = (params2) => inst.check(_gt(BigInt(0), params2));
  inst.negative = (params2) => inst.check(_lt(BigInt(0), params2));
  inst.nonpositive = (params2) => inst.check(_lte(BigInt(0), params2));
  inst.nonnegative = (params2) => inst.check(_gte(BigInt(0), params2));
  inst.multipleOf = (value, params2) => inst.check(_multipleOf(value, params2));
  const bag = inst._zod.bag;
  inst.minValue = bag.minimum ?? null;
  inst.maxValue = bag.maximum ?? null;
  inst.format = bag.format ?? null;
});
function bigint2(params2) {
  return _bigint(ZodBigInt, params2);
}
var ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => {
  $ZodBigIntFormat.init(inst, def);
  ZodBigInt.init(inst, def);
});
function int64(params2) {
  return _int64(ZodBigIntFormat, params2);
}
function uint64(params2) {
  return _uint64(ZodBigIntFormat, params2);
}
var ZodSymbol = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => {
  $ZodSymbol.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => symbolProcessor(inst, ctx, json, params2);
});
function symbol2(params2) {
  return _symbol(ZodSymbol, params2);
}
var ZodUndefined = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => {
  $ZodUndefined.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => undefinedProcessor(inst, ctx, json, params2);
});
function _undefined3(params2) {
  return _undefined2(ZodUndefined, params2);
}
var ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => {
  $ZodNull.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => nullProcessor(inst, ctx, json, params2);
});
function _null3(params2) {
  return _null2(ZodNull, params2);
}
var ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => {
  $ZodAny.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => anyProcessor(inst, ctx, json, params2);
});
function any2() {
  return _any(ZodAny);
}
var ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
  $ZodUnknown.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => unknownProcessor(inst, ctx, json, params2);
});
function unknown() {
  return _unknown(ZodUnknown);
}
var ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
  $ZodNever.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => neverProcessor(inst, ctx, json, params2);
});
function never(params2) {
  return _never(ZodNever, params2);
}
var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => {
  $ZodVoid.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => voidProcessor(inst, ctx, json, params2);
});
function _void2(params2) {
  return _void(ZodVoid, params2);
}
var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => {
  $ZodDate.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => dateProcessor(inst, ctx, json, params2);
  inst.min = (value, params2) => inst.check(_gte(value, params2));
  inst.max = (value, params2) => inst.check(_lte(value, params2));
  const c = inst._zod.bag;
  inst.minDate = c.minimum ? new Date(c.minimum) : null;
  inst.maxDate = c.maximum ? new Date(c.maximum) : null;
});
function date3(params2) {
  return _date(ZodDate, params2);
}
var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
  $ZodArray.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => arrayProcessor(inst, ctx, json, params2);
  inst.element = def.element;
  inst.min = (minLength, params2) => inst.check(_minLength(minLength, params2));
  inst.nonempty = (params2) => inst.check(_minLength(1, params2));
  inst.max = (maxLength, params2) => inst.check(_maxLength(maxLength, params2));
  inst.length = (len, params2) => inst.check(_length(len, params2));
  inst.unwrap = () => inst.element;
});
function array2(element, params2) {
  return _array(ZodArray, element, params2);
}
function keyof2(schema) {
  const shape2 = schema._zod.def.shape;
  return _enum2(Object.keys(shape2));
}
var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
  $ZodObjectJIT.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => objectProcessor(inst, ctx, json, params2);
  exports_util.defineLazy(inst, "shape", () => {
    return def.shape;
  });
  inst.keyof = () => _enum2(Object.keys(inst._zod.def.shape));
  inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall });
  inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
  inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
  inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });
  inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });
  inst.extend = (incoming) => {
    return exports_util.extend(inst, incoming);
  };
  inst.safeExtend = (incoming) => {
    return exports_util.safeExtend(inst, incoming);
  };
  inst.merge = (other) => exports_util.merge(inst, other);
  inst.pick = (mask) => exports_util.pick(inst, mask);
  inst.omit = (mask) => exports_util.omit(inst, mask);
  inst.partial = (...args2) => exports_util.partial(ZodOptional, inst, args2[0]);
  inst.required = (...args2) => exports_util.required(ZodNonOptional, inst, args2[0]);
});
function object(shape2, params2) {
  const def = {
    type: "object",
    shape: shape2 ?? {},
    ...exports_util.normalizeParams(params2)
  };
  return new ZodObject(def);
}
function strictObject(shape2, params2) {
  return new ZodObject({
    type: "object",
    shape: shape2,
    catchall: never(),
    ...exports_util.normalizeParams(params2)
  });
}
function looseObject(shape2, params2) {
  return new ZodObject({
    type: "object",
    shape: shape2,
    catchall: unknown(),
    ...exports_util.normalizeParams(params2)
  });
}
var ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
  $ZodUnion.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => unionProcessor(inst, ctx, json, params2);
  inst.options = def.options;
});
function union(options, params2) {
  return new ZodUnion({
    type: "union",
    options,
    ...exports_util.normalizeParams(params2)
  });
}
var ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => {
  ZodUnion.init(inst, def);
  $ZodXor.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => unionProcessor(inst, ctx, json, params2);
  inst.options = def.options;
});
function xor(options, params2) {
  return new ZodXor({
    type: "union",
    options,
    inclusive: false,
    ...exports_util.normalizeParams(params2)
  });
}
var ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => {
  ZodUnion.init(inst, def);
  $ZodDiscriminatedUnion.init(inst, def);
});
function discriminatedUnion(discriminator, options, params2) {
  return new ZodDiscriminatedUnion({
    type: "union",
    options,
    discriminator,
    ...exports_util.normalizeParams(params2)
  });
}
var ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
  $ZodIntersection.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => intersectionProcessor(inst, ctx, json, params2);
});
function intersection(left, right) {
  return new ZodIntersection({
    type: "intersection",
    left,
    right
  });
}
var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => {
  $ZodTuple.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => tupleProcessor(inst, ctx, json, params2);
  inst.rest = (rest) => inst.clone({
    ...inst._zod.def,
    rest
  });
});
function tuple(items, _paramsOrRest, _params) {
  const hasRest = _paramsOrRest instanceof $ZodType;
  const params2 = hasRest ? _params : _paramsOrRest;
  const rest = hasRest ? _paramsOrRest : null;
  return new ZodTuple({
    type: "tuple",
    items,
    rest,
    ...exports_util.normalizeParams(params2)
  });
}
var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
  $ZodRecord.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => recordProcessor(inst, ctx, json, params2);
  inst.keyType = def.keyType;
  inst.valueType = def.valueType;
});
function record(keyType, valueType, params2) {
  return new ZodRecord({
    type: "record",
    keyType,
    valueType,
    ...exports_util.normalizeParams(params2)
  });
}
function partialRecord(keyType, valueType, params2) {
  const k = clone(keyType);
  k._zod.values = undefined;
  return new ZodRecord({
    type: "record",
    keyType: k,
    valueType,
    ...exports_util.normalizeParams(params2)
  });
}
function looseRecord(keyType, valueType, params2) {
  return new ZodRecord({
    type: "record",
    keyType,
    valueType,
    mode: "loose",
    ...exports_util.normalizeParams(params2)
  });
}
var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => {
  $ZodMap.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => mapProcessor(inst, ctx, json, params2);
  inst.keyType = def.keyType;
  inst.valueType = def.valueType;
  inst.min = (...args2) => inst.check(_minSize(...args2));
  inst.nonempty = (params2) => inst.check(_minSize(1, params2));
  inst.max = (...args2) => inst.check(_maxSize(...args2));
  inst.size = (...args2) => inst.check(_size(...args2));
});
function map3(keyType, valueType, params2) {
  return new ZodMap({
    type: "map",
    keyType,
    valueType,
    ...exports_util.normalizeParams(params2)
  });
}
var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => {
  $ZodSet.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => setProcessor(inst, ctx, json, params2);
  inst.min = (...args2) => inst.check(_minSize(...args2));
  inst.nonempty = (params2) => inst.check(_minSize(1, params2));
  inst.max = (...args2) => inst.check(_maxSize(...args2));
  inst.size = (...args2) => inst.check(_size(...args2));
});
function set(valueType, params2) {
  return new ZodSet({
    type: "set",
    valueType,
    ...exports_util.normalizeParams(params2)
  });
}
var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
  $ZodEnum.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => enumProcessor(inst, ctx, json, params2);
  inst.enum = def.entries;
  inst.options = Object.values(def.entries);
  const keys2 = new Set(Object.keys(def.entries));
  inst.extract = (values, params2) => {
    const newEntries = {};
    for (const value of values) {
      if (keys2.has(value)) {
        newEntries[value] = def.entries[value];
      } else
        throw new Error(`Key ${value} not found in enum`);
    }
    return new ZodEnum({
      ...def,
      checks: [],
      ...exports_util.normalizeParams(params2),
      entries: newEntries
    });
  };
  inst.exclude = (values, params2) => {
    const newEntries = { ...def.entries };
    for (const value of values) {
      if (keys2.has(value)) {
        delete newEntries[value];
      } else
        throw new Error(`Key ${value} not found in enum`);
    }
    return new ZodEnum({
      ...def,
      checks: [],
      ...exports_util.normalizeParams(params2),
      entries: newEntries
    });
  };
});
function _enum2(values, params2) {
  const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
  return new ZodEnum({
    type: "enum",
    entries,
    ...exports_util.normalizeParams(params2)
  });
}
function nativeEnum(entries, params2) {
  return new ZodEnum({
    type: "enum",
    entries,
    ...exports_util.normalizeParams(params2)
  });
}
var ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
  $ZodLiteral.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => literalProcessor(inst, ctx, json, params2);
  inst.values = new Set(def.values);
  Object.defineProperty(inst, "value", {
    get() {
      if (def.values.length > 1) {
        throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
      }
      return def.values[0];
    }
  });
});
function literal(value, params2) {
  return new ZodLiteral({
    type: "literal",
    values: Array.isArray(value) ? value : [value],
    ...exports_util.normalizeParams(params2)
  });
}
var ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => {
  $ZodFile.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => fileProcessor(inst, ctx, json, params2);
  inst.min = (size2, params2) => inst.check(_minSize(size2, params2));
  inst.max = (size2, params2) => inst.check(_maxSize(size2, params2));
  inst.mime = (types, params2) => inst.check(_mime(Array.isArray(types) ? types : [types], params2));
});
function file(params2) {
  return _file(ZodFile, params2);
}
var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
  $ZodTransform.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => transformProcessor(inst, ctx, json, params2);
  inst._zod.parse = (payload, _ctx) => {
    if (_ctx.direction === "backward") {
      throw new $ZodEncodeError(inst.constructor.name);
    }
    payload.addIssue = (issue2) => {
      if (typeof issue2 === "string") {
        payload.issues.push(exports_util.issue(issue2, payload.value, def));
      } else {
        const _issue = issue2;
        if (_issue.fatal)
          _issue.continue = false;
        _issue.code ?? (_issue.code = "custom");
        _issue.input ?? (_issue.input = payload.value);
        _issue.inst ?? (_issue.inst = inst);
        payload.issues.push(exports_util.issue(_issue));
      }
    };
    const output = def.transform(payload.value, payload);
    if (output instanceof Promise) {
      return output.then((output2) => {
        payload.value = output2;
        return payload;
      });
    }
    payload.value = output;
    return payload;
  };
});
function transform(fn) {
  return new ZodTransform({
    type: "transform",
    transform: fn
  });
}
var ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
  $ZodOptional.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => optionalProcessor(inst, ctx, json, params2);
  inst.unwrap = () => inst._zod.def.innerType;
});
function optional(innerType) {
  return new ZodOptional({
    type: "optional",
    innerType
  });
}
var ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => {
  $ZodExactOptional.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => optionalProcessor(inst, ctx, json, params2);
  inst.unwrap = () => inst._zod.def.innerType;
});
function exactOptional(innerType) {
  return new ZodExactOptional({
    type: "optional",
    innerType
  });
}
var ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
  $ZodNullable.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => nullableProcessor(inst, ctx, json, params2);
  inst.unwrap = () => inst._zod.def.innerType;
});
function nullable(innerType) {
  return new ZodNullable({
    type: "nullable",
    innerType
  });
}
function nullish2(innerType) {
  return optional(nullable(innerType));
}
var ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
  $ZodDefault.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => defaultProcessor(inst, ctx, json, params2);
  inst.unwrap = () => inst._zod.def.innerType;
  inst.removeDefault = inst.unwrap;
});
function _default2(innerType, defaultValue) {
  return new ZodDefault({
    type: "default",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : exports_util.shallowClone(defaultValue);
    }
  });
}
var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
  $ZodPrefault.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => prefaultProcessor(inst, ctx, json, params2);
  inst.unwrap = () => inst._zod.def.innerType;
});
function prefault(innerType, defaultValue) {
  return new ZodPrefault({
    type: "prefault",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : exports_util.shallowClone(defaultValue);
    }
  });
}
var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
  $ZodNonOptional.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => nonoptionalProcessor(inst, ctx, json, params2);
  inst.unwrap = () => inst._zod.def.innerType;
});
function nonoptional(innerType, params2) {
  return new ZodNonOptional({
    type: "nonoptional",
    innerType,
    ...exports_util.normalizeParams(params2)
  });
}
var ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => {
  $ZodSuccess.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => successProcessor(inst, ctx, json, params2);
  inst.unwrap = () => inst._zod.def.innerType;
});
function success(innerType) {
  return new ZodSuccess({
    type: "success",
    innerType
  });
}
var ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
  $ZodCatch.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => catchProcessor(inst, ctx, json, params2);
  inst.unwrap = () => inst._zod.def.innerType;
  inst.removeCatch = inst.unwrap;
});
function _catch2(innerType, catchValue) {
  return new ZodCatch({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => {
  $ZodNaN.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => nanProcessor(inst, ctx, json, params2);
});
function nan(params2) {
  return _nan(ZodNaN, params2);
}
var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
  $ZodPipe.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => pipeProcessor(inst, ctx, json, params2);
  inst.in = def.in;
  inst.out = def.out;
});
function pipe(in_, out) {
  return new ZodPipe({
    type: "pipe",
    in: in_,
    out
  });
}
var ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => {
  ZodPipe.init(inst, def);
  $ZodCodec.init(inst, def);
});
function codec(in_, out, params2) {
  return new ZodCodec({
    type: "pipe",
    in: in_,
    out,
    transform: params2.decode,
    reverseTransform: params2.encode
  });
}
var ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
  $ZodReadonly.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => readonlyProcessor(inst, ctx, json, params2);
  inst.unwrap = () => inst._zod.def.innerType;
});
function readonly(innerType) {
  return new ZodReadonly({
    type: "readonly",
    innerType
  });
}
var ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => {
  $ZodTemplateLiteral.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => templateLiteralProcessor(inst, ctx, json, params2);
});
function templateLiteral(parts, params2) {
  return new ZodTemplateLiteral({
    type: "template_literal",
    parts,
    ...exports_util.normalizeParams(params2)
  });
}
var ZodLazy = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => {
  $ZodLazy.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => lazyProcessor(inst, ctx, json, params2);
  inst.unwrap = () => inst._zod.def.getter();
});
function lazy(getter) {
  return new ZodLazy({
    type: "lazy",
    getter
  });
}
var ZodPromise = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => {
  $ZodPromise.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => promiseProcessor(inst, ctx, json, params2);
  inst.unwrap = () => inst._zod.def.innerType;
});
function promise(innerType) {
  return new ZodPromise({
    type: "promise",
    innerType
  });
}
var ZodFunction = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => {
  $ZodFunction.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => functionProcessor(inst, ctx, json, params2);
});
function _function(params2) {
  return new ZodFunction({
    type: "function",
    input: Array.isArray(params2?.input) ? tuple(params2?.input) : params2?.input ?? array2(unknown()),
    output: params2?.output ?? unknown()
  });
}
var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
  $ZodCustom.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params2) => customProcessor(inst, ctx, json, params2);
});
function check(fn) {
  const ch = new $ZodCheck({
    check: "custom"
  });
  ch._zod.check = fn;
  return ch;
}
function custom2(fn, _params) {
  return _custom(ZodCustom, fn ?? (() => true), _params);
}
function refine(fn, _params = {}) {
  return _refine(ZodCustom, fn, _params);
}
function superRefine(fn) {
  return _superRefine(fn);
}
var describe2 = describe;
var meta2 = meta;
function _instanceof(cls, params2 = {}) {
  const inst = new ZodCustom({
    type: "custom",
    check: "custom",
    fn: (data) => data instanceof cls,
    abort: true,
    ...exports_util.normalizeParams(params2)
  });
  inst._zod.bag.Class = cls;
  inst._zod.check = (payload) => {
    if (!(payload.value instanceof cls)) {
      payload.issues.push({
        code: "invalid_type",
        expected: cls.name,
        input: payload.value,
        inst,
        path: [...inst._zod.def.path ?? []]
      });
    }
  };
  return inst;
}
var stringbool = (...args2) => _stringbool({
  Codec: ZodCodec,
  Boolean: ZodBoolean,
  String: ZodString
}, ...args2);
function json(params2) {
  const jsonSchema = lazy(() => {
    return union([string2(params2), number4(), boolean2(), _null3(), array2(jsonSchema), record(string2(), jsonSchema)]);
  });
  return jsonSchema;
}
function preprocess(fn, schema) {
  return pipe(transform(fn), schema);
}
// node_modules/zod/v4/classic/compat.js
var ZodIssueCode = {
  invalid_type: "invalid_type",
  too_big: "too_big",
  too_small: "too_small",
  invalid_format: "invalid_format",
  not_multiple_of: "not_multiple_of",
  unrecognized_keys: "unrecognized_keys",
  invalid_union: "invalid_union",
  invalid_key: "invalid_key",
  invalid_element: "invalid_element",
  invalid_value: "invalid_value",
  custom: "custom"
};
function setErrorMap(map4) {
  config({
    customError: map4
  });
}
function getErrorMap() {
  return config().customError;
}
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind2) {})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
// node_modules/zod/v4/classic/from-json-schema.js
var z = {
  ...exports_schemas2,
  ...exports_checks2,
  iso: exports_iso
};
var RECOGNIZED_KEYS = new Set([
  "$schema",
  "$ref",
  "$defs",
  "definitions",
  "$id",
  "id",
  "$comment",
  "$anchor",
  "$vocabulary",
  "$dynamicRef",
  "$dynamicAnchor",
  "type",
  "enum",
  "const",
  "anyOf",
  "oneOf",
  "allOf",
  "not",
  "properties",
  "required",
  "additionalProperties",
  "patternProperties",
  "propertyNames",
  "minProperties",
  "maxProperties",
  "items",
  "prefixItems",
  "additionalItems",
  "minItems",
  "maxItems",
  "uniqueItems",
  "contains",
  "minContains",
  "maxContains",
  "minLength",
  "maxLength",
  "pattern",
  "format",
  "minimum",
  "maximum",
  "exclusiveMinimum",
  "exclusiveMaximum",
  "multipleOf",
  "description",
  "default",
  "contentEncoding",
  "contentMediaType",
  "contentSchema",
  "unevaluatedItems",
  "unevaluatedProperties",
  "if",
  "then",
  "else",
  "dependentSchemas",
  "dependentRequired",
  "nullable",
  "readOnly"
]);
function detectVersion(schema, defaultTarget) {
  const $schema = schema.$schema;
  if ($schema === "https://json-schema.org/draft/2020-12/schema") {
    return "draft-2020-12";
  }
  if ($schema === "http://json-schema.org/draft-07/schema#") {
    return "draft-7";
  }
  if ($schema === "http://json-schema.org/draft-04/schema#") {
    return "draft-4";
  }
  return defaultTarget ?? "draft-2020-12";
}
function resolveRef(ref, ctx) {
  if (!ref.startsWith("#")) {
    throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
  }
  const path3 = ref.slice(1).split("/").filter(Boolean);
  if (path3.length === 0) {
    return ctx.rootSchema;
  }
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
  if (path3[0] === defsKey) {
    const key = path3[1];
    if (!key || !ctx.defs[key]) {
      throw new Error(`Reference not found: ${ref}`);
    }
    return ctx.defs[key];
  }
  throw new Error(`Reference not found: ${ref}`);
}
function convertBaseSchema(schema, ctx) {
  if (schema.not !== undefined) {
    if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) {
      return z.never();
    }
    throw new Error("not is not supported in Zod (except { not: {} } for never)");
  }
  if (schema.unevaluatedItems !== undefined) {
    throw new Error("unevaluatedItems is not supported");
  }
  if (schema.unevaluatedProperties !== undefined) {
    throw new Error("unevaluatedProperties is not supported");
  }
  if (schema.if !== undefined || schema.then !== undefined || schema.else !== undefined) {
    throw new Error("Conditional schemas (if/then/else) are not supported");
  }
  if (schema.dependentSchemas !== undefined || schema.dependentRequired !== undefined) {
    throw new Error("dependentSchemas and dependentRequired are not supported");
  }
  if (schema.$ref) {
    const refPath = schema.$ref;
    if (ctx.refs.has(refPath)) {
      return ctx.refs.get(refPath);
    }
    if (ctx.processing.has(refPath)) {
      return z.lazy(() => {
        if (!ctx.refs.has(refPath)) {
          throw new Error(`Circular reference not resolved: ${refPath}`);
        }
        return ctx.refs.get(refPath);
      });
    }
    ctx.processing.add(refPath);
    const resolved = resolveRef(refPath, ctx);
    const zodSchema2 = convertSchema(resolved, ctx);
    ctx.refs.set(refPath, zodSchema2);
    ctx.processing.delete(refPath);
    return zodSchema2;
  }
  if (schema.enum !== undefined) {
    const enumValues = schema.enum;
    if (ctx.version === "openapi-3.0" && schema.nullable === true && enumValues.length === 1 && enumValues[0] === null) {
      return z.null();
    }
    if (enumValues.length === 0) {
      return z.never();
    }
    if (enumValues.length === 1) {
      return z.literal(enumValues[0]);
    }
    if (enumValues.every((v) => typeof v === "string")) {
      return z.enum(enumValues);
    }
    const literalSchemas = enumValues.map((v) => z.literal(v));
    if (literalSchemas.length < 2) {
      return literalSchemas[0];
    }
    return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]);
  }
  if (schema.const !== undefined) {
    return z.literal(schema.const);
  }
  const type = schema.type;
  if (Array.isArray(type)) {
    const typeSchemas = type.map((t) => {
      const typeSchema = { ...schema, type: t };
      return convertBaseSchema(typeSchema, ctx);
    });
    if (typeSchemas.length === 0) {
      return z.never();
    }
    if (typeSchemas.length === 1) {
      return typeSchemas[0];
    }
    return z.union(typeSchemas);
  }
  if (!type) {
    return z.any();
  }
  let zodSchema;
  switch (type) {
    case "string": {
      let stringSchema = z.string();
      if (schema.format) {
        const format2 = schema.format;
        if (format2 === "email") {
          stringSchema = stringSchema.check(z.email());
        } else if (format2 === "uri" || format2 === "uri-reference") {
          stringSchema = stringSchema.check(z.url());
        } else if (format2 === "uuid" || format2 === "guid") {
          stringSchema = stringSchema.check(z.uuid());
        } else if (format2 === "date-time") {
          stringSchema = stringSchema.check(z.iso.datetime());
        } else if (format2 === "date") {
          stringSchema = stringSchema.check(z.iso.date());
        } else if (format2 === "time") {
          stringSchema = stringSchema.check(z.iso.time());
        } else if (format2 === "duration") {
          stringSchema = stringSchema.check(z.iso.duration());
        } else if (format2 === "ipv4") {
          stringSchema = stringSchema.check(z.ipv4());
        } else if (format2 === "ipv6") {
          stringSchema = stringSchema.check(z.ipv6());
        } else if (format2 === "mac") {
          stringSchema = stringSchema.check(z.mac());
        } else if (format2 === "cidr") {
          stringSchema = stringSchema.check(z.cidrv4());
        } else if (format2 === "cidr-v6") {
          stringSchema = stringSchema.check(z.cidrv6());
        } else if (format2 === "base64") {
          stringSchema = stringSchema.check(z.base64());
        } else if (format2 === "base64url") {
          stringSchema = stringSchema.check(z.base64url());
        } else if (format2 === "e164") {
          stringSchema = stringSchema.check(z.e164());
        } else if (format2 === "jwt") {
          stringSchema = stringSchema.check(z.jwt());
        } else if (format2 === "emoji") {
          stringSchema = stringSchema.check(z.emoji());
        } else if (format2 === "nanoid") {
          stringSchema = stringSchema.check(z.nanoid());
        } else if (format2 === "cuid") {
          stringSchema = stringSchema.check(z.cuid());
        } else if (format2 === "cuid2") {
          stringSchema = stringSchema.check(z.cuid2());
        } else if (format2 === "ulid") {
          stringSchema = stringSchema.check(z.ulid());
        } else if (format2 === "xid") {
          stringSchema = stringSchema.check(z.xid());
        } else if (format2 === "ksuid") {
          stringSchema = stringSchema.check(z.ksuid());
        }
      }
      if (typeof schema.minLength === "number") {
        stringSchema = stringSchema.min(schema.minLength);
      }
      if (typeof schema.maxLength === "number") {
        stringSchema = stringSchema.max(schema.maxLength);
      }
      if (schema.pattern) {
        stringSchema = stringSchema.regex(new RegExp(schema.pattern));
      }
      zodSchema = stringSchema;
      break;
    }
    case "number":
    case "integer": {
      let numberSchema = type === "integer" ? z.number().int() : z.number();
      if (typeof schema.minimum === "number") {
        numberSchema = numberSchema.min(schema.minimum);
      }
      if (typeof schema.maximum === "number") {
        numberSchema = numberSchema.max(schema.maximum);
      }
      if (typeof schema.exclusiveMinimum === "number") {
        numberSchema = numberSchema.gt(schema.exclusiveMinimum);
      } else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") {
        numberSchema = numberSchema.gt(schema.minimum);
      }
      if (typeof schema.exclusiveMaximum === "number") {
        numberSchema = numberSchema.lt(schema.exclusiveMaximum);
      } else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") {
        numberSchema = numberSchema.lt(schema.maximum);
      }
      if (typeof schema.multipleOf === "number") {
        numberSchema = numberSchema.multipleOf(schema.multipleOf);
      }
      zodSchema = numberSchema;
      break;
    }
    case "boolean": {
      zodSchema = z.boolean();
      break;
    }
    case "null": {
      zodSchema = z.null();
      break;
    }
    case "object": {
      const shape2 = {};
      const properties = schema.properties || {};
      const requiredSet = new Set(schema.required || []);
      for (const [key, propSchema] of Object.entries(properties)) {
        const propZodSchema = convertSchema(propSchema, ctx);
        shape2[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional();
      }
      if (schema.propertyNames) {
        const keySchema = convertSchema(schema.propertyNames, ctx);
        const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any();
        if (Object.keys(shape2).length === 0) {
          zodSchema = z.record(keySchema, valueSchema);
          break;
        }
        const objectSchema2 = z.object(shape2).passthrough();
        const recordSchema = z.looseRecord(keySchema, valueSchema);
        zodSchema = z.intersection(objectSchema2, recordSchema);
        break;
      }
      if (schema.patternProperties) {
        const patternProps = schema.patternProperties;
        const patternKeys = Object.keys(patternProps);
        const looseRecords = [];
        for (const pattern of patternKeys) {
          const patternValue = convertSchema(patternProps[pattern], ctx);
          const keySchema = z.string().regex(new RegExp(pattern));
          looseRecords.push(z.looseRecord(keySchema, patternValue));
        }
        const schemasToIntersect = [];
        if (Object.keys(shape2).length > 0) {
          schemasToIntersect.push(z.object(shape2).passthrough());
        }
        schemasToIntersect.push(...looseRecords);
        if (schemasToIntersect.length === 0) {
          zodSchema = z.object({}).passthrough();
        } else if (schemasToIntersect.length === 1) {
          zodSchema = schemasToIntersect[0];
        } else {
          let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]);
          for (let i = 2;i < schemasToIntersect.length; i++) {
            result = z.intersection(result, schemasToIntersect[i]);
          }
          zodSchema = result;
        }
        break;
      }
      const objectSchema = z.object(shape2);
      if (schema.additionalProperties === false) {
        zodSchema = objectSchema.strict();
      } else if (typeof schema.additionalProperties === "object") {
        zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx));
      } else {
        zodSchema = objectSchema.passthrough();
      }
      break;
    }
    case "array": {
      const prefixItems = schema.prefixItems;
      const items = schema.items;
      if (prefixItems && Array.isArray(prefixItems)) {
        const tupleItems = prefixItems.map((item) => convertSchema(item, ctx));
        const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : undefined;
        if (rest) {
          zodSchema = z.tuple(tupleItems).rest(rest);
        } else {
          zodSchema = z.tuple(tupleItems);
        }
        if (typeof schema.minItems === "number") {
          zodSchema = zodSchema.check(z.minLength(schema.minItems));
        }
        if (typeof schema.maxItems === "number") {
          zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
        }
      } else if (Array.isArray(items)) {
        const tupleItems = items.map((item) => convertSchema(item, ctx));
        const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : undefined;
        if (rest) {
          zodSchema = z.tuple(tupleItems).rest(rest);
        } else {
          zodSchema = z.tuple(tupleItems);
        }
        if (typeof schema.minItems === "number") {
          zodSchema = zodSchema.check(z.minLength(schema.minItems));
        }
        if (typeof schema.maxItems === "number") {
          zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
        }
      } else if (items !== undefined) {
        const element = convertSchema(items, ctx);
        let arraySchema = z.array(element);
        if (typeof schema.minItems === "number") {
          arraySchema = arraySchema.min(schema.minItems);
        }
        if (typeof schema.maxItems === "number") {
          arraySchema = arraySchema.max(schema.maxItems);
        }
        zodSchema = arraySchema;
      } else {
        zodSchema = z.array(z.any());
      }
      break;
    }
    default:
      throw new Error(`Unsupported type: ${type}`);
  }
  if (schema.description) {
    zodSchema = zodSchema.describe(schema.description);
  }
  if (schema.default !== undefined) {
    zodSchema = zodSchema.default(schema.default);
  }
  return zodSchema;
}
function convertSchema(schema, ctx) {
  if (typeof schema === "boolean") {
    return schema ? z.any() : z.never();
  }
  let baseSchema = convertBaseSchema(schema, ctx);
  const hasExplicitType = schema.type || schema.enum !== undefined || schema.const !== undefined;
  if (schema.anyOf && Array.isArray(schema.anyOf)) {
    const options = schema.anyOf.map((s) => convertSchema(s, ctx));
    const anyOfUnion = z.union(options);
    baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion;
  }
  if (schema.oneOf && Array.isArray(schema.oneOf)) {
    const options = schema.oneOf.map((s) => convertSchema(s, ctx));
    const oneOfUnion = z.xor(options);
    baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion;
  }
  if (schema.allOf && Array.isArray(schema.allOf)) {
    if (schema.allOf.length === 0) {
      baseSchema = hasExplicitType ? baseSchema : z.any();
    } else {
      let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx);
      const startIdx = hasExplicitType ? 0 : 1;
      for (let i = startIdx;i < schema.allOf.length; i++) {
        result = z.intersection(result, convertSchema(schema.allOf[i], ctx));
      }
      baseSchema = result;
    }
  }
  if (schema.nullable === true && ctx.version === "openapi-3.0") {
    baseSchema = z.nullable(baseSchema);
  }
  if (schema.readOnly === true) {
    baseSchema = z.readonly(baseSchema);
  }
  const extraMeta = {};
  const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"];
  for (const key of coreMetadataKeys) {
    if (key in schema) {
      extraMeta[key] = schema[key];
    }
  }
  const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"];
  for (const key of contentMetadataKeys) {
    if (key in schema) {
      extraMeta[key] = schema[key];
    }
  }
  for (const key of Object.keys(schema)) {
    if (!RECOGNIZED_KEYS.has(key)) {
      extraMeta[key] = schema[key];
    }
  }
  if (Object.keys(extraMeta).length > 0) {
    ctx.registry.add(baseSchema, extraMeta);
  }
  return baseSchema;
}
function fromJSONSchema(schema, params2) {
  if (typeof schema === "boolean") {
    return schema ? z.any() : z.never();
  }
  const version2 = detectVersion(schema, params2?.defaultTarget);
  const defs = schema.$defs || schema.definitions || {};
  const ctx = {
    version: version2,
    defs,
    refs: new Map,
    processing: new Set,
    rootSchema: schema,
    registry: params2?.registry ?? globalRegistry
  };
  return convertSchema(schema, ctx);
}
// node_modules/zod/v4/classic/coerce.js
var exports_coerce = {};
__export(exports_coerce, {
  string: () => string3,
  number: () => number5,
  date: () => date4,
  boolean: () => boolean3,
  bigint: () => bigint3
});
function string3(params2) {
  return _coercedString(ZodString, params2);
}
function number5(params2) {
  return _coercedNumber(ZodNumber, params2);
}
function boolean3(params2) {
  return _coercedBoolean(ZodBoolean, params2);
}
function bigint3(params2) {
  return _coercedBigint(ZodBigInt, params2);
}
function date4(params2) {
  return _coercedDate(ZodDate, params2);
}

// node_modules/zod/v4/classic/external.js
config(en_default());
// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/types.js
var definePresentationRecipeScript = (script) => script;

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/chart-style/dashboard-minimal.js
var dashboardMinimalChartStyleScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Dashboard KPI view"),
  categories: exports_external.array(exports_external.string().min(1)).min(4).default(["Mercury", "Venus", "Earth", "Mars"]),
  values: exports_external.array(exports_external.number()).min(4).default([3, 7, 12, 9]),
  seriesName: exports_external.string().min(1).default("Missions"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var dashboardMinimalChartStyleRecipeScript = definePresentationRecipeScript({
  name: "recipes.chartStyle.dashboard_minimal",
  summary: "Minimal chart style that removes non-essential chrome and emphasizes values.",
  labels: ["chart", "chart style", "dashboard", "minimalist"],
  paramsSchema: dashboardMinimalChartStyleScriptParamsSchema,
  exampleParams: {
    title: "Dashboard KPI view",
    categories: ["Mercury", "Venus", "Earth", "Mars"],
    values: [3, 7, 12, 9],
    seriesName: "Missions"
  },
  run: (presentation, params2) => {
    const categories = params2.categories;
    const values = params2.values.length === categories.length ? params2.values : categories.map((_, index) => params2.values[index] ?? params2.values.at(-1) ?? 0);
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 90, top: 70, width: 1000, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 42, color: "tx1" };
    const chart2 = slide.charts.add("bar", {
      position: { left: 90, top: 170, width: 1120, height: 500 },
      categories,
      series: [{ name: params2.seriesName, values }],
      hasLegend: false,
      title: ""
    });
    chart2.apply({
      title: "",
      titlePlacement: "none",
      hasLegend: false,
      xAxis: { deleted: true },
      yAxis: { deleted: true },
      barOptions: { direction: "column", grouping: "clustered", gapWidth: 45 },
      dataLabels: {
        showValue: true,
        position: "outEnd",
        textStyle: { bold: true, fontSize: 14 }
      }
    });
    chart2.chartLine.fill = "background1";
    chart2.chartLine.width = 0;
    chart2.plotAreaLine.fill = "background1";
    chart2.plotAreaLine.width = 0;
  },
  notes: ["Use for executive dashboards that prioritize rapid value scanning."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/chart-style/editorial.js
var editorialChartStyleScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Editorial comparison view"),
  categories: exports_external.array(exports_external.string().min(1)).min(2).default(["Inner", "Outer"]),
  exploredValues: exports_external.array(exports_external.number()).min(2).default([14, 6]),
  plannedValues: exports_external.array(exports_external.number()).min(2).default([4, 8]),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var editorialChartStyleRecipeScript = definePresentationRecipeScript({
  name: "recipes.chartStyle.editorial",
  summary: "Editorial chart style with stronger axis framing and selective outline emphasis.",
  labels: ["chart", "chart style", "editorial", "professional"],
  paramsSchema: editorialChartStyleScriptParamsSchema,
  exampleParams: {
    title: "Editorial comparison view",
    categories: ["Inner", "Outer"],
    exploredValues: [14, 6],
    plannedValues: [4, 8]
  },
  run: (presentation, params2) => {
    const categories = params2.categories;
    const exploredValues = params2.exploredValues.length === categories.length ? params2.exploredValues : categories.map((_, index) => params2.exploredValues[index] ?? params2.exploredValues.at(-1) ?? 0);
    const plannedValues = params2.plannedValues.length === categories.length ? params2.plannedValues : categories.map((_, index) => params2.plannedValues[index] ?? params2.plannedValues.at(-1) ?? 0);
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 90, top: 70, width: 1000, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 42, color: "tx1" };
    const chart2 = slide.charts.add("bar", {
      position: { left: 100, top: 170, width: 1080, height: 500 },
      categories,
      series: [
        { name: "Explored", values: exploredValues },
        { name: "Planned", values: plannedValues }
      ],
      hasLegend: false,
      title: ""
    });
    chart2.apply({
      title: "",
      hasLegend: false,
      xAxis: {
        deleted: false,
        line: { fill: "slate-500/85", style: "solid", width: 1 }
      },
      yAxis: { deleted: true },
      dataLabels: {
        showValue: true,
        position: "inEnd",
        textStyle: { bold: true, fontSize: 12, fill: "white" }
      }
    });
    chart2.series.items.forEach((series, index) => {
      series.fill = { type: "none" };
      series.stroke = {
        color: index % 2 === 0 ? "accent5" : "accent2",
        style: "solid",
        weight: 1.8
      };
    });
  },
  notes: ["Use this style in narrative decks where visual texture supports the story."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/chart-style/scientific.js
var scientificChartStyleScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Scientific trend view"),
  categories: exports_external.array(exports_external.string().min(1)).min(4).default(["2000", "2005", "2010", "2015", "2020"]),
  values: exports_external.array(exports_external.number()).min(4).default([1.2, 1.6, 2.1, 2.4, 2.8]),
  seriesName: exports_external.string().min(1).default("Signal"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var scientificChartStyleRecipeScript = definePresentationRecipeScript({
  name: "recipes.chartStyle.scientific",
  summary: "Scientific chart style with visible axes and subtle dashed gridlines.",
  labels: ["chart", "chart style", "scientific", "professional"],
  paramsSchema: scientificChartStyleScriptParamsSchema,
  exampleParams: {
    title: "Scientific trend view",
    categories: ["2000", "2005", "2010", "2015", "2020"],
    values: [1.2, 1.6, 2.1, 2.4, 2.8],
    seriesName: "Signal"
  },
  run: (presentation, params2) => {
    const categories = params2.categories;
    const values = params2.values.length === categories.length ? params2.values : categories.map((_, index) => params2.values[index] ?? params2.values.at(-1) ?? 0);
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 90, top: 70, width: 1000, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 42, color: "tx1" };
    const chart2 = slide.charts.add("line", {
      position: { left: 90, top: 170, width: 1120, height: 500 },
      categories,
      series: [{ name: params2.seriesName, values }],
      hasLegend: true,
      title: ""
    });
    chart2.apply({
      legend: { position: "top", textStyle: { fontSize: 12 } },
      xAxis: {
        deleted: false,
        line: { fill: "slate-500/90", style: "solid", width: 1 },
        textStyle: { fontSize: 11 }
      },
      yAxis: {
        deleted: false,
        line: { fill: "slate-500/90", style: "solid", width: 1 },
        majorGridlines: { fill: "slate-300/90", style: "dashed", width: 1 },
        minorGridlines: { fill: "slate-200/80", style: "dotted", width: 0.5 },
        textStyle: { fontSize: 11 }
      },
      dataLabels: { showValue: false }
    });
  },
  notes: ["Use this style for technical audiences where axis fidelity matters."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/chart-type/bubble-correlation.js
var bubbleCorrelationChartTypeScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Bubble correlation starter"),
  xValues: exports_external.array(exports_external.number()).min(4).default([0.8, 1.1, 1.6, 2.1]),
  yValues: exports_external.array(exports_external.number()).min(4).default([1.2, 1.8, 1.5, 2.4]),
  bubbleSizes: exports_external.array(exports_external.number()).min(4).default([6, 18, 10, 24]),
  seriesName: exports_external.string().min(1).default("Targets"),
  xAxisTitle: exports_external.string().min(1).default("Orbital distance (AU)"),
  yAxisTitle: exports_external.string().min(1).default("Relative gravity"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var bubbleCorrelationChartTypeRecipeScript = definePresentationRecipeScript({
  name: "recipes.chartType.bubble_correlation",
  summary: "Bubble chart starter for showing correlation and relative magnitude.",
  labels: ["chart", "chart type", "bubble", "analysis"],
  paramsSchema: bubbleCorrelationChartTypeScriptParamsSchema,
  exampleParams: {
    title: "Bubble correlation starter",
    xValues: [0.8, 1.1, 1.6, 2.1],
    yValues: [1.2, 1.8, 1.5, 2.4],
    bubbleSizes: [6, 18, 10, 24],
    seriesName: "Targets",
    xAxisTitle: "Orbital distance (AU)",
    yAxisTitle: "Relative gravity"
  },
  run: (presentation, params2) => {
    const count3 = Math.min(params2.xValues.length, params2.yValues.length, params2.bubbleSizes.length);
    const xValues = params2.xValues.slice(0, count3);
    const yValues = params2.yValues.slice(0, count3);
    const bubbleSizes = params2.bubbleSizes.slice(0, count3);
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 90, top: 70, width: 1100, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 42, color: "tx1" };
    const chart2 = slide.charts.add("bubble", {
      position: { left: 90, top: 170, width: 1120, height: 500 },
      title: "",
      hasLegend: false
    });
    const series = chart2.series.add(params2.seriesName);
    series.xValues = xValues;
    series.values = yValues;
    series.bubbleSizes = bubbleSizes;
    chart2.xAxis = { title: { text: params2.xAxisTitle }, deleted: false };
    chart2.yAxis = {
      title: { text: params2.yAxisTitle },
      deleted: false,
      majorGridlines: { fill: "slate-300/80", style: "dashed", width: 1 }
    };
  },
  notes: ["Bubble size should encode magnitude with a clear legend or explanation."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/chart-type/treemap-hierarchy.js
var treemapHierarchyChartTypeScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Treemap hierarchy starter"),
  labels: exports_external.array(exports_external.string().min(1)).min(5).default(["Sun", "Jupiter", "Saturn", "Neptune", "Earth"]),
  values: exports_external.array(exports_external.number()).min(5).default([120, 80, 55, 30, 20]),
  parentLabelLayout: exports_external.enum(["none", "banner", "overlapping"]).default("banner"),
  seriesName: exports_external.string().min(1).default("Mass index"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var treemapHierarchyChartTypeRecipeScript = definePresentationRecipeScript({
  name: "recipes.chartType.treemap_hierarchy",
  summary: "Treemap chart starter for hierarchical area comparisons.",
  labels: ["chart", "chart type", "treemap", "analysis"],
  paramsSchema: treemapHierarchyChartTypeScriptParamsSchema,
  exampleParams: {
    title: "Treemap hierarchy starter",
    labels: ["Sun", "Jupiter", "Saturn", "Neptune", "Earth"],
    values: [120, 80, 55, 30, 20],
    parentLabelLayout: "banner",
    seriesName: "Mass index"
  },
  run: (presentation, params2) => {
    const labels = params2.labels;
    const values = params2.values.length === labels.length ? params2.values : labels.map((_, index) => params2.values[index] ?? params2.values.at(-1) ?? 0);
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 90, top: 70, width: 1100, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 42, color: "tx1" };
    const chart2 = slide.charts.add("treemap", {
      position: { left: 90, top: 170, width: 1120, height: 500 },
      title: "",
      hasLegend: false
    });
    const series = chart2.series.add(params2.seriesName);
    series.values = values;
    series.categories = labels;
    chart2.treemapOptions.parentLabelLayout = params2.parentLabelLayout;
  },
  notes: ["Treemap works best when values vary meaningfully across categories."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/chart-type/waterfall-change.js
var waterfallChangeChartTypeScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Waterfall change starter"),
  categories: exports_external.array(exports_external.string().min(1)).min(4).default(["Launch", "Cruise", "Orbit insertion", "Surface ops"]),
  values: exports_external.array(exports_external.number()).min(4).default([3.2, 1.7, 2.8, 0.9]),
  seriesName: exports_external.string().min(1).default("Delta-v contribution"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var waterfallChangeChartTypeRecipeScript = definePresentationRecipeScript({
  name: "recipes.chartType.waterfall_change",
  summary: "Waterfall chart starter for additive and subtractive change decomposition.",
  labels: ["chart", "chart type", "waterfall", "analysis"],
  paramsSchema: waterfallChangeChartTypeScriptParamsSchema,
  exampleParams: {
    title: "Waterfall change starter",
    categories: ["Launch", "Cruise", "Orbit insertion", "Surface ops"],
    values: [3.2, 1.7, 2.8, 0.9],
    seriesName: "Delta-v contribution"
  },
  run: (presentation, params2) => {
    const categories = params2.categories;
    const values = params2.values.length === categories.length ? params2.values : categories.map((_, index) => params2.values[index] ?? params2.values.at(-1) ?? 0);
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 90, top: 70, width: 1100, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 42, color: "tx1" };
    const chart2 = slide.charts.add("waterfall", {
      position: { left: 90, top: 170, width: 1120, height: 500 },
      categories,
      title: "",
      hasLegend: false
    });
    const series = chart2.series.add(params2.seriesName);
    series.values = values;
    series.categories = categories;
    chart2.apply({
      barOptions: { direction: "column", grouping: "clustered", gapWidth: 70 },
      yAxis: {
        majorGridlines: { fill: "slate-300/80", style: "dashed", width: 1 }
      }
    });
  },
  notes: ["Use consistent sign conventions when mixing positive and negative deltas."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/agenda.js
var agendaScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Agenda"),
  items: exports_external.array(exports_external.string().min(1)).min(1).default([
    "Solar system structure",
    "Planet classes",
    "Distance and scale",
    "Mission timeline",
    "Open questions"
  ]),
  railColor: exports_external.string().min(1).default("accent1"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var agendaRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.agenda",
  summary: "Agenda slide with numbered list and a narrow left accent rail.",
  labels: ["agenda", "professional", "consulting"],
  paramsSchema: agendaScriptParamsSchema,
  exampleParams: {
    title: "Agenda",
    items: [
      "Solar system structure",
      "Planet classes",
      "Distance and scale",
      "Mission timeline",
      "Open questions"
    ]
  },
  run: (presentation, params2) => {
    const u = 8;
    const grid2 = {
      columns: 12,
      marginX: 10 * u,
      marginY: 8 * u,
      gutter: 3 * u,
      rowHeight: 9 * u,
      rowGap: 2 * u,
      baseUnit: u
    };
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const rail = slide.shapes.add({
      geometry: "rect",
      position: { left: 0, top: 0, width: 8 * u, height: 8 * u },
      fill: params2.railColor,
      line: { width: 0, style: "solid", fill: params2.railColor },
      borderRadius: "rounded-full"
    });
    rail.name = "agenda_rail";
    slide.gridLayout([
      {
        shape: rail,
        area: { colStart: 1, colSpan: 1, rowStart: 1, rowSpan: 7 },
        insetLeft: 2 * u,
        insetRight: 2 * u,
        insetTop: 4 * u,
        insetBottom: 4 * u
      }
    ], grid2);
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { width: 44 * u, height: 10 * u }
    });
    title.name = "agenda_title";
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 48, color: "tx1" };
    const items = slide.shapes.add({
      geometry: "textbox",
      position: { width: 96 * u, height: 42 * u }
    });
    items.name = "agenda_items";
    items.text.set(params2.items.map((item, index) => `${index + 1}. ${item}`).join(`
`));
    items.text.style = { fontSize: 30, lineSpacing: 1.25, color: "tx1" };
    const contentFrame = slide.gridFrame({ colStart: 2, colSpan: 10, rowStart: 1, rowSpan: 7 }, grid2);
    slide.stackVertical([title, items], {
      frame: contentFrame,
      verticalGap: 4 * u,
      align: AutoLayoutAlign.topLeft
    });
  }
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/big-number.js
var bigNumberScriptParamsSchema = exports_external.object({
  label: exports_external.string().min(1).default("TOTAL QUALIFIED PIPELINE"),
  value: exports_external.string().min(1).default("$84.2M"),
  note: exports_external.string().min(1).default("+18% quarter-over-quarter, driven by enterprise expansion and faster deal velocity."),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var bigNumberRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.big_number",
  summary: "Big-number slide for one KPI with brief interpretation.",
  labels: ["financial", "kpi", "metric", "professional"],
  paramsSchema: bigNumberScriptParamsSchema,
  exampleParams: {
    label: "TOTAL QUALIFIED PIPELINE",
    value: "$84.2M",
    note: "+18% quarter-over-quarter, driven by enterprise expansion and faster deal velocity."
  },
  run: (presentation, params2) => {
    const u = 8;
    const grid2 = {
      columns: 12,
      marginX: 10 * u,
      marginY: 8 * u,
      gutter: 3 * u,
      rowHeight: 9 * u,
      rowGap: 2 * u,
      baseUnit: u
    };
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const label = slide.shapes.add({
      geometry: "textbox",
      position: { width: 96 * u, height: 8 * u }
    });
    label.name = "bigNumber_label";
    label.text.set(params2.label);
    label.text.style = { bold: true, fontSize: 24, alignment: "center", color: "slate-600" };
    const value = slide.shapes.add({
      geometry: "textbox",
      position: { width: 96 * u, height: 20 * u }
    });
    value.name = "bigNumber_value";
    value.text.set(params2.value);
    value.text.style = { bold: true, fontSize: 112, alignment: "center", color: "tx1" };
    const note = slide.shapes.add({
      geometry: "textbox",
      position: { width: 88 * u, height: 10 * u }
    });
    note.name = "bigNumber_note";
    note.text.set(params2.note);
    note.text.style = { fontSize: 26, alignment: "center", lineSpacing: 1.25, color: "slate-700" };
    const frame = slide.gridFrame({ colStart: 1, colSpan: 12, rowStart: 2, rowSpan: 5 }, grid2);
    slide.stackVertical([label, value, note], {
      frame,
      verticalGap: 2 * u,
      align: AutoLayoutAlign.topCenter
    });
  }
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/big-quote.js
var bigQuoteScriptParamsSchema = exports_external.object({
  quote: exports_external.string().min(1).default("The teams with the shortest insight-to-action loop will outpace the market."),
  attribution: exports_external.string().min(1).default("VP Product, Q4 review"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var bigQuoteRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.big_quote",
  summary: "Quote slide with oversized statement and concise attribution.",
  labels: ["slide", "quote", "minimalist", "professional"],
  paramsSchema: bigQuoteScriptParamsSchema,
  exampleParams: {
    quote: "The teams with the shortest insight-to-action loop will outpace the market.",
    attribution: "VP Product, Q4 review"
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const quote = slide.shapes.add({
      geometry: "textbox",
      position: { left: 140, top: 170, width: 1080, height: 330 }
    });
    quote.text.set(`"${params2.quote}"`);
    quote.text.style = {
      bold: true,
      fontSize: 58,
      lineSpacing: 1.2,
      alignment: "center",
      color: "tx1"
    };
    const attribution = slide.shapes.add({
      geometry: "textbox",
      position: { left: 320, top: 560, width: 720, height: 80 }
    });
    attribution.text.set(params2.attribution);
    attribution.text.style = {
      fontSize: 26,
      alignment: "center",
      color: "slate-600"
    };
  },
  notes: ["Reserve quote slides for statements that move audience decision-making."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/bullet-list.js
var bulletListScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Key takeaways"),
  bullets: exports_external.array(exports_external.string().min(1)).min(3).default([
    "Consolidate tooling around the highest-frequency workflows.",
    "Prioritize latency and reliability for customer-visible actions.",
    "Instrument the flow to measure outcome quality, not just throughput.",
    "Scale rollout in phases with clear ownership and feedback loops."
  ]),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var bulletListRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.bullet_list",
  summary: "Bullet-list slide for concise recommendations and summary points.",
  labels: ["slide", "bullet list", "professional"],
  paramsSchema: bulletListScriptParamsSchema,
  exampleParams: {
    title: "Key takeaways",
    bullets: [
      "Consolidate tooling around the highest-frequency workflows.",
      "Prioritize latency and reliability for customer-visible actions.",
      "Instrument the flow to measure outcome quality, not just throughput.",
      "Scale rollout in phases with clear ownership and feedback loops."
    ]
  },
  run: (presentation, params2) => {
    const bulletText = params2.bullets.map((bullet) => `• ${bullet}`).join(`

`);
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 110, top: 80, width: 1100, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 48, color: "tx1" };
    const list = slide.shapes.add({
      geometry: "textbox",
      position: { left: 140, top: 200, width: 1120, height: 470 }
    });
    list.text.set(bulletText);
    list.text.style = { fontSize: 30, lineSpacing: 1.25, color: "slate-700" };
  },
  notes: ["Keep each bullet to one sentence to maintain presentation pacing."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/captioned-content.js
var captionedContentScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Why this matters"),
  body: exports_external.string().min(1).default("Customers are consolidating vendors and favor platforms that reduce handoffs across the lifecycle."),
  caption: exports_external.string().min(1).default("Interpretation: consolidation pressure rewards integrated product surfaces."),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var captionedContentRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.captioned_content",
  summary: "Content slide with a body paragraph and a highlighted caption line.",
  labels: ["slide", "content", "professional"],
  paramsSchema: captionedContentScriptParamsSchema,
  exampleParams: {
    title: "Why this matters",
    body: "Customers are consolidating vendors and favor platforms that reduce handoffs across the lifecycle.",
    caption: "Interpretation: consolidation pressure rewards integrated product surfaces."
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 110, top: 90, width: 980, height: 90 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 50, color: "tx1" };
    const body = slide.shapes.add({
      geometry: "textbox",
      position: { left: 110, top: 220, width: 1140, height: 280 }
    });
    body.text.set(params2.body);
    body.text.style = { fontSize: 34, lineSpacing: 1.25, color: "slate-700" };
    const caption = slide.shapes.add({
      geometry: "rect",
      position: { left: 110, top: 560, width: 1140, height: 110 },
      fill: "slate-100",
      borderRadius: "rounded-md",
      line: { style: "solid", width: 0, fill: "slate-100" }
    });
    caption.text.set(params2.caption);
    caption.text.style = {
      bold: true,
      fontSize: 24,
      color: "slate-800",
      alignment: "center"
    };
    caption.text.verticalAlignment = "middle";
  },
  notes: ["Use caption text to state the implication, not to repeat the body."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/center-title-solid-band-with-background-image.js
var centerTitleSolidBandWithBackgroundImageScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Strategic narrative"),
  subtitle: exports_external.string().min(1).default("A centered title over a strong contrast band and background visual."),
  bandFill: exports_external.string().min(1).default("slate-900/80"),
  imageFill: exports_external.string().min(1).default("slate-300"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var centerTitleSolidBandWithBackgroundImageRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.center_title_solid_band_with_background_image",
  summary: "Centered title band layered over a full background image.",
  labels: ["slide", "cover", "section divider", "professional"],
  paramsSchema: centerTitleSolidBandWithBackgroundImageScriptParamsSchema,
  exampleParams: {
    title: "Strategic narrative",
    subtitle: "A centered title over a strong contrast band and background visual.",
    bandFill: "slate-900/80",
    imageFill: "slate-300"
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const image2 = slide.shapes.add({
      geometry: "rect",
      position: { left: 0, top: 0, width: 1366, height: 768 },
      fill: params2.imageFill,
      line: { style: "solid", width: 0, fill: params2.imageFill }
    });
    image2.text.set("BACKGROUND IMAGE");
    image2.text.style = { bold: true, fontSize: 34, alignment: "center", color: "slate-500" };
    image2.text.verticalAlignment = "middle";
    const band2 = slide.shapes.add({
      geometry: "rect",
      position: { left: 120, top: 270, width: 1126, height: 230 },
      fill: params2.bandFill,
      borderRadius: "rounded-md",
      line: { style: "solid", width: 0, fill: params2.bandFill }
    });
    band2.text.set(`${params2.title}
${params2.subtitle}`);
    band2.text.style = {
      bold: true,
      fontSize: 48,
      lineSpacing: 1.25,
      alignment: "center",
      color: "white"
    };
    band2.text.verticalAlignment = "middle";
  },
  notes: ["Increase band opacity when background imagery has high visual noise."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/centered-headline.js
var centeredHeadlineScriptParamsSchema = exports_external.object({
  headline: exports_external.string().min(1).default("Mission update"),
  subheadline: exports_external.string().min(1).default("A concise statement that frames the audience takeaway."),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var centeredHeadlineRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.centered_headline",
  summary: "Centered headline slide for a short, high-signal statement.",
  labels: ["slide", "headline", "minimalist", "pitch deck"],
  paramsSchema: centeredHeadlineScriptParamsSchema,
  exampleParams: {
    headline: "Mission update",
    subheadline: "A concise statement that frames the audience takeaway."
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const headline = slide.shapes.add({
      geometry: "textbox",
      position: { left: 160, top: 250, width: 1040, height: 120 }
    });
    headline.text.set(params2.headline);
    headline.text.style = {
      bold: true,
      fontSize: 64,
      alignment: "center",
      color: "tx1",
      lineSpacing: 1.1
    };
    const subheadline = slide.shapes.add({
      geometry: "textbox",
      position: { left: 220, top: 390, width: 920, height: 120 }
    });
    subheadline.text.set(params2.subheadline);
    subheadline.text.style = {
      fontSize: 30,
      alignment: "center",
      color: "slate-600",
      lineSpacing: 1.25
    };
  },
  notes: [
    "Use this recipe when one idea needs to land quickly before deeper detail slides."
  ]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/chart-with-caption.js
var chartWithCaptionScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Performance trend"),
  caption: exports_external.string().min(1).default("Growth accelerates after onboarding improvements in weeks 4-6."),
  categories: exports_external.array(exports_external.string().min(1)).min(3).default(["W1", "W2", "W3", "W4", "W5", "W6"]),
  values: exports_external.array(exports_external.number()).min(3).default([18, 24, 29, 33, 39, 44]),
  seriesName: exports_external.string().min(1).default("Net new"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var chartWithCaptionRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.chart_with_caption",
  summary: "Chart-led slide with explanatory caption text.",
  labels: ["slide", "chart", "analysis", "professional"],
  paramsSchema: chartWithCaptionScriptParamsSchema,
  exampleParams: {
    title: "Performance trend",
    caption: "Growth accelerates after onboarding improvements in weeks 4-6.",
    categories: ["W1", "W2", "W3", "W4", "W5", "W6"],
    values: [18, 24, 29, 33, 39, 44],
    seriesName: "Net new"
  },
  run: (presentation, params2) => {
    const categories = params2.categories;
    const values = params2.values.length === categories.length ? params2.values : categories.map((_, index) => params2.values[index] ?? params2.values.at(-1) ?? 0);
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 100, top: 80, width: 1120, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 48, color: "tx1" };
    slide.charts.add("bar", {
      position: { left: 100, top: 190, width: 820, height: 460 },
      categories,
      series: [{ name: params2.seriesName, values }],
      hasLegend: false,
      title: ""
    });
    const caption = slide.shapes.add({
      geometry: "textbox",
      position: { left: 960, top: 230, width: 300, height: 360 }
    });
    caption.text.set(params2.caption);
    caption.text.style = { fontSize: 26, lineSpacing: 1.3, color: "slate-700" };
  },
  notes: ["Prefer one dominant series unless direct comparison is the key insight."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/contents-toc.js
var contentsTocScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Contents"),
  sections: exports_external.array(exports_external.string().min(1)).min(3).default([
    "1. Context and goals",
    "2. Current performance",
    "3. Strategic initiatives",
    "4. Risks and mitigations",
    "5. Next-quarter plan"
  ]),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var contentsTocRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.contents_toc",
  summary: "Table-of-contents slide with a numbered section list.",
  labels: ["slide", "toc", "outline", "professional"],
  paramsSchema: contentsTocScriptParamsSchema,
  exampleParams: {
    title: "Contents",
    sections: [
      "1. Context and goals",
      "2. Current performance",
      "3. Strategic initiatives",
      "4. Risks and mitigations",
      "5. Next-quarter plan"
    ]
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 120, top: 100, width: 720, height: 90 }
    });
    title.text.set(params2.title);
    title.text.style = {
      bold: true,
      fontSize: 52,
      color: "tx1"
    };
    const list = slide.shapes.add({
      geometry: "textbox",
      position: { left: 160, top: 220, width: 980, height: 420 }
    });
    list.text.set(params2.sections.join(`
`));
    list.text.style = {
      fontSize: 30,
      lineSpacing: 1.3,
      color: "slate-700"
    };
  },
  notes: ["Keep entries short so the list remains scannable in one glance."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/data-dashboard.js
var dashboardMetricSchema = exports_external.object({
  label: exports_external.string().min(1),
  value: exports_external.string().min(1)
});
var dataDashboardScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Weekly growth dashboard"),
  categories: exports_external.array(exports_external.string().min(1)).min(4).default(["W1", "W2", "W3", "W4", "W5", "W6"]),
  values: exports_external.array(exports_external.number()).min(4).default([18, 24, 29, 33, 39, 44]),
  seriesName: exports_external.string().min(1).default("Net new"),
  metrics: exports_external.array(dashboardMetricSchema).min(2).default([
    { label: "Conversion", value: "8.4%" },
    { label: "CAC", value: "$122" },
    { label: "Payback", value: "7 mo" }
  ]),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var dataDashboardRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.data_dashboard",
  summary: "Dashboard slide combining a lead chart with supporting KPI cards.",
  labels: ["slide", "dashboard", "chart", "financial", "professional"],
  paramsSchema: dataDashboardScriptParamsSchema,
  exampleParams: {
    title: "Weekly growth dashboard",
    categories: ["W1", "W2", "W3", "W4", "W5", "W6"],
    values: [18, 24, 29, 33, 39, 44],
    seriesName: "Net new",
    metrics: [
      { label: "Conversion", value: "8.4%" },
      { label: "CAC", value: "$122" },
      { label: "Payback", value: "7 mo" }
    ]
  },
  run: (presentation, params2) => {
    const categories = params2.categories;
    const values = params2.values.length === categories.length ? params2.values : categories.map((_, index) => params2.values[index] ?? params2.values.at(-1) ?? 0);
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 100, top: 70, width: 1100, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 44, color: "tx1" };
    const chart2 = slide.charts.add("bar", {
      position: { left: 100, top: 180, width: 820, height: 470 },
      categories,
      series: [{ name: params2.seriesName, values }],
      hasLegend: false,
      title: ""
    });
    chart2.apply({
      barOptions: { direction: "column", grouping: "clustered", gapWidth: 45 },
      xAxis: { deleted: true },
      yAxis: { deleted: true },
      dataLabels: {
        showValue: true,
        position: "outEnd",
        textStyle: { bold: true, fontSize: 14 }
      }
    });
    params2.metrics.forEach((metric, index) => {
      const top = 220 + index * 150;
      const card2 = slide.shapes.add({
        geometry: "rect",
        position: { left: 960, top, width: 300, height: 120 },
        fill: "slate-50",
        borderRadius: "rounded-lg",
        line: { style: "solid", width: 1, fill: "slate-200" }
      });
      card2.text.set(`${metric.value}
${metric.label}`);
      card2.text.style = {
        bold: true,
        fontSize: 28,
        lineSpacing: 1.2,
        alignment: "center",
        color: "tx1"
      };
      card2.text.verticalAlignment = "middle";
    });
  },
  notes: ["Use one dominant chart and 2-4 support metrics for quick scanning."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/feature-grid.js
var featureSchema = exports_external.object({
  title: exports_external.string().min(1),
  body: exports_external.string().min(1)
});
var featureGridScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Key capabilities"),
  features: exports_external.array(featureSchema).length(4).default([
    { title: "Unified context", body: "Cross-surface context passed across workflows." },
    { title: "Agentic automation", body: "Task delegation and stateful follow-through." },
    { title: "Governance", body: "Traceability, policy checks, and auditable outputs." },
    { title: "Extensibility", body: "Composable interfaces for domain-specific tooling." }
  ]),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var featureGridRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.feature_grid",
  summary: "2x2 feature grid for capability overviews.",
  labels: ["slide", "feature grid", "professional"],
  paramsSchema: featureGridScriptParamsSchema,
  exampleParams: {
    title: "Key capabilities",
    features: [
      { title: "Unified context", body: "Cross-surface context passed across workflows." },
      { title: "Agentic automation", body: "Task delegation and stateful follow-through." },
      { title: "Governance", body: "Traceability, policy checks, and auditable outputs." },
      { title: "Extensibility", body: "Composable interfaces for domain-specific tooling." }
    ]
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 100, top: 70, width: 1100, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 46, color: "tx1" };
    params2.features.forEach((feature, index) => {
      const column2 = index % 2;
      const row2 = Math.floor(index / 2);
      const left = 100 + column2 * 610;
      const top = 180 + row2 * 260;
      const card2 = slide.shapes.add({
        geometry: "rect",
        position: { left, top, width: 560, height: 230 },
        fill: "slate-50",
        borderRadius: "rounded-lg",
        line: { style: "solid", width: 1, fill: "slate-200" }
      });
      card2.text.set(`${feature.title}

${feature.body}`);
      card2.text.style = { bold: true, fontSize: 28, lineSpacing: 1.2, color: "tx1" };
    });
  },
  notes: ["Cap feature grids at four items to preserve readability."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/full-bleed-left-image-right-caption.js
var fullBleedLeftImageRightCaptionScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Customer spotlight"),
  body: exports_external.string().min(1).default("A left-anchored visual with concise commentary on outcomes, context, and next steps."),
  imageFill: exports_external.string().min(1).default("slate-300"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var fullBleedLeftImageRightCaptionRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.full_bleed_left_image_right_caption",
  summary: "Full-bleed left image with right-side explanatory copy.",
  labels: ["slide", "image", "full bleed", "professional"],
  paramsSchema: fullBleedLeftImageRightCaptionScriptParamsSchema,
  exampleParams: {
    title: "Customer spotlight",
    body: "A left-anchored visual with concise commentary on outcomes, context, and next steps.",
    imageFill: "slate-300"
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const image2 = slide.shapes.add({
      geometry: "rect",
      position: { left: 0, top: 0, width: 760, height: 768 },
      fill: params2.imageFill,
      line: { style: "solid", width: 0, fill: params2.imageFill }
    });
    image2.text.set("IMAGE");
    image2.text.style = { bold: true, fontSize: 36, alignment: "center", color: "slate-600" };
    image2.text.verticalAlignment = "middle";
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 820, top: 180, width: 470, height: 120 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 50, color: "tx1", lineSpacing: 1.1 };
    const body = slide.shapes.add({
      geometry: "textbox",
      position: { left: 820, top: 320, width: 470, height: 260 }
    });
    body.text.set(params2.body);
    body.text.style = { fontSize: 28, color: "slate-700", lineSpacing: 1.25 };
  },
  notes: ["This recipe works best when the image carries most of the narrative weight."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/full-bleed-top-image-bottom-caption.js
var fullBleedTopImageBottomCaptionScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Program snapshot"),
  body: exports_external.string().min(1).default("Top visual context with a lower-third summary of implications and actions."),
  imageFill: exports_external.string().min(1).default("slate-300"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var fullBleedTopImageBottomCaptionRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.full_bleed_top_image_bottom_caption",
  summary: "Full-bleed top image with caption and context at the bottom.",
  labels: ["slide", "image", "full bleed", "professional"],
  paramsSchema: fullBleedTopImageBottomCaptionScriptParamsSchema,
  exampleParams: {
    title: "Program snapshot",
    body: "Top visual context with a lower-third summary of implications and actions.",
    imageFill: "slate-300"
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const image2 = slide.shapes.add({
      geometry: "rect",
      position: { left: 0, top: 0, width: 1366, height: 460 },
      fill: params2.imageFill,
      line: { style: "solid", width: 0, fill: params2.imageFill }
    });
    image2.text.set("IMAGE");
    image2.text.style = { bold: true, fontSize: 36, alignment: "center", color: "slate-600" };
    image2.text.verticalAlignment = "middle";
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 90, top: 500, width: 1180, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 44, color: "tx1" };
    const body = slide.shapes.add({
      geometry: "textbox",
      position: { left: 90, top: 585, width: 1180, height: 130 }
    });
    body.text.set(params2.body);
    body.text.style = { fontSize: 26, color: "slate-700", lineSpacing: 1.2 };
  },
  notes: ["Use this when the top image provides immediate context for the narrative."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/icon-list.js
var iconListItemSchema = exports_external.object({
  icon: exports_external.string().min(1),
  title: exports_external.string().min(1),
  body: exports_external.string().min(1)
});
var iconListScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Operating principles"),
  items: exports_external.array(iconListItemSchema).min(3).default([
    {
      icon: "◉",
      title: "Outcome-first",
      body: "Prioritize measurable customer outcomes over output volume."
    },
    {
      icon: "◆",
      title: "Default transparent",
      body: "Expose assumptions, trade-offs, and decision rationale early."
    },
    {
      icon: "▲",
      title: "Ship and learn",
      body: "Deploy in small increments and tighten the feedback loop weekly."
    }
  ]),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var iconListRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.icon_list",
  summary: "Icon-list slide for compact principle or capability callouts.",
  labels: ["slide", "icon list", "professional"],
  paramsSchema: iconListScriptParamsSchema,
  exampleParams: {
    title: "Operating principles",
    items: [
      {
        icon: "◉",
        title: "Outcome-first",
        body: "Prioritize measurable customer outcomes over output volume."
      },
      {
        icon: "◆",
        title: "Default transparent",
        body: "Expose assumptions, trade-offs, and decision rationale early."
      },
      {
        icon: "▲",
        title: "Ship and learn",
        body: "Deploy in small increments and tighten the feedback loop weekly."
      }
    ]
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 100, top: 70, width: 1100, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 46, color: "tx1" };
    params2.items.forEach((item, index) => {
      const top = 190 + index * 160;
      const icon = slide.shapes.add({
        geometry: "ellipse",
        position: { left: 110, top, width: 72, height: 72 },
        fill: "accent1",
        line: { style: "solid", width: 0, fill: "accent1" }
      });
      icon.text.set(item.icon);
      icon.text.style = { bold: true, fontSize: 28, alignment: "center", color: "white" };
      icon.text.verticalAlignment = "middle";
      const text2 = slide.shapes.add({
        geometry: "textbox",
        position: { left: 220, top: top + 2, width: 1020, height: 130 }
      });
      text2.text.set(`${item.title}
${item.body}`);
      text2.text.style = { bold: true, fontSize: 28, color: "tx1", lineSpacing: 1.2 };
    });
  },
  notes: ["Keep icon semantics simple and consistent across items."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/image-montage-caption.js
var imageMontageCaptionScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Pilot snapshots"),
  caption: exports_external.string().min(1).default("Representative moments across onboarding, usage, and support interactions."),
  imageLabels: exports_external.array(exports_external.string().min(1)).length(3).default(["Onboarding", "In-product workflow", "Support follow-up"]),
  imageFill: exports_external.string().min(1).default("slate-200"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var imageMontageCaptionRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.image_montage_caption",
  summary: "Three-image montage with a single synthesis caption.",
  labels: ["slide", "image", "montage", "professional"],
  paramsSchema: imageMontageCaptionScriptParamsSchema,
  exampleParams: {
    title: "Pilot snapshots",
    caption: "Representative moments across onboarding, usage, and support interactions.",
    imageLabels: ["Onboarding", "In-product workflow", "Support follow-up"]
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const { width: slideWidth } = slide.frame;
    const cardWidth = 360;
    const cardHeight = 330;
    const cardGap = 50;
    const montageWidth = cardWidth * 3 + cardGap * 2;
    const montageLeft = Math.round((slideWidth - montageWidth) / 2);
    const titleTop = 56;
    const cardsTop = 176;
    const captionTop = cardsTop + cardHeight + 36;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: montageLeft, top: titleTop, width: montageWidth, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 48, alignment: "center", color: "tx1" };
    params2.imageLabels.forEach((label, index) => {
      const left = montageLeft + index * (cardWidth + cardGap);
      const image2 = slide.shapes.add({
        geometry: "rect",
        position: { left, top: cardsTop, width: cardWidth, height: cardHeight },
        fill: params2.imageFill,
        borderRadius: "rounded-lg",
        line: { style: "solid", width: 1, fill: "slate-300" }
      });
      image2.text.set(label);
      image2.text.style = {
        bold: true,
        fontSize: 24,
        alignment: "center",
        color: "slate-600"
      };
      image2.text.verticalAlignment = "middle";
    });
    const caption = slide.shapes.add({
      geometry: "textbox",
      position: { left: montageLeft, top: captionTop, width: montageWidth, height: 120 }
    });
    caption.text.set(params2.caption);
    caption.text.style = {
      fontSize: 28,
      lineSpacing: 1.2,
      alignment: "center",
      color: "slate-700"
    };
  },
  notes: ["Choose images with consistent visual tone for cleaner montage rhythm."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/image-only.js
var imageOnlyScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Visual reference"),
  imageFill: exports_external.string().min(1).default("slate-300"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var imageOnlyRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.image_only",
  summary: "Image-only slide with lightweight title labeling.",
  labels: ["slide", "image", "minimalist"],
  paramsSchema: imageOnlyScriptParamsSchema,
  exampleParams: {
    title: "Visual reference",
    imageFill: "slate-300"
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const { width: slideWidth, height: slideHeight } = slide.frame;
    const labelWidth = Math.min(420, Math.round(slideWidth * 0.34));
    const labelHeight = 56;
    const labelLeft = Math.round((slideWidth - labelWidth) / 2);
    const labelTop = 48;
    const image2 = slide.shapes.add({
      geometry: "rect",
      position: { left: 0, top: 0, width: slideWidth, height: slideHeight },
      fill: params2.imageFill,
      borderRadius: "rounded-lg",
      line: { style: "solid", width: 0, fill: params2.imageFill }
    });
    image2.text.set("IMAGE");
    image2.text.style = { bold: true, fontSize: 40, alignment: "center", color: "slate-600" };
    image2.text.verticalAlignment = "middle";
    const label = slide.shapes.add({
      geometry: "rect",
      position: { left: labelLeft, top: labelTop, width: labelWidth, height: labelHeight },
      fill: "slate-900/70",
      borderRadius: "rounded-sm",
      line: { style: "solid", width: 0, fill: "slate-900/70" }
    });
    label.text.set(params2.title);
    label.text.style = { bold: true, fontSize: 24, color: "white", alignment: "center" };
    label.text.verticalAlignment = "middle";
  },
  notes: ["Use for high-impact visuals where narration happens verbally."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/image-with-caption.js
var imageWithCaptionScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Field observation"),
  caption: exports_external.string().min(1).default("Annotated visual evidence from pilot workflows and user interviews."),
  imageFill: exports_external.string().min(1).default("slate-200"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var imageWithCaptionRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.image_with_caption",
  summary: "Image-led slide with a caption column.",
  labels: ["slide", "image", "caption", "professional"],
  paramsSchema: imageWithCaptionScriptParamsSchema,
  exampleParams: {
    title: "Field observation",
    caption: "Annotated visual evidence from pilot workflows and user interviews.",
    imageFill: "slate-200"
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 100, top: 80, width: 1100, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 48, color: "tx1" };
    const image2 = slide.shapes.add({
      geometry: "rect",
      position: { left: 100, top: 190, width: 760, height: 480 },
      fill: params2.imageFill,
      borderRadius: "rounded-lg",
      line: { style: "solid", width: 1, fill: "slate-300" }
    });
    image2.text.set("IMAGE");
    image2.text.style = { bold: true, fontSize: 32, color: "slate-500", alignment: "center" };
    image2.text.verticalAlignment = "middle";
    const caption = slide.shapes.add({
      geometry: "textbox",
      position: { left: 900, top: 230, width: 360, height: 360 }
    });
    caption.text.set(params2.caption);
    caption.text.style = { fontSize: 28, color: "slate-700", lineSpacing: 1.3 };
  },
  notes: ["Keep caption text interpretive so the image can stay uncluttered."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/metric-strip.js
var metricStripItemSchema = exports_external.object({
  label: exports_external.string().min(1),
  value: exports_external.string().min(1)
});
var metricStripScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Quarterly KPI strip"),
  metrics: exports_external.array(metricStripItemSchema).min(3).default([
    { label: "Pipeline", value: "$84.2M" },
    { label: "Win rate", value: "28.4%" },
    { label: "CAC", value: "$122" },
    { label: "NPS", value: "61" }
  ]),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var metricStripRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.metric_strip",
  summary: "Horizontal strip of headline metrics for dashboard snapshots.",
  labels: ["slide", "metrics", "financial", "professional"],
  paramsSchema: metricStripScriptParamsSchema,
  exampleParams: {
    title: "Quarterly KPI strip",
    metrics: [
      { label: "Pipeline", value: "$84.2M" },
      { label: "Win rate", value: "28.4%" },
      { label: "CAC", value: "$122" },
      { label: "NPS", value: "61" }
    ]
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 100, top: 90, width: 1100, height: 70 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 42, color: "tx1" };
    const metricCount = params2.metrics.length;
    const cardWidth = Math.max(220, Math.floor((1180 - (metricCount - 1) * 20) / metricCount));
    params2.metrics.forEach((metric, index) => {
      const left = 100 + index * (cardWidth + 20);
      const card2 = slide.shapes.add({
        geometry: "rect",
        position: { left, top: 250, width: cardWidth, height: 260 },
        fill: "slate-50",
        borderRadius: "rounded-lg",
        line: { style: "solid", width: 1, fill: "slate-200" }
      });
      card2.text.set(`${metric.value}
${metric.label}`);
      card2.text.style = {
        bold: true,
        fontSize: 42,
        lineSpacing: 1.3,
        alignment: "center",
        color: "tx1"
      };
      card2.text.verticalAlignment = "middle";
    });
  },
  notes: ["Use consistent units and precision across all metric values."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/numbered-steps.js
var numberedStepsScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Implementation steps"),
  steps: exports_external.array(exports_external.string().min(1)).min(3).default([
    "Align stakeholders on measurable success criteria.",
    "Build the core workflow and validate with pilot users.",
    "Operationalize instrumentation and weekly review loops.",
    "Scale with playbooks and role-specific enablement."
  ]),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var numberedStepsRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.numbered_steps",
  summary: "Numbered process slide for sequential execution plans.",
  labels: ["slide", "process", "numbered steps", "professional"],
  paramsSchema: numberedStepsScriptParamsSchema,
  exampleParams: {
    title: "Implementation steps",
    steps: [
      "Align stakeholders on measurable success criteria.",
      "Build the core workflow and validate with pilot users.",
      "Operationalize instrumentation and weekly review loops.",
      "Scale with playbooks and role-specific enablement."
    ]
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 100, top: 70, width: 1100, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 46, color: "tx1" };
    params2.steps.forEach((step, index) => {
      const top = 180 + index * 130;
      const marker = slide.shapes.add({
        geometry: "ellipse",
        position: { left: 120, top, width: 72, height: 72 },
        fill: "accent1",
        line: { style: "solid", width: 0, fill: "accent1" }
      });
      marker.text.set(String(index + 1));
      marker.text.style = { bold: true, fontSize: 28, alignment: "center", color: "white" };
      marker.text.verticalAlignment = "middle";
      const body = slide.shapes.add({
        geometry: "textbox",
        position: { left: 220, top: top + 8, width: 1030, height: 80 }
      });
      body.text.set(step);
      body.text.style = { fontSize: 30, color: "slate-700" };
    });
  },
  notes: ["Use 3-5 steps; longer processes usually need a timeline or appendix view."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/pictogram.js
var pictogramScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Customer impact"),
  pictogram: exports_external.string().min(1).default("⚡"),
  value: exports_external.string().min(1).default("3.2x"),
  label: exports_external.string().min(1).default("faster time-to-resolution"),
  description: exports_external.string().min(1).default("Measured across support workflows after assistant routing and summarization."),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var pictogramRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.pictogram",
  summary: "Pictogram slide with one symbolic visual and one headline metric.",
  labels: ["slide", "pictogram", "kpi", "professional"],
  paramsSchema: pictogramScriptParamsSchema,
  exampleParams: {
    title: "Customer impact",
    pictogram: "⚡",
    value: "3.2x",
    label: "faster time-to-resolution",
    description: "Measured across support workflows after assistant routing and summarization."
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 100, top: 80, width: 1100, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 46, color: "tx1" };
    const icon = slide.shapes.add({
      geometry: "ellipse",
      position: { left: 180, top: 220, width: 320, height: 320 },
      fill: "accent1",
      line: { style: "solid", width: 0, fill: "accent1" }
    });
    icon.text.set(params2.pictogram);
    icon.text.style = { bold: true, fontSize: 140, alignment: "center", color: "white" };
    icon.text.verticalAlignment = "middle";
    const metric = slide.shapes.add({
      geometry: "textbox",
      position: { left: 560, top: 260, width: 700, height: 120 }
    });
    metric.text.set(`${params2.value}
${params2.label}`);
    metric.text.style = {
      bold: true,
      fontSize: 58,
      lineSpacing: 1.2,
      color: "tx1"
    };
    const description = slide.shapes.add({
      geometry: "textbox",
      position: { left: 560, top: 450, width: 700, height: 150 }
    });
    description.text.set(params2.description);
    description.text.style = { fontSize: 26, lineSpacing: 1.25, color: "slate-700" };
  },
  notes: ["Use one symbol only; multiple icons dilute the focal metric."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/section-divider-round-icon.js
var sectionDividerRoundIconScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Section 02"),
  subtitle: exports_external.string().min(1).default("Operating model and execution plan"),
  iconText: exports_external.string().min(1).default("02"),
  accentFill: exports_external.string().min(1).default("accent1"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var sectionDividerRoundIconRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.section_divider_round_icon",
  summary: "Section divider with a large circular icon marker.",
  labels: ["slide", "section divider", "pitch deck"],
  paramsSchema: sectionDividerRoundIconScriptParamsSchema,
  exampleParams: {
    title: "Section 02",
    subtitle: "Operating model and execution plan",
    iconText: "02",
    accentFill: "accent1"
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const circle = slide.shapes.add({
      geometry: "ellipse",
      position: { left: 540, top: 150, width: 280, height: 280 },
      fill: params2.accentFill,
      line: { style: "solid", width: 0, fill: params2.accentFill }
    });
    circle.text.set(params2.iconText);
    circle.text.style = {
      bold: true,
      fontSize: 96,
      alignment: "center",
      color: "white"
    };
    circle.text.verticalAlignment = "middle";
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 180, top: 470, width: 1000, height: 90 }
    });
    title.text.set(params2.title);
    title.text.style = {
      bold: true,
      fontSize: 56,
      alignment: "center",
      color: "tx1"
    };
    const subtitle = slide.shapes.add({
      geometry: "textbox",
      position: { left: 260, top: 560, width: 840, height: 80 }
    });
    subtitle.text.set(params2.subtitle);
    subtitle.text.style = {
      fontSize: 28,
      alignment: "center",
      color: "slate-600"
    };
  },
  notes: ["Use this divider to clearly mark a major narrative transition."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/section-divider-vertical-band-left.js
var sectionDividerVerticalBandLeftScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Go-to-market plan"),
  subtitle: exports_external.string().min(1).default("Segment strategy, messaging, and launch sequence"),
  bandFill: exports_external.string().min(1).default("accent1"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var sectionDividerVerticalBandLeftRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.section_divider_vertical_band_left",
  summary: "Section divider with a strong vertical color band on the left.",
  labels: ["slide", "section divider", "professional"],
  paramsSchema: sectionDividerVerticalBandLeftScriptParamsSchema,
  exampleParams: {
    title: "Go-to-market plan",
    subtitle: "Segment strategy, messaging, and launch sequence",
    bandFill: "accent1"
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    slide.shapes.add({
      geometry: "rect",
      position: { left: 0, top: 0, width: 120, height: 768 },
      fill: params2.bandFill,
      line: { style: "solid", width: 0, fill: params2.bandFill }
    });
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 180, top: 260, width: 1040, height: 120 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 62, color: "tx1" };
    const subtitle = slide.shapes.add({
      geometry: "textbox",
      position: { left: 180, top: 390, width: 930, height: 120 }
    });
    subtitle.text.set(params2.subtitle);
    subtitle.text.style = { fontSize: 30, color: "slate-700", lineSpacing: 1.2 };
  },
  notes: ["This divider works well when the deck already uses accent rails."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/section-divider-vertical-band-right.js
var sectionDividerVerticalBandRightScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Delivery roadmap"),
  subtitle: exports_external.string().min(1).default("Milestones, owners, and measurable outcomes"),
  bandFill: exports_external.string().min(1).default("accent2"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var sectionDividerVerticalBandRightRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.section_divider_vertical_band_right",
  summary: "Section divider with a strong vertical color band on the right.",
  labels: ["slide", "section divider", "professional"],
  paramsSchema: sectionDividerVerticalBandRightScriptParamsSchema,
  exampleParams: {
    title: "Delivery roadmap",
    subtitle: "Milestones, owners, and measurable outcomes",
    bandFill: "accent2"
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    slide.shapes.add({
      geometry: "rect",
      position: { left: 1246, top: 0, width: 120, height: 768 },
      fill: params2.bandFill,
      line: { style: "solid", width: 0, fill: params2.bandFill }
    });
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 140, top: 260, width: 1040, height: 120 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 62, color: "tx1" };
    const subtitle = slide.shapes.add({
      geometry: "textbox",
      position: { left: 140, top: 390, width: 930, height: 120 }
    });
    subtitle.text.set(params2.subtitle);
    subtitle.text.style = { fontSize: 30, color: "slate-700", lineSpacing: 1.2 };
  },
  notes: ["Use the right-band variant to alternate visual rhythm with left-band sections."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/table-slide.js
var tableSlideScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Regional performance table"),
  headers: exports_external.array(exports_external.string().min(1)).min(2).default(["Region", "Pipeline", "Win rate", "YoY"]),
  rows: exports_external.array(exports_external.array(exports_external.string().min(1)).min(2)).min(2).default([
    ["North America", "$31M", "29%", "+14%"],
    ["EMEA", "$22M", "26%", "+11%"],
    ["APAC", "$18M", "24%", "+9%"]
  ]),
  caption: exports_external.string().min(1).default("North America leads pipeline while EMEA sustains strong conversion performance."),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var tableSlideRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.table_slide",
  summary: "Table-first slide for exact values and concise interpretation.",
  labels: ["slide", "table", "financial", "professional"],
  paramsSchema: tableSlideScriptParamsSchema,
  exampleParams: {
    title: "Regional performance table",
    headers: ["Region", "Pipeline", "Win rate", "YoY"],
    rows: [
      ["North America", "$31M", "29%", "+14%"],
      ["EMEA", "$22M", "26%", "+11%"],
      ["APAC", "$18M", "24%", "+9%"]
    ],
    caption: "North America leads pipeline while EMEA sustains strong conversion performance."
  },
  run: (presentation, params2) => {
    const columnCount = params2.headers.length;
    const rowCount = params2.rows.length + 1;
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 90, top: 70, width: 1120, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 44, color: "tx1" };
    const table2 = slide.tables.add({
      left: 90,
      top: 180,
      width: 1180,
      height: 400,
      rows: rowCount,
      columns: columnCount
    });
    params2.headers.forEach((header, columnIndex2) => {
      table2.getCell(0, columnIndex2).value = header;
    });
    params2.rows.forEach((row2, rowIndex2) => {
      row2.forEach((cell, columnIndex2) => {
        table2.getCell(rowIndex2 + 1, columnIndex2).value = cell;
      });
    });
    table2.style = "TableStyleMedium2";
    const caption = slide.shapes.add({
      geometry: "textbox",
      position: { left: 90, top: 610, width: 1180, height: 90 }
    });
    caption.text.set(params2.caption);
    caption.text.style = { fontSize: 24, lineSpacing: 1.2, color: "slate-700" };
  },
  notes: ["Choose this template when exact values matter more than trend shape."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/three-column-comparison.js
var comparisonColumnSchema = exports_external.object({
  title: exports_external.string().min(1),
  body: exports_external.string().min(1)
});
var threeColumnComparisonScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Option comparison"),
  columns: exports_external.array(comparisonColumnSchema).length(3).default([
    { title: "Option A", body: "Fastest to launch with moderate customization." },
    { title: "Option B", body: "Balanced implementation effort and flexibility." },
    { title: "Option C", body: "Highest ceiling with heavier delivery cost." }
  ]),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var threeColumnComparisonRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.three_column_comparison",
  summary: "Three-card comparison slide for option trade-offs.",
  labels: ["slide", "comparison", "professional"],
  paramsSchema: threeColumnComparisonScriptParamsSchema,
  exampleParams: {
    title: "Option comparison",
    columns: [
      { title: "Option A", body: "Fastest to launch with moderate customization." },
      { title: "Option B", body: "Balanced implementation effort and flexibility." },
      { title: "Option C", body: "Highest ceiling with heavier delivery cost." }
    ]
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 100, top: 80, width: 1100, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 48, color: "tx1" };
    params2.columns.forEach((column2, index) => {
      const left = 100 + index * 420;
      const card2 = slide.shapes.add({
        geometry: "rect",
        position: { left, top: 210, width: 360, height: 440 },
        fill: "slate-50",
        borderRadius: "rounded-lg",
        line: { style: "solid", width: 1, fill: "slate-200" }
      });
      card2.text.set(`${column2.title}

${column2.body}`);
      card2.text.style = {
        bold: true,
        fontSize: 26,
        lineSpacing: 1.25,
        color: "tx1"
      };
    });
  },
  notes: ["Keep each column to one claim and one supporting sentence."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/three-image-carousel.js
var threeImageCarouselScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Journey highlights"),
  captions: exports_external.array(exports_external.string().min(1)).length(3).default(["Discover", "Adopt", "Expand"]),
  imageFill: exports_external.string().min(1).default("slate-200"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var threeImageCarouselRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.three_image_carousel",
  summary: "Three-panel image carousel for sequence storytelling.",
  labels: ["slide", "image", "carousel", "professional"],
  paramsSchema: threeImageCarouselScriptParamsSchema,
  exampleParams: {
    title: "Journey highlights",
    captions: ["Discover", "Adopt", "Expand"]
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const { width: slideWidth } = slide.frame;
    const cardWidth = 360;
    const cardHeight = 430;
    const cardGap = 50;
    const rowWidth = cardWidth * 3 + cardGap * 2;
    const rowLeft = Math.round((slideWidth - rowWidth) / 2);
    const titleTop = 56;
    const cardsTop = 170;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: rowLeft, top: titleTop, width: rowWidth, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 46, alignment: "center", color: "tx1" };
    params2.captions.forEach((caption, index) => {
      const left = rowLeft + index * (cardWidth + cardGap);
      const image2 = slide.shapes.add({
        geometry: "rect",
        position: { left, top: cardsTop, width: cardWidth, height: cardHeight },
        fill: params2.imageFill,
        borderRadius: "rounded-lg",
        line: { style: "solid", width: 1, fill: "slate-300" }
      });
      image2.text.set(caption);
      image2.text.style = {
        bold: true,
        fontSize: 24,
        alignment: "center",
        color: "slate-700"
      };
      image2.text.verticalAlignment = "bottom";
    });
  },
  notes: ["Use consistent composition across all three frames for smooth progression."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/title-cover.js
var titleCoverScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("A Guided Tour of Our Cosmic Neighborhood"),
  subtitle: exports_external.string().min(1).default("From rocky planets to icy outskirts"),
  backgroundFill: exports_external.string().min(1).default("background1"),
  accentStartColor: exports_external.string().min(1).default("blue-500/90"),
  accentEndColor: exports_external.string().min(1).default("violet-500/85")
});
var titleCoverRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.title_cover",
  summary: "Title slide with centered title/subtitle and a subtle accent band.",
  labels: ["cover", "pitch deck", "professional", "modern"],
  paramsSchema: titleCoverScriptParamsSchema,
  exampleParams: {
    title: "A Guided Tour of Our Cosmic Neighborhood",
    subtitle: "From rocky planets to icy outskirts"
  },
  run: (presentation, params2) => {
    const u = 8;
    const grid2 = {
      columns: 12,
      marginX: 10 * u,
      marginY: 8 * u,
      gutter: 3 * u,
      rowHeight: 9 * u,
      rowGap: 2 * u,
      baseUnit: u
    };
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const { width: slideWidth } = slide.frame;
    const accentBand = slide.shapes.add({
      geometry: "rect",
      position: { left: 0, top: 0, width: slideWidth, height: 20 * u },
      fill: {
        type: "gradient",
        gradientKind: "linear",
        angleDeg: 135,
        stops: [
          { offset: 0, color: params2.accentStartColor },
          { offset: 1e5, color: params2.accentEndColor }
        ]
      },
      line: { style: "solid", width: 0, fill: params2.backgroundFill }
    });
    accentBand.name = "titleCover_accentBand";
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { width: 108 * u, height: 18 * u }
    });
    title.name = "titleCover_title";
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 52, alignment: "center", color: "tx1" };
    const subtitle = slide.shapes.add({
      geometry: "textbox",
      position: { width: 92 * u, height: 10 * u }
    });
    subtitle.name = "titleCover_subtitle";
    subtitle.text.set(params2.subtitle);
    subtitle.text.style = { fontSize: 28, alignment: "center", color: "slate-600" };
    const headlineFrame = slide.gridFrame({ colStart: 2, colSpan: 10, rowStart: 3, rowSpan: 4 }, grid2);
    slide.stackVertical([title, subtitle], {
      frame: headlineFrame,
      verticalGap: 2 * u,
      align: AutoLayoutAlign.topCenter
    });
  }
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/two-column.js
var twoColumnScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Current state vs target state"),
  leftHeading: exports_external.string().min(1).default("Current state"),
  leftBody: exports_external.string().min(1).default("Fragmented tooling, duplicated effort, and inconsistent handoff quality."),
  rightHeading: exports_external.string().min(1).default("Target state"),
  rightBody: exports_external.string().min(1).default("Shared platform, unified operating model, and clear ownership boundaries."),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var twoColumnRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.two_column",
  summary: "Two-column slide for contrast, before/after, or option framing.",
  labels: ["slide", "comparison", "professional"],
  paramsSchema: twoColumnScriptParamsSchema,
  exampleParams: {
    title: "Current state vs target state",
    leftHeading: "Current state",
    leftBody: "Fragmented tooling, duplicated effort, and inconsistent handoff quality.",
    rightHeading: "Target state",
    rightBody: "Shared platform, unified operating model, and clear ownership boundaries."
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 90, top: 80, width: 1140, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 46, color: "tx1" };
    const left = slide.shapes.add({
      geometry: "rect",
      position: { left: 90, top: 190, width: 560, height: 470 },
      fill: "slate-50",
      borderRadius: "rounded-lg",
      line: { style: "solid", width: 1, fill: "slate-200" }
    });
    left.text.set(`${params2.leftHeading}

${params2.leftBody}`);
    left.text.style = { bold: true, fontSize: 30, lineSpacing: 1.25, color: "tx1" };
    const right = slide.shapes.add({
      geometry: "rect",
      position: { left: 710, top: 190, width: 560, height: 470 },
      fill: "slate-50",
      borderRadius: "rounded-lg",
      line: { style: "solid", width: 1, fill: "slate-200" }
    });
    right.text.set(`${params2.rightHeading}

${params2.rightBody}`);
    right.text.style = { bold: true, fontSize: 30, lineSpacing: 1.25, color: "tx1" };
  },
  notes: ["Keep both columns close in text density for balanced visual weight."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/two-image-carousel.js
var twoImageCarouselScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Before and after"),
  leftCaption: exports_external.string().min(1).default("Before: fragmented workflow"),
  rightCaption: exports_external.string().min(1).default("After: unified workflow"),
  imageFill: exports_external.string().min(1).default("slate-200"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var twoImageCarouselRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.two_image_carousel",
  summary: "Two-panel image carousel slide for direct visual comparison.",
  labels: ["slide", "image", "comparison", "professional"],
  paramsSchema: twoImageCarouselScriptParamsSchema,
  exampleParams: {
    title: "Before and after",
    leftCaption: "Before: fragmented workflow",
    rightCaption: "After: unified workflow"
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const { width: slideWidth } = slide.frame;
    const cardWidth = 560;
    const cardHeight = 420;
    const cardGap = 40;
    const rowWidth = cardWidth * 2 + cardGap;
    const rowLeft = Math.round((slideWidth - rowWidth) / 2);
    const titleTop = 56;
    const cardsTop = 170;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: rowLeft, top: titleTop, width: rowWidth, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 46, alignment: "center", color: "tx1" };
    const left = slide.shapes.add({
      geometry: "rect",
      position: { left: rowLeft, top: cardsTop, width: cardWidth, height: cardHeight },
      fill: params2.imageFill,
      borderRadius: "rounded-lg",
      line: { style: "solid", width: 1, fill: "slate-300" }
    });
    left.text.set(params2.leftCaption);
    left.text.style = { bold: true, fontSize: 24, alignment: "center", color: "slate-700" };
    left.text.verticalAlignment = "bottom";
    const right = slide.shapes.add({
      geometry: "rect",
      position: {
        left: rowLeft + cardWidth + cardGap,
        top: cardsTop,
        width: cardWidth,
        height: cardHeight
      },
      fill: params2.imageFill,
      borderRadius: "rounded-lg",
      line: { style: "solid", width: 1, fill: "slate-300" }
    });
    right.text.set(params2.rightCaption);
    right.text.style = { bold: true, fontSize: 24, alignment: "center", color: "slate-700" };
    right.text.verticalAlignment = "bottom";
  },
  notes: ["Keep both panels framed similarly to avoid visual bias in comparison."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/venn-diagram.js
var vennDiagramScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("Capability overlap"),
  leftLabel: exports_external.string().min(1).default("Platform"),
  rightLabel: exports_external.string().min(1).default("Operations"),
  bottomLabel: exports_external.string().min(1).default("Experience"),
  overlapLabel: exports_external.string().min(1).default("Integrated advantage"),
  backgroundFill: exports_external.string().min(1).default("background1")
});
var vennDiagramRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.venn_diagram",
  summary: "Three-circle Venn diagram slide for overlap storytelling.",
  labels: ["slide", "diagram", "venn", "professional"],
  paramsSchema: vennDiagramScriptParamsSchema,
  exampleParams: {
    title: "Capability overlap",
    leftLabel: "Platform",
    rightLabel: "Operations",
    bottomLabel: "Experience",
    overlapLabel: "Integrated advantage"
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const title = slide.shapes.add({
      geometry: "textbox",
      position: { left: 120, top: 70, width: 1060, height: 80 }
    });
    title.text.set(params2.title);
    title.text.style = { bold: true, fontSize: 48, alignment: "center", color: "tx1" };
    const left = slide.shapes.add({
      geometry: "ellipse",
      position: { left: 360, top: 220, width: 320, height: 320 },
      fill: "blue-400/45",
      line: { style: "solid", width: 0, fill: "blue-400/45" }
    });
    const right = slide.shapes.add({
      geometry: "ellipse",
      position: { left: 690, top: 220, width: 320, height: 320 },
      fill: "emerald-400/45",
      line: { style: "solid", width: 0, fill: "emerald-400/45" }
    });
    const bottom = slide.shapes.add({
      geometry: "ellipse",
      position: { left: 525, top: 380, width: 320, height: 320 },
      fill: "violet-400/45",
      line: { style: "solid", width: 0, fill: "violet-400/45" }
    });
    left.text.set(params2.leftLabel);
    left.text.style = { bold: true, fontSize: 28, alignment: "center", color: "tx1" };
    right.text.set(params2.rightLabel);
    right.text.style = { bold: true, fontSize: 28, alignment: "center", color: "tx1" };
    bottom.text.set(params2.bottomLabel);
    bottom.text.style = { bold: true, fontSize: 28, alignment: "center", color: "tx1" };
    const overlap = slide.shapes.add({
      geometry: "textbox",
      position: { left: 530, top: 410, width: 300, height: 80 }
    });
    overlap.text.set(params2.overlapLabel);
    overlap.text.style = {
      bold: true,
      fontSize: 26,
      alignment: "center",
      color: "slate-900"
    };
  },
  notes: ["Use overlap text to call out the differentiated intersection."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/work-pitch/work-pitch-agenda.js
var agendaItemSchema = exports_external.object({
  number: exports_external.string().min(1),
  heading: exports_external.string().min(1),
  body: exports_external.string().min(1)
});
var workPitchAgendaScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("AGENDA"),
  subtitle: exports_external.string().min(1).default("table of contents"),
  items: exports_external.array(agendaItemSchema).length(6).default([
    { number: "01", heading: "Section 1", body: "Agenda item description." },
    { number: "02", heading: "Section 2", body: "Agenda item description." },
    { number: "03", heading: "Section 3", body: "Agenda item description." },
    { number: "04", heading: "Section 4", body: "Agenda item description." },
    { number: "05", heading: "Section 5", body: "Agenda item description." },
    { number: "06", heading: "Section 6", body: "Agenda item description." }
  ]),
  backgroundFill: exports_external.string().min(1).default("accent1"),
  textColor: exports_external.string().min(1).default("white"),
  accentColor: exports_external.string().min(1).default("accent2"),
  footerBrand: exports_external.string().min(1).default("Brand"),
  footerPage: exports_external.string().min(1).default("02"),
  displayTypeface: exports_external.string().min(1).default("Helvetica Neue"),
  serifTypeface: exports_external.string().min(1).default("Times New Roman")
});
var workPitchAgendaRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.work_pitch_agenda",
  summary: "Work Pitch agenda slide with six numbered sections in a 3x2 grid.",
  labels: ["slide", "work pitch", "agenda", "layout"],
  paramsSchema: workPitchAgendaScriptParamsSchema,
  exampleParams: {
    title: "AGENDA",
    subtitle: "table of contents",
    items: [
      { number: "01", heading: "Section 1", body: "Agenda item description." },
      { number: "02", heading: "Section 2", body: "Agenda item description." },
      { number: "03", heading: "Section 3", body: "Agenda item description." },
      { number: "04", heading: "Section 4", body: "Agenda item description." },
      { number: "05", heading: "Section 5", body: "Agenda item description." },
      { number: "06", heading: "Section 6", body: "Agenda item description." }
    ],
    backgroundFill: "accent1",
    textColor: "white",
    accentColor: "accent2",
    displayTypeface: "Helvetica Neue",
    serifTypeface: "Times New Roman"
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const styles = slide.theme.textStyles({
      title: {
        typeface: params2.displayTypeface,
        fontSize: "text-display",
        bold: true,
        color: params2.textColor,
        alignment: "center",
        wrap: "none"
      },
      subtitle: {
        typeface: params2.serifTypeface,
        fontSize: "text-subtitle",
        italic: true,
        color: params2.accentColor,
        alignment: "center",
        wrap: "none"
      },
      agendaNumber: {
        typeface: params2.serifTypeface,
        fontSize: "text-subtitle",
        color: params2.accentColor,
        alignment: "center",
        wrap: "none"
      },
      agendaHeading: {
        typeface: params2.displayTypeface,
        fontSize: "text-section",
        bold: true,
        color: params2.textColor,
        alignment: "center",
        wrap: "none"
      },
      agendaBody: {
        typeface: params2.serifTypeface,
        fontSize: "text-body",
        color: params2.textColor,
        alignment: "center",
        wrap: "square"
      },
      footer: {
        typeface: params2.displayTypeface,
        fontSize: "text-caption",
        color: params2.textColor,
        wrap: "none"
      }
    });
    const root = column({
      name: "workPitchAgenda.root",
      width: "fill",
      height: "fill",
      padding: { x: "s-8", top: "s-18", bottom: "s-4" },
      align: "stretch",
      justify: "between"
    }, [
      column({
        name: "workPitchAgenda.header",
        gap: "s-1",
        align: "center"
      }, [
        text(params2.title, {
          name: "workPitchAgenda.title",
          style: styles.title
        }),
        text(params2.subtitle.toLowerCase(), {
          name: "workPitchAgenda.subtitle",
          style: styles.subtitle
        })
      ]),
      grid({
        name: "workPitchAgenda.grid",
        width: "fill",
        height: "fill",
        columns: repeat(3, fr(1)),
        rows: repeat(2, auto),
        columnGap: "s-40",
        rowGap: "s-4",
        alignItems: "center",
        justifyItems: "center"
      }, params2.items.map((item) => column({
        name: `workPitchAgenda.item.${item.number}`,
        gap: "s-1",
        align: "center"
      }, [
        text(item.number, {
          name: `workPitchAgenda.itemNumber.${item.number}`,
          style: styles.agendaNumber
        }),
        column({
          name: `workPitchAgenda.itemText.${item.number}`,
          gap: 0,
          align: "center"
        }, [
          text(item.heading, {
            name: `workPitchAgenda.itemHeading.${item.number}`,
            style: styles.agendaHeading,
            transform: "uppercase"
          }),
          text(item.body, {
            name: `workPitchAgenda.itemBody.${item.number}`,
            style: styles.agendaBody,
            width: wrap(216)
          })
        ])
      ]))),
      column({
        name: "workPitchAgenda.footer",
        width: "fill",
        gap: "s-1",
        align: "stretch"
      }, [
        rule({
          name: "workPitchAgenda.footerLine",
          stroke: params2.textColor,
          opacity: 0.24,
          weight: 1
        }),
        row({
          name: "workPitchAgenda.footerRow",
          width: "fill",
          align: "center",
          justify: "between"
        }, [
          text(params2.footerBrand, {
            name: "workPitchAgenda.footerBrand",
            style: styles.footer
          }),
          text(params2.footerPage, {
            name: "workPitchAgenda.footerPage",
            style: styles.footer
          })
        ])
      ])
    ]);
    slide.compose(root, { baseUnit: 4 });
  },
  notes: ["Pass six agenda items in reading order from left-to-right, top-to-bottom."]
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/work-pitch/work-pitch-cover.js
var workPitchCoverScriptParamsSchema = exports_external.object({
  backgroundImage: exports_external.string().min(1),
  accentColor: exports_external.string().min(1).default("accent1"),
  title: exports_external.string().min(1).default("Title"),
  titleColor: exports_external.string().min(1).default("white"),
  titleFontSize: exports_external.number().min(12).max(220).default(96),
  titleTypeface: exports_external.string().min(1).default("Helvetica Neue"),
  tableCells: exports_external.array(exports_external.string().min(1)).length(6).default([
    "Header 1",
    "Header 2",
    "Header 3",
    "Value 1",
    "Value 2",
    "Value 3"
  ]),
  tableTextColor: exports_external.string().min(1).default("white"),
  tableHeaderFontSize: exports_external.number().min(8).max(72).default(12),
  tableBodyFontSize: exports_external.number().min(8).max(72).default(11)
});
var workPitchCoverRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.work_pitch_cover",
  summary: "Work Pitch slide-level layout with image background, center accent panel, title, and a 2x3 table.",
  labels: ["slide", "work pitch", "cover", "branding", "layout"],
  paramsSchema: workPitchCoverScriptParamsSchema,
  exampleParams: {
    backgroundImage: "tests/presentation/assets/checkerboard.png",
    accentColor: "accent1",
    title: "Title",
    tableCells: [
      "Header 1",
      "Header 2",
      "Header 3",
      "Value 1",
      "Value 2",
      "Value 3"
    ]
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    const imageSource = params2.backgroundImage.trim();
    const imageOptions = imageSource.startsWith("data:") ? { dataUrl: imageSource } : { path: imageSource };
    slide.compose(image({
      name: "workPitchCover.background",
      ...imageOptions,
      fit: "cover",
      alt: "Work Pitch background image",
      width: "fill",
      height: "fill"
    }), { frame: slide.frame, baseUnit: 1 });
    const panelFrame = getPanelFrame(slide.frame);
    const tableFrame = getTableFrame(panelFrame);
    slide.compose(shape({
      name: "workPitchCover.panelBackground",
      geometry: "rect",
      fill: params2.accentColor,
      line: { style: "solid", width: 0, fill: params2.accentColor },
      width: "fill",
      height: "fill"
    }), { frame: panelFrame, baseUnit: 1 });
    const styles = slide.theme.textStyles({
      title: {
        typeface: params2.titleTypeface,
        fontSize: params2.titleFontSize,
        bold: true,
        color: params2.titleColor,
        alignment: "center",
        wrap: "none"
      }
    });
    const panelLayout = column({
      name: "workPitchCover.panel",
      width: "fill",
      height: "fill",
      padding: { x: "s-10", top: "s-16", bottom: "s-20" },
      align: "center",
      justify: "start"
    }, [
      text(params2.title.toUpperCase(), {
        name: "workPitchCover.title",
        style: styles.title,
        width: "fill"
      })
    ]);
    slide.compose(panelLayout, { frame: panelFrame, baseUnit: 1 });
    const [tableElement] = slide.compose(table({
      name: "workPitchCover.metricsTable",
      rows: 2,
      columns: 3,
      values: [params2.tableCells.slice(0, 3), params2.tableCells.slice(3, 6)],
      style: "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}",
      styleOptions: {
        headerRow: true,
        bandedRows: true,
        firstColumn: false,
        lastColumn: false,
        bandedColumns: false,
        totalRow: false
      },
      width: "fill",
      height: "fill"
    }), { frame: tableFrame, baseUnit: 1 });
    if (tableElement?.type !== "table") {
      return;
    }
    for (let rowIndex2 = 0;rowIndex2 < 2; rowIndex2 += 1) {
      for (let columnIndex2 = 0;columnIndex2 < 3; columnIndex2 += 1) {
        const cell = tableElement.getCell(rowIndex2, columnIndex2);
        cell.anchor = "ctr";
        cell.text.style = {
          bold: rowIndex2 === 0,
          fontSize: rowIndex2 === 0 ? params2.tableHeaderFontSize : params2.tableBodyFontSize,
          color: params2.tableTextColor,
          alignment: "center",
          typeface: params2.titleTypeface
        };
      }
    }
  },
  notes: [
    "Pass six tableCells values in row-major order: top-left to bottom-right."
  ]
});
var getPanelFrame = (slideFrame) => ({
  left: slideFrame.left + slideFrame.width * 0.2,
  top: slideFrame.top + slideFrame.height * 0.2,
  width: slideFrame.width * 0.6,
  height: slideFrame.height * 0.6
});
var getTableFrame = (panelFrame) => ({
  left: panelFrame.left + panelFrame.width * 0.07,
  top: panelFrame.top + panelFrame.height * 0.63,
  width: panelFrame.width * 0.86,
  height: panelFrame.height * 0.18
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/work-pitch/work-pitch-founders.js
var founderSchema = exports_external.object({
  name: exports_external.string().min(1),
  title: exports_external.string().min(1)
});
var workPitchFoundersScriptParamsSchema = exports_external.object({
  sectionNumber: exports_external.string().min(1).default("06"),
  headingPrimary: exports_external.string().min(1).default("Meet our"),
  headingAccent: exports_external.string().min(1).default("founders"),
  missionBody: exports_external.string().min(1).default("Use this space to describe the mission and vision in a short, human narrative."),
  founders: exports_external.array(founderSchema).length(3).default([
    { name: "Founder 1", title: "CEO" },
    { name: "Founder 2", title: "COO" },
    { name: "Founder 3", title: "Chief Scientist" }
  ]),
  foundersImage: exports_external.string().min(1),
  backgroundFill: exports_external.string().min(1).default("background1"),
  leftPanelFill: exports_external.string().min(1).default("accent1"),
  textColor: exports_external.string().min(1).default("tx1"),
  inverseTextColor: exports_external.string().min(1).default("white"),
  accentColor: exports_external.string().min(1).default("accent1"),
  footerBrand: exports_external.string().min(1).default("Brand"),
  footerPage: exports_external.string().min(1).default("09"),
  typeface: exports_external.string().min(1).default("Helvetica Neue")
});
var workPitchFoundersRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.work_pitch_founders",
  summary: "Work Pitch founders slide with left mission panel, founder callouts, and a right-side team image.",
  labels: ["slide", "work pitch", "team", "founders"],
  paramsSchema: workPitchFoundersScriptParamsSchema,
  exampleParams: {
    sectionNumber: "06",
    headingPrimary: "Meet our",
    headingAccent: "founders",
    missionBody: "Use this space to describe the mission and vision in a short, human narrative.",
    founders: [
      { name: "Founder 1", title: "CEO" },
      { name: "Founder 2", title: "COO" },
      { name: "Founder 3", title: "Chief Scientist" }
    ],
    foundersImage: "tests/presentation/assets/checkerboard.png"
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const leftPanel = getLeftPanelFrame(slide.frame);
    const imageFrame = getFoundersImageFrame(slide.frame);
    slide.compose(shape({
      name: "workPitchFounders.leftPanelBackground",
      geometry: "rect",
      fill: params2.leftPanelFill,
      line: { style: "solid", width: 0, fill: params2.leftPanelFill },
      width: "fill",
      height: "fill"
    }), { frame: leftPanel, baseUnit: 1 });
    const imageSource = params2.foundersImage.trim();
    const imageOptions = imageSource.startsWith("data:") ? { dataUrl: imageSource } : { path: imageSource };
    slide.compose(image({
      name: "workPitchFounders.heroImage",
      ...imageOptions,
      fit: "cover",
      alt: "Founders image",
      width: "fill",
      height: "fill"
    }), { frame: imageFrame, baseUnit: 1 });
    const styles = slide.theme.textStyles({
      sectionNumber: {
        typeface: params2.typeface,
        fontSize: "text-64",
        bold: true,
        color: params2.inverseTextColor,
        alignment: "left",
        wrap: "none"
      },
      heading: {
        typeface: "EB Garamond",
        fontSize: "text-54",
        color: params2.inverseTextColor,
        alignment: "left",
        wrap: "square"
      },
      mission: {
        typeface: "EB Garamond",
        fontSize: "text-22",
        lineSpacing: 1.2,
        color: params2.inverseTextColor,
        alignment: "left",
        wrap: "square"
      },
      founder: {
        typeface: params2.typeface,
        fontSize: "text-16",
        color: params2.textColor,
        alignment: "left",
        wrap: "none"
      },
      footerBrand: {
        typeface: params2.typeface,
        fontSize: "text-caption",
        color: params2.textColor,
        alignment: "left",
        wrap: "none"
      },
      footerPage: {
        typeface: params2.typeface,
        fontSize: "text-caption",
        color: params2.textColor,
        alignment: "right",
        wrap: "none"
      }
    });
    const headingContent = `${params2.headingPrimary}
${params2.headingAccent}`;
    const root = column({
      name: "workPitchFounders.root",
      width: "fill",
      height: "fill",
      padding: { x: "s-8", top: "s-13", bottom: "s-4" },
      align: "stretch",
      justify: "between"
    }, [
      row({
        name: "workPitchFounders.content",
        width: "fill",
        height: "fill",
        align: "stretch",
        justify: "between",
        gap: "s-8"
      }, [
        column({
          name: "workPitchFounders.leftColumn",
          width: wrap(leftPanel.width - 96),
          height: "fill",
          align: "start",
          justify: "between"
        }, [
          row({
            name: "workPitchFounders.headingRow",
            width: "fill",
            align: "start",
            gap: "s-4"
          }, [
            text(params2.sectionNumber, {
              name: "workPitchFounders.sectionNumber",
              style: styles.sectionNumber
            }),
            text(headingContent, {
              name: "workPitchFounders.heading",
              style: styles.heading,
              width: "fill"
            })
          ]),
          text(params2.missionBody, {
            name: "workPitchFounders.mission",
            style: styles.mission,
            width: "fill"
          })
        ]),
        column({
          name: "workPitchFounders.rightColumn",
          width: "fill",
          height: "fill",
          align: "stretch",
          justify: "start",
          padding: { top: "s-7" }
        }, [
          row({
            name: "workPitchFounders.founderRow",
            width: "fill",
            align: "start",
            justify: "between",
            gap: "s-4"
          }, params2.founders.map((founder) => column({
            name: `workPitchFounders.founder.${founder.name}`,
            width: "fill",
            align: "start",
            gap: "s-2"
          }, [
            text(`${founder.name} — ${founder.title}`, {
              name: `workPitchFounders.founderText.${founder.name}`,
              style: styles.founder,
              width: "fill"
            }),
            rule({
              name: `workPitchFounders.founderConnector.${founder.name}`,
              stroke: params2.accentColor,
              weight: 2,
              width: "fill"
            })
          ])))
        ])
      ]),
      column({
        name: "workPitchFounders.footer",
        width: "fill",
        gap: "s-1",
        align: "stretch"
      }, [
        rule({
          name: "workPitchFounders.footerLine",
          stroke: params2.textColor,
          opacity: 0.24,
          weight: 1
        }),
        row({
          name: "workPitchFounders.footerRow",
          width: "fill",
          align: "center",
          justify: "between"
        }, [
          text(params2.footerBrand, {
            name: "workPitchFounders.footerBrand",
            style: styles.footerBrand
          }),
          text(params2.footerPage, {
            name: "workPitchFounders.footerPage",
            style: styles.footerPage
          })
        ])
      ])
    ]);
    slide.compose(root, { baseUnit: 1 });
  }
});
var getLeftPanelFrame = (slideFrame) => ({
  left: slideFrame.left,
  top: slideFrame.top,
  width: slideFrame.width * 0.41,
  height: slideFrame.height
});
var getFoundersImageFrame = (slideFrame) => ({
  left: slideFrame.left + slideFrame.width * 0.41,
  top: slideFrame.top + slideFrame.height * 0.25,
  width: slideFrame.width * 0.59,
  height: slideFrame.height * 0.75
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/work-pitch/work-pitch-funding-ask.js
var workPitchFundingAskScriptParamsSchema = exports_external.object({
  sectionNumber: exports_external.string().min(1).default("07"),
  headline: exports_external.string().min(1).default("Join us in redefining radiance"),
  fundingAsk: exports_external.string().min(1).default(`Funding Ask
Seeking: $1.2M
Seed Round
For scaling production, retail expansion, marketing, and R&D.`),
  closing: exports_external.string().min(1).default("Use this closing line to invite next steps and share the strategic ask."),
  backgroundFill: exports_external.string().min(1).default("background1"),
  accentColor: exports_external.string().min(1).default("accent1"),
  textColor: exports_external.string().min(1).default("tx1"),
  footerBrand: exports_external.string().min(1).default("Brand"),
  footerPage: exports_external.string().min(1).default("10"),
  typeface: exports_external.string().min(1).default("Helvetica Neue")
});
var workPitchFundingAskRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.work_pitch_funding_ask",
  summary: "Work Pitch closing slide with a main headline, funding ask block, and final call-to-action.",
  labels: ["slide", "work pitch", "closing", "funding"],
  paramsSchema: workPitchFundingAskScriptParamsSchema,
  exampleParams: {
    sectionNumber: "07",
    headline: "Join us in redefining radiance",
    fundingAsk: `Funding Ask
Seeking: $1.2M
Seed Round
For scaling production, retail expansion, marketing, and R&D.`,
    closing: "Use this closing line to invite next steps and share the strategic ask."
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const styles = slide.theme.textStyles({
      sectionNumber: {
        typeface: params2.typeface,
        fontSize: "text-64",
        bold: true,
        color: params2.accentColor,
        alignment: "left",
        wrap: "none"
      },
      headline: {
        typeface: "EB Garamond",
        fontSize: "text-64",
        color: params2.textColor,
        alignment: "right",
        wrap: "square"
      },
      funding: {
        typeface: params2.typeface,
        fontSize: "text-24",
        lineSpacing: 1.2,
        color: params2.textColor,
        alignment: "left",
        wrap: "square"
      },
      closing: {
        typeface: "EB Garamond",
        fontSize: "text-24",
        lineSpacing: 1.2,
        color: params2.textColor,
        alignment: "right",
        wrap: "square"
      },
      footerBrand: {
        typeface: params2.typeface,
        fontSize: "text-caption",
        color: params2.textColor,
        alignment: "left",
        wrap: "none"
      },
      footerPage: {
        typeface: params2.typeface,
        fontSize: "text-caption",
        color: params2.textColor,
        alignment: "right",
        wrap: "none"
      }
    });
    const root = column({
      name: "workPitchFundingAsk.root",
      width: "fill",
      height: "fill",
      padding: { x: "s-8", top: "s-13", bottom: "s-4" },
      align: "stretch",
      justify: "between"
    }, [
      row({
        name: "workPitchFundingAsk.header",
        width: "fill",
        justify: "between",
        align: "start",
        gap: "s-8"
      }, [
        text(params2.sectionNumber, {
          name: "workPitchFundingAsk.sectionNumber",
          style: styles.sectionNumber
        }),
        text(params2.headline, {
          name: "workPitchFundingAsk.headline",
          style: styles.headline,
          width: wrap(640)
        })
      ]),
      column({
        name: "workPitchFundingAsk.content",
        width: "fill",
        height: "fill",
        justify: "between",
        align: "stretch",
        padding: { top: "s-8", bottom: "s-4" }
      }, [
        row({
          name: "workPitchFundingAsk.fundingRow",
          width: "fill",
          align: "center",
          gap: "s-6"
        }, [
          text(params2.fundingAsk, {
            name: "workPitchFundingAsk.funding",
            style: styles.funding,
            width: wrap(280)
          }),
          rule({
            name: "workPitchFundingAsk.fundingConnector",
            stroke: params2.accentColor,
            weight: 2,
            width: "fill"
          })
        ]),
        row({
          name: "workPitchFundingAsk.closingRow",
          width: "fill",
          justify: "end"
        }, [
          text(params2.closing, {
            name: "workPitchFundingAsk.closing",
            style: styles.closing,
            width: wrap(288)
          })
        ])
      ]),
      column({
        name: "workPitchFundingAsk.footer",
        width: "fill",
        gap: "s-1",
        align: "stretch"
      }, [
        rule({
          name: "workPitchFundingAsk.footerLine",
          stroke: params2.textColor,
          opacity: 0.24,
          weight: 1
        }),
        row({
          name: "workPitchFundingAsk.footerRow",
          width: "fill",
          justify: "between",
          align: "center"
        }, [
          text(params2.footerBrand, {
            name: "workPitchFundingAsk.footerBrand",
            style: styles.footerBrand
          }),
          text(params2.footerPage, {
            name: "workPitchFundingAsk.footerPage",
            style: styles.footerPage
          })
        ])
      ])
    ]);
    const shapes = slide.compose(root, { baseUnit: 1 });
    const headlineShape = shapes.find((shape2) => shape2.name === "workPitchFundingAsk.headline");
    const fundingShape = shapes.find((shape2) => shape2.name === "workPitchFundingAsk.funding");
    if (headlineShape?.type === "shape") {
      const headlineAccent = resolveHeadlineAccentPhrase(params2.headline);
      if (headlineAccent) {
        const accentRange = headlineShape.text.get(headlineAccent);
        accentRange.italic = true;
        accentRange.color = params2.accentColor;
      }
    }
    if (fundingShape?.type === "shape") {
      const emphasisChunk = resolveFundingEmphasisChunk(params2.fundingAsk);
      if (emphasisChunk) {
        const emphasisRange = fundingShape.text.get(emphasisChunk);
        emphasisRange.bold = true;
        emphasisRange.color = params2.accentColor;
      }
    }
  }
});
var resolveHeadlineAccentPhrase = (headline) => {
  const joinUsMatch = /join us/i.exec(headline);
  if (joinUsMatch?.index !== undefined) {
    return headline.slice(joinUsMatch.index, joinUsMatch.index + joinUsMatch[0].length);
  }
  const words = headline.trim().split(/\s+/).filter(Boolean);
  if (words.length < 2) {
    return words[0];
  }
  return `${words[0]} ${words[1]}`;
};
var resolveFundingEmphasisChunk = (fundingAsk) => {
  const lines = fundingAsk.split(/\r?\n/).map((line) => line.trimEnd()).filter((line) => line.length > 0);
  if (lines.length === 0) {
    return;
  }
  return lines.slice(0, Math.min(3, lines.length)).join(`
`);
};

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/work-pitch/work-pitch-inspiration.js
var pointSchema = exports_external.object({
  label: exports_external.string().min(1)
});
var workPitchInspirationScriptParamsSchema = exports_external.object({
  sectionNumber: exports_external.string().min(1).default("01"),
  headlinePrimary: exports_external.string().min(1).default("The inspiration"),
  headlineAccent: exports_external.string().min(1).default("behind"),
  brandWord: exports_external.string().min(1).default("Title"),
  body: exports_external.string().min(1).default("Use this section to describe the product inspiration and why the idea matters."),
  quote: exports_external.string().min(1).default("Add a short sentence that captures the emotional thesis."),
  rightPoints: exports_external.array(pointSchema).length(4).default([
    { label: "Point 1" },
    { label: "Point 2" },
    { label: "Point 3" },
    { label: "Point 4" }
  ]),
  backgroundFill: exports_external.string().min(1).default("background1"),
  accentColor: exports_external.string().min(1).default("accent1"),
  textColor: exports_external.string().min(1).default("tx1"),
  footerBrand: exports_external.string().min(1).default("Brand"),
  footerPage: exports_external.string().min(1).default("04"),
  typeface: exports_external.string().min(1).default("Helvetica Neue")
});
var workPitchInspirationRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.work_pitch_inspiration",
  summary: "Work Pitch inspiration slide with narrative copy on the left and four right-side points.",
  labels: ["slide", "work pitch", "narrative", "story"],
  paramsSchema: workPitchInspirationScriptParamsSchema,
  exampleParams: {
    sectionNumber: "01",
    headlinePrimary: "The inspiration",
    headlineAccent: "behind",
    brandWord: "Title",
    body: "Use this section to describe the product inspiration and why the idea matters.",
    quote: "Add a short sentence that captures the emotional thesis.",
    rightPoints: [
      { label: "Point 1" },
      { label: "Point 2" },
      { label: "Point 3" },
      { label: "Point 4" }
    ]
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const styles = slide.theme.textStyles({
      sectionNumber: {
        typeface: params2.typeface,
        fontSize: "text-64",
        bold: true,
        color: params2.accentColor,
        alignment: "left",
        wrap: "none"
      },
      headline: {
        typeface: params2.typeface,
        fontSize: "text-54",
        bold: true,
        color: params2.textColor,
        alignment: "left",
        wrap: "square"
      },
      body: {
        typeface: "EB Garamond",
        fontSize: "text-26",
        lineSpacing: 1.2,
        color: params2.textColor,
        alignment: "left",
        wrap: "square"
      },
      quote: {
        typeface: "EB Garamond",
        fontSize: "text-32",
        color: params2.accentColor,
        alignment: "left",
        wrap: "square"
      },
      point: {
        typeface: params2.typeface,
        fontSize: "text-body",
        color: params2.textColor,
        alignment: "left",
        wrap: "none"
      },
      footerBrand: {
        typeface: params2.typeface,
        fontSize: "text-caption",
        color: params2.textColor,
        alignment: "left",
        wrap: "none"
      },
      footerPage: {
        typeface: params2.typeface,
        fontSize: "text-caption",
        color: params2.textColor,
        alignment: "right",
        wrap: "none"
      }
    });
    const headlineContent = `${params2.headlinePrimary}
${params2.headlineAccent} ${params2.brandWord}`;
    const root = column({
      name: "workPitchInspiration.root",
      width: "fill",
      height: "fill",
      padding: { x: "s-8", top: "s-13", bottom: "s-4" },
      align: "stretch",
      justify: "between"
    }, [
      row({
        name: "workPitchInspiration.header",
        width: "fill",
        align: "start",
        gap: "s-6"
      }, [
        text(params2.sectionNumber, {
          name: "workPitchInspiration.sectionNumber",
          style: styles.sectionNumber
        }),
        text(headlineContent, {
          name: "workPitchInspiration.headline",
          style: styles.headline,
          width: wrap(540)
        })
      ]),
      row({
        name: "workPitchInspiration.content",
        width: "fill",
        height: "fill",
        align: "stretch",
        justify: "between",
        gap: "s-10",
        padding: { top: "s-6", bottom: "s-4" }
      }, [
        column({
          name: "workPitchInspiration.leftColumn",
          width: wrap(460),
          height: "fill",
          align: "start",
          justify: "between",
          gap: "s-6"
        }, [
          text(params2.body, {
            name: "workPitchInspiration.body",
            style: styles.body,
            width: "fill"
          }),
          text(params2.quote, {
            name: "workPitchInspiration.quote",
            style: styles.quote,
            width: "fill"
          })
        ]),
        column({
          name: "workPitchInspiration.points",
          width: wrap(320),
          height: "fill",
          justify: "between",
          align: "stretch",
          padding: { y: "s-4" }
        }, params2.rightPoints.map((point3) => row({
          name: `workPitchInspiration.pointRow.${point3.label}`,
          width: "fill",
          align: "center",
          gap: "s-2"
        }, [
          rule({
            name: `workPitchInspiration.pointConnector.${point3.label}`,
            stroke: params2.accentColor,
            weight: 2,
            width: "fill"
          }),
          text(point3.label, {
            name: `workPitchInspiration.pointText.${point3.label}`,
            style: styles.point,
            width: wrap(180)
          })
        ])))
      ]),
      column({
        name: "workPitchInspiration.footer",
        width: "fill",
        gap: "s-1",
        align: "stretch"
      }, [
        rule({
          name: "workPitchInspiration.footerLine",
          stroke: params2.textColor,
          opacity: 0.24,
          weight: 1
        }),
        row({
          name: "workPitchInspiration.footerRow",
          width: "fill",
          align: "center",
          justify: "between"
        }, [
          text(params2.footerBrand, {
            name: "workPitchInspiration.footerBrand",
            style: styles.footerBrand
          }),
          text(params2.footerPage, {
            name: "workPitchInspiration.footerPage",
            style: styles.footerPage
          })
        ])
      ])
    ]);
    const shapes = slide.compose(root, { baseUnit: 1 });
    const headlineShape = shapes.find((shape2) => shape2.name === "workPitchInspiration.headline");
    if (headlineShape?.type === "shape") {
      const accentRange = headlineShape.text.get(params2.headlineAccent);
      accentRange.bold = false;
      accentRange.color = params2.accentColor;
      const brandRange = headlineShape.text.get(params2.brandWord);
      brandRange.bold = false;
      brandRange.color = params2.accentColor;
      brandRange.fontSize = 58;
    }
  }
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/work-pitch/work-pitch-market-growth.js
var quarterSchema = exports_external.object({
  label: exports_external.string().min(1),
  previousValue: exports_external.number().nonnegative(),
  currentValue: exports_external.number().nonnegative()
});
var workPitchMarketGrowthScriptParamsSchema = exports_external.object({
  sectionNumber: exports_external.string().min(1).default("03"),
  heading: exports_external.string().min(1).default("The market is ready for a"),
  headingAccent: exports_external.string().min(1).default("new kind of glow"),
  narrative: exports_external.string().min(1).default("Use this paragraph to describe market momentum and demand for the category."),
  chartTitle: exports_external.string().min(1).default("Projected market demand for natural glow products"),
  quarters: exports_external.array(quarterSchema).length(4).default([
    { label: "Q1", previousValue: 2800, currentValue: 3850 },
    { label: "Q2", previousValue: 3050, currentValue: 4180 },
    { label: "Q3", previousValue: 3320, currentValue: 4520 },
    { label: "Q4", previousValue: 3600, currentValue: 4910 }
  ]),
  backgroundFill: exports_external.string().min(1).default("background1"),
  bandFill: exports_external.string().min(1).default("accent1"),
  barPreviousFill: exports_external.string().min(1).default("white"),
  barCurrentFill: exports_external.string().min(1).default("tx1"),
  textColor: exports_external.string().min(1).default("tx1"),
  inverseTextColor: exports_external.string().min(1).default("white"),
  footerBrand: exports_external.string().min(1).default("Brand"),
  footerPage: exports_external.string().min(1).default("06"),
  typeface: exports_external.string().min(1).default("Helvetica Neue")
});
var workPitchMarketGrowthRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.work_pitch_market_growth",
  summary: "Work Pitch market slide with paired quarter bars and a supporting narrative block.",
  labels: ["slide", "work pitch", "market", "chart"],
  paramsSchema: workPitchMarketGrowthScriptParamsSchema,
  exampleParams: {
    sectionNumber: "03",
    heading: "The market is ready for a",
    headingAccent: "new kind of glow",
    narrative: "Use this paragraph to describe market momentum and demand for the category.",
    chartTitle: "Projected market demand for natural glow products",
    quarters: [
      { label: "Q1", previousValue: 2800, currentValue: 3850 },
      { label: "Q2", previousValue: 3050, currentValue: 4180 },
      { label: "Q3", previousValue: 3320, currentValue: 4520 },
      { label: "Q4", previousValue: 3600, currentValue: 4910 }
    ]
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const bandFrame = getBandFrame(slide.frame);
    const chartFrame = getChartFrame(slide.frame);
    slide.compose(shape({
      name: "workPitchMarketGrowth.bandBackground",
      geometry: "rect",
      fill: params2.bandFill,
      line: { style: "solid", width: 0, fill: params2.bandFill },
      width: "fill",
      height: "fill"
    }), { frame: bandFrame, baseUnit: 1 });
    const styles = slide.theme.textStyles({
      sectionNumber: {
        typeface: params2.typeface,
        fontSize: "text-64",
        bold: true,
        color: params2.bandFill,
        alignment: "left",
        wrap: "none"
      },
      heading: {
        typeface: "EB Garamond",
        fontSize: "text-54",
        color: params2.textColor,
        alignment: "left",
        wrap: "square"
      },
      narrative: {
        typeface: "EB Garamond",
        fontSize: "text-24",
        lineSpacing: 1.2,
        color: params2.textColor,
        alignment: "left",
        wrap: "square"
      },
      chartTitle: {
        typeface: params2.typeface,
        fontSize: "text-16",
        color: params2.inverseTextColor,
        alignment: "left",
        wrap: "square"
      },
      barLabel: {
        typeface: params2.typeface,
        fontSize: "text-11",
        color: params2.inverseTextColor,
        alignment: "center",
        wrap: "none"
      },
      footerBrand: {
        typeface: params2.typeface,
        fontSize: "text-caption",
        color: params2.inverseTextColor,
        alignment: "left",
        wrap: "none"
      },
      footerPage: {
        typeface: params2.typeface,
        fontSize: "text-caption",
        color: params2.inverseTextColor,
        alignment: "right",
        wrap: "none"
      }
    });
    const headingContent = `${params2.heading}
${params2.headingAccent}`;
    const root = column({
      name: "workPitchMarketGrowth.root",
      width: "fill",
      height: "fill",
      padding: { x: "s-8", top: "s-13", bottom: "s-4" },
      align: "stretch",
      justify: "between"
    }, [
      row({
        name: "workPitchMarketGrowth.header",
        width: "fill",
        align: "start",
        gap: "s-6"
      }, [
        text(params2.sectionNumber, {
          name: "workPitchMarketGrowth.sectionNumber",
          style: styles.sectionNumber
        }),
        text(headingContent, {
          name: "workPitchMarketGrowth.heading",
          style: styles.heading,
          width: wrap(700)
        })
      ]),
      row({
        name: "workPitchMarketGrowth.content",
        width: "fill",
        height: "fill",
        align: "start",
        justify: "between",
        padding: { top: "s-4", bottom: "s-4" }
      }, [
        text(params2.narrative, {
          name: "workPitchMarketGrowth.narrative",
          style: styles.narrative,
          width: wrap(460)
        })
      ]),
      column({
        name: "workPitchMarketGrowth.footer",
        width: "fill",
        gap: "s-1",
        align: "stretch"
      }, [
        rule({
          name: "workPitchMarketGrowth.footerLine",
          stroke: params2.inverseTextColor,
          opacity: 0.24,
          weight: 1
        }),
        row({
          name: "workPitchMarketGrowth.footerRow",
          width: "fill",
          align: "center",
          justify: "between"
        }, [
          text(params2.footerBrand, {
            name: "workPitchMarketGrowth.footerBrand",
            style: styles.footerBrand
          }),
          text(params2.footerPage, {
            name: "workPitchMarketGrowth.footerPage",
            style: styles.footerPage
          })
        ])
      ])
    ]);
    const composedShapes = slide.compose(root, { baseUnit: 1 });
    const headingShape = composedShapes.find((element) => element.name === "workPitchMarketGrowth.heading");
    if (headingShape?.type === "shape") {
      const accentRange = headingShape.text.get(params2.headingAccent);
      accentRange.color = params2.bandFill;
    }
    const maxValue = Math.max(...params2.quarters.map((quarter) => Math.max(quarter.previousValue, quarter.currentValue)), 1);
    params2.quarters.forEach((quarter, index) => {
      const groupWidth = chartFrame.width / params2.quarters.length;
      const groupLeft = chartFrame.left + index * groupWidth;
      const barWidth = Math.min(90, groupWidth * 0.33);
      const previousLeft = groupLeft + groupWidth * 0.12;
      const currentLeft = groupLeft + groupWidth * 0.55;
      const previousHeight = quarter.previousValue / maxValue * chartFrame.height;
      const currentHeight = quarter.currentValue / maxValue * chartFrame.height;
      slide.compose(shape({
        name: `workPitchMarketGrowth.bar.previous.${quarter.label}`,
        geometry: "rect",
        fill: params2.barPreviousFill,
        line: { style: "solid", width: 0, fill: params2.barPreviousFill },
        width: "fill",
        height: "fill"
      }), {
        frame: {
          left: previousLeft,
          top: chartFrame.top + (chartFrame.height - previousHeight),
          width: barWidth,
          height: previousHeight
        },
        baseUnit: 1
      });
      slide.compose(shape({
        name: `workPitchMarketGrowth.bar.current.${quarter.label}`,
        geometry: "rect",
        fill: params2.barCurrentFill,
        line: { style: "solid", width: 0, fill: params2.barCurrentFill },
        width: "fill",
        height: "fill"
      }), {
        frame: {
          left: currentLeft,
          top: chartFrame.top + (chartFrame.height - currentHeight),
          width: barWidth,
          height: currentHeight
        },
        baseUnit: 1
      });
      slide.compose(text(`${quarter.label}-Prev
$${quarter.previousValue.toLocaleString()}`, {
        name: `workPitchMarketGrowth.label.previous.${quarter.label}`,
        style: styles.barLabel,
        width: "fill",
        height: "fill"
      }), {
        frame: {
          left: previousLeft,
          top: bandFrame.top + bandFrame.height * 0.16,
          width: barWidth,
          height: bandFrame.height * 0.26
        },
        baseUnit: 1
      });
      slide.compose(text(`${quarter.label}-Now
$${quarter.currentValue.toLocaleString()}`, {
        name: `workPitchMarketGrowth.label.current.${quarter.label}`,
        style: styles.barLabel,
        width: "fill",
        height: "fill"
      }), {
        frame: {
          left: currentLeft,
          top: bandFrame.top + bandFrame.height * 0.5,
          width: barWidth,
          height: bandFrame.height * 0.26
        },
        baseUnit: 1
      });
    });
    slide.compose(text(params2.chartTitle, {
      name: "workPitchMarketGrowth.chartTitle",
      style: styles.chartTitle,
      width: "fill",
      height: "fill"
    }), {
      frame: {
        left: bandFrame.left + bandFrame.width * 0.05,
        top: bandFrame.top + bandFrame.height * 0.2,
        width: bandFrame.width * 0.28,
        height: bandFrame.height * 0.34
      },
      baseUnit: 1
    });
  }
});
var getBandFrame = (slideFrame) => ({
  left: slideFrame.left,
  top: slideFrame.top + slideFrame.height * 0.765,
  width: slideFrame.width,
  height: slideFrame.height * 0.235
});
var getChartFrame = (slideFrame) => ({
  left: slideFrame.left + slideFrame.width * 0.33,
  top: slideFrame.top + slideFrame.height * 0.37,
  width: slideFrame.width * 0.61,
  height: slideFrame.height * 0.39
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/work-pitch/work-pitch-opening-mark.js
var workPitchOpeningMarkScriptParamsSchema = exports_external.object({
  backgroundImage: exports_external.string().min(1),
  panelFill: exports_external.string().min(1).default("accent1"),
  wordmarkLeft: exports_external.string().min(1).default("FIGL"),
  wordmarkRight: exports_external.string().min(1).default("W"),
  wordmarkColor: exports_external.string().min(1).default("white"),
  wordmarkFontSize: exports_external.number().min(32).max(220).default(96),
  emblemColor: exports_external.string().min(1).default("white"),
  deckLabel: exports_external.string().min(1).default("PITCH DECK"),
  tableCells: exports_external.array(exports_external.string().min(1)).length(6).default([
    "Header 1",
    "Header 2",
    "Header 3",
    "Value 1",
    "Value 2",
    "Value 3"
  ]),
  tableTextColor: exports_external.string().min(1).default("white"),
  tableHeaderFontSize: exports_external.number().min(8).max(72).default(12),
  tableBodyFontSize: exports_external.number().min(8).max(72).default(11),
  typeface: exports_external.string().min(1).default("Helvetica Neue")
});
var WORK_PITCH_EMBLEM = {
  ringSize: 30,
  dotSize: 4.5,
  radius: 26,
  dotCount: 12
};
var workPitchOpeningMarkRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.work_pitch_opening_mark",
  summary: "Work Pitch opening layout with split wordmark, emblem, deck label, and 2x3 table.",
  labels: ["slide", "work pitch", "branding", "cover", "layout"],
  paramsSchema: workPitchOpeningMarkScriptParamsSchema,
  exampleParams: {
    backgroundImage: "tests/presentation/assets/checkerboard.png",
    panelFill: "accent1",
    wordmarkLeft: "FIGL",
    wordmarkRight: "W",
    tableCells: [
      "Header 1",
      "Header 2",
      "Header 3",
      "Value 1",
      "Value 2",
      "Value 3"
    ]
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    const imageSource = params2.backgroundImage.trim();
    const imageOptions = imageSource.startsWith("data:") ? { dataUrl: imageSource } : { path: imageSource };
    slide.compose(image({
      name: "workPitchOpeningMark.background",
      ...imageOptions,
      fit: "cover",
      alt: "Work Pitch background image",
      width: "fill",
      height: "fill"
    }), { frame: slide.frame, baseUnit: 1 });
    const panelFrame = getPanelFrame2(slide.frame);
    const tableFrame = getTableFrame2(panelFrame);
    const emblemCenter = getEmblemCenter(panelFrame);
    slide.compose(shape({
      name: "workPitchOpeningMark.panelBackground",
      geometry: "rect",
      fill: params2.panelFill,
      line: { style: "solid", width: 0, fill: params2.panelFill },
      width: "fill",
      height: "fill"
    }), { frame: panelFrame, baseUnit: 1 });
    const styles = slide.theme.textStyles({
      wordmark: {
        typeface: params2.typeface,
        fontSize: params2.wordmarkFontSize,
        bold: true,
        color: params2.wordmarkColor,
        alignment: "center",
        wrap: "none"
      },
      deckLabel: {
        typeface: params2.typeface,
        fontSize: "text-14",
        color: params2.wordmarkColor,
        alignment: "center",
        wrap: "none"
      }
    });
    const panelLayout = column({
      name: "workPitchOpeningMark.panel",
      width: "fill",
      height: "fill",
      padding: { x: "s-10", top: "s-16", bottom: "s-20" },
      justify: "between",
      align: "stretch"
    }, [
      row({
        name: "workPitchOpeningMark.wordmarkRow",
        width: "fill",
        align: "center",
        justify: "between"
      }, [
        text(params2.wordmarkLeft, {
          name: "workPitchOpeningMark.wordmarkLeft",
          style: styles.wordmark,
          width: wrap(panelFrame.width * 0.42)
        }),
        text(params2.wordmarkRight, {
          name: "workPitchOpeningMark.wordmarkRight",
          style: styles.wordmark,
          width: wrap(panelFrame.width * 0.28)
        })
      ]),
      text(params2.deckLabel, {
        name: "workPitchOpeningMark.deckLabel",
        style: styles.deckLabel,
        width: "fill"
      })
    ]);
    slide.compose(panelLayout, { frame: panelFrame, baseUnit: 1 });
    slide.compose(shape({
      name: "workPitchOpeningMark.emblemRing",
      geometry: "ellipse",
      fill: "none",
      line: { style: "solid", width: 2, fill: params2.emblemColor },
      width: "fill",
      height: "fill"
    }), {
      frame: {
        left: emblemCenter.x - WORK_PITCH_EMBLEM.ringSize / 2,
        top: emblemCenter.y - WORK_PITCH_EMBLEM.ringSize / 2,
        width: WORK_PITCH_EMBLEM.ringSize,
        height: WORK_PITCH_EMBLEM.ringSize
      },
      baseUnit: 1
    });
    for (let index = 0;index < WORK_PITCH_EMBLEM.dotCount; index += 1) {
      const angle = index / WORK_PITCH_EMBLEM.dotCount * Math.PI * 2;
      const left = emblemCenter.x + Math.cos(angle) * WORK_PITCH_EMBLEM.radius - WORK_PITCH_EMBLEM.dotSize / 2;
      const top = emblemCenter.y + Math.sin(angle) * WORK_PITCH_EMBLEM.radius - WORK_PITCH_EMBLEM.dotSize / 2;
      slide.compose(shape({
        name: `workPitchOpeningMark.emblemDot.${index + 1}`,
        geometry: "ellipse",
        fill: params2.emblemColor,
        line: { style: "solid", width: 0, fill: params2.emblemColor },
        width: "fill",
        height: "fill"
      }), {
        frame: {
          left,
          top,
          width: WORK_PITCH_EMBLEM.dotSize,
          height: WORK_PITCH_EMBLEM.dotSize
        },
        baseUnit: 1
      });
    }
    const [tableElement] = slide.compose(table({
      name: "workPitchOpeningMark.metricsTable",
      rows: 2,
      columns: 3,
      values: [params2.tableCells.slice(0, 3), params2.tableCells.slice(3, 6)],
      style: "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}",
      styleOptions: {
        headerRow: true,
        bandedRows: true,
        firstColumn: false,
        lastColumn: false,
        bandedColumns: false,
        totalRow: false
      },
      width: "fill",
      height: "fill"
    }), { frame: tableFrame, baseUnit: 1 });
    if (tableElement?.type !== "table") {
      return;
    }
    for (let rowIndex2 = 0;rowIndex2 < 2; rowIndex2 += 1) {
      for (let columnIndex2 = 0;columnIndex2 < 3; columnIndex2 += 1) {
        const cell = tableElement.getCell(rowIndex2, columnIndex2);
        cell.anchor = "ctr";
        cell.text.style = {
          bold: rowIndex2 === 0,
          fontSize: rowIndex2 === 0 ? params2.tableHeaderFontSize : params2.tableBodyFontSize,
          color: params2.tableTextColor,
          alignment: "center",
          typeface: params2.typeface
        };
      }
    }
  },
  notes: [
    "Pass six tableCells values in row-major order: top-left to bottom-right."
  ]
});
var getPanelFrame2 = (slideFrame) => ({
  left: slideFrame.left + slideFrame.width * 0.2,
  top: slideFrame.top + slideFrame.height * 0.2,
  width: slideFrame.width * 0.6,
  height: slideFrame.height * 0.6
});
var getTableFrame2 = (panelFrame) => ({
  left: panelFrame.left + panelFrame.width * 0.07,
  top: panelFrame.top + panelFrame.height * 0.63,
  width: panelFrame.width * 0.86,
  height: panelFrame.height * 0.18
});
var getEmblemCenter = (panelFrame) => ({
  x: panelFrame.left + panelFrame.width * 0.5,
  y: panelFrame.top + panelFrame.height * 0.37
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/work-pitch/work-pitch-problem.js
var calloutSchema = exports_external.object({
  text: exports_external.string().min(1)
});
var workPitchProblemScriptParamsSchema = exports_external.object({
  sectionNumber: exports_external.string().min(1).default("02"),
  heading: exports_external.string().min(1).default("Statement headline"),
  highlight: exports_external.string().min(1).default("“Key highlighted phrase”"),
  callouts: exports_external.array(calloutSchema).length(3).default([
    { text: "Callout one" },
    { text: "Callout two" },
    { text: "Callout three" }
  ]),
  backgroundFill: exports_external.string().min(1).default("background1"),
  accentColor: exports_external.string().min(1).default("accent1"),
  textColor: exports_external.string().min(1).default("tx1"),
  footerBrand: exports_external.string().min(1).default("Brand"),
  footerPage: exports_external.string().min(1).default("05"),
  typeface: exports_external.string().min(1).default("Helvetica Neue")
});
var workPitchProblemRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.work_pitch_problem",
  summary: "Work Pitch problem slide with a headline, highlight phrase, and three supporting callouts.",
  labels: ["slide", "work pitch", "problem", "narrative"],
  paramsSchema: workPitchProblemScriptParamsSchema,
  exampleParams: {
    sectionNumber: "02",
    heading: "Statement headline",
    highlight: "“Key highlighted phrase”",
    callouts: [{ text: "Callout one" }, { text: "Callout two" }, { text: "Callout three" }]
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const styles = slide.theme.textStyles({
      sectionNumber: {
        typeface: params2.typeface,
        fontSize: "text-64",
        bold: true,
        color: params2.accentColor,
        alignment: "left",
        wrap: "none"
      },
      heading: {
        typeface: "EB Garamond",
        fontSize: "text-56",
        color: params2.textColor,
        alignment: "left",
        wrap: "square"
      },
      callout: {
        typeface: params2.typeface,
        fontSize: "text-18",
        color: params2.textColor,
        alignment: "left",
        wrap: "square"
      },
      footerBrand: {
        typeface: params2.typeface,
        fontSize: "text-caption",
        color: params2.textColor,
        alignment: "left",
        wrap: "none"
      },
      footerPage: {
        typeface: params2.typeface,
        fontSize: "text-caption",
        color: params2.textColor,
        alignment: "right",
        wrap: "none"
      }
    });
    const headingContent = `${params2.heading}
${params2.highlight}`;
    const root = column({
      name: "workPitchProblem.root",
      width: "fill",
      height: "fill",
      padding: { x: "s-8", top: "s-13", bottom: "s-4" },
      align: "stretch",
      justify: "between"
    }, [
      row({
        name: "workPitchProblem.header",
        width: "fill",
        align: "start",
        gap: "s-6"
      }, [
        text(params2.sectionNumber, {
          name: "workPitchProblem.sectionNumber",
          style: styles.sectionNumber
        }),
        text(headingContent, {
          name: "workPitchProblem.heading",
          style: styles.heading,
          width: wrap(1120)
        })
      ]),
      row({
        name: "workPitchProblem.callouts",
        width: "fill",
        align: "start",
        justify: "between",
        gap: "s-8",
        padding: { top: "s-8", bottom: "s-4" }
      }, params2.callouts.map((callout) => column({
        name: `workPitchProblem.callout.${callout.text}`,
        width: "fill",
        align: "start",
        gap: "s-2"
      }, [
        rule({
          name: `workPitchProblem.calloutConnector.${callout.text}`,
          stroke: params2.accentColor,
          weight: 2,
          width: "fill"
        }),
        text(callout.text, {
          name: `workPitchProblem.calloutText.${callout.text}`,
          style: styles.callout,
          width: "fill"
        })
      ]))),
      column({
        name: "workPitchProblem.footer",
        width: "fill",
        gap: "s-1",
        align: "stretch"
      }, [
        rule({
          name: "workPitchProblem.footerLine",
          stroke: params2.textColor,
          opacity: 0.24,
          weight: 1
        }),
        row({
          name: "workPitchProblem.footerRow",
          width: "fill",
          align: "center",
          justify: "between"
        }, [
          text(params2.footerBrand, {
            name: "workPitchProblem.footerBrand",
            style: styles.footerBrand
          }),
          text(params2.footerPage, {
            name: "workPitchProblem.footerPage",
            style: styles.footerPage
          })
        ])
      ])
    ]);
    const shapes = slide.compose(root, { baseUnit: 1 });
    const headingShape = shapes.find((shape2) => shape2.name === "workPitchProblem.heading");
    if (headingShape?.type === "shape") {
      const highlightRange = headingShape.text.get(params2.highlight);
      highlightRange.color = params2.accentColor;
      highlightRange.fontSize = 58;
    }
  }
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/work-pitch/work-pitch-product-proof.js
var statSchema = exports_external.object({
  value: exports_external.string().min(1),
  label: exports_external.string().min(1)
});
var workPitchProductProofScriptParamsSchema = exports_external.object({
  sectionNumber: exports_external.string().min(1).default("04"),
  headline: exports_external.string().min(1).default("Powered by the intelligence of fig extract"),
  narrative: exports_external.string().min(1).default("Use this block to explain the formulation and why the product performs."),
  stats: exports_external.array(statSchema).length(3).default([
    { value: "+37%", label: "Hydration in 48 hours" },
    { value: "+42%", label: "Smoother texture after 4 weeks" },
    { value: "9/10", label: "Users report a natural glow" }
  ]),
  backgroundFill: exports_external.string().min(1).default("background1"),
  accentColor: exports_external.string().min(1).default("accent1"),
  textColor: exports_external.string().min(1).default("tx1"),
  footerBrand: exports_external.string().min(1).default("Brand"),
  footerPage: exports_external.string().min(1).default("07"),
  typeface: exports_external.string().min(1).default("Helvetica Neue")
});
var workPitchProductProofRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.work_pitch_product_proof",
  summary: "Work Pitch product proof slide with three metrics, connector lines, and supporting narrative.",
  labels: ["slide", "work pitch", "product", "proof"],
  paramsSchema: workPitchProductProofScriptParamsSchema,
  exampleParams: {
    sectionNumber: "04",
    headline: "Powered by the intelligence of fig extract",
    narrative: "Use this block to explain the formulation and why the product performs.",
    stats: [
      { value: "+37%", label: "Hydration in 48 hours" },
      { value: "+42%", label: "Smoother texture after 4 weeks" },
      { value: "9/10", label: "Users report a natural glow" }
    ]
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const styles = slide.theme.textStyles({
      sectionNumber: {
        typeface: params2.typeface,
        fontSize: "text-64",
        bold: true,
        color: params2.accentColor,
        alignment: "left",
        wrap: "none"
      },
      headline: {
        typeface: "EB Garamond",
        fontSize: "text-54",
        color: params2.textColor,
        alignment: "left",
        wrap: "square"
      },
      narrative: {
        typeface: "EB Garamond",
        fontSize: "text-24",
        lineSpacing: 1.2,
        color: params2.textColor,
        alignment: "left",
        wrap: "square"
      },
      statValue: {
        typeface: params2.typeface,
        fontSize: "text-56",
        bold: true,
        color: params2.accentColor,
        alignment: "left",
        wrap: "none"
      },
      statLabel: {
        typeface: params2.typeface,
        fontSize: "text-20",
        color: params2.textColor,
        alignment: "left",
        wrap: "square"
      },
      footerBrand: {
        typeface: params2.typeface,
        fontSize: "text-caption",
        color: params2.textColor,
        alignment: "left",
        wrap: "none"
      },
      footerPage: {
        typeface: params2.typeface,
        fontSize: "text-caption",
        color: params2.textColor,
        alignment: "right",
        wrap: "none"
      }
    });
    const root = column({
      name: "workPitchProductProof.root",
      width: "fill",
      height: "fill",
      padding: { x: "s-8", top: "s-13", bottom: "s-4" },
      align: "stretch",
      justify: "between"
    }, [
      row({
        name: "workPitchProductProof.header",
        width: "fill",
        align: "start",
        gap: "s-6"
      }, [
        text(params2.sectionNumber, {
          name: "workPitchProductProof.sectionNumber",
          style: styles.sectionNumber
        })
      ]),
      row({
        name: "workPitchProductProof.content",
        width: "fill",
        height: "fill",
        align: "stretch",
        justify: "between",
        gap: "s-10",
        padding: { top: "s-2", bottom: "s-4" }
      }, [
        column({
          name: "workPitchProductProof.statsColumn",
          width: wrap(520),
          height: "fill",
          align: "stretch",
          justify: "between",
          padding: { y: "s-4" }
        }, params2.stats.map((stat) => row({
          name: `workPitchProductProof.statRow.${stat.value}`,
          width: "fill",
          align: "center",
          gap: "s-3"
        }, [
          column({
            name: `workPitchProductProof.statText.${stat.value}`,
            width: wrap(220),
            align: "start",
            gap: "s-1"
          }, [
            text(stat.value, {
              name: `workPitchProductProof.statValue.${stat.value}`,
              style: styles.statValue
            }),
            text(stat.label, {
              name: `workPitchProductProof.statLabel.${stat.value}`,
              style: styles.statLabel,
              width: "fill"
            })
          ]),
          rule({
            name: `workPitchProductProof.statConnector.${stat.value}`,
            stroke: params2.accentColor,
            weight: 2,
            width: "fill"
          })
        ]))),
        column({
          name: "workPitchProductProof.narrativeColumn",
          width: wrap(540),
          height: "fill",
          align: "start",
          justify: "between",
          gap: "s-6"
        }, [
          text(params2.headline, {
            name: "workPitchProductProof.headline",
            style: styles.headline,
            width: "fill"
          }),
          text(params2.narrative, {
            name: "workPitchProductProof.narrative",
            style: styles.narrative,
            width: "fill"
          })
        ])
      ]),
      column({
        name: "workPitchProductProof.footer",
        width: "fill",
        gap: "s-1",
        align: "stretch"
      }, [
        rule({
          name: "workPitchProductProof.footerLine",
          stroke: params2.textColor,
          opacity: 0.24,
          weight: 1
        }),
        row({
          name: "workPitchProductProof.footerRow",
          width: "fill",
          align: "center",
          justify: "between"
        }, [
          text(params2.footerBrand, {
            name: "workPitchProductProof.footerBrand",
            style: styles.footerBrand
          }),
          text(params2.footerPage, {
            name: "workPitchProductProof.footerPage",
            style: styles.footerPage
          })
        ])
      ])
    ]);
    slide.compose(root, { baseUnit: 1 });
  }
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/work-pitch/work-pitch-revenue-mix.js
var segmentSchema = exports_external.object({
  label: exports_external.string().min(1),
  value: exports_external.number().nonnegative()
});
var workPitchRevenueMixScriptParamsSchema = exports_external.object({
  sectionNumber: exports_external.string().min(1).default("05"),
  headingPrimary: exports_external.string().min(1).default("How this business"),
  headingAccent: exports_external.string().min(1).default("makes money"),
  narrative: exports_external.string().min(1).default("Use this section to describe the revenue model and the role of each channel."),
  segments: exports_external.array(segmentSchema).length(5).default([
    { label: "Direct-to-consumer", value: 62 },
    { label: "Retail partners", value: 22 },
    { label: "Subscription box", value: 10 },
    { label: "Limited editions", value: 4 },
    { label: "Collaborations", value: 2 }
  ]),
  backgroundFill: exports_external.string().min(1).default("background1"),
  leftPanelFill: exports_external.string().min(1).default("accent1"),
  textColor: exports_external.string().min(1).default("tx1"),
  inverseTextColor: exports_external.string().min(1).default("white"),
  accentColor: exports_external.string().min(1).default("accent1"),
  footerBrand: exports_external.string().min(1).default("Brand"),
  footerPage: exports_external.string().min(1).default("08"),
  typeface: exports_external.string().min(1).default("Helvetica Neue")
});
var workPitchRevenueMixRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.work_pitch_revenue_mix",
  summary: "Work Pitch revenue slide with left-side narrative and right-side pie chart with five channel callouts.",
  labels: ["slide", "work pitch", "revenue", "chart"],
  paramsSchema: workPitchRevenueMixScriptParamsSchema,
  exampleParams: {
    sectionNumber: "05",
    headingPrimary: "How this business",
    headingAccent: "makes money",
    narrative: "Use this section to describe the revenue model and the role of each channel.",
    segments: [
      { label: "Direct-to-consumer", value: 62 },
      { label: "Retail partners", value: 22 },
      { label: "Subscription box", value: 10 },
      { label: "Limited editions", value: 4 },
      { label: "Collaborations", value: 2 }
    ]
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const leftPanel = getLeftPanelFrame2(slide.frame);
    const pieChartFrame = getPieChartFrame(slide.frame);
    slide.compose(shape({
      name: "workPitchRevenueMix.leftPanelBackground",
      geometry: "rect",
      fill: params2.leftPanelFill,
      line: { style: "solid", width: 0, fill: params2.leftPanelFill },
      width: "fill",
      height: "fill"
    }), { frame: leftPanel, baseUnit: 1 });
    const styles = slide.theme.textStyles({
      sectionNumber: {
        typeface: params2.typeface,
        fontSize: "text-64",
        bold: true,
        color: params2.inverseTextColor,
        alignment: "left",
        wrap: "none"
      },
      heading: {
        typeface: "EB Garamond",
        fontSize: "text-54",
        color: params2.inverseTextColor,
        alignment: "left",
        wrap: "square"
      },
      narrative: {
        typeface: "EB Garamond",
        fontSize: "text-22",
        lineSpacing: 1.2,
        color: params2.inverseTextColor,
        alignment: "left",
        wrap: "square"
      },
      callout: {
        typeface: params2.typeface,
        fontSize: "text-12",
        bold: true,
        color: params2.textColor,
        alignment: "left",
        wrap: "square"
      },
      footerBrand: {
        typeface: params2.typeface,
        fontSize: "text-caption",
        color: params2.textColor,
        alignment: "left",
        wrap: "none"
      },
      footerPage: {
        typeface: params2.typeface,
        fontSize: "text-caption",
        color: params2.textColor,
        alignment: "right",
        wrap: "none"
      }
    });
    const headingContent = `${params2.headingPrimary}
${params2.headingAccent}`;
    const [pieChart] = slide.compose(chart({
      name: "workPitchRevenueMix.pieChart",
      chartType: "pie",
      width: "fill",
      height: "fill"
    }), { frame: pieChartFrame, baseUnit: 1 });
    if (pieChart?.type !== "chart") {
      return;
    }
    pieChart.categories = params2.segments.map((segment) => segment.label);
    pieChart.title = "";
    pieChart.hasLegend = false;
    const series = pieChart.series.add("Revenue mix");
    series.values = params2.segments.map((segment) => segment.value);
    series.categories = params2.segments.map((segment) => segment.label);
    series.valuesFormatCode = "0%";
    series.explosion = 10;
    pieChart.pieOptions.firstSliceAngle = 90;
    pieChart.dataLabels.showPercent = true;
    pieChart.dataLabels.showCategoryName = false;
    pieChart.dataLabels.showValue = false;
    pieChart.dataLabels.position = "outEnd";
    pieChart.dataLabels.showLeaderLines = true;
    pieChart.dataLabels.textStyle.fontSize = 11;
    pieChart.dataLabels.textStyle.fill = params2.textColor;
    const root = column({
      name: "workPitchRevenueMix.root",
      width: "fill",
      height: "fill",
      padding: { x: "s-8", top: "s-13", bottom: "s-4" },
      align: "stretch",
      justify: "between"
    }, [
      row({
        name: "workPitchRevenueMix.content",
        width: "fill",
        height: "fill",
        align: "stretch",
        justify: "between",
        gap: "s-8"
      }, [
        column({
          name: "workPitchRevenueMix.leftColumn",
          width: wrap(leftPanel.width - 96),
          height: "fill",
          align: "start",
          justify: "between",
          padding: { top: "s-1", bottom: "s-6" }
        }, [
          row({
            name: "workPitchRevenueMix.headingRow",
            width: "fill",
            align: "start",
            gap: "s-4"
          }, [
            text(params2.sectionNumber, {
              name: "workPitchRevenueMix.sectionNumber",
              style: styles.sectionNumber
            }),
            text(headingContent, {
              name: "workPitchRevenueMix.heading",
              style: styles.heading,
              width: "fill"
            })
          ]),
          text(params2.narrative, {
            name: "workPitchRevenueMix.narrative",
            style: styles.narrative,
            width: "fill"
          })
        ]),
        column({
          name: "workPitchRevenueMix.rightColumn",
          width: "fill",
          height: "fill",
          align: "stretch",
          justify: "end",
          padding: { bottom: "s-6" }
        }, [
          grid({
            name: "workPitchRevenueMix.callouts",
            width: "fill",
            columns: repeat(3, fr(1)),
            rows: repeat(2, "auto"),
            columnGap: "s-3",
            rowGap: "s-3",
            justifyItems: "stretch",
            alignItems: "start"
          }, params2.segments.map((segment) => row({
            name: `workPitchRevenueMix.callout.${segment.label}`,
            width: "fill",
            align: "center",
            gap: "s-1"
          }, [
            rule({
              name: `workPitchRevenueMix.calloutDot.${segment.label}`,
              stroke: params2.accentColor,
              width: fixed(14),
              height: fixed(14),
              weight: 14
            }),
            text(`${segment.value}% ${segment.label}`.toUpperCase(), {
              name: `workPitchRevenueMix.calloutText.${segment.label}`,
              style: styles.callout,
              width: "fill"
            })
          ])))
        ])
      ]),
      column({
        name: "workPitchRevenueMix.footer",
        width: "fill",
        gap: "s-1",
        align: "stretch"
      }, [
        rule({
          name: "workPitchRevenueMix.footerLine",
          stroke: params2.textColor,
          opacity: 0.24,
          weight: 1
        }),
        row({
          name: "workPitchRevenueMix.footerRow",
          width: "fill",
          align: "center",
          justify: "between"
        }, [
          text(params2.footerBrand, {
            name: "workPitchRevenueMix.footerBrand",
            style: styles.footerBrand
          }),
          text(params2.footerPage, {
            name: "workPitchRevenueMix.footerPage",
            style: styles.footerPage
          })
        ])
      ])
    ]);
    slide.compose(root, { baseUnit: 1 });
  }
});
var getLeftPanelFrame2 = (slideFrame) => ({
  left: slideFrame.left,
  top: slideFrame.top,
  width: slideFrame.width * 0.42,
  height: slideFrame.height
});
var getPieChartFrame = (slideFrame) => ({
  left: slideFrame.left + slideFrame.width * 0.53,
  top: slideFrame.top + slideFrame.height * 0.12,
  width: slideFrame.width * 0.45,
  height: slideFrame.height * 0.54
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/slide/work-pitch/work-pitch-style-guide.js
var swatchSchema = exports_external.object({
  name: exports_external.string().min(1),
  color: exports_external.string().min(1),
  tokenLabel: exports_external.string().min(1)
});
var workPitchStyleGuideScriptParamsSchema = exports_external.object({
  title: exports_external.string().min(1).default("STYLE GUIDE"),
  subtitle: exports_external.string().min(1).default("& font guide"),
  swatches: exports_external.array(swatchSchema).length(5).default([
    { name: "Accent One", color: "accent1", tokenLabel: "accent1" },
    { name: "Background", color: "background1", tokenLabel: "background1" },
    { name: "Accent Two", color: "accent2", tokenLabel: "accent2" },
    { name: "Accent Three", color: "accent3", tokenLabel: "accent3" },
    { name: "Text", color: "tx1", tokenLabel: "tx1" }
  ]),
  displayBrand: exports_external.string().min(1).default("COMPANY NAME & LOGO"),
  displayPageLabel: exports_external.string().min(1).default("PAGE NUMBER"),
  headlineSample: exports_external.string().min(1).default("Super Title"),
  headlineTypefaceLabel: exports_external.string().min(1).default("Helvetica Neue 54 pts"),
  subheadlineSample: exports_external.string().min(1).default("Secondary Title"),
  subheadlineTypefaceLabel: exports_external.string().min(1).default("EB Garamond 54 pts"),
  bodySample: exports_external.string().min(1).default("Use this block to document body typography, paragraph rhythm, and brand tone."),
  backgroundFill: exports_external.string().min(1).default("background1"),
  titleColor: exports_external.string().min(1).default("accent1"),
  textColor: exports_external.string().min(1).default("tx1"),
  typeface: exports_external.string().min(1).default("Helvetica Neue")
});
var workPitchStyleGuideRecipeScript = definePresentationRecipeScript({
  name: "recipes.slide.work_pitch_style_guide",
  summary: "Work Pitch style guide slide with five color swatches and typography samples.",
  labels: ["slide", "work pitch", "style guide", "branding"],
  paramsSchema: workPitchStyleGuideScriptParamsSchema,
  exampleParams: {
    title: "STYLE GUIDE",
    subtitle: "& font guide",
    swatches: [
      { name: "Accent One", color: "accent1", tokenLabel: "accent1" },
      { name: "Background", color: "background1", tokenLabel: "background1" },
      { name: "Accent Two", color: "accent2", tokenLabel: "accent2" },
      { name: "Accent Three", color: "accent3", tokenLabel: "accent3" },
      { name: "Text", color: "tx1", tokenLabel: "tx1" }
    ],
    displayBrand: "COMPANY NAME & LOGO",
    displayPageLabel: "PAGE NUMBER",
    headlineSample: "Super Title",
    headlineTypefaceLabel: "Helvetica Neue 54 pts",
    subheadlineSample: "Secondary Title",
    subheadlineTypefaceLabel: "EB Garamond 54 pts",
    bodySample: "Use this block to document body typography, paragraph rhythm, and brand tone."
  },
  run: (presentation, params2) => {
    const slide = presentation.slides.add();
    slide.background.fill = params2.backgroundFill;
    const styles = slide.theme.textStyles({
      title: {
        typeface: params2.typeface,
        fontSize: "text-56",
        bold: true,
        color: params2.titleColor,
        alignment: "center",
        wrap: "none"
      },
      subtitle: {
        typeface: "EB Garamond",
        fontSize: "text-34",
        color: params2.textColor,
        alignment: "center",
        wrap: "none"
      },
      swatchName: {
        typeface: params2.typeface,
        fontSize: "text-26",
        color: params2.textColor,
        alignment: "left",
        wrap: "none"
      },
      swatchToken: {
        typeface: params2.typeface,
        fontSize: "text-24",
        color: params2.textColor,
        alignment: "left",
        wrap: "none"
      },
      headlineSample: {
        typeface: params2.typeface,
        fontSize: "text-54",
        bold: true,
        color: params2.textColor,
        alignment: "left",
        wrap: "none"
      },
      headlineLabel: {
        typeface: params2.typeface,
        fontSize: "text-16",
        color: params2.textColor,
        alignment: "left",
        wrap: "none"
      },
      subheadlineSample: {
        typeface: "EB Garamond",
        fontSize: "text-54",
        color: params2.textColor,
        alignment: "left",
        wrap: "none"
      },
      body: {
        typeface: "EB Garamond",
        fontSize: "text-24",
        lineSpacing: 1.2,
        color: params2.textColor,
        alignment: "left",
        wrap: "square"
      },
      footerBrand: {
        typeface: params2.typeface,
        fontSize: "text-caption",
        color: params2.textColor,
        alignment: "left",
        wrap: "none"
      },
      footerPage: {
        typeface: params2.typeface,
        fontSize: "text-caption",
        color: params2.textColor,
        alignment: "right",
        wrap: "none"
      }
    });
    const root = column({
      name: "workPitchStyleGuide.root",
      width: "fill",
      height: "fill",
      padding: { x: "s-8", top: "s-12", bottom: "s-4" },
      align: "stretch",
      justify: "between"
    }, [
      column({
        name: "workPitchStyleGuide.header",
        width: "fill",
        align: "center",
        gap: "s-1"
      }, [
        text(params2.title, {
          name: "workPitchStyleGuide.title",
          style: styles.title
        }),
        text(params2.subtitle, {
          name: "workPitchStyleGuide.subtitle",
          style: styles.subtitle
        })
      ]),
      row({
        name: "workPitchStyleGuide.content",
        width: "fill",
        height: "fill",
        align: "stretch",
        justify: "between",
        gap: "s-10",
        padding: { top: "s-2", bottom: "s-3" }
      }, [
        column({
          name: "workPitchStyleGuide.swatches",
          width: wrap(500),
          height: "fill",
          align: "stretch",
          justify: "between",
          padding: { y: "s-2" }
        }, params2.swatches.map((swatch, index) => row({
          name: `workPitchStyleGuide.swatchRow.${index}`,
          width: "fill",
          align: "center",
          gap: "s-6"
        }, [
          text(swatch.name, {
            name: `workPitchStyleGuide.swatchName.${index}`,
            style: styles.swatchName,
            width: wrap(210)
          }),
          text(swatch.tokenLabel, {
            name: `workPitchStyleGuide.swatchToken.${index}`,
            style: styles.swatchToken,
            width: wrap(170)
          })
        ]))),
        column({
          name: "workPitchStyleGuide.typeScale",
          width: wrap(520),
          height: "fill",
          align: "start",
          justify: "between"
        }, [
          text(params2.headlineSample, {
            name: "workPitchStyleGuide.headlineSample",
            style: styles.headlineSample,
            width: "fill"
          }),
          text(params2.headlineTypefaceLabel, {
            name: "workPitchStyleGuide.headlineLabel",
            style: styles.headlineLabel,
            width: "fill"
          }),
          text(params2.subheadlineSample, {
            name: "workPitchStyleGuide.subheadlineSample",
            style: styles.subheadlineSample,
            width: "fill"
          }),
          text(params2.subheadlineTypefaceLabel, {
            name: "workPitchStyleGuide.subheadlineLabel",
            style: styles.headlineLabel,
            width: "fill"
          }),
          text(params2.bodySample, {
            name: "workPitchStyleGuide.body",
            style: styles.body,
            width: "fill"
          })
        ])
      ]),
      column({
        name: "workPitchStyleGuide.footer",
        width: "fill",
        gap: "s-1",
        align: "stretch"
      }, [
        rule({
          name: "workPitchStyleGuide.footerLine",
          stroke: params2.textColor,
          opacity: 0.24,
          weight: 1
        }),
        row({
          name: "workPitchStyleGuide.footerRow",
          width: "fill",
          align: "center",
          justify: "between"
        }, [
          text(params2.displayBrand, {
            name: "workPitchStyleGuide.footerBrand",
            style: styles.footerBrand
          }),
          text(params2.displayPageLabel, {
            name: "workPitchStyleGuide.footerPage",
            style: styles.footerPage
          })
        ])
      ])
    ]);
    const elements = slide.compose(root, { baseUnit: 1 });
    params2.swatches.forEach((swatch, index) => {
      const swatchNameShape = elements.find((element) => element.name === `workPitchStyleGuide.swatchName.${index}`);
      const frame = swatchNameShape?.frame;
      if (!frame || frame.left === undefined || frame.top === undefined || frame.height === undefined) {
        return;
      }
      const circleSize = 64;
      slide.compose(shape({
        name: `workPitchStyleGuide.swatchCircle.${index}`,
        geometry: "ellipse",
        fill: swatch.color,
        line: { style: "solid", width: 1.333, fill: params2.textColor },
        width: "fill",
        height: "fill"
      }), {
        frame: {
          left: frame.left - 96,
          top: frame.top + (frame.height - circleSize) / 2,
          width: circleSize,
          height: circleSize
        },
        baseUnit: 1
      });
    });
  }
});

// node_modules/@oai/granola/dist/models/presentation/recipes/scripts/registry.js
var PRESENTATION_RECIPE_SCRIPTS = [
  titleCoverRecipeScript,
  centeredHeadlineRecipeScript,
  agendaRecipeScript,
  contentsTocRecipeScript,
  sectionDividerRoundIconRecipeScript,
  sectionDividerVerticalBandLeftRecipeScript,
  sectionDividerVerticalBandRightRecipeScript,
  workPitchCoverRecipeScript,
  workPitchOpeningMarkRecipeScript,
  workPitchAgendaRecipeScript,
  workPitchInspirationRecipeScript,
  workPitchProblemRecipeScript,
  workPitchMarketGrowthRecipeScript,
  workPitchProductProofRecipeScript,
  workPitchRevenueMixRecipeScript,
  workPitchFoundersRecipeScript,
  workPitchFundingAskRecipeScript,
  workPitchStyleGuideRecipeScript,
  captionedContentRecipeScript,
  imageWithCaptionRecipeScript,
  chartWithCaptionRecipeScript,
  threeColumnComparisonRecipeScript,
  vennDiagramRecipeScript,
  imageMontageCaptionRecipeScript,
  twoImageCarouselRecipeScript,
  threeImageCarouselRecipeScript,
  fullBleedLeftImageRightCaptionRecipeScript,
  fullBleedTopImageBottomCaptionRecipeScript,
  centerTitleSolidBandWithBackgroundImageRecipeScript,
  imageOnlyRecipeScript,
  bigQuoteRecipeScript,
  twoColumnRecipeScript,
  featureGridRecipeScript,
  bulletListRecipeScript,
  numberedStepsRecipeScript,
  iconListRecipeScript,
  pictogramRecipeScript,
  bigNumberRecipeScript,
  metricStripRecipeScript,
  dataDashboardRecipeScript,
  tableSlideRecipeScript,
  scientificChartStyleRecipeScript,
  dashboardMinimalChartStyleRecipeScript,
  editorialChartStyleRecipeScript,
  bubbleCorrelationChartTypeRecipeScript,
  treemapHierarchyChartTypeRecipeScript,
  waterfallChangeChartTypeRecipeScript
];
var PRESENTATION_RECIPE_SCRIPT_MAP = new Map(PRESENTATION_RECIPE_SCRIPTS.map((script) => [script.name, script]));
function getPresentationRecipeScript(scriptName) {
  return PRESENTATION_RECIPE_SCRIPT_MAP.get(scriptName) ?? null;
}
function runPresentationRecipeScript(presentation, scriptName, params2 = {}) {
  const script = getPresentationRecipeScript(scriptName);
  if (!script) {
    throw new Error(`Unknown presentation recipe script: ${scriptName}`);
  }
  const beforeSnapshot = presentation.toSnapshot();
  const parsedParams = script.paramsSchema.parse(params2);
  script.run(presentation, parsedParams);
  const afterSnapshot = presentation.toSnapshot();
  return {
    scriptName: script.name,
    labels: [...script.labels],
    params: parsedParams,
    inspect: buildScriptRunInspect(beforeSnapshot, afterSnapshot)
  };
}
var buildScriptRunInspect = (before, after) => {
  const records = [];
  const beforeSlidesById = new Map(before.slides.map((slide) => [slide.id, slide]));
  for (const slide of after.slides) {
    const beforeSlide = beforeSlidesById.get(slide.id);
    const slideNumber = slide.index + 1;
    if (!beforeSlide) {
      records.push({
        kind: "slide",
        change: "added",
        id: slide.aid,
        slide: slideNumber,
        title: slide.title
      });
    } else if (beforeSlide.title !== slide.title || (beforeSlide.layoutId ?? "") !== (slide.layoutId ?? "")) {
      records.push({
        kind: "slide",
        change: "updated",
        id: slide.aid,
        slide: slideNumber,
        title: slide.title
      });
    }
    collectShapeChanges(records, beforeSlide?.shapes ?? [], slide.shapes, slideNumber);
    collectTableChanges(records, beforeSlide?.tables ?? [], slide.tables, slideNumber);
    collectChartChanges(records, beforeSlide?.charts ?? [], slide.charts, slideNumber);
    collectImageChanges(records, beforeSlide?.images ?? [], slide.images, slideNumber);
    if (!beforeSlide && slide.notes.text.trim().length > 0) {
      records.push({
        kind: "notes",
        change: "added",
        id: slide.notes.aid,
        slide: slideNumber,
        textPreview: buildPreview(slide.notes.text)
      });
    } else if (beforeSlide && beforeSlide.notes.text !== slide.notes.text) {
      records.push({
        kind: "notes",
        change: "updated",
        id: slide.notes.aid,
        slide: slideNumber,
        textPreview: buildPreview(slide.notes.text)
      });
    }
  }
  const targetIds = Array.from(new Set(records.map((record2) => record2.id)));
  return {
    targetIds,
    records,
    ndjson: records.map((record2) => JSON.stringify(record2)).join(`
`)
  };
};
var collectShapeChanges = (records, beforeShapes, afterShapes, slide) => {
  const beforeById = new Map(beforeShapes.map((shape2) => [shape2.id, shape2]));
  for (const shape2 of afterShapes) {
    const beforeShape = beforeById.get(shape2.id);
    const change = resolveChange(beforeShape, shape2);
    if (!change) {
      continue;
    }
    const text2 = shape2.text.trim();
    records.push({
      kind: text2.length > 0 ? "textbox" : "shape",
      change,
      id: shape2.aid,
      slide,
      name: shape2.name || undefined,
      textPreview: text2.length > 0 ? buildPreview(shape2.text) : undefined,
      bbox: toBbox(shape2.frame)
    });
  }
};
var collectTableChanges = (records, beforeTables, afterTables, slide) => {
  const beforeById = new Map(beforeTables.map((table2) => [table2.id, table2]));
  for (const table2 of afterTables) {
    const beforeTable = beforeById.get(table2.id);
    const change = resolveChange(beforeTable, table2);
    if (!change) {
      continue;
    }
    records.push({
      kind: "table",
      change,
      id: table2.aid,
      slide,
      name: table2.name || undefined,
      textPreview: table2.preview ? buildPreview(table2.preview) : undefined,
      bbox: toBbox(table2.frame)
    });
  }
};
var collectChartChanges = (records, beforeCharts, afterCharts, slide) => {
  const beforeById = new Map(beforeCharts.map((chart2) => [chart2.id, chart2]));
  for (const chart2 of afterCharts) {
    const beforeChart = beforeById.get(chart2.id);
    const change = resolveChange(beforeChart, chart2);
    if (!change) {
      continue;
    }
    records.push({
      kind: "chart",
      change,
      id: chart2.aid,
      slide,
      name: chart2.name || undefined,
      title: chart2.title || undefined,
      bbox: toBbox(chart2.frame)
    });
  }
};
var collectImageChanges = (records, beforeImages, afterImages, slide) => {
  const beforeById = new Map(beforeImages.map((image2) => [image2.id, image2]));
  for (const image2 of afterImages) {
    const beforeImage = beforeById.get(image2.id);
    const change = resolveChange(beforeImage, image2);
    if (!change) {
      continue;
    }
    records.push({
      kind: "image",
      change,
      id: image2.aid,
      slide,
      name: image2.name || undefined,
      textPreview: image2.alt ? buildPreview(image2.alt) : undefined,
      bbox: toBbox(image2.frame)
    });
  }
};
var resolveChange = (before, after) => {
  if (!before) {
    return "added";
  }
  if (JSON.stringify(before) !== JSON.stringify(after)) {
    return "updated";
  }
  return;
};
var buildPreview = (value, maxLength = 120) => {
  const normalized = value.replace(/\r?\n/g, " | ").trim();
  if (normalized.length <= maxLength) {
    return normalized;
  }
  return `${normalized.slice(0, Math.max(1, maxLength - 3))}...`;
};
var toBbox = (frame) => {
  if (!frame) {
    return;
  }
  const left = toRounded(frame.left);
  const top = toRounded(frame.top);
  const width = toRounded(frame.width);
  const height = toRounded(frame.height);
  if (left === undefined || top === undefined || width === undefined || height === undefined) {
    return;
  }
  return [left, top, width, height];
};
var toRounded = (value) => {
  if (value === undefined || !Number.isFinite(value)) {
    return;
  }
  return Math.round(value * 100) / 100;
};

// node_modules/@oai/granola/dist/models/presentation/templates/registry.js
var TITLE_SLIDE_PATCH = [
  { op: "slide.add", as: "@slide" },
  {
    op: "shape.add",
    slide: "@slide",
    as: "@title",
    props: {
      geometry: "rect",
      position: { left: 80, top: 80, width: 800, height: 120 },
      fill: "background1"
    }
  },
  { op: "text.set", target: "@title", value: "Title" },
  {
    op: "shape.add",
    slide: "@slide",
    as: "@subtitle",
    props: {
      geometry: "rect",
      position: { left: 80, top: 220, width: 800, height: 80 },
      fill: "background1"
    }
  },
  { op: "text.set", target: "@subtitle", value: "Subtitle" }
];
var TWO_UP_PATCH = [
  { op: "slide.add", as: "@slide" },
  {
    op: "shape.add",
    slide: "@slide",
    as: "@left",
    props: {
      geometry: "rect",
      position: { left: 60, top: 100, width: 390, height: 320 },
      fill: "background1"
    }
  },
  {
    op: "shape.add",
    slide: "@slide",
    as: "@right",
    props: {
      geometry: "rect",
      position: { left: 510, top: 100, width: 390, height: 320 },
      fill: "background1"
    }
  },
  { op: "text.set", target: "@left", value: "Left column" },
  { op: "text.set", target: "@right", value: "Right column" }
];
var AGENDA_PATCH = [
  { op: "slide.add", as: "@slide" },
  {
    op: "shape.add",
    slide: "@slide",
    as: "@title",
    props: {
      geometry: "rect",
      position: { left: 60, top: 60, width: 840, height: 80 },
      fill: "background1"
    }
  },
  {
    op: "shape.add",
    slide: "@slide",
    as: "@body",
    props: {
      geometry: "rect",
      position: { left: 80, top: 170, width: 800, height: 300 },
      fill: "background1"
    }
  },
  { op: "text.set", target: "@title", value: "Agenda" },
  {
    op: "text.set",
    target: "@body",
    value: `1. Intro
2. Highlights
3. Next steps`
  }
];
var PRESENTATION_TEMPLATES = [
  {
    name: "title-slide",
    summary: "Title + subtitle slide with centered text boxes.",
    patch: TITLE_SLIDE_PATCH
  },
  {
    name: "two-up",
    summary: "Two-column slide with left/right content boxes.",
    patch: TWO_UP_PATCH
  },
  {
    name: "agenda",
    summary: "Agenda slide with a title and list body.",
    patch: AGENDA_PATCH
  }
];
var PRESENTATION_TEMPLATE_MAP = new Map(PRESENTATION_TEMPLATES.map((entry) => [entry.name, entry]));

// node_modules/@oai/granola/dist/models/presentation/google-slides/units.js
var ID_SAFE_PATTERN = /[^A-Za-z0-9_:-]/g;
var pointsFromPixels = (value) => {
  return value * POINTS_PER_PIXEL;
};
var pixelsFromPoints = (value) => {
  return value / POINTS_PER_PIXEL;
};
var pixelsFromSlidesDimension = (dimension) => {
  if (!dimension) {
    return;
  }
  const magnitude = dimension.magnitude;
  if (typeof magnitude !== "number" || !Number.isFinite(magnitude)) {
    return;
  }
  if (dimension.unit === "PT") {
    return pixelsFromPoints(magnitude);
  }
  return pixelsFromEmu(magnitude);
};
var pointsFromSlidesDimension = (dimension) => {
  if (!dimension) {
    return;
  }
  const magnitude = dimension.magnitude;
  if (typeof magnitude !== "number" || !Number.isFinite(magnitude)) {
    return;
  }
  if (dimension.unit === "PT") {
    return magnitude;
  }
  return pointsFromPixels(pixelsFromEmu(magnitude));
};
var buildSlidesObjectId = (parts) => {
  const raw = parts.filter((part) => Boolean(part)).map((part) => String(part)).join("_");
  let cleaned = raw.replace(ID_SAFE_PATTERN, "_");
  if (!/^[A-Za-z0-9_]/.test(cleaned)) {
    cleaned = `_${cleaned}`;
  }
  if (cleaned.length < 5) {
    cleaned = cleaned.padEnd(5, "_");
  }
  if (cleaned.length > 50) {
    cleaned = cleaned.slice(0, 50);
  }
  return cleaned;
};

// node_modules/@oai/granola/dist/models/presentation/google-slides/adapter.js
var SHAPE_TYPE_FROM_GEOMETRY = {
  textbox: "TEXT_BOX",
  rect: "RECTANGLE",
  roundRect: "ROUND_RECTANGLE",
  ellipse: "ELLIPSE"
};
var GEOMETRY_FROM_SHAPE_TYPE = {
  TEXT_BOX: "textbox",
  RECTANGLE: "rect",
  ROUND_RECTANGLE: "roundRect",
  ELLIPSE: "ellipse"
};
var THEME_COLOR_MAP = {
  accent1: "ACCENT1",
  accent2: "ACCENT2",
  accent3: "ACCENT3",
  accent4: "ACCENT4",
  accent5: "ACCENT5",
  accent6: "ACCENT6",
  bg1: "BACKGROUND1",
  bg2: "BACKGROUND2",
  tx1: "TEXT1",
  tx2: "TEXT2",
  dk1: "DARK1",
  dk2: "DARK2",
  lt1: "LIGHT1",
  lt2: "LIGHT2",
  hlink: "HYPERLINK",
  folHlink: "FOLLOWED_HYPERLINK"
};
var ALIGNMENT_MAP = {
  left: "START",
  center: "CENTER",
  right: "END",
  justify: "JUSTIFIED"
};
var VERTICAL_ALIGNMENT_MAP = {
  top: "TOP",
  middle: "MIDDLE",
  bottom: "BOTTOM"
};
var AUTOFIT_MAP = {
  none: "NONE",
  shrinkText: "TEXT_AUTOFIT",
  resizeShapeToFitText: "SHAPE_AUTOFIT"
};

class GoogleSlidesAdapter {
  #presentation;
  #client;
  #presentationId;
  #fields;
  #writeControl;
  #slideObjectIds = new WeakMap;
  #shapeObjectIds = new WeakMap;
  #notesObjectIds = new WeakMap;
  #slidesByRemoteId = new Map;
  #elementBaseSizes = new Map;
  constructor(presentation, config2) {
    this.#presentation = presentation;
    this.#client = config2.client;
    this.#presentationId = config2.presentationId;
    this.#fields = config2.fields;
    this.#writeControl = config2.writeControl;
  }
  get presentationId() {
    return this.#presentationId;
  }
  async hydrateFromSlides(data) {
    const blankLayout = this.#presentation.layouts.add("Slides Blank", {
      type: "blank"
    });
    const slides = data.slides ?? [];
    slides.forEach((slideData) => {
      const slide = this.#presentation.slides.add({ layoutId: blankLayout.id });
      if (slideData.objectId) {
        this.#registerSlide(slide, slideData.objectId);
      }
      const notesId = slideData.slideProperties?.notesPage?.notesProperties?.speakerNotesObjectId;
      if (notesId) {
        this.#notesObjectIds.set(slide.speakerNotes, notesId);
      }
      this.#importSlideElements(slideData, slide);
    });
  }
  async applyPatch(patch, applyResult) {
    const warnings = [...applyResult.warnings];
    const { requests, pendingNotesSlides } = this.#buildRequests(patch, applyResult, warnings);
    if (requests.length > 0) {
      const request = {
        requests,
        writeControl: this.#writeControl
      };
      await this.#client.batchUpdate(this.#presentationId, request);
    }
    if (pendingNotesSlides.length > 0) {
      await this.#refreshNotesMapping();
    }
    return { ...applyResult, warnings };
  }
  #buildRequests(patch, applyResult, warnings) {
    const requests = [];
    const aliasMap = applyResult.idMap;
    const pendingNotesSlides = [];
    const newlyCreatedShapeObjectIds = new Set;
    const newSlidesQueue = this.#presentation.slides.items.filter((slide) => !this.#slideObjectIds.has(slide));
    const newShapesBySlide = new Map;
    this.#presentation.slides.items.forEach((slide) => {
      const shapes = slide.shapes.items.filter((shape2) => !this.#shapeObjectIds.has(shape2));
      if (shapes.length > 0) {
        newShapesBySlide.set(slide, shapes);
      }
    });
    for (const op of patch) {
      switch (op.op) {
        case "slide.add": {
          const slide = this.#resolveNewSlide(op.as, aliasMap, newSlidesQueue);
          const objectId = this.#registerSlideObjectId(slide);
          requests.push({ createSlide: { objectId } });
          pendingNotesSlides.push(slide);
          if (op.layout || op.layoutId) {
            warnings.push("googleSlides: slide.add layout mapping is not implemented.");
          }
          break;
        }
        case "slide.remove": {
          const slide = this.#resolveSlide(op.target, aliasMap);
          const objectId = this.#requireSlideObjectId(slide);
          requests.push({ deleteObject: { objectId } });
          this.#dropSlideMapping(slide, objectId);
          break;
        }
        case "shape.add": {
          const slide = this.#resolveSlide(op.slide, aliasMap);
          const shape2 = this.#resolveNewShape(op.as, aliasMap, slide, newShapesBySlide);
          const slideObjectId = this.#requireSlideObjectId(slide);
          const shapeType = this.#mapShapeGeometry(op.props, warnings);
          const frame = shape2.frame;
          if (!frame) {
            throw new Error("googleSlides: shape.add requires a frame.");
          }
          const size2 = this.#buildSizeFromFrame(frame);
          const transform2 = this.#buildTransformFromFrame(frame);
          const isNewShape = !this.#shapeObjectIds.has(shape2);
          const objectId = this.#registerShapeObjectId(shape2);
          if (isNewShape) {
            newlyCreatedShapeObjectIds.add(objectId);
          }
          this.#registerBaseSize(objectId, size2.widthPt, size2.heightPt);
          requests.push({
            createShape: {
              objectId,
              shapeType,
              elementProperties: {
                pageObjectId: slideObjectId,
                size: size2.size,
                transform: transform2
              }
            }
          });
          break;
        }
        case "shape.remove": {
          const shape2 = this.#resolveShape(op.target, aliasMap);
          const objectId = this.#requireShapeObjectId(shape2);
          requests.push({ deleteObject: { objectId } });
          this.#dropShapeMapping(shape2, objectId);
          break;
        }
        case "shape.set": {
          const shape2 = this.#resolveShape(op.target, aliasMap);
          const objectId = this.#requireShapeObjectId(shape2);
          this.#addShapeSetRequests(shape2, objectId, op.props, requests, warnings);
          break;
        }
        case "text.set": {
          const shape2 = this.#resolveShape(op.target, aliasMap);
          const objectId = this.#requireShapeObjectId(shape2);
          const value = shape2.text.toString();
          this.#addTextSetRequests(objectId, value, requests, {
            skipDelete: newlyCreatedShapeObjectIds.has(objectId)
          });
          break;
        }
        case "text.replace": {
          const shape2 = this.#resolveShape(op.target, aliasMap);
          const objectId = this.#requireShapeObjectId(shape2);
          const value = shape2.text.toString();
          this.#addTextSetRequests(objectId, value, requests, {
            skipDelete: newlyCreatedShapeObjectIds.has(objectId)
          });
          break;
        }
        case "text.style.set": {
          const shape2 = this.#resolveShape(op.target, aliasMap);
          const objectId = this.#requireShapeObjectId(shape2);
          this.#addTextStyleRequests(objectId, op.props, { type: "ALL" }, requests, warnings);
          this.#addShapeTextBoxRequests(objectId, op.props, requests, warnings);
          break;
        }
        case "textrange.style.set": {
          const target = this.#resolveTextRange(op.target, aliasMap);
          this.#addTextStyleRequests(target.objectId, op.props, target.range, requests, warnings);
          break;
        }
        case "notes.set": {
          const notes = this.#resolveNotes(op.target, aliasMap);
          const objectId = this.#notesObjectIds.get(notes);
          if (!objectId) {
            throw new Error("googleSlides: notes.set requires a mapped notes object id.");
          }
          const value = notes.text;
          this.#addTextSetRequests(objectId, value, requests);
          break;
        }
        default: {
          throw new Error(`googleSlides: op not supported: ${op.op}`);
        }
      }
    }
    return { requests, pendingNotesSlides };
  }
  #resolveNewSlide(alias, aliasMap, newSlidesQueue) {
    if (alias) {
      const anchor = aliasMap[alias];
      if (!anchor) {
        throw new Error(`googleSlides: missing alias mapping for ${alias}`);
      }
      const resolved = this.#presentation.resolve(anchor);
      if (resolved instanceof Slide2) {
        return resolved;
      }
      throw new Error("googleSlides: slide.add alias is not a slide.");
    }
    const slide = newSlidesQueue.shift();
    if (!slide) {
      throw new Error("googleSlides: slide.add failed to find a new slide.");
    }
    return slide;
  }
  #resolveNewShape(alias, aliasMap, slide, newShapesBySlide) {
    if (alias) {
      const anchor = aliasMap[alias];
      if (!anchor) {
        throw new Error(`googleSlides: missing alias mapping for ${alias}`);
      }
      const resolved = this.#presentation.resolve(anchor);
      if (resolved instanceof Shape2) {
        return resolved;
      }
      throw new Error("googleSlides: shape.add alias is not a shape.");
    }
    const queue = newShapesBySlide.get(slide) ?? [];
    const shape2 = queue.shift();
    if (!shape2) {
      throw new Error("googleSlides: shape.add failed to find a new shape.");
    }
    newShapesBySlide.set(slide, queue);
    return shape2;
  }
  #resolveTarget(ref, aliasMap) {
    if (this.#isPatchAlias(ref)) {
      const anchor = aliasMap[ref];
      if (!anchor) {
        throw new Error(`googleSlides: missing alias mapping for ${ref}`);
      }
      return this.#presentation.resolve(anchor);
    }
    return this.#presentation.resolve(ref);
  }
  #resolveSlide(ref, aliasMap) {
    const resolved = this.#resolveTarget(ref, aliasMap);
    if (resolved instanceof Slide2) {
      return resolved;
    }
    throw new Error("googleSlides: expected a slide target.");
  }
  #resolveShape(ref, aliasMap) {
    const resolved = this.#resolveTarget(ref, aliasMap);
    if (resolved instanceof Shape2) {
      return resolved;
    }
    throw new Error("googleSlides: expected a shape target.");
  }
  #resolveNotes(ref, aliasMap) {
    const resolved = this.#resolveTarget(ref, aliasMap);
    if (resolved instanceof SpeakerNotes) {
      return resolved;
    }
    throw new Error("googleSlides: expected a notes target.");
  }
  #resolveTextRange(ref, aliasMap) {
    const aliasRange = this.#parseTextRangeAlias(ref);
    if (aliasRange) {
      const baseAnchor = aliasMap[aliasRange.alias];
      if (!baseAnchor) {
        throw new Error(`googleSlides: missing alias mapping for ${aliasRange.alias}`);
      }
      return this.#resolveTextRangeAnchor(baseAnchor, aliasRange.start, aliasRange.length);
    }
    const anchorRange = this.#parseTextRangeAnchor(ref);
    if (!anchorRange) {
      throw new Error(`googleSlides: invalid text range target ${ref}`);
    }
    return this.#resolveTextRangeAnchor(anchorRange.anchor, anchorRange.start, anchorRange.length);
  }
  #resolveTextRangeAnchor(anchor, start, length2) {
    const element = this.#presentation.resolve(anchor);
    if (!(element instanceof Shape2)) {
      throw new Error("googleSlides: text range anchor is not a shape.");
    }
    const objectId = this.#requireShapeObjectId(element);
    return {
      objectId,
      range: {
        type: "FIXED_RANGE",
        startIndex: start,
        endIndex: start + length2
      }
    };
  }
  #parseTextRangeAlias(ref) {
    if (!ref.startsWith("tr/@")) {
      return null;
    }
    const parts = ref.split("/");
    if (parts.length !== 4) {
      throw new Error(`googleSlides: invalid text range alias ${ref}`);
    }
    const alias = parts[1];
    const start = Number(parts[2]);
    const length2 = Number(parts[3]);
    if (!Number.isFinite(start) || !Number.isFinite(length2)) {
      throw new Error(`googleSlides: invalid text range ${ref}`);
    }
    return { alias, start, length: length2 };
  }
  #parseTextRangeAnchor(ref) {
    if (!ref.startsWith("tr/")) {
      return null;
    }
    const parts = ref.split("/");
    if (parts.length !== 5) {
      return null;
    }
    const prefix = parts[1];
    const suffix = parts[2];
    const start = Number(parts[3]);
    const length2 = Number(parts[4]);
    if (!prefix || !suffix) {
      return null;
    }
    if (!Number.isFinite(start) || !Number.isFinite(length2)) {
      return null;
    }
    return { anchor: `${prefix}/${suffix}`, start, length: length2 };
  }
  #isPatchAlias(value) {
    return value.startsWith("@") && value.length > 1;
  }
  #mapShapeGeometry(props, warnings) {
    if (props.geometry === "custom" || props.geometry === "connector") {
      throw new Error("googleSlides: shape.add does not support custom shapes.");
    }
    const mapped = SHAPE_TYPE_FROM_GEOMETRY[props.geometry];
    if (!mapped) {
      warnings.push(`googleSlides: shape.add geometry "${props.geometry}" is not mapped.`);
      return "RECTANGLE";
    }
    return mapped;
  }
  #addShapeSetRequests(shape2, objectId, props, requests, warnings) {
    if (props.position) {
      const transform2 = this.#buildTransformFromShape(shape2, objectId);
      requests.push({
        updatePageElementTransform: {
          objectId,
          transform: transform2,
          applyMode: "ABSOLUTE"
        }
      });
    }
    if (props.fill !== undefined) {
      const color2 = this.#resolveFillColor(props.fill, warnings);
      if (color2) {
        requests.push({
          updateShapeProperties: {
            objectId,
            shapeProperties: {
              shapeBackgroundFill: { solidFill: { color: color2 } }
            },
            fields: "shapeBackgroundFill.solidFill.color"
          }
        });
      }
    }
    if (props.line || props.name !== undefined || props.zIndex !== undefined || props.placeholderType !== undefined || props.placeholderIndex !== undefined) {
      warnings.push("googleSlides: shape.set props are partially supported.");
    }
  }
  #addTextSetRequests(objectId, value, requests, options) {
    const text2 = String(value);
    if (!options?.skipDelete) {
      requests.push({
        deleteText: {
          objectId,
          textRange: { type: "ALL" }
        }
      });
    }
    if (text2) {
      requests.push({
        insertText: {
          objectId,
          text: text2,
          insertionIndex: 0
        }
      });
    }
  }
  #addTextStyleRequests(objectId, props, range2, requests, warnings) {
    const { style, fields } = this.#buildTextStyle(props, warnings);
    if (fields.length > 0 && style) {
      requests.push({
        updateTextStyle: {
          objectId,
          style,
          textRange: range2,
          fields: fields.join(",")
        }
      });
    }
    const paragraph = this.#buildParagraphStyle(props);
    if (paragraph) {
      requests.push({
        updateParagraphStyle: {
          objectId,
          style: paragraph.style,
          textRange: range2,
          fields: paragraph.fields.join(",")
        }
      });
    }
  }
  #addShapeTextBoxRequests(objectId, props, requests, warnings) {
    const shapeProps = {};
    const fields = [];
    if (props.verticalAlignment) {
      const mapped = VERTICAL_ALIGNMENT_MAP[props.verticalAlignment];
      if (mapped) {
        shapeProps.contentAlignment = mapped;
        fields.push("contentAlignment");
      } else {
        warnings.push(`googleSlides: unsupported vertical alignment "${props.verticalAlignment}".`);
      }
    }
    if (props.autoFit) {
      const mapped = AUTOFIT_MAP[props.autoFit];
      if (mapped) {
        shapeProps.autofit = { autofitType: mapped };
        fields.push("autofit.autofitType");
      } else {
        warnings.push(`googleSlides: unsupported autoFit "${props.autoFit}".`);
      }
    }
    if (fields.length > 0) {
      requests.push({
        updateShapeProperties: {
          objectId,
          shapeProperties: shapeProps,
          fields: fields.join(",")
        }
      });
    }
    if (props.wrap || props.insets || props.style) {
      warnings.push("googleSlides: text.style.set wrap/insets/style are not mapped.");
    }
  }
  #buildTextStyle(props, warnings) {
    const style = {};
    const fields = [];
    if (props.bold !== undefined) {
      style.bold = props.bold;
      fields.push("bold");
    }
    if (props.italic !== undefined) {
      style.italic = props.italic;
      fields.push("italic");
    }
    if (props.underline !== undefined) {
      const normalized = String(props.underline).trim().toLowerCase();
      style.underline = normalized !== "" && normalized !== "none";
      fields.push("underline");
    }
    const fontSizePt = this.#resolveFontSizePt(props);
    if (fontSizePt !== undefined) {
      style.fontSize = { magnitude: fontSizePt, unit: "PT" };
      fields.push("fontSize");
    }
    if (props.color !== undefined) {
      const color2 = this.#resolveTextColor(props.color, warnings);
      if (color2) {
        style.foregroundColor = { opaqueColor: color2 };
        fields.push("foregroundColor");
      }
    }
    if ("link" in props && props.link !== undefined) {
      const link2 = props.link;
      if (link2 === null) {
        fields.push("link");
      } else if (link2.isExternal) {
        style.link = { url: link2.uri };
        fields.push("link");
      } else {
        warnings.push("googleSlides: only external links are supported.");
      }
    }
    if ("style" in props && props.style) {
      warnings.push("googleSlides: named text styles are not mapped.");
    }
    if (fields.length === 0) {
      return { style: null, fields: [] };
    }
    return { style, fields };
  }
  #buildParagraphStyle(props) {
    const style = {};
    const fields = [];
    if ("alignment" in props && props.alignment) {
      const mapped = ALIGNMENT_MAP[props.alignment];
      if (mapped) {
        style.alignment = mapped;
        fields.push("alignment");
      }
    }
    if ("lineSpacing" in props && props.lineSpacing !== undefined) {
      style.lineSpacing = props.lineSpacing * 100;
      fields.push("lineSpacing");
    }
    if ("spacingBefore" in props && props.spacingBefore !== undefined) {
      style.spaceAbove = {
        magnitude: pointsFromPixels(props.spacingBefore),
        unit: "PT"
      };
      fields.push("spaceAbove");
    }
    if ("spacingAfter" in props && props.spacingAfter !== undefined) {
      style.spaceBelow = {
        magnitude: pointsFromPixels(props.spacingAfter),
        unit: "PT"
      };
      fields.push("spaceBelow");
    }
    if ("indentLeft" in props && props.indentLeft !== undefined) {
      style.indentStart = {
        magnitude: pointsFromPixels(props.indentLeft),
        unit: "PT"
      };
      fields.push("indentStart");
    }
    if ("indentFirstLine" in props && props.indentFirstLine !== undefined) {
      style.indentFirstLine = {
        magnitude: pointsFromPixels(props.indentFirstLine),
        unit: "PT"
      };
      fields.push("indentFirstLine");
    }
    if (fields.length === 0) {
      return null;
    }
    return { style, fields };
  }
  #resolveFontSizePt(props) {
    if (props.fontSize !== undefined) {
      return pointsFromPixels(props.fontSize);
    }
    if (props.fontSizePt !== undefined) {
      return props.fontSizePt;
    }
    return;
  }
  #resolveTextColor(color2, warnings) {
    try {
      return this.#toOpaqueColor(color2);
    } catch (error48) {
      warnings.push(`googleSlides: failed to map text color: ${error48.message}`);
      return;
    }
  }
  #resolveFillColor(value, warnings) {
    if (!value) {
      return;
    }
    if (typeof value === "string") {
      return this.#toOpaqueColor(value);
    }
    if ("type" in value && value.type === "solid") {
      return this.#toOpaqueColor(value.color);
    }
    warnings.push("googleSlides: only solid fills are supported.");
    return;
  }
  #toOpaqueColor(value) {
    const color2 = new Color4(value);
    if (color2.type === "theme") {
      const mapped = THEME_COLOR_MAP[color2.value];
      if (!mapped) {
        throw new Error(`theme color not mapped: ${color2.value}`);
      }
      return { themeColor: mapped };
    }
    const hex4 = color2.hex.replace("#", "");
    if (hex4.length !== 6) {
      throw new Error(`invalid hex color: ${color2.hex}`);
    }
    const red = parseInt(hex4.slice(0, 2), 16) / 255;
    const green = parseInt(hex4.slice(2, 4), 16) / 255;
    const blue = parseInt(hex4.slice(4, 6), 16) / 255;
    return { rgbColor: { red, green, blue } };
  }
  #buildTransformFromShape(shape2, objectId) {
    const base = this.#elementBaseSizes.get(objectId);
    if (!base) {
      throw new Error("googleSlides: missing base size for transform.");
    }
    if (base.widthPt <= 0 || base.heightPt <= 0) {
      throw new Error("googleSlides: base size must be positive.");
    }
    const { left, top, width, height } = shape2.position;
    if (left === undefined || top === undefined || width === undefined || height === undefined) {
      throw new Error("googleSlides: shape position is incomplete.");
    }
    const widthPt = pointsFromPixels(width);
    const heightPt = pointsFromPixels(height);
    const scaleX = widthPt / base.widthPt;
    const scaleY = heightPt / base.heightPt;
    return {
      scaleX,
      scaleY,
      translateX: pointsFromPixels(left),
      translateY: pointsFromPixels(top),
      unit: "PT"
    };
  }
  #buildSizeFromFrame(frame) {
    if (frame.width === undefined || frame.height === undefined) {
      throw new Error("googleSlides: shape frame is missing size.");
    }
    const widthPt = pointsFromPixels(frame.width);
    const heightPt = pointsFromPixels(frame.height);
    return {
      size: {
        width: { magnitude: widthPt, unit: "PT" },
        height: { magnitude: heightPt, unit: "PT" }
      },
      widthPt,
      heightPt
    };
  }
  #buildTransformFromFrame(frame) {
    if (frame.left === undefined || frame.top === undefined) {
      throw new Error("googleSlides: shape frame is missing position.");
    }
    return {
      scaleX: 1,
      scaleY: 1,
      translateX: pointsFromPixels(frame.left),
      translateY: pointsFromPixels(frame.top),
      unit: "PT"
    };
  }
  #registerSlide(slide, objectId) {
    this.#slideObjectIds.set(slide, objectId);
    this.#slidesByRemoteId.set(objectId, slide);
  }
  #dropSlideMapping(slide, objectId) {
    this.#slideObjectIds.delete(slide);
    this.#slidesByRemoteId.delete(objectId);
    this.#notesObjectIds.delete(slide.speakerNotes);
  }
  #registerSlideObjectId(slide) {
    const existing = this.#slideObjectIds.get(slide);
    if (existing) {
      return existing;
    }
    const objectId = buildSlidesObjectId(["granola", "slide", slide.id]);
    this.#registerSlide(slide, objectId);
    return objectId;
  }
  #requireSlideObjectId(slide) {
    const objectId = this.#slideObjectIds.get(slide);
    if (!objectId) {
      throw new Error("googleSlides: slide object id is not mapped.");
    }
    return objectId;
  }
  #registerShapeObjectId(shape2) {
    const existing = this.#shapeObjectIds.get(shape2);
    if (existing) {
      return existing;
    }
    const slideId = shape2.slideId ?? "slide";
    const objectId = buildSlidesObjectId([
      "granola",
      "shape",
      slideId,
      shape2.id
    ]);
    this.#shapeObjectIds.set(shape2, objectId);
    return objectId;
  }
  #dropShapeMapping(shape2, objectId) {
    this.#shapeObjectIds.delete(shape2);
    this.#elementBaseSizes.delete(objectId);
  }
  #requireShapeObjectId(shape2) {
    const objectId = this.#shapeObjectIds.get(shape2);
    if (!objectId) {
      throw new Error("googleSlides: shape object id is not mapped.");
    }
    return objectId;
  }
  #registerBaseSize(objectId, widthPt, heightPt) {
    if (!Number.isFinite(widthPt) || !Number.isFinite(heightPt)) {
      return;
    }
    this.#elementBaseSizes.set(objectId, { widthPt, heightPt });
  }
  #importSlideElements(slideData, slide) {
    const elements = slideData.pageElements ?? [];
    elements.forEach((element) => {
      if (!element.objectId || !element.shape) {
        return;
      }
      const geometry = GEOMETRY_FROM_SHAPE_TYPE[element.shape.shapeType ?? ""] ?? "rect";
      const frame = this.#buildFrameFromElement(element);
      if (!frame) {
        console.warn(`googleSlides: skipped shape ${element.objectId} without size.`);
        return;
      }
      const shape2 = slide.shapes.add({ geometry, position: frame });
      const text2 = this.#extractTextContent(element.shape.text);
      if (text2) {
        shape2.text = text2;
      }
      this.#shapeObjectIds.set(shape2, element.objectId);
      const base = this.#baseSizeFromElement(element);
      if (base) {
        this.#registerBaseSize(element.objectId, base.widthPt, base.heightPt);
      }
    });
  }
  #buildFrameFromElement(element) {
    const size2 = element.size;
    if (!size2?.width || !size2.height) {
      return null;
    }
    const widthPt = pointsFromSlidesDimension(size2.width);
    const heightPt = pointsFromSlidesDimension(size2.height);
    if (widthPt === undefined || heightPt === undefined) {
      return null;
    }
    const transform2 = element.transform;
    const scaleX = transform2?.scaleX ?? 1;
    const scaleY = transform2?.scaleY ?? 1;
    const translateX = this.#translatePoints(transform2);
    if (!translateX) {
      return null;
    }
    const widthPx = pixelsFromPoints(widthPt * scaleX);
    const heightPx = pixelsFromPoints(heightPt * scaleY);
    return {
      left: pixelsFromPoints(translateX.x),
      top: pixelsFromPoints(translateX.y),
      width: widthPx,
      height: heightPx
    };
  }
  #translatePoints(transform2) {
    if (!transform2) {
      return { x: 0, y: 0 };
    }
    const tx = transform2.translateX;
    const ty = transform2.translateY;
    if (typeof tx !== "number" || typeof ty !== "number" || !Number.isFinite(tx) || !Number.isFinite(ty)) {
      return null;
    }
    if (transform2.unit === "PT") {
      return { x: tx, y: ty };
    }
    const unit2 = "EMU";
    const pxX = pixelsFromSlidesDimension({
      magnitude: tx,
      unit: unit2
    });
    const pxY = pixelsFromSlidesDimension({
      magnitude: ty,
      unit: unit2
    });
    if (pxX === undefined || pxY === undefined) {
      return null;
    }
    return { x: pointsFromPixels(pxX), y: pointsFromPixels(pxY) };
  }
  #baseSizeFromElement(element) {
    const widthPt = pointsFromSlidesDimension(element.size?.width);
    const heightPt = pointsFromSlidesDimension(element.size?.height);
    if (widthPt === undefined || heightPt === undefined) {
      return null;
    }
    return { widthPt, heightPt };
  }
  #extractTextContent(text2) {
    const elements = text2?.textElements ?? [];
    let output = "";
    let isFirstParagraph = true;
    for (const element of elements) {
      if (element.paragraphMarker) {
        if (!isFirstParagraph) {
          output += `
`;
        }
        isFirstParagraph = false;
        continue;
      }
      if (element.textRun?.content) {
        output += element.textRun.content;
        continue;
      }
      if (element.autoText?.content) {
        output += element.autoText.content;
      }
    }
    return output;
  }
  async#refreshNotesMapping() {
    const data = await this.#client.getPresentation(this.#presentationId, {
      fields: this.#fields
    });
    const slides = data.slides ?? [];
    slides.forEach((slideData) => {
      if (!slideData.objectId) {
        return;
      }
      const localSlide = this.#slidesByRemoteId.get(slideData.objectId);
      if (!localSlide) {
        return;
      }
      const notesId = slideData.slideProperties?.notesPage?.notesProperties?.speakerNotesObjectId;
      if (notesId) {
        this.#notesObjectIds.set(localSlide.speakerNotes, notesId);
      }
    });
  }
}
var resolveSlidesPageSize = (data) => {
  const width = pixelsFromSlidesDimension(data.pageSize?.width);
  const height = pixelsFromSlidesDimension(data.pageSize?.height);
  if (width === undefined || height === undefined) {
    return;
  }
  return { width, height };
};

// node_modules/@oai/granola/dist/models/presentation/presentation-awareness-state.js
function cloneCursor(cursor) {
  if (!cursor) {
    return null;
  }
  return {
    slideId: cursor.slideId,
    point: {
      x: cursor.point.x,
      y: cursor.point.y
    },
    label: cursor.label,
    status: cursor.status
  };
}
function cloneSelection(selection) {
  if (!selection) {
    return null;
  }
  return {
    slideId: selection.slideId,
    selectedElementIds: [...selection.selectedElementIds],
    label: selection.label,
    status: selection.status
  };
}

class PresentationAwarenessState {
  #presence = new Map;
  activeSlideId;
  cursor = null;
  selection = null;
  constructor(options = {}) {
    this.activeSlideId = options.activeSlideId ?? null;
  }
  setActiveSlideId(slideId) {
    this.activeSlideId = slideId?.trim() || null;
  }
  setCursor(cursor) {
    this.cursor = cloneCursor(cursor);
  }
  setSelection(selection) {
    this.selection = cloneSelection(selection);
  }
  clearCursor(options = {}) {
    if (!this.cursor) {
      return;
    }
    if (options.slideId && this.cursor.slideId !== options.slideId) {
      return;
    }
    this.cursor = null;
  }
  clearSelection(options = {}) {
    if (!this.selection) {
      return;
    }
    if (options.slideId && this.selection.slideId !== options.slideId) {
      return;
    }
    this.selection = null;
  }
  setPresenceCursor(presenceId, cursor, options = {}) {
    if (!presenceId) {
      throw new Error("Presence id is required.");
    }
    if (!cursor) {
      this.clearPresenceCursor(presenceId);
      return;
    }
    const existing = this.#presence.get(presenceId);
    this.#presence.set(presenceId, {
      id: presenceId,
      kind: options.kind ?? existing?.kind ?? "collaborator",
      cursor: cloneCursor(cursor),
      selection: cloneSelection(existing?.selection ?? null)
    });
  }
  setPresenceSelection(presenceId, selection, options = {}) {
    if (!presenceId) {
      throw new Error("Presence id is required.");
    }
    if (!selection) {
      this.clearPresenceSelection(presenceId);
      return;
    }
    const existing = this.#presence.get(presenceId);
    this.#presence.set(presenceId, {
      id: presenceId,
      kind: options.kind ?? existing?.kind ?? "collaborator",
      cursor: cloneCursor(existing?.cursor ?? null),
      selection: cloneSelection(selection)
    });
  }
  clearPresenceCursor(presenceId, options = {}) {
    if (!presenceId) {
      throw new Error("Presence id is required.");
    }
    const existing = this.#presence.get(presenceId);
    if (!existing) {
      return;
    }
    if (options.slideId && existing.cursor?.slideId !== options.slideId) {
      return;
    }
    if (existing.selection) {
      this.#presence.set(presenceId, {
        ...existing,
        cursor: null
      });
      return;
    }
    this.#presence.delete(presenceId);
  }
  clearPresenceSelection(presenceId, options = {}) {
    if (!presenceId) {
      throw new Error("Presence id is required.");
    }
    const existing = this.#presence.get(presenceId);
    if (!existing) {
      return;
    }
    if (options.slideId && existing.selection?.slideId !== options.slideId) {
      return;
    }
    if (existing.cursor) {
      this.#presence.set(presenceId, {
        ...existing,
        selection: null
      });
      return;
    }
    this.#presence.delete(presenceId);
  }
  getPresenceCursorsForSlide(slideId) {
    const key = slideId?.trim();
    if (!key) {
      return [];
    }
    const cursors = [];
    for (const presence of this.#presence.values()) {
      if (!presence.cursor || presence.cursor.slideId !== key) {
        continue;
      }
      cursors.push({
        presenceId: presence.id,
        kind: presence.kind,
        slideId: presence.cursor.slideId,
        point: {
          x: presence.cursor.point.x,
          y: presence.cursor.point.y
        },
        label: presence.cursor.label,
        status: presence.cursor.status
      });
    }
    return cursors;
  }
  getPresenceSelectionsForSlide(slideId) {
    const key = slideId?.trim();
    if (!key) {
      return [];
    }
    const selections = [];
    for (const presence of this.#presence.values()) {
      if (!presence.selection || presence.selection.slideId !== key) {
        continue;
      }
      selections.push({
        presenceId: presence.id,
        kind: presence.kind,
        slideId: presence.selection.slideId,
        selectedElementIds: [...presence.selection.selectedElementIds],
        label: presence.selection.label,
        status: presence.selection.status
      });
    }
    return selections;
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/collab/json-snapshot-branch-store.js
class JsonSnapshotBranchStore {
  #root;
  #prefix;
  #schemaVersion;
  #runLocalTransaction;
  #getCollabOrigins;
  #readSnapshotFromOwner;
  #applySnapshotToOwner;
  #encodeSnapshot;
  #decodeSnapshot;
  #actorId;
  #lastAppliedWinner;
  #observer;
  constructor(config2) {
    this.#root = config2.root;
    this.#prefix = config2.prefix;
    this.#schemaVersion = config2.schemaVersion;
    this.#runLocalTransaction = config2.runLocalTransaction;
    this.#getCollabOrigins = config2.getCollabOrigins;
    this.#readSnapshotFromOwner = config2.readSnapshotFromOwner;
    this.#applySnapshotToOwner = config2.applySnapshotToOwner;
    this.#encodeSnapshot = config2.encodeSnapshot;
    this.#decodeSnapshot = config2.decodeSnapshot;
    this.#actorId = String(config2.root.doc?.clientID ?? "0");
    this.#observer = (event, transaction) => {
      this.#handleRootEvent(event, transaction);
    };
    this.#root.observe(this.#observer);
    const winner = this.#resolveWinningState();
    this.#lastAppliedWinner = winner;
    if (winner) {
      this.#applySnapshotToOwner(this.#decodeSnapshotJson(winner.snapshot));
    }
  }
  dispose() {
    this.#root.unobserve(this.#observer);
  }
  activate() {
    this.#setSchemaVersion();
  }
  flushFromOwner() {
    this.activate();
    const snapshot = this.#readSnapshotFromOwner();
    const nextSnapshotJson = snapshot === undefined ? undefined : this.#encodeSnapshotJson(snapshot);
    const current = this.#readState(this.#actorId);
    const winner = this.#resolveWinningState();
    if (current?.snapshot === nextSnapshotJson) {
      return;
    }
    if (!current && winner?.snapshot === nextSnapshotJson) {
      return;
    }
    const nextClock = Math.max(current?.clock ?? -1, winner?.clock ?? -1) + 1;
    this.#runLocalTransaction(() => {
      this.#root.set(this.#stateKey(this.#actorId), {
        clock: nextClock,
        snapshot: nextSnapshotJson
      });
    });
  }
  #handleRootEvent(event, transaction) {
    const changedRelevantKey = [...event.keysChanged].some((key) => key === this.#schemaKey() || key.startsWith(this.#stateKeyPrefix()));
    if (!changedRelevantKey) {
      return;
    }
    const origins = this.#getCollabOrigins();
    if (transaction.origin === origins.local || transaction.origin === origins.record) {
      return;
    }
    const winner = this.#resolveWinningState();
    if (winner?.actorId === this.#lastAppliedWinner?.actorId && winner?.clock === this.#lastAppliedWinner?.clock && winner?.snapshot === this.#lastAppliedWinner?.snapshot) {
      return;
    }
    this.#lastAppliedWinner = winner;
    this.#applySnapshotToOwner(this.#decodeSnapshotJson(winner?.snapshot));
  }
  #setSchemaVersion() {
    if (this.#root.get(this.#schemaKey()) === this.#schemaVersion) {
      return;
    }
    this.#runLocalTransaction(() => {
      this.#root.set(this.#schemaKey(), this.#schemaVersion);
    });
  }
  #resolveWinningState() {
    let winner;
    for (const [key, value] of this.#root.entries()) {
      if (!key.startsWith(this.#stateKeyPrefix())) {
        continue;
      }
      if (!isSnapshotState(value)) {
        continue;
      }
      const actorId = key.slice(this.#stateKeyPrefix().length);
      if (!winner) {
        winner = { actorId, clock: value.clock, snapshot: value.snapshot };
        continue;
      }
      if (value.clock > winner.clock) {
        winner = { actorId, clock: value.clock, snapshot: value.snapshot };
        continue;
      }
      if (value.clock === winner.clock && actorId > winner.actorId) {
        winner = { actorId, clock: value.clock, snapshot: value.snapshot };
      }
    }
    return winner;
  }
  #readState(actorId) {
    const raw = this.#root.get(this.#stateKey(actorId));
    return isSnapshotState(raw) ? raw : undefined;
  }
  #schemaKey() {
    return `${this.#prefix}.schemaVersion`;
  }
  #stateKeyPrefix() {
    return `${this.#prefix}.state.`;
  }
  #stateKey(actorId) {
    return `${this.#stateKeyPrefix()}${actorId}`;
  }
  #encodeSnapshotJson(snapshot) {
    return JSON.stringify(this.#encodeSnapshot(snapshot));
  }
  #decodeSnapshotJson(snapshotJson) {
    if (snapshotJson === undefined) {
      return;
    }
    return this.#decodeSnapshot(JSON.parse(snapshotJson));
  }
}
function isSnapshotState(value) {
  if (!value || typeof value !== "object") {
    return false;
  }
  const record2 = value;
  return typeof record2["clock"] === "number" && (record2["snapshot"] === undefined || typeof record2["snapshot"] === "string");
}

// node_modules/@oai/granola/dist/models/spreadsheet/collab/collab-schema.js
var WORKBOOK_COLLAB_SCHEMA_VERSION = 1;
var WORKSHEET_COLLAB_SCHEMA_VERSION = 1;
var SNAPSHOT_BRANCH_SCHEMA_VERSION = 1;
var ROOT_META_KEY = "meta";
var ROOT_SCHEMA_VERSION_KEY = "schemaVersion";
var WORKBOOK_STATE_ROOT_KEY = "workbookState";
function getWorkbookCollabRoot(doc2) {
  return doc2.getMap(WORKBOOK_STATE_ROOT_KEY);
}
function activateWorkbookCollabRoot(config2) {
  activateCollabRoot({
    root: config2.root,
    schemaVersion: WORKBOOK_COLLAB_SCHEMA_VERSION,
    runLocalTransaction: config2.runLocalTransaction
  });
}
function activateWorksheetCollabRoot(config2) {
  activateCollabRoot({
    root: config2.root,
    schemaVersion: WORKSHEET_COLLAB_SCHEMA_VERSION,
    runLocalTransaction: config2.runLocalTransaction
  });
}
function getOrCreateCollabChildMap(config2) {
  const existing = config2.root.get(config2.key);
  if (existing instanceof YMap) {
    return existing;
  }
  const created = new YMap;
  config2.runLocalTransaction(() => {
    config2.root.set(config2.key, created);
  });
  return created;
}
function activateCollabRoot(config2) {
  const meta3 = getOrCreateCollabChildMap({
    root: config2.root,
    key: ROOT_META_KEY,
    runLocalTransaction: config2.runLocalTransaction
  });
  if (meta3.get(ROOT_SCHEMA_VERSION_KEY) === config2.schemaVersion) {
    return;
  }
  config2.runLocalTransaction(() => {
    meta3.set(ROOT_SCHEMA_VERSION_KEY, config2.schemaVersion);
  });
}

// node_modules/@oai/granola/dist/models/comments/comments-collab-store.js
class CommentsCollabStore {
  #store;
  constructor(config2) {
    this.#store = new JsonSnapshotBranchStore({
      root: config2.root,
      prefix: config2.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION,
      runLocalTransaction: config2.runLocalTransaction,
      getCollabOrigins: config2.getCollabOrigins,
      readSnapshotFromOwner: config2.readComments,
      applySnapshotToOwner: (snapshot) => config2.applyComments(snapshot ?? { people: [], threads: [] }),
      encodeSnapshot: (snapshot) => snapshot,
      decodeSnapshot: (snapshot) => snapshot
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/presentation/collab/collab-schema.js
var PRESENTATION_COLLAB_SCHEMA_VERSION = 1;
var SNAPSHOT_BRANCH_SCHEMA_VERSION2 = 1;
var PRESENTATION_STATE_ROOT_KEY = "presentationState";
var ROOT_META_KEY2 = "meta";
var ROOT_SCHEMA_VERSION_KEY2 = "schemaVersion";
var SLIDES_BY_ID_KEY = "slidesById";
function getPresentationCollabRoot(doc2) {
  return doc2.getMap(PRESENTATION_STATE_ROOT_KEY);
}
function activatePresentationCollabRoot(config2) {
  const meta3 = getOrCreateCollabChildMap2({
    root: config2.root,
    key: ROOT_META_KEY2,
    runLocalTransaction: config2.runLocalTransaction
  });
  if (meta3.get(ROOT_SCHEMA_VERSION_KEY2) === PRESENTATION_COLLAB_SCHEMA_VERSION) {
    return;
  }
  config2.runLocalTransaction(() => {
    meta3.set(ROOT_SCHEMA_VERSION_KEY2, PRESENTATION_COLLAB_SCHEMA_VERSION);
  });
}
function readPresentationSlidesById(root) {
  const existing = root.get(SLIDES_BY_ID_KEY);
  if (existing instanceof YMap) {
    return existing;
  }
  return;
}
function getOrCreatePresentationSlidesById(config2) {
  return getOrCreateCollabChildMap2({
    root: config2.root,
    key: SLIDES_BY_ID_KEY,
    runLocalTransaction: config2.runLocalTransaction
  });
}
function getOrCreateCollabChildMap2(config2) {
  const existing = config2.root.get(config2.key);
  if (existing instanceof YMap) {
    return existing;
  }
  const created = new YMap;
  config2.runLocalTransaction(() => {
    config2.root.set(config2.key, created);
  });
  return created;
}

// node_modules/@oai/granola/dist/models/presentation/presentation-charts-collab-store.js
class PresentationChartsCollabStore {
  #store;
  constructor(config2) {
    this.#store = new JsonSnapshotBranchStore({
      root: config2.root,
      prefix: config2.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION2,
      runLocalTransaction: config2.runLocalTransaction,
      getCollabOrigins: config2.getCollabOrigins,
      readSnapshotFromOwner: config2.readCharts,
      applySnapshotToOwner: (charts) => config2.applyCharts(charts ?? []),
      encodeSnapshot: (charts) => charts,
      decodeSnapshot: (charts) => charts
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/presentation/presentation-citations-collab-store.js
class PresentationCitationsCollabStore {
  #store;
  constructor(config2) {
    this.#store = new JsonSnapshotBranchStore({
      root: config2.root,
      prefix: config2.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION2,
      runLocalTransaction: config2.runLocalTransaction,
      getCollabOrigins: config2.getCollabOrigins,
      readSnapshotFromOwner: config2.readCitations,
      applySnapshotToOwner: (citations) => config2.applyCitations(citations ?? []),
      encodeSnapshot: (citations) => citations,
      decodeSnapshot: (citations) => citations
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/presentation/presentation-image-assets-collab-store.js
class PresentationImageAssetsCollabStore {
  #store;
  constructor(config2) {
    this.#store = new JsonSnapshotBranchStore({
      root: config2.root,
      prefix: config2.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION2,
      runLocalTransaction: config2.runLocalTransaction,
      getCollabOrigins: config2.getCollabOrigins,
      readSnapshotFromOwner: config2.readImages,
      applySnapshotToOwner: (images) => config2.applyImages(images ?? []),
      encodeSnapshot: (images) => images.map(({ data: _data, ...image2 }) => ({
        ...image2
      })),
      decodeSnapshot: (images) => images.map((image2) => ({
        ...image2,
        data: new Uint8Array
      }))
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/presentation/presentation-layouts-collab-store.js
class PresentationLayoutsCollabStore {
  #store;
  constructor(config2) {
    this.#store = new JsonSnapshotBranchStore({
      root: config2.root,
      prefix: config2.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION2,
      runLocalTransaction: config2.runLocalTransaction,
      getCollabOrigins: config2.getCollabOrigins,
      readSnapshotFromOwner: config2.readLayouts,
      applySnapshotToOwner: (layouts) => config2.applyLayouts(layouts ?? []),
      encodeSnapshot: (layouts) => layouts,
      decodeSnapshot: (layouts) => layouts
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/presentation/presentation-slides-collab-store.js
class PresentationSlidesCollabStore {
  #store;
  constructor(config2) {
    this.#store = new JsonSnapshotBranchStore({
      root: config2.root,
      prefix: config2.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION2,
      runLocalTransaction: config2.runLocalTransaction,
      getCollabOrigins: config2.getCollabOrigins,
      readSnapshotFromOwner: config2.readSlides,
      applySnapshotToOwner: (slides) => config2.applySlides(slides ?? []),
      encodeSnapshot: (slides) => slides,
      decodeSnapshot: (slides) => slides
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/presentation/presentation-table-styles-collab-store.js
class PresentationTableStylesCollabStore {
  #store;
  constructor(config2) {
    this.#store = new JsonSnapshotBranchStore({
      root: config2.root,
      prefix: config2.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION2,
      runLocalTransaction: config2.runLocalTransaction,
      getCollabOrigins: config2.getCollabOrigins,
      readSnapshotFromOwner: config2.readTableStyles,
      applySnapshotToOwner: config2.applyTableStyles,
      encodeSnapshot: (value) => value,
      decodeSnapshot: (value) => value
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/presentation/presentation-theme-collab-store.js
class PresentationThemeCollabStore {
  #store;
  constructor(config2) {
    this.#store = new JsonSnapshotBranchStore({
      root: config2.root,
      prefix: config2.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION2,
      runLocalTransaction: config2.runLocalTransaction,
      getCollabOrigins: config2.getCollabOrigins,
      readSnapshotFromOwner: config2.readTheme,
      applySnapshotToOwner: config2.applyTheme,
      encodeSnapshot: (theme) => theme,
      decodeSnapshot: (theme) => theme
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/presentation/presentation-collab-state.js
class PresentationCollabState {
  #stores;
  constructor(config2) {
    this.#stores = [
      new PresentationThemeCollabStore({
        root: config2.root,
        prefix: "theme",
        runLocalTransaction: config2.runLocalTransaction,
        getCollabOrigins: config2.getCollabOrigins,
        readTheme: config2.readTheme,
        applyTheme: config2.applyTheme
      }),
      new PresentationTableStylesCollabStore({
        root: config2.root,
        prefix: "tableStyles",
        runLocalTransaction: config2.runLocalTransaction,
        getCollabOrigins: config2.getCollabOrigins,
        readTableStyles: config2.readTableStyles,
        applyTableStyles: config2.applyTableStyles
      }),
      new PresentationLayoutsCollabStore({
        root: config2.root,
        prefix: "layouts",
        runLocalTransaction: config2.runLocalTransaction,
        getCollabOrigins: config2.getCollabOrigins,
        readLayouts: config2.readLayouts,
        applyLayouts: config2.applyLayouts
      }),
      new PresentationChartsCollabStore({
        root: config2.root,
        prefix: "charts",
        runLocalTransaction: config2.runLocalTransaction,
        getCollabOrigins: config2.getCollabOrigins,
        readCharts: config2.readCharts,
        applyCharts: config2.applyCharts
      }),
      new PresentationImageAssetsCollabStore({
        root: config2.root,
        prefix: "images",
        runLocalTransaction: config2.runLocalTransaction,
        getCollabOrigins: config2.getCollabOrigins,
        readImages: config2.readImages,
        applyImages: config2.applyImages
      }),
      new PresentationCitationsCollabStore({
        root: config2.root,
        prefix: "citations",
        runLocalTransaction: config2.runLocalTransaction,
        getCollabOrigins: config2.getCollabOrigins,
        readCitations: config2.readCitations,
        applyCitations: config2.applyCitations
      }),
      new CommentsCollabStore({
        root: config2.root,
        prefix: "comments",
        runLocalTransaction: config2.runLocalTransaction,
        getCollabOrigins: config2.getCollabOrigins,
        readComments: config2.readComments,
        applyComments: config2.applyComments
      }),
      new PresentationSlidesCollabStore({
        root: config2.root,
        prefix: "slides",
        runLocalTransaction: config2.runLocalTransaction,
        getCollabOrigins: config2.getCollabOrigins,
        readSlides: config2.readSlides,
        applySlides: config2.applySlides
      })
    ];
  }
  dispose() {
    for (const store of this.#stores) {
      store.dispose();
    }
  }
  activate() {
    for (const store of this.#stores) {
      store.activate();
    }
  }
  flushFromOwner() {
    for (const store of this.#stores) {
      store.flushFromOwner();
    }
  }
}

// node_modules/@oai/granola/dist/models/presentation/presentation.js
var PRESENTATION_COMPOSE_API = Object.freeze({
  auto,
  card,
  chart,
  column,
  fill,
  fixed,
  fr,
  grow,
  grid,
  hug,
  image,
  panel,
  repeat,
  row,
  rule,
  shape,
  table,
  text,
  wrap
});
function cloneImageBytes(data) {
  return new Uint8Array(data ?? []);
}
function mergeImagesPreservingLocalHydration(currentImages, incomingImages) {
  const currentById = new Map(currentImages.filter((image2) => typeof image2.id === "string" && image2.id.length > 0).map((image2) => [image2.id, image2]));
  return incomingImages.map((incoming) => {
    const nextData = cloneImageBytes(incoming.data);
    const current = incoming.id ? currentById.get(incoming.id) : undefined;
    const currentData = current ? cloneImageBytes(current.data) : undefined;
    const shouldPreserveHydratedData = nextData.byteLength === 0 && (currentData?.byteLength ?? 0) > 0 && current?.contentType === incoming.contentType && current?.prompt === incoming.prompt && current?.uri === incoming.uri;
    return {
      ...incoming,
      data: shouldPreserveHydratedData ? currentData ?? nextData : nextData
    };
  });
}

class Presentation2 {
  #data;
  #yDoc;
  #presentationCollabRoot;
  #undoManager;
  #recordOrigin;
  #localOrigin;
  #collabState;
  #isApplyingCrdtUpdate = false;
  #presentationCollabDirty = false;
  #collabPublishQueued = false;
  #collaborativeStateReady = false;
  #tableStyles;
  #defaultLayoutId;
  #recorder;
  #imageGenerationRequests = [];
  styles;
  theme;
  slides;
  layouts;
  masters;
  charts;
  images;
  citations;
  scripts;
  comments;
  awareness;
  #assetResolver;
  #googleSlides;
  constructor(_context, proto, options = {}) {
    normalizePresentationProtoIds(proto);
    this.#data = {
      id: proto.id && proto.id.length > 0 ? proto.id : generateAidSuffix()
    };
    this.#yDoc = new Doc;
    this.#presentationCollabRoot = getPresentationCollabRoot(this.#yDoc);
    this.#recordOrigin = {};
    this.#localOrigin = {};
    this.#undoManager = new UndoManager(this.#yDoc, {
      trackedOrigins: new Set([this.#recordOrigin]),
      captureTimeout: 0
    });
    this.#tableStyles = proto.tableStyles ? { ...proto.tableStyles } : undefined;
    this.styles = new StylesCollection;
    const runtime = {
      resolveThemeColor: (name) => this.theme?.resolveThemeColorHex(name)
    };
    const themeProto = proto.theme ?? {};
    const layoutsProto = proto.layouts ?? [];
    const slidesProto = proto.slides ?? [];
    const chartsProto = proto.charts ?? [];
    const imagesProto = proto.images ?? [];
    const citationsProto = proto.contentReferences ?? [];
    this.theme = new Theme2(this.#themeContext(), themeProto, runtime);
    this.charts = new ChartCollection(this.#chartCollectionContext(), chartsProto);
    this.images = new ImageCollection(this.#imageCollectionContext(), imagesProto);
    this.#assetResolver = {
      getChartById: (id2) => this.charts.getById(id2),
      getImageById: (id2) => this.images.getById(id2),
      createImageAsset: (init) => this.images.add(init),
      createChartAsset: (type) => this.charts.add(type),
      attachChartAsset: (chart2) => this.charts.attach(chart2)
    };
    this.layouts = new LayoutCollection(this.#layoutCollectionContext(), layoutsProto);
    this.masters = new Masters(this.layouts);
    const slideCollectionOptions = this.#buildSlideCollectionOptions(options.slideSize);
    this.slides = new SlideCollection(this.#slideCollectionContext(), slidesProto, slideCollectionOptions);
    this.awareness = new PresentationAwarenessState({
      activeSlideId: this.slides.items[0]?.id ?? null
    });
    this.citations = new CitationsCollection(this.#citationsCollectionContext(), citationsProto);
    this.scripts = new Scripts({ presentation: this });
    this.comments = new Comments({
      people: proto.people ?? [],
      threads: proto.threads ?? [],
      recordOp: (op) => {
        this.queuePresentationCollabPublish();
        if (this.#recorder) {
          this.#recorder.record(op);
        }
      }
    });
    this.#collabState = new PresentationCollabState({
      root: this.#presentationCollabRoot,
      runLocalTransaction: (fn) => this.runLocalCollabTransaction(fn),
      getCollabOrigins: () => this.getCollabOrigins(),
      readTheme: () => this.theme.toProto(),
      applyTheme: (theme) => {
        this.theme.replaceFromProto(theme);
      },
      readTableStyles: () => this.tableStyles,
      applyTableStyles: (value) => {
        this.#tableStyles = value ? { ...value } : undefined;
      },
      readLayouts: () => this.layouts.toProto(),
      applyLayouts: (layouts) => {
        this.layouts.replace(layouts);
      },
      readCharts: () => this.charts.toProto(),
      applyCharts: (charts) => {
        this.charts.replace(charts);
      },
      readImages: () => this.images.toProto(),
      applyImages: (images) => {
        this.images.replace(mergeImagesPreservingLocalHydration(this.images.toProto(), images));
      },
      readCitations: () => this.citations.toProto(),
      applyCitations: (citations) => {
        this.citations.replace(citations);
      },
      readComments: () => this.comments.toProto(),
      applyComments: (snapshot) => {
        this.comments.replaceFromProto(snapshot);
      },
      readSlides: () => this.slides.toProto(),
      applySlides: (slides) => {
        this.slides.replace(slides);
      }
    });
    this.#googleSlides = options.googleSlides ? new GoogleSlidesAdapter(this, options.googleSlides) : undefined;
  }
  static create(arg1, arg2) {
    const { context, options } = resolvePresentationArgs(arg1, arg2);
    const proto = {
      id: "",
      slides: [],
      layouts: [],
      theme: undefined,
      charts: [],
      images: [],
      contentReferences: [],
      textStyles: [],
      people: [],
      threads: []
    };
    const presentation = new Presentation2(context, proto, options);
    presentation.#seedDefaultLayouts();
    return presentation;
  }
  static load(proto, arg1, arg2) {
    const { context, options } = resolvePresentationArgs(arg1, arg2);
    return new Presentation2(context, proto, options);
  }
  static async fromGoogleSlides(config2) {
    const data = await config2.client.getPresentation(config2.presentationId, {
      fields: config2.fields
    });
    const slideSize = resolveSlidesPageSize(data);
    const options = slideSize ? { slideSize, googleSlides: config2 } : { googleSlides: config2 };
    const presentation = Presentation2.create(options);
    const adapter = presentation.googleSlides;
    if (!adapter) {
      throw new Error("Google Slides adapter was not initialized.");
    }
    await adapter.hydrateFromSlides(data);
    return presentation;
  }
  get id() {
    return this.#data.id;
  }
  get compose() {
    return PRESENTATION_COMPOSE_API;
  }
  toSnapshot() {
    return {
      aid: `pr/${this.id}`,
      kind: "presentation",
      id: this.id,
      title: "Deck",
      slides: this.slides.items.map((slide) => slide.toSnapshot()),
      threads: this.comments.threads.items.map((thread) => thread.toSnapshot())
    };
  }
  get tableStyles() {
    return this.#tableStyles ? { ...this.#tableStyles } : undefined;
  }
  set tableStyles(value) {
    this.#tableStyles = value ? { ...value } : undefined;
    this.queuePresentationCollabPublish();
  }
  getActiveSlide() {
    return this.slides.getActive();
  }
  setActiveSlide(slide) {
    this.slides.setActive(slide);
  }
  export(options = { format: "png" }) {
    const targetSlide = options.slide ?? this.getActiveSlide() ?? (this.slides.count > 0 ? this.slides.getItem(0) : undefined);
    if (!targetSlide) {
      throw new Error("Cannot export presentation without any slides.");
    }
    const { slide: _explicitSlide, ...rest } = options;
    const exportOptions = {
      ...rest,
      format: rest.format ?? "png"
    };
    return targetSlide.export(exportOptions);
  }
  toProto() {
    return {
      id: this.#data.id,
      slides: this.slides.toProto(),
      layouts: this.layouts.toProto(),
      theme: this.theme.toProto(),
      charts: this.charts.toProto(),
      images: this.images.toProto(),
      contentReferences: this.citations.toProto(),
      tableStyles: this.#tableStyles,
      textStyles: [],
      people: this.comments.people.toProto(),
      threads: this.comments.threads.toProto()
    };
  }
  save(options) {}
  inspect(options) {
    return inspectPresentation(this, options);
  }
  help(query, options) {
    return getPresentationHelpProviderOrThrow().buildPresentationHelp(query, options);
  }
  script(scriptName, params2) {
    return runPresentationRecipeScript(this, scriptName, params2 ?? {});
  }
  template(name) {
    const entry = PRESENTATION_TEMPLATE_MAP.get(name);
    if (!entry) {
      throw new Error(`Unknown presentation template: ${name}`);
    }
    return clonePresentationPatch(entry.patch);
  }
  resolve(aid) {
    return resolvePresentation(this, aid);
  }
  apply(patch, options) {
    const result = applyPresentationPatch(this, patch);
    if (options?.target === "googleSlides") {
      const adapter = this.#googleSlides;
      if (!adapter) {
        throw new Error("Google Slides adapter is not configured.");
      }
      return adapter.applyPatch(patch, result);
    }
    return result;
  }
  record(fn) {
    if (this.#recorder) {
      throw new Error("Presentation.record does not support nested recordings.");
    }
    const recorder = new PresentationRecorder(this);
    const crdtUpdates = [];
    const onUpdateV2 = (update, origin) => {
      if (origin !== this.#recordOrigin && origin !== this.#localOrigin) {
        return;
      }
      crdtUpdates.push(new Uint8Array(update));
    };
    this.#yDoc.on("updateV2", onUpdateV2);
    this.#recorder = recorder;
    let result;
    try {
      if (!this.#collaborativeStateReady) {
        this.#prepareLocalRecordingState();
      }
      this.#yDoc.transact(() => {
        result = fn();
      }, this.#recordOrigin);
      this.queuePresentationCollabPublish();
      this.#flushPendingCollaborativePublishes();
      return {
        result,
        patch: recorder.getPatch(),
        idMap: recorder.getIdMap(),
        crdtUpdateV2: crdtUpdates.length > 0 ? mergeUpdatesV2(crdtUpdates) : undefined
      };
    } finally {
      this.#yDoc.off("updateV2", onUpdateV2);
      this.#undoManager.stopCapturing();
      this.#recorder = undefined;
    }
  }
  hydrateCrdtFromProto() {
    this.runLocalCollabTransaction(() => {
      this.#activatePresentationCollabRoot();
      this.#collaborativeStateReady = true;
      for (const slide of this.slides.items) {
        this.#getOrCreateSlideCollabState(slide.id);
      }
      for (const slide of this.slides.items) {
        slide.hydrateCollaborativeRefsFromProto();
      }
      this.#collabState.activate();
      this.#collabState.flushFromOwner();
    });
  }
  loadInitialCrdtStateV2(update) {
    this.#throwIfCrdtDocIsNotEmpty("loadInitialCrdtStateV2");
    this.applyCrdtUpdateV2(update);
  }
  getCrdtDoc() {
    return this.#yDoc;
  }
  isCollaborativeStateReady() {
    return this.#collaborativeStateReady;
  }
  __flushPendingCollaborativePublishes() {
    this.#flushPendingCollaborativePublishes();
  }
  getCollabOrigins() {
    return { record: this.#recordOrigin, local: this.#localOrigin };
  }
  queuePresentationCollabPublish() {
    if (!this.#collaborativeStateReady || this.#isApplyingCrdtUpdate) {
      return;
    }
    this.#presentationCollabDirty = true;
    this.#queueCollaborativePublishFlush();
  }
  runLocalCollabTransaction(fn) {
    let result;
    this.#yDoc.transact(() => {
      result = fn();
    }, this.#localOrigin);
    return result;
  }
  getSlideCollabState(slideId) {
    if (slideId.length === 0) {
      return;
    }
    const slidesById = readPresentationSlidesById(this.#presentationCollabRoot);
    if (!slidesById) {
      return;
    }
    const existing = slidesById.get(slideId);
    return existing instanceof YMap ? existing : undefined;
  }
  hydrateSlideCollaborativeState(slide) {
    if (!this.#collaborativeStateReady) {
      return;
    }
    this.runLocalCollabTransaction(() => {
      this.#activatePresentationCollabRoot();
      this.#getOrCreateSlideCollabState(slide.id);
      slide.hydrateCollaborativeRefsFromProto();
    });
  }
  removeSlideCollaborativeState(slideId) {
    if (!this.#collaborativeStateReady || slideId.length === 0) {
      return;
    }
    const slidesById = readPresentationSlidesById(this.#presentationCollabRoot);
    if (!slidesById || !slidesById.has(slideId)) {
      return;
    }
    this.runLocalCollabTransaction(() => {
      slidesById.delete(slideId);
    });
  }
  getRecorder() {
    return this.#recorder;
  }
  queueImageGenerationRequest(request) {
    this.#imageGenerationRequests.push({ ...request });
  }
  drainImageGenerationRequests() {
    const requests = this.#imageGenerationRequests.map((request) => ({
      ...request
    }));
    this.#imageGenerationRequests = [];
    return requests;
  }
  getPendingImageHydrationRequests() {
    return this.images.items.flatMap((image2) => {
      if (image2.data.byteLength > 0 || !image2.uri) {
        return [];
      }
      return [
        {
          assetId: image2.id,
          contentType: image2.contentType || undefined,
          uri: image2.uri
        }
      ];
    });
  }
  hydrateImageAssets(assets) {
    let hydratedAny = false;
    for (const asset of assets) {
      if (!asset.assetId || asset.data.byteLength === 0) {
        continue;
      }
      const image2 = this.images.getById(asset.assetId);
      if (!image2) {
        continue;
      }
      image2.data = asset.data;
      if (asset.contentType) {
        image2.contentType = asset.contentType;
      }
      hydratedAny = true;
    }
    return hydratedAny;
  }
  applyCrdtUpdateV2(update) {
    this.#collaborativeStateReady = true;
    this.#isApplyingCrdtUpdate = true;
    try {
      applyUpdateV2(this.#yDoc, update instanceof Uint8Array ? update : new Uint8Array(update));
    } finally {
      this.#isApplyingCrdtUpdate = false;
    }
  }
  onCrdtUpdateV2(handler) {
    const wrapped = (update, origin) => {
      handler(new Uint8Array(update), origin);
    };
    this.#yDoc.on("updateV2", wrapped);
    return () => {
      this.#yDoc.off("updateV2", wrapped);
    };
  }
  undo() {
    this.#undoManager.undo();
  }
  redo() {
    this.#undoManager.redo();
  }
  canUndo() {
    return this.#undoManager.canUndo();
  }
  canRedo() {
    return this.#undoManager.canRedo();
  }
  get googleSlides() {
    return this.#googleSlides;
  }
  async#renderSlidePreview(slide, options) {
    const format2 = options.format ?? "png";
    const { quality } = options;
    const scale = options.scale && Number.isFinite(options.scale) && options.scale > 0 ? options.scale : 1;
    const baseWidthPx = slide.frame.width ?? DEFAULT_SLIDE_DIMENSION_EMU;
    const baseHeightPx = slide.frame.height ?? DEFAULT_SLIDE_DIMENSION_EMU;
    const canvas = this.#createCanvas(baseWidthPx, baseHeightPx, scale);
    const ctx = canvas.getContext("2d");
    if (!ctx) {
      throw new Error("Unable to acquire a 2D canvas context for slide export.");
    }
    ctx.save();
    try {
      if (scale !== 1) {
        ctx.scale(scale, scale);
      }
      await drawSlideToCtx(slide, this, ctx);
    } finally {
      ctx.restore();
    }
    return this.#canvasToBlob(canvas, format2, quality);
  }
  #createCanvas(widthPx, heightPx, scale) {
    const targetWidth = Math.max(1, Math.round(widthPx * scale));
    const targetHeight = Math.max(1, Math.round(heightPx * scale));
    if (typeof OffscreenCanvas !== "undefined") {
      const canvas = new OffscreenCanvas(targetWidth, targetHeight);
      return canvas;
    }
    throw new Error("OffscreenCanvas API is not available for slide export.");
  }
  async#canvasToBlob(canvas, format2, quality) {
    const mime = format2 === "jpeg" ? "image/jpeg" : format2 === "webp" ? "image/webp" : "image/png";
    const normalizedQuality = typeof quality === "number" && quality >= 0 && quality <= 1 ? quality : undefined;
    if ("convertToBlob" in canvas && typeof canvas.convertToBlob === "function") {
      return canvas.convertToBlob({ type: mime, quality: normalizedQuality });
    }
    if ("toBlob" in canvas) {
      return new Promise((resolve2, reject) => {
        canvas.toBlob((blob) => {
          if (!blob) {
            reject(new Error("Canvas export produced an empty blob."));
            return;
          }
          resolve2(blob);
        }, mime, normalizedQuality);
      });
    }
    throw new Error("Canvas export is not supported in this environment.");
  }
  #seedDefaultLayouts() {
    if (this.layouts.items.length > 0) {
      return;
    }
    const master = this.masters.add("Master");
    this.#applyDefaultMasterLayout(master);
    const titleLayout = this.layouts.add("Title Slide", { type: "title" });
    titleLayout.setParentLayoutId(master.id);
    this.#applyDefaultTitleLayout(titleLayout);
    this.#defaultLayoutId = titleLayout.id;
    this.tableStyles = DEFAULT_TABLE_STYLES;
  }
  #getDefaultLayout() {
    if (!this.#defaultLayoutId) {
      return;
    }
    return this.layouts.getById(this.#defaultLayoutId);
  }
  #applyDefaultMasterLayout(master) {
    master.background.ref = { index: 1001, schemeColor: "bg1" };
    master.setColorMap(DEFAULT_MASTER_COLOR_MAP);
    master.bodyLevelStyles.push(...DEFAULT_MASTER_BODY_LEVEL_STYLES);
    master.titleLevelStyles.push(...DEFAULT_MASTER_TITLE_LEVEL_STYLES);
    master.otherLevelStyles.push(...DEFAULT_MASTER_OTHER_LEVEL_STYLES);
    DEFAULT_MASTER_PLACEHOLDERS.forEach((spec) => {
      const shape2 = master.shapes.add({ geometry: "rect" });
      shape2.name = spec.name;
      shape2.placeholderType = spec.placeholderType;
      shape2.placeholderIndex = spec.placeholderIndex;
      shape2.frame = {
        left: pixelsFromEmu(spec.frame.xEmu),
        top: pixelsFromEmu(spec.frame.yEmu),
        width: pixelsFromEmu(spec.frame.widthEmu),
        height: pixelsFromEmu(spec.frame.heightEmu)
      };
      if (spec.textStyle) {
        shape2.textStyle = new TextStyle2(spec.textStyle);
      }
      if (spec.levelsStyles?.length) {
        shape2.levelsStyles.push(...spec.levelsStyles);
      }
    });
  }
  #applyDefaultTitleLayout(layout) {
    DEFAULT_TITLE_LAYOUT_PLACEHOLDERS.forEach((spec) => {
      const shape2 = layout.shapes.addPlaceholder(spec.name);
      shape2.placeholderType = spec.placeholderType;
      shape2.placeholderIndex = spec.placeholderIndex;
      if (spec.frame) {
        shape2.frame = {
          left: pixelsFromEmu(spec.frame.xEmu),
          top: pixelsFromEmu(spec.frame.yEmu),
          width: pixelsFromEmu(spec.frame.widthEmu),
          height: pixelsFromEmu(spec.frame.heightEmu)
        };
      }
      if (spec.textStyle) {
        shape2.textStyle = new TextStyle2(spec.textStyle);
      }
      if (spec.levelsStyles?.length) {
        shape2.levelsStyles.push(...spec.levelsStyles);
      }
    });
  }
  #activatePresentationCollabRoot() {
    activatePresentationCollabRoot({
      root: this.#presentationCollabRoot,
      runLocalTransaction: (fn) => this.runLocalCollabTransaction(fn)
    });
  }
  #getOrCreateSlideCollabState(slideId) {
    if (slideId.length === 0) {
      throw new Error("Slide collaborative state requires a non-empty slideId.");
    }
    const slidesById = getOrCreatePresentationSlidesById({
      root: this.#presentationCollabRoot,
      runLocalTransaction: (fn) => this.runLocalCollabTransaction(fn)
    });
    const existing = slidesById.get(slideId);
    if (existing instanceof YMap) {
      return existing;
    }
    const created = new YMap;
    slidesById.set(slideId, created);
    return created;
  }
  #queueCollaborativePublishFlush() {
    if (this.#collabPublishQueued) {
      return;
    }
    this.#collabPublishQueued = true;
    queueMicrotask(() => {
      this.#flushPendingCollaborativePublishes();
    });
  }
  #flushPendingCollaborativePublishes() {
    this.#collabPublishQueued = false;
    if (!this.#presentationCollabDirty || this.#isApplyingCrdtUpdate) {
      return;
    }
    this.#presentationCollabDirty = false;
    this.runLocalCollabTransaction(() => {
      this.#activatePresentationCollabRoot();
      this.#collabState.activate();
      this.#collabState.flushFromOwner();
    });
  }
  #throwIfCrdtDocIsNotEmpty(methodName) {
    if (!this.#hasCollaborativeContent()) {
      return;
    }
    throw new Error(`${methodName} requires an empty collaborative document.`);
  }
  #hasCollaborativeContent() {
    return decodeUpdateV2(encodeStateAsUpdateV2(this.#yDoc)).structs.length > 0;
  }
  #prepareLocalRecordingState() {
    for (const slide of this.slides.items) {
      this.#getOrCreateSlideCollabState(slide.id);
    }
    for (const slide of this.slides.items) {
      slide.hydrateCollaborativeRefsFromProto();
    }
  }
  #themeContext() {
    return {
      stub: () => {},
      addTextStyle: (name) => this.styles.add(name).textStyle,
      resolveTextStyle: (name) => this.styles.resolveTextStyle(name),
      queueCollaborativePublish: () => this.queuePresentationCollabPublish()
    };
  }
  #layoutCollectionContext() {
    return {
      stub: () => {},
      ...this.#assetResolver,
      getTextStyleByName: (name) => this.styles.resolveTextStyle(name)
    };
  }
  #slideCollectionContext() {
    return {
      stub: () => {},
      ...this.#assetResolver,
      getPresentation: () => this,
      getLayoutByName: (name) => this.layouts.getItem(name),
      getLayoutById: (id2) => this.layouts.getById(id2),
      getDefaultLayout: () => this.#getDefaultLayout(),
      renderSlidePreview: (slide, options) => this.#renderSlidePreview(slide, options),
      getTextStyleByName: (name) => this.styles.resolveTextStyle(name)
    };
  }
  #chartCollectionContext() {
    return {
      stub: () => {}
    };
  }
  #imageCollectionContext() {
    return {
      stub: () => {}
    };
  }
  #citationsCollectionContext() {
    return {
      stub: () => {}
    };
  }
  #buildSlideCollectionOptions(slideSize) {
    if (!slideSize) {
      return {};
    }
    const widthEmu = emuFromPixels(slideSize.width);
    const heightEmu = emuFromPixels(slideSize.height);
    const options = {};
    if (widthEmu !== undefined) {
      options.defaultWidthEmu = widthEmu;
    }
    if (heightEmu !== undefined) {
      options.defaultHeightEmu = heightEmu;
    }
    return options;
  }
}
var AID_SUFFIX_LENGTH = 8;
var normalizePresentationProtoIds = (proto) => {
  if (proto.id) {
    proto.id = normalizeAidSuffix("pr", proto.id, AID_SUFFIX_LENGTH);
  }
  const slideIdMap = new Map;
  const usedSlideIds = new Set;
  (proto.slides ?? []).forEach((slide) => {
    if (!slide.id) {
      return;
    }
    const originalId = slide.id;
    let normalized = normalizeAidSuffix("sl", originalId, AID_SUFFIX_LENGTH);
    if (usedSlideIds.has(normalized)) {
      let collisionIndex = 1;
      let candidate = normalized;
      while (usedSlideIds.has(candidate)) {
        candidate = deriveDeterministicAidSuffix(`${originalId}#${collisionIndex}`, AID_SUFFIX_LENGTH);
        collisionIndex += 1;
      }
      normalized = candidate;
    }
    usedSlideIds.add(normalized);
    if (normalized !== slide.id) {
      if (!slideIdMap.has(slide.id)) {
        slideIdMap.set(slide.id, normalized);
      }
      slide.id = normalized;
    }
  });
  (proto.threads ?? []).forEach((thread) => {
    if (thread.id) {
      thread.id = normalizeAidSuffix("th", thread.id, AID_SUFFIX_LENGTH);
    }
    const target = thread.target;
    if (!target || slideIdMap.size === 0) {
      return;
    }
    if (target.slide?.slideId) {
      target.slide.slideId = slideIdMap.get(target.slide.slideId) ?? target.slide.slideId;
    }
    if (target.element?.slideId) {
      target.element.slideId = slideIdMap.get(target.element.slideId) ?? target.element.slideId;
    }
    if (target.textRange?.slideId) {
      target.textRange.slideId = slideIdMap.get(target.textRange.slideId) ?? target.textRange.slideId;
    }
  });
};
function resolvePresentationArgs(arg1, arg2) {
  let context = DEFAULT_PRESENTATION_CONTEXT;
  let options = {};
  if (isPresentationContext(arg1)) {
    context = arg1;
    options = arg2 ?? {};
  } else if (arg1) {
    options = arg1;
  } else if (arg2) {
    options = arg2;
  }
  return { context, options };
}
function isPresentationContext(value) {
  return typeof value === "object" && value !== null && "stub" in value && typeof value.stub === "function";
}
function clonePresentationPatch(patch) {
  if (typeof structuredClone === "function") {
    return structuredClone(patch);
  }
  return JSON.parse(JSON.stringify(patch));
}

// node_modules/@oai/granola/dist/draw-utils/draw-sheet-shapes.js
var pxToEmu2 = (px) => Math.round(px * 9525);
function drawSheetShapes(ctx, worksheet, colOffsets, rowOffsets, scrollX, scrollY, viewportW, viewportH, themeMap, layoutExpand, addShapeTarget, zoom, textLayoutCollector) {
  const shapes = worksheet.shapes.items;
  if (shapes.length === 0)
    return;
  const resolvedZoom = zoom ?? 1;
  const dummyPres = Presentation2.load({
    id: undefined,
    slides: [],
    theme: {
      colorScheme: { name: "", colors: [] },
      backgroundFillStyleList: [],
      lineStyleList: [],
      effectStyleList: []
    },
    layouts: [],
    charts: [],
    images: [],
    contentReferences: [],
    textStyles: [],
    people: [],
    threads: []
  });
  const dummySlide = dummyPres.slides.add();
  for (const [shapeIndex, shape2] of shapes.entries()) {
    const d = shape2.toDrawingProto({ preferPreview: true });
    if (!d.shape)
      continue;
    const logicalBounds = shape2.resolveBoundsPx({
      columnOffsets: colOffsets,
      rowOffsets
    }, { preferPreview: true });
    if (!logicalBounds)
      continue;
    const x0 = ROW_HEADER_W + logicalBounds.x - scrollX;
    const y0 = COL_HEADER_H + logicalBounds.y - scrollY;
    let w = logicalBounds.width;
    let h = logicalBounds.height;
    if (w <= 0 && h <= 0)
      continue;
    if (w <= 0 && h > 0)
      w = 1;
    if (h <= 0 && w > 0)
      h = 1;
    if (x0 + w < 0 || y0 + h < 0 || x0 > viewportW || y0 > viewportH)
      continue;
    layoutExpand?.(x0, y0, w, h, "shape");
    const shapeId = shape2.id || d.shape?.id || `shape-${shapeIndex}`;
    if (addShapeTarget) {
      addShapeTarget({
        id: shapeId,
        logicalBounds: { x: x0, y: y0, width: w, height: h },
        cssBounds: {
          x: x0 * resolvedZoom,
          y: y0 * resolvedZoom,
          width: w * resolvedZoom,
          height: h * resolvedZoom
        },
        drawing: d,
        usesTwoCellAnchor: Boolean(d.toAnchor)
      });
    }
    const el = { ...d.shape };
    const oldBbox = d.shape?.bbox ?? {};
    el.bbox = {
      ...oldBbox,
      xEmu: pxToEmu2(x0),
      yEmu: pxToEmu2(y0),
      widthEmu: pxToEmu2(w),
      heightEmu: pxToEmu2(h)
    };
    drawShape(el, ctx, dummyPres, dummySlide, themeMap);
    if (el.paragraphs && el.paragraphs.length > 0) {
      try {
        const solid = el.shape?.fill?.color ?? el.shape?.fill?.pattern?.color;
        const bgCss = themeMap ? resolveColor(solid, themeMap) : undefined;
        if (bgCss && (!el.textStyle || !el.textStyle.fill)) {
          const rgb2 = rgbaToRgb(bgCss);
          if (rgb2) {
            const r = rgb2[0] / 255;
            const g = rgb2[1] / 255;
            const b = rgb2[2] / 255;
            const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;
            if (lum < 0.45) {
              el.textStyle = el.textStyle ?? {};
              el.textStyle.fill = {
                color: {
                  type: 1 /* COLOR_TYPE_RGB */,
                  value: "FFFFFFFF",
                  transform: undefined
                },
                type: 1 /* FILL_TYPE_SOLID */,
                gradientStops: []
              };
              if (!el.textStyle.anchor && (el.paragraphs?.length ?? 0) >= 1) {
                el.textStyle.anchor = 3;
              }
            }
          }
        }
        if (el.fontReference?.color && (!el.textStyle || !el.textStyle.fill)) {
          el.textStyle = el.textStyle ?? {};
          el.textStyle.fill = {
            type: 1 /* FILL_TYPE_SOLID */,
            color: el.fontReference.color,
            gradientStops: []
          };
        }
      } catch {}
      const resolved = resolveStyles(el, dummyPres, dummySlide);
      let paddingPx;
      ctx.save();
      const centerX = x0 + w / 2;
      const centerY = y0 + h / 2;
      const rotationRad = emuRotationToRadians(el.bbox?.rotation ?? 0);
      const scaleX = el.bbox?.horizontalFlip ? -1 : 1;
      const scaleY = el.bbox?.verticalFlip ? -1 : 1;
      ctx.translate(centerX, centerY);
      if (rotationRad !== 0) {
        ctx.rotate(rotationRad);
      }
      if (scaleX !== 1 || scaleY !== 1) {
        ctx.scale(scaleX, scaleY);
      }
      ctx.translate(-centerX, -centerY);
      const layout = drawText(el, ctx, themeMap, undefined, {
        bboxPx: { x: x0, y: y0, width: w, height: h },
        resolvedStyle: resolved,
        paddingPx
      });
      ctx.restore();
      if (layout && textLayoutCollector) {
        textLayoutCollector.add({
          id: shapeId,
          layout,
          rotationDeg: emuRotationToDegrees(el.bbox?.rotation ?? 0) ?? 0,
          zIndex: shapeIndex,
          hitBox: { x: x0, y: y0, width: w, height: h },
          getRunText: (paraIndex, runIndex) => {
            const paragraph = (el.paragraphs ?? [])[paraIndex];
            const run = paragraph?.runs?.[runIndex];
            return run?.text ?? run?.run ?? "";
          }
        });
      }
    }
  }
}

// node_modules/@oai/granola/dist/models/pivot-layout.js
init_address_utils();

class PivotLayout {
  #pivotTable;
  constructor(pivotTable) {
    this.#pivotTable = pivotTable;
  }
  get layoutType() {
    return this.#pivotTable.__getLayoutType();
  }
  set layoutType(value) {
    this.#pivotTable.__setLayoutType(value);
  }
  get fillEmptyCells() {
    return this.#pivotTable.__getLayoutMeta().fillEmptyCells;
  }
  set fillEmptyCells(value) {
    this.#pivotTable.__setLayoutMeta({ fillEmptyCells: value });
  }
  get preserveFormatting() {
    return this.#pivotTable.__getLayoutMeta().preserveFormatting;
  }
  set preserveFormatting(value) {
    this.#pivotTable.__setLayoutMeta({ preserveFormatting: value });
  }
  get emptyCellText() {
    return this.#pivotTable.__getLayoutMeta().emptyCellText;
  }
  set emptyCellText(value) {
    this.#pivotTable.__setLayoutMeta({ emptyCellText: value });
  }
  getDataBodyRange() {
    const location2 = this.#pivotTable.__getLocationForLayout();
    if (!location2.reference) {
      throw new Error("PivotTable location reference is not set");
    }
    const parsed = parseRangeAddress(location2.reference);
    if (!parsed) {
      throw new Error(`Invalid pivot location reference: ${location2.reference}`);
    }
    const shape2 = this.#pivotTable.__getDataBodyShapeForLayout();
    const dataRowCount = shape2.dataRowCount;
    const dataColCount = shape2.dataColCount;
    const startRow = parsed.bounds.startRow + Math.max(0, location2.firstDataRow);
    const startCol = parsed.bounds.startCol + Math.max(0, location2.firstDataColumn);
    const endRow = dataRowCount > 0 ? startRow + dataRowCount - 1 : startRow;
    const endCol = dataColCount > 0 ? startCol + dataColCount - 1 : startCol;
    const bounds = {
      startRow,
      startCol,
      endRow,
      endCol
    };
    const ref = buildRangeRef(bounds);
    return this.#pivotTable.worksheet.getRange(ref);
  }
  load(properties) {
    return this;
  }
  getCellStyleType(address) {
    const parsed = parseRangeAddress(address);
    if (!parsed)
      return null;
    const { startRow, startCol, endRow, endCol } = parsed.bounds;
    if (startRow !== endRow || startCol !== endCol) {
      return null;
    }
    return this.#pivotTable.__getPivotCellRenderHint(startRow, startCol)?.type ?? null;
  }
  getCellIndentLevel(address) {
    const parsed = parseRangeAddress(address);
    if (!parsed)
      return 0;
    const { startRow, startCol, endRow, endCol } = parsed.bounds;
    if (startRow !== endRow || startCol !== endCol) {
      return 0;
    }
    return this.#pivotTable.__getPivotCellRenderHint(startRow, startCol)?.indentLevel ?? 0;
  }
}

// node_modules/@oai/granola/dist/models/pivot-engine.js
init_address_utils();

// node_modules/@oai/granola/dist/models/show-as.js
function normalizeShowAsKey(value) {
  return value.trim().replace(/[^a-z0-9]/gi, "").toLowerCase();
}
var SHOW_AS_CALC_BY_KEY = {
  [normalizeShowAsKey(ShowAsCalculation.none)]: ShowAsCalculation.none,
  [normalizeShowAsKey(ShowAsCalculation.percentOfColumnTotal)]: ShowAsCalculation.percentOfColumnTotal,
  [normalizeShowAsKey(ShowAsCalculation.percentOfRowTotal)]: ShowAsCalculation.percentOfRowTotal,
  [normalizeShowAsKey(ShowAsCalculation.percentOfGrandTotal)]: ShowAsCalculation.percentOfGrandTotal,
  [normalizeShowAsKey(ShowAsCalculation.differenceFrom)]: ShowAsCalculation.differenceFrom,
  [normalizeShowAsKey(ShowAsCalculation.percentDifferenceFrom)]: ShowAsCalculation.percentDifferenceFrom,
  [normalizeShowAsKey("normal")]: ShowAsCalculation.none,
  [normalizeShowAsKey("percentOfCol")]: ShowAsCalculation.percentOfColumnTotal,
  [normalizeShowAsKey("percentOfRow")]: ShowAsCalculation.percentOfRowTotal,
  [normalizeShowAsKey("percentOfTotal")]: ShowAsCalculation.percentOfGrandTotal,
  [normalizeShowAsKey("difference")]: ShowAsCalculation.differenceFrom,
  [normalizeShowAsKey("percentDiff")]: ShowAsCalculation.percentDifferenceFrom
};
function parseShowAsCalculation(value) {
  if (value == null)
    return ShowAsCalculation.none;
  const key = normalizeShowAsKey(value);
  return SHOW_AS_CALC_BY_KEY[key] ?? ShowAsCalculation.none;
}
function compileShowAsCalculation(value) {
  switch (value) {
    case ShowAsCalculation.none:
      return;
    case ShowAsCalculation.percentOfColumnTotal:
      return "percentOfCol";
    case ShowAsCalculation.percentOfRowTotal:
      return "percentOfRow";
    case ShowAsCalculation.percentOfGrandTotal:
      return "percentOfTotal";
    case ShowAsCalculation.differenceFrom:
      return "difference";
    case ShowAsCalculation.percentDifferenceFrom:
      return "percentDiff";
    default:
      return;
  }
}

class ShowAs {
  #calculation;
  #baseField;
  #baseItem;
  constructor(options = {}) {
    this.#calculation = options.calculation ?? ShowAsCalculation.none;
    this.#baseField = options.baseField;
    this.#baseItem = options.baseItem;
  }
  get calculation() {
    return this.#calculation;
  }
  set calculation(value) {
    this.#calculation = value;
  }
  get baseField() {
    return this.#baseField;
  }
  set baseField(value) {
    this.#baseField = value;
  }
  get baseItem() {
    return this.#baseItem;
  }
  set baseItem(value) {
    this.#baseItem = value;
  }
  clone() {
    return new ShowAs({
      calculation: this.#calculation,
      baseField: this.#baseField,
      baseItem: this.#baseItem
    });
  }
}

// node_modules/@oai/granola/dist/models/pivot-item.js
var PIVOT_ITEM_PROTO = new WeakMap;

class PivotItem {
  constructor(pivotFieldItem) {
    const extended = pivotFieldItem;
    PIVOT_ITEM_PROTO.set(this, extended);
  }
  get name() {
    const proto = this.#proto();
    if (proto.displayName && proto.displayName.length > 0) {
      return proto.displayName;
    }
    if (proto.index != null) {
      return String(proto.index);
    }
    if (proto.type != null) {
      return String(proto.type);
    }
    return "";
  }
  #proto() {
    const proto = PIVOT_ITEM_PROTO.get(this);
    if (!proto) {
      throw new Error("PivotItem proto not found");
    }
    return proto;
  }
}
function getPivotItemProto(item) {
  const proto = PIVOT_ITEM_PROTO.get(item);
  if (!proto) {
    throw new Error("PivotItem proto not found");
  }
  return proto;
}

// node_modules/@oai/granola/dist/models/pivot-data-hierarchy.js
var PIVOT_DATA_FIELD_PROTO = new WeakMap;
var AGGREGATION_TO_PROTO = {
  [AggregationFunction.automatic]: 1 /* DATA_CONSOLIDATE_FUNCTION_SUM */,
  [AggregationFunction.sum]: 1 /* DATA_CONSOLIDATE_FUNCTION_SUM */,
  [AggregationFunction.count]: 3 /* DATA_CONSOLIDATE_FUNCTION_COUNT */,
  [AggregationFunction.average]: 2 /* DATA_CONSOLIDATE_FUNCTION_AVERAGE */,
  [AggregationFunction.max]: 5 /* DATA_CONSOLIDATE_FUNCTION_MAXIMUM */,
  [AggregationFunction.min]: 6 /* DATA_CONSOLIDATE_FUNCTION_MINIMUM */,
  [AggregationFunction.product]: 7 /* DATA_CONSOLIDATE_FUNCTION_PRODUCT */,
  [AggregationFunction.countNumbers]: 4 /* DATA_CONSOLIDATE_FUNCTION_COUNT_NUMBERS */,
  [AggregationFunction.standardDeviation]: 8 /* DATA_CONSOLIDATE_FUNCTION_STD_DEV */,
  [AggregationFunction.standardDeviationP]: 9 /* DATA_CONSOLIDATE_FUNCTION_STD_DEVP */,
  [AggregationFunction.variance]: 10 /* DATA_CONSOLIDATE_FUNCTION_VARIANCE */,
  [AggregationFunction.varianceP]: 11 /* DATA_CONSOLIDATE_FUNCTION_VARIANCEP */
};
function protoToAggregation(value) {
  for (const [aggregation, proto] of Object.entries(AGGREGATION_TO_PROTO)) {
    if (proto === value)
      return aggregation;
  }
  return AggregationFunction.sum;
}
var DATA_CONSOLIDATE_TO_SUBTOTAL = {
  [1 /* DATA_CONSOLIDATE_FUNCTION_SUM */]: "sum",
  [3 /* DATA_CONSOLIDATE_FUNCTION_COUNT */]: "count",
  [2 /* DATA_CONSOLIDATE_FUNCTION_AVERAGE */]: "average",
  [5 /* DATA_CONSOLIDATE_FUNCTION_MAXIMUM */]: "max",
  [6 /* DATA_CONSOLIDATE_FUNCTION_MINIMUM */]: "min",
  [7 /* DATA_CONSOLIDATE_FUNCTION_PRODUCT */]: "product",
  [4 /* DATA_CONSOLIDATE_FUNCTION_COUNT_NUMBERS */]: "countNums",
  [8 /* DATA_CONSOLIDATE_FUNCTION_STD_DEV */]: "stdDev",
  [9 /* DATA_CONSOLIDATE_FUNCTION_STD_DEVP */]: "stdDevp",
  [10 /* DATA_CONSOLIDATE_FUNCTION_VARIANCE */]: "var",
  [11 /* DATA_CONSOLIDATE_FUNCTION_VARIANCEP */]: "varp"
};
var SUBTOTAL_ALIASES = [
  ["sum", 1 /* DATA_CONSOLIDATE_FUNCTION_SUM */],
  ["average", 2 /* DATA_CONSOLIDATE_FUNCTION_AVERAGE */],
  ["avg", 2 /* DATA_CONSOLIDATE_FUNCTION_AVERAGE */],
  ["count", 3 /* DATA_CONSOLIDATE_FUNCTION_COUNT */],
  [
    "countnums",
    4 /* DATA_CONSOLIDATE_FUNCTION_COUNT_NUMBERS */
  ],
  [
    "countnumbers",
    4 /* DATA_CONSOLIDATE_FUNCTION_COUNT_NUMBERS */
  ],
  ["max", 5 /* DATA_CONSOLIDATE_FUNCTION_MAXIMUM */],
  ["maximum", 5 /* DATA_CONSOLIDATE_FUNCTION_MAXIMUM */],
  ["min", 6 /* DATA_CONSOLIDATE_FUNCTION_MINIMUM */],
  ["minimum", 6 /* DATA_CONSOLIDATE_FUNCTION_MINIMUM */],
  ["product", 7 /* DATA_CONSOLIDATE_FUNCTION_PRODUCT */],
  ["stddev", 8 /* DATA_CONSOLIDATE_FUNCTION_STD_DEV */],
  ["stddevp", 9 /* DATA_CONSOLIDATE_FUNCTION_STD_DEVP */],
  ["var", 10 /* DATA_CONSOLIDATE_FUNCTION_VARIANCE */],
  ["variance", 10 /* DATA_CONSOLIDATE_FUNCTION_VARIANCE */],
  ["varp", 11 /* DATA_CONSOLIDATE_FUNCTION_VARIANCEP */],
  ["variancep", 11 /* DATA_CONSOLIDATE_FUNCTION_VARIANCEP */]
];
var SUBTOTAL_STRING_TO_DATA_CONSOLIDATE = SUBTOTAL_ALIASES.reduce((map4, [alias, value]) => {
  map4[normalizeSubtotalKey(alias)] = value;
  return map4;
}, {});
function normalizeSubtotalKey(value) {
  return value.replace(/\s+/g, "").toLowerCase();
}
function normalizeSubtotalAlias(value) {
  if (!value) {
    return;
  }
  const trimmed = value.trim();
  if (trimmed.length === 0) {
    return;
  }
  return normalizeSubtotalKey(trimmed);
}
function isPercentShowAsCalculation(value) {
  return value === ShowAsCalculation.percentOfColumnTotal || value === ShowAsCalculation.percentOfRowTotal || value === ShowAsCalculation.percentOfGrandTotal || value === ShowAsCalculation.percentDifferenceFrom;
}

class PivotDataHierarchy {
  #pivotDataField;
  #pivotTable;
  #showAs;
  constructor(pivotDataField, options) {
    this.#pivotDataField = pivotDataField;
    this.#pivotTable = options.pivotTable;
    PIVOT_DATA_FIELD_PROTO.set(this, pivotDataField);
  }
  get name() {
    const name = this.#pivotDataField.name;
    if (name && name.length > 0)
      return name;
    const field = this.#sourceField();
    return field ? `Sum of ${field.name}` : "Values";
  }
  set name(value) {
    this.#pivotDataField.name = value;
  }
  get numberFormatId() {
    return this.#pivotDataField.numberFormatId ?? undefined;
  }
  set numberFormatId(value) {
    this.#pivotDataField.numberFormatId = value;
  }
  get summarizeBy() {
    return protoToAggregation(getPivotDataFieldSubtotal(this.#pivotDataField));
  }
  set summarizeBy(value) {
    const protoValue = AGGREGATION_TO_PROTO[value] ?? AGGREGATION_TO_PROTO[AggregationFunction.sum];
    setPivotDataFieldSubtotal(this.#pivotDataField, protoValue);
    recomputePivotTable(this.#pivotTable);
  }
  get showAs() {
    if (this.#showAs) {
      return this.#showAs.clone();
    }
    const proto = this.#pivotDataField;
    const calculation = parseShowAsCalculation(proto.showAs);
    const baseField = proto.baseField != null ? this.#getFieldByIndex(proto.baseField) : undefined;
    const baseItem = baseField && proto.baseItem != null ? this.#getItemByIndex(baseField, proto.baseItem) : undefined;
    const showAs = new ShowAs({
      calculation,
      baseField,
      baseItem
    });
    this.#showAs = showAs.clone();
    return showAs;
  }
  set showAs(value) {
    this.#showAs = value;
    const proto = this.#pivotDataField;
    proto.showAs = compileShowAsCalculation(value.calculation);
    const sourceFieldNumberFormatId = this.#sourceField()?.numberFormatId;
    if (isPercentShowAsCalculation(value.calculation) && (proto.numberFormatId == null || proto.numberFormatId === sourceFieldNumberFormatId)) {
      proto.numberFormatId = 10;
    }
    const baseField = value.baseField;
    if (baseField) {
      const fieldIndex = this.#ensureFieldIndex(baseField);
      proto.baseField = fieldIndex;
    } else {
      proto.baseField = undefined;
    }
    const baseItem = value.baseItem;
    if (baseItem) {
      const itemProto = getPivotItemProto(baseItem);
      proto.baseItem = itemProto.index ?? undefined;
    } else {
      proto.baseItem = undefined;
    }
    recomputePivotTable(this.#pivotTable);
  }
  #sourceField() {
    const fieldIndex = this.#pivotDataField.field;
    if (fieldIndex == null)
      return;
    const hierarchy2 = this.#pivotTable._getHierarchyByFieldIndex(fieldIndex);
    const fields = hierarchy2?.fields.items ?? [];
    return fields[0];
  }
  #getFieldByIndex(index) {
    const hierarchy2 = this.#pivotTable._getHierarchyByFieldIndex(index);
    const fields = hierarchy2?.fields.items ?? [];
    return fields[0];
  }
  #getItemByIndex(field, index) {
    const collection = field.items;
    const items = collection.items;
    return items.find((item) => (getPivotItemProto(item).index ?? -1) === index);
  }
  #ensureFieldIndex(field) {
    return field.__ensureIndex(this.#pivotTable.__getPivotFieldProtos());
  }
}
function getPivotDataFieldSubtotal(proto) {
  if (proto.subtotalEnum !== undefined) {
    return proto.subtotalEnum;
  }
  const rawSubtotal = proto.subtotal;
  if (typeof rawSubtotal === "number") {
    return setSubtotalFromEnum(proto, rawSubtotal);
  }
  if (typeof rawSubtotal === "string") {
    const numeric = Number(rawSubtotal);
    if (Number.isFinite(numeric)) {
      const updated = setSubtotalFromEnum(proto, numeric);
      if (updated !== undefined) {
        return updated;
      }
    }
    const normalized = normalizeSubtotalAlias(rawSubtotal);
    if (normalized) {
      const mapped = SUBTOTAL_STRING_TO_DATA_CONSOLIDATE[normalized];
      if (mapped !== undefined) {
        setPivotDataFieldSubtotal(proto, mapped);
        return mapped;
      }
    }
  }
  return;
}
function setPivotDataFieldSubtotal(proto, value) {
  proto.subtotalEnum = value;
  const serialized = DATA_CONSOLIDATE_TO_SUBTOTAL[value];
  proto.subtotal = serialized ?? undefined;
}
function setSubtotalFromEnum(proto, value) {
  const consolidateValue = value;
  const serialized = DATA_CONSOLIDATE_TO_SUBTOTAL[consolidateValue];
  if (serialized === undefined) {
    return;
  }
  proto.subtotalEnum = consolidateValue;
  proto.subtotal = serialized;
  return consolidateValue;
}

// node_modules/@oai/granola/dist/models/pivot-engine.js
function recomputePivotTable(pivot) {
  pivot.__clearPivotCellRenderHints();
  const context = buildContext(pivot);
  if (context.dataFields.length === 0) {
    return;
  }
  const aggregates = aggregatePivotData(context);
  writePivotOutput(context, aggregates);
}
function buildContext(pivot) {
  const pivotProto = getPivotTableProto(pivot);
  const cacheProto = getPivotCacheProto(pivot);
  const pivotFields = Array.isArray(pivotProto.pivotFields) ? pivotProto.pivotFields : [];
  const rowFieldIndices = Array.isArray(pivotProto.rowFields) ? pivotProto.rowFields : [];
  const columnFieldIndices = Array.isArray(pivotProto.columnFields) ? pivotProto.columnFields : [];
  const dataFieldProtos = Array.isArray(pivotProto.dataFields) ? pivotProto.dataFields : [];
  const fieldBindings = pivotFields.map((fieldProto, idx) => {
    const headerIndex = fieldProto.index ?? idx;
    const cacheField = cacheProto.fields?.[headerIndex];
    const name = fieldProto.name ?? cacheField?.name ?? `Field ${idx + 1}`;
    return {
      pivotIndex: idx,
      headerIndex,
      name
    };
  });
  const fieldBindingByPivotIndex = new Map;
  fieldBindings.forEach((binding) => {
    fieldBindingByPivotIndex.set(binding.pivotIndex, binding);
  });
  const rowFields = rowFieldIndices.map((pivotIdx) => fieldBindingByPivotIndex.get(pivotIdx)).filter((binding) => binding != null);
  const columnFields = columnFieldIndices.map((pivotIdx) => fieldBindingByPivotIndex.get(pivotIdx)).filter((binding) => binding != null);
  const dataFields = dataFieldProtos.map((proto) => {
    const binding = fieldBindingByPivotIndex.get(proto.field ?? -1);
    if (!binding)
      return null;
    return {
      pivotIndex: binding.pivotIndex,
      headerIndex: binding.headerIndex,
      name: proto.name ?? binding.name,
      proto
    };
  }).filter((binding) => binding != null);
  const rowGrandTotals = pivotProto.rowGrandTotals !== false;
  const columnGrandTotals = pivotProto.columnGrandTotals !== false;
  let reference = pivotProto.location?.reference;
  if (!reference || reference.length === 0) {
    reference = pivotProto.location?.reference ?? "A1";
  }
  const parsedReference = parseRangeAddress(reference);
  if (!parsedReference) {
    throw new Error(`Invalid pivot location reference: ${reference}`);
  }
  const startRow = parsedReference.bounds.startRow;
  const startCol = parsedReference.bounds.startCol;
  const filters = Array.isArray(pivotProto.filters) ? pivotProto.filters : [];
  const headerRowsBase = columnFields.length > 0 ? columnFields.length : 1;
  const computedHeaderRows = headerRowsBase + (dataFields.length > 1 && columnFields.length > 0 ? 1 : 0);
  const isCompactLayout = pivotProto.outline !== true && pivotProto.compact !== false;
  const computedHeaderCols = rowFields.length > 0 ? isCompactLayout ? 1 : rowFields.length : 1;
  const location2 = pivotProto.location;
  const headerRows = typeof location2?.firstDataRow === "number" && location2.firstDataRow > 0 ? Math.max(0, location2.firstDataRow) : computedHeaderRows;
  const headerCols = typeof location2?.firstDataColumn === "number" && location2.firstDataColumn > 0 ? Math.max(0, location2.firstDataColumn) : computedHeaderCols;
  return {
    pivot,
    pivotProto,
    cacheProto,
    pivotFields,
    rowFields,
    columnFields,
    dataFields,
    rowGrandTotals,
    columnGrandTotals,
    startRow,
    startCol,
    headerRows,
    headerCols,
    filters
  };
}
function aggregatePivotData(context) {
  const { pivot, rowFields, columnFields, dataFields, rowGrandTotals, columnGrandTotals, headerRows, headerCols, filters } = context;
  const source = getPivotSource(pivot);
  const rowEntriesMap = new Map;
  const columnEntriesMap = new Map;
  const rowEntries = [];
  const columnEntries = [];
  const createStatsArray = () => dataFields.map(() => createEmptyStats());
  const ensureRowEntry = (values) => {
    const key = keyFromValues(values);
    let entry = rowEntriesMap.get(key);
    if (!entry) {
      entry = {
        key,
        values,
        columns: new Map,
        totals: createStatsArray()
      };
      rowEntriesMap.set(key, entry);
      rowEntries.push(entry);
    }
    return entry;
  };
  const ensureColumnEntry = (values) => {
    const key = keyFromValues(values);
    let entry = columnEntriesMap.get(key);
    if (!entry) {
      entry = {
        key,
        values,
        totals: createStatsArray()
      };
      columnEntriesMap.set(key, entry);
      columnEntries.push(entry);
    }
    return entry;
  };
  const ensureCellStats = (rowEntry, columnEntry) => {
    const existing = rowEntry.columns.get(columnEntry.key);
    if (existing)
      return existing;
    const stats = createStatsArray();
    rowEntry.columns.set(columnEntry.key, stats);
    return stats;
  };
  const grandTotals = createStatsArray();
  const pivotFieldBindings = new Map;
  context.pivotFields.forEach((fieldProto, idx) => {
    const headerIndex = fieldProto.index ?? idx;
    const cacheField = context.cacheProto.fields?.[headerIndex];
    const name = fieldProto.name ?? cacheField?.name ?? `Field ${idx + 1}`;
    pivotFieldBindings.set(idx, {
      pivotIndex: idx,
      headerIndex,
      name
    });
  });
  const filterDescriptors = filters.map((filter) => parseFilterDescriptor(filter));
  const valueFilterRules = buildValueFilterRules(filters, filterDescriptors, rowFields, columnFields, dataFields);
  const relevantPivotFieldIndices = new Set([
    ...rowFields.map((binding) => binding.pivotIndex),
    ...columnFields.map((binding) => binding.pivotIndex),
    ...(context.pivotProto.pageFields ?? []).map((field) => field?.field).filter((idx) => typeof idx === "number")
  ]);
  const itemVisibilityByPivotIndex = buildPivotFieldItemVisibility(context, pivotFieldBindings);
  for (const row2 of source.rows) {
    const fieldValues = new Map;
    pivotFieldBindings.forEach((binding, pivotIdx) => {
      fieldValues.set(pivotIdx, row2[binding.headerIndex] ?? null);
    });
    if (!passesFilters(filterDescriptors, filters, fieldValues)) {
      continue;
    }
    if (!passesItemVisibility(itemVisibilityByPivotIndex, relevantPivotFieldIndices, fieldValues)) {
      continue;
    }
    const fullRowValues = rowFields.length ? rowFields.map((binding) => row2[binding.headerIndex] ?? null) : ["Grand Total"];
    const columnValues = columnFields.length ? columnFields.map((binding) => row2[binding.headerIndex] ?? null) : ["Values"];
    const columnEntry = ensureColumnEntry(columnValues);
    const rollupEntries = [];
    if (rowFields.length > 0) {
      for (let depth = 1;depth <= fullRowValues.length; depth++) {
        rollupEntries.push(ensureRowEntry(fullRowValues.slice(0, depth)));
      }
    } else {
      rollupEntries.push(ensureRowEntry(fullRowValues));
    }
    dataFields.forEach((dataField, index) => {
      const raw = row2[dataField.headerIndex];
      const cellValue = raw === undefined ? null : raw;
      const columnTotalsEntry = getStats(columnEntry.totals, index);
      updateStats(columnTotalsEntry, cellValue);
      const grandTotalsEntry = getStats(grandTotals, index);
      updateStats(grandTotalsEntry, cellValue);
      for (const rowEntry of rollupEntries) {
        const cellStats = ensureCellStats(rowEntry, columnEntry);
        const cellStatsEntry = getStats(cellStats, index);
        updateStats(cellStatsEntry, cellValue);
        const rowTotalsEntry = getStats(rowEntry.totals, index);
        updateStats(rowTotalsEntry, cellValue);
      }
    });
  }
  if (rowFields.length > 0) {
    const root = { children: new Map };
    const getOrCreateChild = (node, label) => {
      const existing = node.children.get(label);
      if (existing)
        return existing;
      const created = { children: new Map };
      node.children.set(label, created);
      return created;
    };
    for (const entry of rowEntries) {
      if (!Array.isArray(entry.values) || entry.values.length === 0)
        continue;
      let node = root;
      for (const value of entry.values) {
        node = getOrCreateChild(node, formatLabel(value));
      }
      node.entry = entry;
    }
    const ordered = [];
    const walk = (node, depth) => {
      const fieldBinding = rowFields[depth];
      const order = fieldBinding != null ? itemVisibilityByPivotIndex.get(fieldBinding.pivotIndex)?.order : undefined;
      const children = Array.from(node.children.entries()).map(([label, child], idx) => ({
        label,
        child,
        idx,
        orderIndex: order && order.has(label) ? order.get(label) ?? idx : undefined
      }));
      if (order) {
        children.sort((a, b) => {
          const aKey = a.orderIndex === undefined ? Number.POSITIVE_INFINITY : a.orderIndex;
          const bKey = b.orderIndex === undefined ? Number.POSITIVE_INFINITY : b.orderIndex;
          if (aKey !== bKey)
            return aKey - bKey;
          const labelCompare = a.label.localeCompare(b.label);
          if (labelCompare !== 0)
            return labelCompare;
          return a.idx - b.idx;
        });
      } else {
        children.sort((a, b) => {
          const labelCompare = a.label.localeCompare(b.label);
          if (labelCompare !== 0)
            return labelCompare;
          return a.idx - b.idx;
        });
      }
      for (const { child } of children) {
        if (child.entry)
          ordered.push(child.entry);
        walk(child, depth + 1);
      }
    };
    walk(root, 0);
    rowEntries.length = 0;
    rowEntries.push(...ordered);
  }
  if (valueFilterRules.length > 0) {
    applyValueFilterRules(rowEntries, valueFilterRules, dataFields, "row");
    applyValueFilterRules(columnEntries, valueFilterRules, dataFields, "column");
  }
  const columnSegments = [];
  columnEntries.forEach((columnEntry) => {
    dataFields.forEach((_, index) => {
      columnSegments.push({
        columnEntry,
        dataFieldIndex: index,
        isGrandTotal: false
      });
    });
  });
  if (columnGrandTotals && columnFields.length > 0 && columnSegments.length > 0) {
    dataFields.forEach((_, index) => {
      columnSegments.push({
        columnEntry: undefined,
        dataFieldIndex: index,
        isGrandTotal: true
      });
    });
  }
  const bodyRowCount = rowEntries.length + (rowGrandTotals && rowEntries.length > 0 ? 1 : 0);
  const bodyColCount = columnSegments.length;
  const totalRows = headerRows + bodyRowCount;
  const totalCols = headerCols + bodyColCount;
  const matrix = Array.from({ length: totalRows }, () => Array.from({ length: totalCols }, () => null));
  fillHeaders(matrix, headerRows, headerCols, rowFields, columnFields, columnSegments, dataFields);
  fillBody(matrix, headerRows, headerCols, rowEntries, columnSegments, dataFields, rowFields, columnFields, context.pivotFields, context.cacheProto, rowGrandTotals, grandTotals);
  pivot.__setRowItems(buildRowItems(rowEntries, rowGrandTotals));
  pivot.__setColumnItems(buildColumnItems(columnSegments));
  return {
    rows: rowEntries,
    columns: columnEntries,
    columnSegments,
    grandTotals,
    headerRows,
    headerCols,
    matrix
  };
}
function writePivotOutput(context, aggregates) {
  const { pivot, startRow, startCol } = context;
  const { matrix, headerRows, headerCols } = aggregates;
  const totalRows = matrix.length;
  const totalCols = matrix[0]?.length ?? 0;
  if (totalRows === 0 || totalCols === 0)
    return;
  const bounds = {
    startRow,
    startCol,
    endRow: startRow + totalRows - 1,
    endCol: startCol + totalCols - 1
  };
  const fullRef = buildRangeRef(bounds);
  pivot.__updateLocation({
    reference: fullRef,
    firstHeaderRow: Math.max(0, headerRows - 1),
    firstDataRow: headerRows,
    firstHeaderColumn: Math.max(0, headerCols - 1),
    firstDataColumn: headerCols
  });
  const worksheet = pivot.worksheet;
  const range2 = worksheet.getRange(fullRef);
  range2.values = matrix;
  populatePivotCellRenderHints(context, aggregates, bounds);
  renderPageFieldFilters(context, bounds);
  applyDataColumnNumberFormats(context, aggregates, bounds);
  const boundsSize = boundsDimensions(bounds);
  for (let i = 0;i < boundsSize.rows; i++) {
    worksheet.__getOrCreateRow(bounds.startRow + i);
  }
}
function populatePivotCellRenderHints(context, aggregates, bounds) {
  const pivot = context.pivot;
  const headerRowEnd = bounds.startRow + aggregates.headerRows - 1;
  const labelColumnEnd = bounds.startCol + Math.max(0, aggregates.headerCols - 1);
  for (let row2 = bounds.startRow;row2 <= headerRowEnd; row2++) {
    for (let col = bounds.startCol;col <= bounds.endCol; col++) {
      pivot.__setPivotCellRenderHint(row2, col, {
        type: "headerRow",
        indentLevel: 0
      });
    }
  }
  const dataStartRow = bounds.startRow + aggregates.headerRows;
  for (let rowOffset = 0;rowOffset < aggregates.rows.length; rowOffset++) {
    const row2 = dataStartRow + rowOffset;
    const rowEntry = aggregates.rows[rowOffset];
    const depth = rowEntry?.values.length ?? 1;
    const rowType = resolveBodyRowStyleType(depth);
    const indentLevel = Math.max(0, depth - 1);
    for (let col = bounds.startCol;col <= bounds.endCol; col++) {
      const isLabelColumn = col <= labelColumnEnd;
      pivot.__setPivotCellRenderHint(row2, col, {
        type: rowType,
        indentLevel: isLabelColumn ? indentLevel : 0
      });
    }
  }
  if (context.rowGrandTotals && aggregates.rows.length > 0) {
    const row2 = dataStartRow + aggregates.rows.length;
    for (let col = bounds.startCol;col <= bounds.endCol; col++) {
      pivot.__setPivotCellRenderHint(row2, col, {
        type: "totalRow",
        indentLevel: 0
      });
    }
  }
}
function resolveBodyRowStyleType(depth) {
  if (depth <= 1)
    return "firstSubtotalRow";
  if (depth === 2)
    return "secondRowSubheading";
  return "wholeTable";
}
function renderPageFieldFilters(context, bounds) {
  const pageFields = Array.isArray(context.pivotProto.pageFields) ? context.pivotProto.pageFields : [];
  if (pageFields.length === 0)
    return;
  const worksheet = context.pivot.worksheet;
  const reservedRows = pageFields.length + 1;
  const startRow = Math.max(0, bounds.startRow - reservedRows);
  for (let i = 0;i < pageFields.length; i++) {
    const pageField = pageFields[i];
    const fieldIndex = pageField?.field;
    if (typeof fieldIndex !== "number")
      continue;
    const pageFieldName = pageField?.name;
    const pivotField = context.pivotFields[fieldIndex];
    const cacheField = context.cacheProto.fields?.[pivotField?.index ?? fieldIndex];
    const label = pickFirstNonEmptyString(pageFieldName, pivotField?.name, cacheField?.name, `Field ${fieldIndex + 1}`);
    const value = resolvePageFieldSelectionLabel(context, fieldIndex) ?? "";
    const row2 = startRow + i;
    const labelCol = bounds.startCol;
    const valueCol = bounds.startCol + 1;
    worksheet.getRange(makeCellAddress(row2, labelCol)).values = [[label]];
    worksheet.getRange(makeCellAddress(row2, valueCol)).values = [
      [value]
    ];
    context.pivot.__setPivotCellRenderHint(row2, labelCol, {
      type: "pageFieldLabels",
      indentLevel: 0
    });
    context.pivot.__setPivotCellRenderHint(row2, valueCol, {
      type: "pageFieldValues",
      indentLevel: 0
    });
  }
  const spacerRow = startRow + pageFields.length;
  if (spacerRow < bounds.startRow) {
    const spacerRef = buildRangeRef({
      startRow: spacerRow,
      endRow: spacerRow,
      startCol: bounds.startCol,
      endCol: Math.max(bounds.startCol, bounds.startCol + 1)
    });
    worksheet.getRange(spacerRef).values = [["", ""]];
  }
}
function pickFirstNonEmptyString(...candidates) {
  for (const candidate of candidates) {
    const normalized = candidate?.trim();
    if (normalized && normalized.length > 0) {
      return normalized;
    }
  }
  return "";
}
function resolvePageFieldSelectionLabel(context, fieldIndex) {
  for (const filter of context.filters) {
    if (filter?.field !== fieldIndex)
      continue;
    const descriptor = parseFilterDescriptor(filter);
    if (descriptor?.kind === "manualFilter") {
      const selected = descriptor.payload.selectedItems;
      if (Array.isArray(selected) && selected.length > 0) {
        const first2 = selected[0];
        if (first2 != null)
          return String(first2);
      }
    }
  }
  const pivotField = context.pivotFields[fieldIndex];
  if (!pivotField)
    return null;
  const items = Array.isArray(pivotField.items) ? pivotField.items : [];
  if (items.length === 0)
    return null;
  const cacheField = context.cacheProto.fields?.[pivotField.index ?? fieldIndex];
  const sharedValues = Array.isArray(cacheField?.sharedItems?.values) ? cacheField?.sharedItems?.values : [];
  const visible = items.filter((item) => item?.hidden !== true && typeof item?.index === "number");
  if (visible.length === 0)
    return null;
  if (visible.length > 1 && pivotField.showAll !== false)
    return null;
  const first = visible[0];
  if (!first)
    return null;
  const display = first.displayName;
  if (display != null && display !== "") {
    return String(display);
  }
  const sharedIndex = first.index;
  const shared = sharedValues[sharedIndex];
  if (shared != null) {
    return String(shared);
  }
  return null;
}
function applyDataColumnNumberFormats(context, aggregates, bounds) {
  const dataStartRow = bounds.startRow + aggregates.headerRows;
  if (dataStartRow > bounds.endRow)
    return;
  const worksheet = context.pivot.worksheet;
  for (let segmentIdx = 0;segmentIdx < aggregates.columnSegments.length; segmentIdx++) {
    const segment = aggregates.columnSegments[segmentIdx];
    if (!segment)
      continue;
    const dataField = context.dataFields[segment.dataFieldIndex];
    const numFmtId = dataField?.proto.numberFormatId;
    const numberFormatCode = resolveNumberFormatCode(context, numFmtId);
    if (!numberFormatCode)
      continue;
    const col = bounds.startCol + aggregates.headerCols + segmentIdx;
    const colRef = buildRangeRef({
      startRow: dataStartRow,
      endRow: bounds.endRow,
      startCol: col,
      endCol: col
    });
    worksheet.getRange(colRef).format.numberFormat = numberFormatCode;
  }
}
function resolveNumberFormatCode(context, numFmtId) {
  if (numFmtId == null)
    return null;
  switch (numFmtId) {
    case 10:
      return "0.00%";
    case 164:
      return "$#,##0.00";
    case 165:
      return "0.0";
    case 166:
      return "yyyy-mm-dd";
    default:
      return context.pivot.worksheet.workbook.getStyleRegistry().getNumberFormatCode(numFmtId) ?? null;
  }
}
function buildRowItems(rows, includeGrandTotal) {
  const items = rows.map((_entry, index) => ({
    index,
    type: 0 /* PIVOT_ITEM_TYPE_UNSPECIFIED */.toString()
  }));
  if (includeGrandTotal && rows.length > 0) {
    items.push({ type: 14 /* PIVOT_ITEM_TYPE_GRAND */.toString() });
  }
  return items;
}
function buildColumnItems(columnSegments) {
  const items = columnSegments.map((segment, index) => ({
    index,
    type: segment.isGrandTotal ? 14 /* PIVOT_ITEM_TYPE_GRAND */.toString() : 0 /* PIVOT_ITEM_TYPE_UNSPECIFIED */.toString()
  }));
  return items;
}
function fillHeaders(matrix, headerRows, headerCols, rowFields, columnFields, columnSegments, dataFields) {
  const totalCols = matrix[0]?.length ?? 0;
  const columnFieldDepth = columnFields.length;
  for (let level = 0;level < columnFieldDepth; level++) {
    const rowIndex2 = level;
    const targetRow = matrix[rowIndex2];
    if (targetRow === undefined) {
      continue;
    }
    for (let col = headerCols;col < totalCols; col++) {
      const segmentIndex = col - headerCols;
      const segment = columnSegments[segmentIndex];
      if (segment === undefined) {
        continue;
      }
      const columnEntry = segment.columnEntry;
      if (columnEntry === undefined) {
        targetRow[col] = "Grand Total";
        continue;
      }
      const rawValue = columnEntry.values[level];
      if (rawValue === undefined) {
        targetRow[col] = "";
        continue;
      }
      targetRow[col] = formatLabel(rawValue);
    }
  }
  const dataHeaderRowIndex = headerRows - 1;
  const dataHeaderRow = matrix[dataHeaderRowIndex];
  if (dataHeaderRow === undefined) {
    return;
  }
  for (let col = headerCols;col < totalCols; col++) {
    const segmentIndex = col - headerCols;
    const segment = columnSegments[segmentIndex];
    if (segment === undefined) {
      dataHeaderRow[col] = "";
      continue;
    }
    const dataField = dataFields[segment.dataFieldIndex];
    if (dataField === undefined) {
      dataHeaderRow[col] = "";
      continue;
    }
    if (dataFields.length === 1 && columnFields.length === 0) {
      dataHeaderRow[col] = dataField.name;
    } else if (dataFields.length > 1) {
      dataHeaderRow[col] = segment.isGrandTotal ? `Grand Total (${dataField.name})` : dataField.name;
    } else if (segment.isGrandTotal) {
      dataHeaderRow[col] = "Grand Total";
    } else {
      dataHeaderRow[col] = "";
    }
  }
  const rowHeaderRowIndex = headerRows - 1;
  const rowHeaderRow = matrix[rowHeaderRowIndex];
  if (rowHeaderRow === undefined) {
    return;
  }
  if (headerCols === 1 && rowFields.length > 0) {
    rowHeaderRow[0] = "Row Labels";
  } else {
    for (let c = 0;c < headerCols; c++) {
      const binding = rowFields[c];
      rowHeaderRow[c] = binding === undefined ? "" : binding.name;
    }
  }
}
function fillBody(matrix, headerRows, headerCols, rowEntries, columnSegments, dataFields, rowFields, columnFields, pivotFields, cacheProto, rowGrandTotals, grandTotals) {
  const rowEntriesByKey = new Map;
  rowEntries.forEach((entry) => rowEntriesByKey.set(entry.key, entry));
  const columnEntriesByKey = new Map;
  for (const segment of columnSegments) {
    const columnEntry = segment.columnEntry;
    if (columnEntry != null) {
      columnEntriesByKey.set(columnEntry.key, columnEntry);
    }
  }
  const rowFieldDepthByPivotIndex = new Map;
  rowFields.forEach((field, depth) => rowFieldDepthByPivotIndex.set(field.pivotIndex, depth));
  const columnFieldDepthByPivotIndex = new Map;
  columnFields.forEach((field, depth) => columnFieldDepthByPivotIndex.set(field.pivotIndex, depth));
  const totalsRowStart = headerRows + rowEntries.length;
  rowEntries.forEach((rowEntry, rowIdx) => {
    const matrixRowIndex = headerRows + rowIdx;
    const targetRow = matrix[matrixRowIndex];
    if (targetRow === undefined) {
      return;
    }
    fillRowHeader(matrix, matrixRowIndex, headerCols, rowEntry.values);
    for (let segmentIdx = 0;segmentIdx < columnSegments.length; segmentIdx++) {
      const segment = columnSegments[segmentIdx];
      if (segment === undefined) {
        targetRow[headerCols + segmentIdx] = null;
        continue;
      }
      const dataField = dataFields[segment.dataFieldIndex];
      if (dataField === undefined) {
        targetRow[headerCols + segmentIdx] = null;
        continue;
      }
      const columnValues = segment.columnEntry ? rowEntry.columns.get(segment.columnEntry.key) : undefined;
      let stats;
      if (segment.isGrandTotal) {
        stats = getStats(rowEntry.totals, segment.dataFieldIndex);
      } else if (columnValues) {
        stats = getStats(columnValues, segment.dataFieldIndex);
      } else {
        stats = createEmptyStats();
      }
      const subtotal = getPivotDataFieldSubtotal(dataField.proto);
      const value = evaluateAggregation(stats, subtotal);
      const grandTotalValue = evaluateAggregation(getStats(grandTotals, segment.dataFieldIndex), subtotal);
      const rowTotalValue = evaluateAggregation(getStats(rowEntry.totals, segment.dataFieldIndex), subtotal);
      const columnTotalValue = segment.columnEntry != null ? evaluateAggregation(getStats(segment.columnEntry.totals, segment.dataFieldIndex), subtotal) : grandTotalValue;
      const showAsValue = applyShowAs(value, dataField.proto, {
        grandTotalValue,
        rowTotalValue,
        columnTotalValue
      }, {
        dataFieldIndex: segment.dataFieldIndex,
        rowEntry,
        columnEntry: segment.columnEntry,
        isGrandTotalSegment: segment.isGrandTotal,
        rowEntriesByKey,
        columnEntriesByKey,
        rowFieldDepthByPivotIndex,
        columnFieldDepthByPivotIndex,
        pivotFields,
        cacheProto
      });
      targetRow[headerCols + segmentIdx] = showAsValue ?? null;
    }
  });
  if (rowGrandTotals && rowEntries.length > 0) {
    const totalsRowIndex = totalsRowStart;
    const totalsRow = matrix[totalsRowIndex];
    if (totalsRow === undefined) {
      return;
    }
    fillRowHeader(matrix, totalsRowIndex, headerCols, ["Grand Total"]);
    for (let segmentIdx = 0;segmentIdx < columnSegments.length; segmentIdx++) {
      const segment = columnSegments[segmentIdx];
      if (segment === undefined) {
        totalsRow[headerCols + segmentIdx] = null;
        continue;
      }
      const dataField = dataFields[segment.dataFieldIndex];
      if (dataField === undefined) {
        totalsRow[headerCols + segmentIdx] = null;
        continue;
      }
      let stats;
      if (segment.columnEntry) {
        stats = getStats(segment.columnEntry.totals, segment.dataFieldIndex);
      } else {
        stats = getStats(grandTotals, segment.dataFieldIndex);
      }
      const subtotal = getPivotDataFieldSubtotal(dataField.proto);
      const value = evaluateAggregation(stats, subtotal);
      const grandTotalValue = evaluateAggregation(getStats(grandTotals, segment.dataFieldIndex), subtotal);
      const columnTotalValue = segment.columnEntry != null ? evaluateAggregation(getStats(segment.columnEntry.totals, segment.dataFieldIndex), subtotal) : grandTotalValue;
      const showAsValue = applyShowAs(value, dataField.proto, {
        grandTotalValue,
        rowTotalValue: grandTotalValue,
        columnTotalValue
      }, {
        dataFieldIndex: segment.dataFieldIndex,
        rowEntry: undefined,
        columnEntry: segment.columnEntry,
        isGrandTotalSegment: segment.isGrandTotal,
        rowEntriesByKey,
        columnEntriesByKey,
        rowFieldDepthByPivotIndex,
        columnFieldDepthByPivotIndex,
        pivotFields,
        cacheProto
      });
      totalsRow[headerCols + segmentIdx] = showAsValue ?? null;
    }
  }
}
function fillRowHeader(matrix, rowIndex2, headerCols, values) {
  const targetRow = matrix[rowIndex2];
  if (targetRow === undefined) {
    return;
  }
  if (headerCols === 1) {
    const value = values.length > 0 ? values[values.length - 1] ?? "" : "";
    targetRow[0] = formatLabel(value);
    return;
  }
  for (let c = 0;c < headerCols; c++) {
    const value = values[c];
    if (value === undefined) {
      targetRow[c] = "";
      continue;
    }
    targetRow[c] = formatLabel(value);
  }
}
function createEmptyStats() {
  return {
    sum: 0,
    sumSquares: 0,
    count: 0,
    countNumbers: 0,
    product: null,
    min: null,
    max: null
  };
}
function getStats(statsArray, index) {
  const stats = statsArray[index];
  if (stats !== undefined) {
    return stats;
  }
  const fallback = createEmptyStats();
  statsArray[index] = fallback;
  return fallback;
}
function updateStats(stats, value) {
  stats.count += 1;
  const num = coerceNumber4(value);
  if (num != null) {
    stats.countNumbers += 1;
    stats.sum += num;
    stats.sumSquares += num * num;
    stats.product = stats.product == null ? num : stats.product * num;
    stats.min = stats.min == null ? num : Math.min(stats.min, num);
    stats.max = stats.max == null ? num : Math.max(stats.max, num);
  }
}
function evaluateAggregation(stats, func) {
  const aggregation = func ?? 1 /* DATA_CONSOLIDATE_FUNCTION_SUM */;
  switch (aggregation) {
    case 1 /* DATA_CONSOLIDATE_FUNCTION_SUM */:
      return stats.sum;
    case 3 /* DATA_CONSOLIDATE_FUNCTION_COUNT */:
      return stats.count;
    case 4 /* DATA_CONSOLIDATE_FUNCTION_COUNT_NUMBERS */:
      return stats.countNumbers;
    case 2 /* DATA_CONSOLIDATE_FUNCTION_AVERAGE */:
      return stats.countNumbers > 0 ? stats.sum / stats.countNumbers : null;
    case 5 /* DATA_CONSOLIDATE_FUNCTION_MAXIMUM */:
      return stats.max;
    case 6 /* DATA_CONSOLIDATE_FUNCTION_MINIMUM */:
      return stats.min;
    case 7 /* DATA_CONSOLIDATE_FUNCTION_PRODUCT */:
      return stats.product;
    case 8 /* DATA_CONSOLIDATE_FUNCTION_STD_DEV */: {
      const n = stats.countNumbers;
      if (n <= 1)
        return null;
      const variance = (stats.sumSquares - stats.sum * stats.sum / n) / (n - 1);
      return Math.sqrt(Math.max(variance, 0));
    }
    case 9 /* DATA_CONSOLIDATE_FUNCTION_STD_DEVP */: {
      const n = stats.countNumbers;
      if (n === 0)
        return null;
      const variance = (stats.sumSquares - stats.sum * stats.sum / n) / n;
      return Math.sqrt(Math.max(variance, 0));
    }
    case 10 /* DATA_CONSOLIDATE_FUNCTION_VARIANCE */: {
      const n = stats.countNumbers;
      if (n <= 1)
        return null;
      return (stats.sumSquares - stats.sum * stats.sum / n) / (n - 1);
    }
    case 11 /* DATA_CONSOLIDATE_FUNCTION_VARIANCEP */: {
      const n = stats.countNumbers;
      if (n === 0)
        return null;
      return (stats.sumSquares - stats.sum * stats.sum / n) / n;
    }
    default:
      return stats.sum;
  }
}
function formatLabel(value) {
  if (value === null || value === undefined)
    return "";
  if (value instanceof Date)
    return value.toISOString();
  return String(value);
}
function buildPivotFieldItemVisibility(context, pivotFieldBindings) {
  const result = new Map;
  const cacheFields = Array.isArray(context.cacheProto.fields) ? context.cacheProto.fields : [];
  for (const [pivotIdx, binding] of pivotFieldBindings.entries()) {
    const pivotFieldProto = context.pivotFields[pivotIdx];
    if (!pivotFieldProto)
      continue;
    const items = Array.isArray(pivotFieldProto.items) ? pivotFieldProto.items : [];
    if (items.length === 0)
      continue;
    const cacheField = cacheFields[binding.headerIndex];
    const sharedValues = cacheField?.sharedItems?.values ?? [];
    if (!Array.isArray(sharedValues) || sharedValues.length === 0)
      continue;
    const whitelist = new Set;
    const hidden = new Set;
    const order = new Map;
    for (let position = 0;position < items.length; position++) {
      const item = items[position];
      const sharedIndex = item?.index;
      if (typeof sharedIndex !== "number")
        continue;
      const rawLabel = sharedValues[sharedIndex];
      if (rawLabel == null)
        continue;
      const label = String(rawLabel);
      whitelist.add(label);
      order.set(label, position);
      if (item?.hidden === true) {
        hidden.add(label);
      }
    }
    result.set(pivotIdx, {
      showAll: pivotFieldProto.showAll !== false,
      whitelist,
      hidden,
      order
    });
  }
  return result;
}
function passesItemVisibility(visibility, relevantPivotFieldIndices, fieldValues) {
  for (const pivotIdx of relevantPivotFieldIndices) {
    const rules = visibility.get(pivotIdx);
    if (!rules)
      continue;
    const rawValue = fieldValues.get(pivotIdx);
    const value = rawValue === undefined ? null : rawValue;
    const label = formatLabel(value);
    if (rules.hidden.has(label)) {
      return false;
    }
    if (!rules.showAll && rules.whitelist.size > 0 && !rules.whitelist.has(label)) {
      return false;
    }
  }
  return true;
}
function coerceNumber4(value) {
  if (typeof value === "number") {
    return Number.isFinite(value) ? value : null;
  }
  if (typeof value === "string") {
    const trimmed = value.trim();
    if (trimmed.length === 0)
      return null;
    const parsed = Number(trimmed);
    return Number.isFinite(parsed) ? parsed : null;
  }
  if (value instanceof Date) {
    return value.getTime();
  }
  return null;
}
function keyFromValues(values) {
  return JSON.stringify(values ?? []);
}
function parseFilterDescriptor(filter) {
  if (!filter.description)
    return null;
  try {
    const parsed = JSON.parse(filter.description);
    if (!parsed || !parsed.kind) {
      return null;
    }
    if (parsed.kind === "dateFilter" || parsed.kind === "labelFilter" || parsed.kind === "manualFilter" || parsed.kind === "valueFilter") {
      return parsed;
    }
  } catch {
    return null;
  }
  return null;
}
function passesFilters(descriptors, filters, fieldValues) {
  if (filters.length === 0)
    return true;
  for (let i = 0;i < filters.length; i++) {
    const descriptor = descriptors[i];
    const filter = filters[i];
    if (!descriptor)
      continue;
    if (filter === undefined) {
      continue;
    }
    const value = fieldValues.get(filter.field ?? -1);
    const normalizedValue = value === undefined ? null : value;
    if (!filterPasses(descriptor, normalizedValue)) {
      return false;
    }
  }
  return true;
}
function filterPasses(descriptor, value) {
  switch (descriptor.kind) {
    case "manualFilter":
      return manualFilterPasses(descriptor.payload, value);
    case "labelFilter":
      return labelFilterPasses(descriptor.payload, value);
    case "dateFilter":
      return dateFilterPasses(descriptor.payload, value);
    case "valueFilter":
      return true;
    default:
      return true;
  }
}
function manualFilterPasses(payload, value) {
  const selected = payload.selectedItems?.map(formatLabel);
  const excluded = payload.excludedItems?.map(formatLabel);
  const label = formatLabel(value);
  if (selected && selected.length > 0) {
    return selected.includes(label);
  }
  if (excluded && excluded.length > 0) {
    return !excluded.includes(label);
  }
  return true;
}
function labelFilterPasses(payload, value) {
  const condition = payload.condition;
  if (!condition)
    return true;
  const label = formatLabel(value);
  const substring = typeof payload.substring === "string" ? payload.substring : "";
  const comparator = typeof payload.comparator === "string" ? payload.comparator : "";
  switch (condition) {
    case "BeginsWith":
    case "beginsWith":
      return label.startsWith(substring);
    case "EndsWith":
    case "endsWith":
      return label.endsWith(substring);
    case "Contains":
    case "contains":
      return label.includes(substring);
    case "NotContains":
    case "notContains":
      return !label.includes(substring);
    case "Equals":
    case "equals":
      return label === comparator;
    case "NotEquals":
    case "notEquals":
      return label !== comparator;
    case "GreaterThan":
    case "greaterThan":
      return label > comparator;
    case "LessThan":
    case "lessThan":
      return label < comparator;
    default:
      return true;
  }
}
function dateFilterPasses(payload, value) {
  const comparator = payload.comparator;
  if (!comparator?.date)
    return true;
  const target = toDate(comparator.date);
  const actual = toDate(value);
  if (!target || !actual)
    return true;
  const condition = payload.condition;
  switch (condition) {
    case "before":
    case "Before":
      return actual.getTime() < target.getTime();
    case "after":
    case "After":
      return actual.getTime() > target.getTime();
    case "equals":
    case "Equals":
      return sameDay(actual, target);
    default:
      return true;
  }
}
function toDate(value) {
  if (value instanceof Date)
    return value;
  if (typeof value === "string") {
    const parsed = new Date(value);
    if (!Number.isNaN(parsed.getTime()))
      return parsed;
  }
  return null;
}
function sameDay(a, b) {
  return a.getUTCFullYear() === b.getUTCFullYear() && a.getUTCMonth() === b.getUTCMonth() && a.getUTCDate() === b.getUTCDate();
}
function buildValueFilterRules(filters, descriptors, rowFields, columnFields, dataFields) {
  const rules = [];
  for (let i = 0;i < descriptors.length; i++) {
    const descriptor = descriptors[i];
    if (!descriptor || descriptor.kind !== "valueFilter")
      continue;
    const filter = filters[i];
    const pivotFieldIndex = filter?.field;
    if (typeof pivotFieldIndex !== "number")
      continue;
    const rowDepth = rowFields.findIndex((field) => field.pivotIndex === pivotFieldIndex);
    const columnDepth = columnFields.findIndex((field) => field.pivotIndex === pivotFieldIndex);
    if (rowDepth === -1 && columnDepth === -1)
      continue;
    const dataFieldIndex = resolveValueFilterDataFieldIndex(descriptor.payload, dataFields);
    if (dataFieldIndex < 0)
      continue;
    const dataField = dataFields[dataFieldIndex];
    if (!dataField)
      continue;
    rules.push({
      axis: rowDepth !== -1 ? "row" : "column",
      depth: rowDepth !== -1 ? rowDepth : columnDepth,
      payload: descriptor.payload,
      dataFieldIndex,
      subtotal: getPivotDataFieldSubtotal(dataField.proto)
    });
  }
  return rules;
}
function resolveValueFilterDataFieldIndex(payload, dataFields) {
  if (dataFields.length === 0)
    return -1;
  const rawName = payload.value?.trim();
  if (!rawName)
    return 0;
  const normalizedTarget = normalizeValueFieldName(rawName);
  for (let i = 0;i < dataFields.length; i++) {
    const dataField = dataFields[i];
    if (!dataField)
      continue;
    const candidates = [dataField.name, dataField.proto.name];
    if (candidates.some((candidate) => normalizeValueFieldName(candidate) === normalizedTarget)) {
      return i;
    }
  }
  return 0;
}
function normalizeValueFieldName(value) {
  if (!value)
    return "";
  return value.trim().replace(/\s+/g, " ").toLowerCase().replace(/^(sum|count|average|max|min|product|stddev|stddevp|variance|variancep)\s+of\s+/, "");
}
function applyValueFilterRules(entries, rules, dataFields, axis) {
  if (entries.length === 0)
    return;
  const axisRules = rules.filter((rule2) => rule2.axis === axis);
  if (axisRules.length === 0)
    return;
  let filteredEntries = [...entries];
  for (const rule2 of axisRules) {
    const dataField = dataFields[rule2.dataFieldIndex];
    if (!dataField)
      continue;
    const candidates = filteredEntries.filter((entry) => entry.values.length === rule2.depth + 1).map((entry) => ({
      key: entry.key,
      value: evaluateAggregation(getStats(entry.totals, rule2.dataFieldIndex), rule2.subtotal)
    }));
    const allowedKeys = pickValueFilterMatches(candidates, rule2.payload);
    const ancestorKeys = buildAncestorKeySet(allowedKeys);
    filteredEntries = filteredEntries.filter((entry) => entryPassesValueRule(entry, rule2.depth, allowedKeys, ancestorKeys));
  }
  entries.length = 0;
  entries.push(...filteredEntries);
}
function pickValueFilterMatches(candidates, payload) {
  const keepAll = new Set(candidates.map((candidate) => candidate.key));
  if (candidates.length === 0)
    return keepAll;
  const condition = normalizeFilterConditionToken(payload.condition);
  const comparator = payload.comparator;
  const matches = new Set;
  const numericCandidates = candidates.filter((candidate) => candidate.value != null && Number.isFinite(candidate.value));
  const addRankedMatches = (descending2, count3) => {
    if (count3 <= 0 || numericCandidates.length === 0)
      return;
    const sorted = [...numericCandidates].sort((a, b) => {
      const aValue = a.value;
      const bValue = b.value;
      return descending2 ? bValue - aValue : aValue - bValue;
    });
    for (let i = 0;i < Math.min(count3, sorted.length); i++) {
      const item = sorted[i];
      if (item)
        matches.add(item.key);
    }
  };
  switch (condition) {
    case "topn": {
      const count3 = Math.floor(Math.max(0, comparator ?? 0));
      addRankedMatches(true, count3);
      return matches;
    }
    case "bottomn": {
      const count3 = Math.floor(Math.max(0, comparator ?? 0));
      addRankedMatches(false, count3);
      return matches;
    }
    case "toppercent": {
      const percent = Math.max(0, Math.min(100, comparator ?? 0));
      const count3 = Math.ceil(numericCandidates.length * percent / 100);
      addRankedMatches(true, count3);
      return matches;
    }
    case "bottompercent": {
      const percent = Math.max(0, Math.min(100, comparator ?? 0));
      const count3 = Math.ceil(numericCandidates.length * percent / 100);
      addRankedMatches(false, count3);
      return matches;
    }
    default:
      break;
  }
  if (comparator == null || !Number.isFinite(comparator)) {
    return keepAll;
  }
  const upperBoundRaw = payload.value ? Number(payload.value) : Number.NaN;
  const hasUpperBound = Number.isFinite(upperBoundRaw);
  const lowerBound = hasUpperBound ? Math.min(comparator, upperBoundRaw) : comparator;
  const upperBound = hasUpperBound ? Math.max(comparator, upperBoundRaw) : comparator;
  for (const candidate of candidates) {
    const numeric = candidate.value;
    if (numeric == null || !Number.isFinite(numeric)) {
      continue;
    }
    let passes = true;
    switch (condition) {
      case "equals":
        passes = numeric === comparator;
        break;
      case "notequals":
        passes = numeric !== comparator;
        break;
      case "greaterthan":
        passes = numeric > comparator;
        break;
      case "greaterthanorequalto":
        passes = numeric >= comparator;
        break;
      case "lessthan":
        passes = numeric < comparator;
        break;
      case "lessthanorequalto":
        passes = numeric <= comparator;
        break;
      case "between":
        passes = numeric >= lowerBound && numeric <= upperBound;
        break;
      default:
        passes = true;
        break;
    }
    if (payload.exclusive === true) {
      passes = !passes;
    }
    if (passes) {
      matches.add(candidate.key);
    }
  }
  return matches;
}
function normalizeFilterConditionToken(value) {
  if (!value)
    return "";
  return String(value).replace(/[^a-z]/gi, "").toLowerCase();
}
function buildAncestorKeySet(keys2) {
  const ancestors = new Set;
  for (const key of keys2) {
    try {
      const values = JSON.parse(key);
      if (!Array.isArray(values))
        continue;
      for (let i = 1;i <= values.length; i++) {
        ancestors.add(keyFromValues(values.slice(0, i)));
      }
    } catch {
      continue;
    }
  }
  return ancestors;
}
function entryPassesValueRule(entry, depth, allowedKeys, ancestorKeys) {
  if (allowedKeys.size === 0)
    return false;
  const entryDepth = entry.values.length - 1;
  if (entryDepth >= depth) {
    const key = keyFromValues(entry.values.slice(0, depth + 1));
    return allowedKeys.has(key);
  }
  return ancestorKeys.has(entry.key);
}
function applyShowAs(value, dataField, totals, references) {
  if (value == null)
    return null;
  const calculation = parseShowAsCalculation(dataField.showAs);
  switch (calculation) {
    case ShowAsCalculation.percentOfGrandTotal: {
      const denom = totals.grandTotalValue;
      if (!denom)
        return null;
      return value / denom;
    }
    case ShowAsCalculation.percentOfRowTotal: {
      const denom = totals.rowTotalValue;
      if (!denom)
        return null;
      return value / denom;
    }
    case ShowAsCalculation.percentOfColumnTotal: {
      const denom = totals.columnTotalValue;
      if (!denom)
        return null;
      return value / denom;
    }
    case ShowAsCalculation.differenceFrom:
    case ShowAsCalculation.percentDifferenceFrom: {
      const subtotal = getPivotDataFieldSubtotal(dataField);
      const baseValue = resolveShowAsBaseValue(dataField, subtotal, references);
      if (baseValue == null)
        return null;
      const difference = value - baseValue;
      if (calculation === ShowAsCalculation.percentDifferenceFrom) {
        if (baseValue === 0)
          return null;
        return difference / baseValue;
      }
      return difference;
    }
    default:
      return value;
  }
}
function resolveShowAsBaseValue(dataField, subtotal, references) {
  const baseFieldIndex = dataField.baseField;
  const baseItemIndex = dataField.baseItem;
  if (typeof baseFieldIndex !== "number" || typeof baseItemIndex !== "number") {
    return null;
  }
  const baseLabel = resolveShowAsBaseItemLabel(baseFieldIndex, baseItemIndex, references.pivotFields, references.cacheProto);
  if (baseLabel == null)
    return null;
  const rowDepth = references.rowFieldDepthByPivotIndex.get(baseFieldIndex);
  if (rowDepth !== undefined) {
    const rowEntry = references.rowEntry;
    if (!rowEntry || rowEntry.values.length <= rowDepth)
      return null;
    const baseValues = [...rowEntry.values];
    baseValues[rowDepth] = baseLabel;
    const baseRow = references.rowEntriesByKey.get(keyFromValues(baseValues));
    if (!baseRow)
      return null;
    return evaluateCellAggregateValue(baseRow, references.columnEntry, references.isGrandTotalSegment, references.dataFieldIndex, subtotal);
  }
  const columnDepth = references.columnFieldDepthByPivotIndex.get(baseFieldIndex);
  if (columnDepth !== undefined) {
    const rowEntry = references.rowEntry;
    const columnEntry = references.columnEntry;
    if (!rowEntry || !columnEntry || columnEntry.values.length <= columnDepth) {
      return null;
    }
    const baseValues = [...columnEntry.values];
    baseValues[columnDepth] = baseLabel;
    const baseColumn = references.columnEntriesByKey.get(keyFromValues(baseValues));
    if (!baseColumn)
      return null;
    return evaluateCellAggregateValue(rowEntry, baseColumn, false, references.dataFieldIndex, subtotal);
  }
  return null;
}
function resolveShowAsBaseItemLabel(pivotFieldIndex, baseItemIndex, pivotFields, cacheProto) {
  const pivotField = pivotFields[pivotFieldIndex];
  if (!pivotField)
    return null;
  const items = Array.isArray(pivotField.items) ? pivotField.items : [];
  const item = items.find((candidate) => candidate?.index === baseItemIndex) ?? items[baseItemIndex];
  const displayName = item?.displayName;
  if (displayName != null && displayName !== "") {
    return displayName;
  }
  const fieldIndex = pivotField.index ?? pivotFieldIndex;
  const sharedValues = cacheProto.fields?.[fieldIndex]?.sharedItems?.values ?? [];
  const sharedIndex = item?.index;
  if (typeof sharedIndex === "number") {
    const sharedValue = sharedValues[sharedIndex];
    if (sharedValue != null) {
      return sharedValue;
    }
  }
  const fallback = sharedValues[baseItemIndex];
  if (fallback != null) {
    return fallback;
  }
  return null;
}
function evaluateCellAggregateValue(rowEntry, columnEntry, isGrandTotalSegment, dataFieldIndex, subtotal) {
  if (isGrandTotalSegment || !columnEntry) {
    return evaluateAggregation(getStats(rowEntry.totals, dataFieldIndex), subtotal);
  }
  const cellStats = rowEntry.columns.get(columnEntry.key);
  if (!cellStats)
    return null;
  return evaluateAggregation(getStats(cellStats, dataFieldIndex), subtotal);
}

// node_modules/@oai/granola/dist/models/pivot-hierarchy-collection.js
class PivotHierarchyCollection {
  #pivotTable;
  #kind;
  #source;
  constructor(options) {
    this.#pivotTable = options.pivotTable;
    this.#kind = options.kind;
    this.#source = options.source;
  }
  add(hierarchy2) {
    if (this.#kind === "all") {
      throw new Error("Cannot add hierarchies to the master collection");
    }
    this.#pivotTable._assignHierarchy(this.#kind, hierarchy2);
    recomputePivotTable(this.#pivotTable);
    return hierarchy2;
  }
  getItem(name) {
    const hierarchy2 = this.items.find((candidate) => candidate.name === name);
    if (!hierarchy2) {
      throw new Error(`PivotHierarchy ${name} not found`);
    }
    return hierarchy2;
  }
  getItemOrNullObject(name) {
    return this.items.find((candidate) => candidate.name === name) ?? null;
  }
  load(_properties) {
    return this;
  }
  get items() {
    if (this.#kind === "all" && this.#source) {
      return [...this.#source];
    }
    return this.#pivotTable._getHierarchies(this.#kind);
  }
}

// node_modules/@oai/granola/dist/models/pivot-field-collection.js
class PivotFieldCollection {
  #fields;
  constructor(fields = []) {
    this.#fields = fields;
  }
  getItem(name) {
    const field = this.#fields.find((candidate) => candidate.name === name);
    if (!field) {
      throw new Error(`PivotField ${name} not found`);
    }
    return field;
  }
  get items() {
    return [...this.#fields];
  }
  _replace(fields) {
    this.#fields = fields;
  }
}

// node_modules/@oai/granola/dist/models/pivot-item-collection.js
class PivotItemCollection {
  #items;
  constructor(items = []) {
    this.#items = items;
  }
  getItem(name) {
    const item = this.#items.find((candidate) => candidate.name === name);
    if (!item) {
      throw new Error(`PivotItem ${name} not found`);
    }
    return item;
  }
  get items() {
    return [...this.#items];
  }
  _replace(items) {
    this.#items = items;
  }
}

// node_modules/@oai/granola/dist/models/pivot-field.js
var PIVOT_FIELD_PROTO = new WeakMap;

class PivotField2 {
  #pivotTable;
  #items;
  constructor(pivotField, options = {}) {
    PIVOT_FIELD_PROTO.set(this, pivotField);
    this.#pivotTable = options.pivotTable;
  }
  get name() {
    return this.#proto().name ?? "";
  }
  get numberFormatId() {
    return this.#proto().numberFormatId ?? undefined;
  }
  set numberFormatId(value) {
    this.#proto().numberFormatId = value;
  }
  get showAll() {
    return this.#proto().showAll !== false;
  }
  set showAll(value) {
    this.#proto().showAll = value;
  }
  get items() {
    if (!this.#items) {
      const proto = this.#proto();
      const itemWrappers = (proto.items ?? []).map((item) => new PivotItem(item));
      this.#items = new PivotItemCollection(itemWrappers);
    }
    return this.#items;
  }
  get pivotTable() {
    return this.#pivotTable;
  }
  applyFilter(options) {
    if (!this.#pivotTable) {
      throw new Error("PivotField is not attached to a PivotTable");
    }
    this.#pivotTable.__applyFilterForField(this, options);
  }
  clearAllFilters() {
    if (!this.#pivotTable)
      return;
    this.#pivotTable.__clearAllFiltersForField(this);
  }
  #proto() {
    const proto = PIVOT_FIELD_PROTO.get(this);
    if (!proto) {
      throw new Error("PivotField proto not found");
    }
    return proto;
  }
  __ensureIndex(pivotFields) {
    const proto = this.#proto();
    if (proto.index != null) {
      return proto.index;
    }
    const idx = pivotFields.indexOf(proto);
    if (idx === -1) {
      throw new Error("PivotField proto not registered with PivotTable");
    }
    proto.index = idx;
    return idx;
  }
}
function getPivotFieldProto(field) {
  const proto = PIVOT_FIELD_PROTO.get(field);
  if (!proto) {
    throw new Error("PivotField proto not found");
  }
  return proto;
}

// node_modules/@oai/granola/dist/models/pivot-hierarchy.js
var PIVOT_HIERARCHY_FIELD = new WeakMap;

class PivotHierarchy {
  #fields;
  constructor(field) {
    PIVOT_HIERARCHY_FIELD.set(this, field);
    this.#fields = new PivotFieldCollection([field]);
  }
  get name() {
    return this.#field().name;
  }
  get fields() {
    return this.#fields;
  }
  #field() {
    const field = PIVOT_HIERARCHY_FIELD.get(this);
    if (!field) {
      throw new Error("PivotHierarchy field not found");
    }
    return field;
  }
}
function getPivotHierarchyField(hierarchy2) {
  const field = PIVOT_HIERARCHY_FIELD.get(hierarchy2);
  if (!field) {
    throw new Error("PivotHierarchy field not found");
  }
  return field;
}
function getPivotHierarchyFieldProto(hierarchy2) {
  return getPivotFieldProto(getPivotHierarchyField(hierarchy2));
}

// node_modules/@oai/granola/dist/models/pivot-data-hierarchy-collection.js
class PivotDataHierarchyCollection {
  #pivotTable;
  #items;
  constructor(options) {
    this.#pivotTable = options.pivotTable;
    this.#items = options.items ?? [];
  }
  add(hierarchy2) {
    const fieldIndex = this.#pivotTable._ensureHierarchyIndex(hierarchy2);
    const sourceFieldProto = getPivotHierarchyFieldProto(hierarchy2);
    const dataFieldProto = {
      field: fieldIndex,
      name: this.#defaultDataFieldName(hierarchy2),
      subtotal: undefined,
      numberFormatId: sourceFieldProto.numberFormatId,
      showAs: undefined,
      baseField: undefined,
      baseItem: undefined
    };
    setPivotDataFieldSubtotal(dataFieldProto, 1 /* DATA_CONSOLIDATE_FUNCTION_SUM */);
    this.#pivotTable.__addDataFieldProto(dataFieldProto);
    const wrapper = new PivotDataHierarchy(dataFieldProto, {
      pivotTable: this.#pivotTable
    });
    this.#items.push(wrapper);
    recomputePivotTable(this.#pivotTable);
    return wrapper;
  }
  getItem(name) {
    const hierarchy2 = this.#items.find((candidate) => candidate.name === name);
    if (!hierarchy2) {
      throw new Error(`PivotDataHierarchy ${name} not found`);
    }
    return hierarchy2;
  }
  load(_properties) {
    return this;
  }
  get items() {
    return [...this.#items];
  }
  #defaultDataFieldName(hierarchy2) {
    const field = getPivotHierarchyFieldProto(hierarchy2);
    const sourceName = field.name ?? "Values";
    return `Sum of ${sourceName}`;
  }
}

// node_modules/@oai/granola/dist/models/pivot-cache.js
function buildCacheField(header, rows, index, options) {
  const values = rows.map((row2) => row2[index]);
  const unique = new Set;
  let containsBlank = false;
  let containsNumeric = false;
  let containsString = false;
  let containsDate = false;
  let minValue;
  let maxValue;
  let minDate;
  let maxDate;
  for (const value of values) {
    if (value == null || value === "") {
      containsBlank = true;
      continue;
    }
    if (typeof value === "number") {
      containsNumeric = true;
      minValue = minValue == null ? value : Math.min(minValue, value);
      maxValue = maxValue == null ? value : Math.max(maxValue, value);
    } else if (typeof value === "string") {
      containsString = true;
    } else if (typeof value === "boolean") {
      containsString = true;
    } else if (value instanceof Date) {
      containsDate = true;
      minDate = minDate == null ? value : minDate < value ? minDate : value;
      maxDate = maxDate == null ? value : maxDate > value ? maxDate : value;
    }
    if (options.includeSharedValues) {
      unique.add(String(value));
    }
  }
  const sharedItems = { values: [] };
  const typeCount = Number(containsNumeric) + Number(containsString) + Number(containsDate);
  const hasMixedTypes = typeCount > 1;
  if (containsNumeric) {
    sharedItems.containsNumeric = true;
    sharedItems.containsString = containsString;
    sharedItems.containsSemiMixedTypes = hasMixedTypes;
    if (minValue != null)
      sharedItems.minValue = minValue;
    if (maxValue != null)
      sharedItems.maxValue = maxValue;
  } else if (containsDate) {
    sharedItems.containsDate = true;
    sharedItems.containsString = containsString;
    sharedItems.containsSemiMixedTypes = hasMixedTypes;
    sharedItems.containsNonDate = containsNumeric || containsString;
    if (minDate)
      sharedItems.minDate = formatPivotDate(minDate);
    if (maxDate)
      sharedItems.maxDate = formatPivotDate(maxDate);
  } else if (options.includeSharedValues) {
    if (containsBlank)
      unique.add("");
    const sharedValues = Array.from(unique);
    sharedItems.values = sharedValues;
    sharedItems.count = sharedValues.length;
  }
  return {
    name: header,
    numFmtId: options.numFmtId ?? 0,
    sharedItems
  };
}
function formatPivotDate(value) {
  return value.toISOString().replace(".000Z", "");
}

class PivotCacheDefinition {
  #proto;
  constructor(proto) {
    this.#proto = proto;
  }
  static createFromSource(options) {
    const proto = {
      id: options.id,
      name: options.name,
      fields: []
    };
    rebuildPivotCacheFromSource(proto, {
      headers: options.headers,
      rows: options.rows,
      sharedValuesFieldIndices: new Set(options.headers.map((_header, idx) => idx)),
      numFmtIdByFieldIndex: new Map
    });
    return new PivotCacheDefinition(proto);
  }
  toProto() {
    return this.#proto;
  }
}
function rebuildPivotCacheFromSource(cache, options) {
  const fields = options.headers.map((header, idx) => buildCacheField(header, options.rows, idx, {
    includeSharedValues: options.sharedValuesFieldIndices.has(idx),
    numFmtId: options.numFmtIdByFieldIndex.get(idx)
  }));
  cache.fields = fields;
}

// node_modules/@oai/granola/dist/models/spreadsheet/pivots/pivot-openxml-filter-compiler.js
function compilePivotLabelFilterTypeToken(condition) {
  switch (condition) {
    case "BeginsWith":
      return "captionBeginsWith";
    case "EndsWith":
      return "captionEndsWith";
    case "Contains":
      return "captionContains";
    case "NotContains":
      return "captionNotContains";
    case "Equals":
      return "captionEqual";
    case "NotEquals":
      return "captionNotEqual";
    case "GreaterThan":
      return "captionGreaterThan";
    case "GreaterThanOrEqualTo":
      return "captionGreaterThanOrEqual";
    case "LessThan":
      return "captionLessThan";
    case "LessThanOrEqualTo":
      return "captionLessThanOrEqual";
    case "Between":
      return "captionBetween";
    default:
      return "unknown";
  }
}
function compilePivotValueFilterTypeToken(condition) {
  switch (condition) {
    case "Equals":
      return "valueEqual";
    case "NotEquals":
      return "valueNotEqual";
    case "GreaterThan":
      return "valueGreaterThan";
    case "GreaterThanOrEqualTo":
      return "valueGreaterThanOrEqual";
    case "LessThan":
      return "valueLessThan";
    case "LessThanOrEqualTo":
      return "valueLessThanOrEqual";
    case "Between":
      return "valueBetween";
    case "TopN":
    case "BottomN":
    case "TopPercent":
    case "BottomPercent":
      return "unknown";
    default:
      return "unknown";
  }
}
function compilePivotDateFilterTypeToken(condition) {
  switch (condition) {
    case "Equals":
      return "dateEqual";
    case "Before":
      return "dateOlderThan";
    case "After":
      return "dateNewerThan";
    case "Between":
      return "dateBetween";
    case "Yesterday":
      return "yesterday";
    case "Today":
      return "today";
    case "Tomorrow":
      return "tomorrow";
    case "ThisWeek":
      return "thisWeek";
    case "LastWeek":
      return "lastWeek";
    case "NextWeek":
      return "nextWeek";
    case "ThisMonth":
      return "thisMonth";
    case "LastMonth":
      return "lastMonth";
    case "NextMonth":
      return "nextMonth";
    case "ThisQuarter":
      return "thisQuarter";
    case "LastQuarter":
      return "lastQuarter";
    case "NextQuarter":
      return "nextQuarter";
    case "ThisYear":
      return "thisYear";
    case "LastYear":
      return "lastYear";
    case "NextYear":
      return "nextYear";
    case "YearToDate":
      return "yearToDate";
    case "AllDatesInPeriodJanuary":
      return "M1";
    case "AllDatesInPeriodFebruary":
      return "M2";
    case "AllDatesInPeriodMarch":
      return "M3";
    case "AllDatesInPeriodApril":
      return "M4";
    case "AllDatesInPeriodMay":
      return "M5";
    case "AllDatesInPeriodJune":
      return "M6";
    case "AllDatesInPeriodJuly":
      return "M7";
    case "AllDatesInPeriodAugust":
      return "M8";
    case "AllDatesInPeriodSeptember":
      return "M9";
    case "AllDatesInPeriodOctober":
      return "M10";
    case "AllDatesInPeriodNovember":
      return "M11";
    case "AllDatesInPeriodDecember":
      return "M12";
    default:
      return "unknown";
  }
}

// node_modules/@oai/granola/dist/models/pivot-table.js
init_address_utils();

// node_modules/@oai/granola/dist/models/pivot-style-hints.js
function buildPivotCellRenderHintKey(row2, col) {
  return `${row2}:${col}`;
}
function parsePivotCellRenderHintKey(key) {
  const sep = key.indexOf(":");
  if (sep < 0)
    return null;
  const row2 = Number.parseInt(key.slice(0, sep), 10);
  const col = Number.parseInt(key.slice(sep + 1), 10);
  if (!Number.isFinite(row2) || !Number.isFinite(col))
    return null;
  return { row: row2, col };
}

// node_modules/@oai/granola/dist/models/spreadsheet/pivots/pivot-openxml-axis-compiler.js
function compilePivotAxisEnum(kind) {
  switch (kind) {
    case "rows":
      return 1 /* PIVOT_AXIS_ROW */;
    case "columns":
      return 2 /* PIVOT_AXIS_COLUMN */;
    case "filters":
      return 3 /* PIVOT_AXIS_PAGE */;
    case "values":
      return 4 /* PIVOT_AXIS_VALUES */;
    default:
      return 0 /* PIVOT_AXIS_UNSPECIFIED */;
  }
}
function compilePivotAxisToken(kind) {
  switch (kind) {
    case "rows":
      return "axisRow";
    case "columns":
      return "axisCol";
    case "filters":
      return "axisPage";
    case "values":
      return "axisValues";
    default:
      return;
  }
}

// node_modules/@oai/granola/dist/models/pivot-table.js
var PIVOT_TABLE_PROTO = new WeakMap;
var PIVOT_CACHE_PROTO = new WeakMap;
var PIVOT_SOURCE = new WeakMap;
var PIVOT_TABLE_WRAPPERS = new WeakMap;
var PIVOT_LAYOUT_META = new WeakMap;
var PIVOT_RENDER_HINTS = new WeakMap;

class PivotTable2 {
  #workbook;
  #worksheet;
  #layout;
  #hierarchies;
  #rowHierarchies;
  #columnHierarchies;
  #dataHierarchies;
  #filterHierarchies;
  #pivotFields;
  #allHierarchies;
  #rowHierarchyOrder;
  #columnHierarchyOrder;
  #filterHierarchyOrder;
  #hierarchyByFieldIndex;
  #deleteListeners;
  #nameChangeListeners;
  constructor(options) {
    this.#workbook = options.workbook;
    this.#worksheet = options.worksheet;
    this.#deleteListeners = new Set;
    this.#nameChangeListeners = new Set;
    PIVOT_TABLE_PROTO.set(this, options.pivot);
    PIVOT_CACHE_PROTO.set(this, options.cache);
    PIVOT_SOURCE.set(this, options.source);
    PIVOT_LAYOUT_META.set(this, {
      fillEmptyCells: false,
      preserveFormatting: false,
      emptyCellText: ""
    });
    PIVOT_RENDER_HINTS.set(this, new Map);
    this.#layout = new PivotLayout(this);
    const pivotProto = this.#pivotProto();
    pivotProto.pivotFields ??= [];
    this.#pivotFields = [];
    this.#allHierarchies = [];
    this.#hierarchyByFieldIndex = new Map;
    pivotProto.pivotFields.forEach((fieldProto) => {
      const field = new PivotField2(fieldProto, { pivotTable: this });
      field.__ensureIndex(pivotProto.pivotFields);
      const hierarchy2 = new PivotHierarchy(field);
      this.#pivotFields.push(field);
      this.#allHierarchies.push(hierarchy2);
      this.#hierarchyByFieldIndex.set(fieldProto.index, hierarchy2);
    });
    this.#syncPivotFieldItemsFromCache();
    this.#hierarchies = new PivotHierarchyCollection({
      pivotTable: this,
      kind: "all",
      source: this.#allHierarchies
    });
    this.#rowHierarchyOrder = [];
    this.#columnHierarchyOrder = [];
    this.#filterHierarchyOrder = [];
    this.#restoreHierarchyAssignments();
    this.#rowHierarchies = new PivotHierarchyCollection({
      pivotTable: this,
      kind: "row"
    });
    this.#columnHierarchies = new PivotHierarchyCollection({
      pivotTable: this,
      kind: "column"
    });
    this.#filterHierarchies = new PivotHierarchyCollection({
      pivotTable: this,
      kind: "filter"
    });
    const dataFieldWrappers = (pivotProto.dataFields ?? []).map((dataField) => new PivotDataHierarchy(dataField, { pivotTable: this }));
    this.#dataHierarchies = new PivotDataHierarchyCollection({
      pivotTable: this,
      items: dataFieldWrappers
    });
    this.#syncPivotFieldAxes();
    if (options.onDelete)
      this.addDeleteListener(options.onDelete);
    if (options.onNameChange)
      this.addNameChangeListener(options.onNameChange);
    PIVOT_TABLE_WRAPPERS.set(options.pivot, this);
  }
  get workbook() {
    return this.#workbook;
  }
  get worksheet() {
    return this.#worksheet;
  }
  get name() {
    return this.#pivotProto().name;
  }
  set name(value) {
    const proto = this.#pivotProto();
    const previous = proto.name || undefined;
    proto.name = value;
    this.#worksheet.__queueCollaborativePublish();
    for (const listener of this.#nameChangeListeners) {
      listener(this, previous, value);
    }
  }
  get layout() {
    return this.#layout;
  }
  get hierarchies() {
    return this.#hierarchies;
  }
  get rowHierarchies() {
    return this.#rowHierarchies;
  }
  get columnHierarchies() {
    return this.#columnHierarchies;
  }
  get dataHierarchies() {
    return this.#dataHierarchies;
  }
  get filterHierarchies() {
    return this.#filterHierarchies;
  }
  _assignHierarchy(kind, hierarchy2) {
    this.#assertHierarchyBelongs(hierarchy2);
    const targetList = this.#getHierarchyList(kind);
    this.#detachHierarchy(hierarchy2);
    if (!targetList.includes(hierarchy2)) {
      targetList.push(hierarchy2);
    }
    this.#syncProtoAssignments();
    this.#worksheet.__queueCollaborativePublish();
  }
  _getHierarchies(kind) {
    if (kind === "all") {
      return [...this.#allHierarchies];
    }
    return [...this.#getHierarchyList(kind)];
  }
  _getHierarchyByFieldIndex(index) {
    return this.#hierarchyByFieldIndex.get(index);
  }
  _ensureHierarchyIndex(hierarchy2) {
    this.#assertHierarchyBelongs(hierarchy2);
    return this.#hierarchyIndex(hierarchy2);
  }
  delete() {
    for (const listener of this.#deleteListeners) {
      listener(this);
    }
  }
  get cache() {
    return getPivotCacheProto(this);
  }
  toProto() {
    return this.#pivotProto();
  }
  rebuildCache() {
    const pivotProto = this.#pivotProto();
    const cacheProto = getPivotCacheProto(this);
    const source = getPivotSource(this);
    cacheProto.worksheetSourceReference = source.address.length > 0 ? source.address : undefined;
    cacheProto.worksheetSourceSheet = source.address.length > 0 ? source.worksheet.name : undefined;
    let headers;
    let rows;
    if (source.address.length > 0) {
      const range2 = source.worksheet.getRange(source.address);
      const values = range2.values;
      if (values.length === 0) {
        cacheProto.fields = [];
        cacheProto.recordCount = 0;
        this.#syncPivotFieldItemsFromCache();
        recomputePivotTable(this);
        return;
      }
      const headersRaw = values[0] ?? [];
      const colCount = headersRaw.length;
      headers = headersRaw.map((value, idx) => value != null && value !== "" ? String(value) : `Column${idx + 1}`);
      rows = [];
      for (let i = 1;i < values.length; i++) {
        const row2 = values[i] ?? [];
        const normalized = [];
        let hasValue = false;
        for (let c = 0;c < colCount; c++) {
          const cell = row2[c];
          normalized[c] = cell ?? null;
          if (cell != null && cell !== "") {
            hasValue = true;
          }
        }
        if (hasValue)
          rows.push(normalized);
      }
    } else {
      headers = [...source.headers];
      rows = source.rows.map((row2) => [...row2]);
      if (headers.length === 0) {
        cacheProto.fields = [];
        cacheProto.recordCount = rows.length;
        this.#syncPivotFieldItemsFromCache();
        recomputePivotTable(this);
        return;
      }
    }
    const sharedValuesFieldIndices = new Set;
    const rowFields = Array.isArray(pivotProto.rowFields) ? pivotProto.rowFields : [];
    const columnFields = Array.isArray(pivotProto.columnFields) ? pivotProto.columnFields : [];
    const pageFields = Array.isArray(pivotProto.pageFields) ? pivotProto.pageFields : [];
    for (const idx of rowFields) {
      if (typeof idx === "number" && idx >= 0)
        sharedValuesFieldIndices.add(idx);
    }
    for (const idx of columnFields) {
      if (typeof idx === "number" && idx >= 0)
        sharedValuesFieldIndices.add(idx);
    }
    for (const field of pageFields) {
      const idx = field?.field;
      if (typeof idx === "number" && idx >= 0)
        sharedValuesFieldIndices.add(idx);
    }
    const numFmtIdByFieldIndex = new Map;
    const pivotFields = Array.isArray(pivotProto.pivotFields) ? pivotProto.pivotFields : [];
    for (let i = 0;i < pivotFields.length; i++) {
      const pivotField = pivotFields[i];
      const fmtId = pivotField?.numberFormatId;
      if (typeof fmtId === "number") {
        numFmtIdByFieldIndex.set(i, fmtId);
      }
    }
    const dataFields = Array.isArray(pivotProto.dataFields) ? pivotProto.dataFields : [];
    for (const dataField of dataFields) {
      const idx = dataField?.field;
      const fmtId = dataField?.numberFormatId;
      if (typeof idx === "number" && typeof fmtId === "number" && !numFmtIdByFieldIndex.has(idx)) {
        numFmtIdByFieldIndex.set(idx, fmtId);
      }
    }
    rebuildPivotCacheFromSource(cacheProto, {
      headers,
      rows,
      sharedValuesFieldIndices,
      numFmtIdByFieldIndex
    });
    cacheProto.recordCount = rows.length;
    this.#syncPivotFieldItemsFromCache();
    recomputePivotTable(this);
  }
  #restoreHierarchyAssignments() {
    const pivot = this.#pivotProto();
    const rowFields = Array.isArray(pivot.rowFields) ? pivot.rowFields : [];
    const columnFields = Array.isArray(pivot.columnFields) ? pivot.columnFields : [];
    const pageFields = Array.isArray(pivot.pageFields) ? pivot.pageFields : [];
    this.#rowHierarchyOrder = this.#mapIndicesToHierarchies(rowFields);
    this.#columnHierarchyOrder = this.#mapIndicesToHierarchies(columnFields);
    this.#filterHierarchyOrder = this.#mapPageFieldsToHierarchies(pageFields);
  }
  #mapIndicesToHierarchies(indices) {
    const seen = new Set;
    const list = [];
    for (const index of indices) {
      const hierarchy2 = this.#hierarchyByFieldIndex.get(index);
      if (hierarchy2 && !seen.has(hierarchy2)) {
        seen.add(hierarchy2);
        list.push(hierarchy2);
      }
    }
    return list;
  }
  #mapPageFieldsToHierarchies(pageFields) {
    const seen = new Set;
    const list = [];
    for (const field of pageFields) {
      if (field.field == null)
        continue;
      const hierarchy2 = this.#hierarchyByFieldIndex.get(field.field);
      if (hierarchy2 && !seen.has(hierarchy2)) {
        seen.add(hierarchy2);
        list.push(hierarchy2);
      }
    }
    return list;
  }
  #syncProtoAssignments() {
    const pivot = this.#pivotProto();
    pivot.rowFields = this.#rowHierarchyOrder.map((hierarchy2) => this.#hierarchyIndex(hierarchy2));
    pivot.columnFields = this.#columnHierarchyOrder.map((hierarchy2) => this.#hierarchyIndex(hierarchy2));
    pivot.pageFields = this.#filterHierarchyOrder.map((hierarchy2) => {
      const fieldIndex = this.#hierarchyIndex(hierarchy2);
      const entry = {
        field: fieldIndex,
        item: undefined,
        name: hierarchy2.name
      };
      return entry;
    });
    this.#syncPivotFieldAxes();
  }
  #hierarchyIndex(hierarchy2) {
    const pivot = this.#pivotProto();
    const field = getPivotHierarchyField(hierarchy2);
    const index = field.__ensureIndex(pivot.pivotFields);
    this.#hierarchyByFieldIndex.set(index, hierarchy2);
    return index;
  }
  #detachHierarchy(hierarchy2) {
    this.#removeHierarchy(this.#rowHierarchyOrder, hierarchy2);
    this.#removeHierarchy(this.#columnHierarchyOrder, hierarchy2);
    this.#removeHierarchy(this.#filterHierarchyOrder, hierarchy2);
  }
  #removeHierarchy(list, hierarchy2) {
    const idx = list.indexOf(hierarchy2);
    if (idx >= 0) {
      list.splice(idx, 1);
    }
  }
  #getHierarchyList(kind) {
    switch (kind) {
      case "row":
        return this.#rowHierarchyOrder;
      case "column":
        return this.#columnHierarchyOrder;
      case "filter":
        return this.#filterHierarchyOrder;
      default:
        throw new Error(`Unknown hierarchy kind: ${kind}`);
    }
  }
  #assertHierarchyBelongs(hierarchy2) {
    if (!this.#allHierarchies.includes(hierarchy2)) {
      throw new Error("Hierarchy does not belong to this PivotTable");
    }
  }
  #pivotProto() {
    const proto = PIVOT_TABLE_PROTO.get(this);
    if (!proto) {
      throw new Error("PivotTable proto not found");
    }
    return proto;
  }
  addDeleteListener(listener) {
    this.#deleteListeners.add(listener);
  }
  removeDeleteListener(listener) {
    this.#deleteListeners.delete(listener);
  }
  addNameChangeListener(listener) {
    this.#nameChangeListeners.add(listener);
  }
  removeNameChangeListener(listener) {
    this.#nameChangeListeners.delete(listener);
  }
  __getLayoutType() {
    const proto = this.#pivotProto();
    if (proto.outline)
      return LayoutType.outline;
    if (proto.compact === false)
      return LayoutType.tabular;
    return LayoutType.compact;
  }
  __setLayoutType(value) {
    const proto = this.#pivotProto();
    switch (value) {
      case LayoutType.compact:
        proto.compact = true;
        proto.outline = false;
        break;
      case LayoutType.outline:
        proto.compact = false;
        proto.outline = true;
        break;
      case LayoutType.tabular:
      default:
        proto.compact = false;
        proto.outline = false;
        break;
    }
    this.#worksheet.__queueCollaborativePublish();
    recomputePivotTable(this);
  }
  __getLayoutMeta() {
    return { ...PIVOT_LAYOUT_META.get(this) ?? this.#defaultLayoutMeta() };
  }
  __setLayoutMeta(update) {
    const current = PIVOT_LAYOUT_META.get(this) ?? this.#defaultLayoutMeta();
    PIVOT_LAYOUT_META.set(this, { ...current, ...update });
    this.#worksheet.__queueCollaborativePublish();
  }
  #defaultLayoutMeta() {
    return {
      fillEmptyCells: false,
      preserveFormatting: false,
      emptyCellText: ""
    };
  }
  __getLocationForLayout() {
    const location2 = this.#pivotProto().location;
    return {
      reference: location2?.reference ?? "",
      firstHeaderRow: location2?.firstHeaderRow ?? 0,
      firstDataRow: location2?.firstDataRow ?? 0,
      firstHeaderColumn: location2?.firstHeaderColumn ?? 0,
      firstDataColumn: location2?.firstDataColumn ?? 0
    };
  }
  __getDataBodyShapeForLayout() {
    const proto = this.#pivotProto();
    const dataRowCount = Array.isArray(proto.rowItems) ? proto.rowItems.length : 0;
    const dataColCount = Array.isArray(proto.columnItems) ? proto.columnItems.length : 0;
    return { dataRowCount, dataColCount };
  }
  __setRowItems(items) {
    this.#pivotProto().rowItems = items ?? [];
  }
  __setColumnItems(items) {
    this.#pivotProto().columnItems = items ?? [];
  }
  __clearPivotCellRenderHints() {
    const hints = PIVOT_RENDER_HINTS.get(this);
    if (!hints) {
      PIVOT_RENDER_HINTS.set(this, new Map);
      return;
    }
    hints.clear();
  }
  __setPivotCellRenderHint(row2, col, hint) {
    const hints = PIVOT_RENDER_HINTS.get(this);
    const key = buildPivotCellRenderHintKey(row2, col);
    if (!hints) {
      PIVOT_RENDER_HINTS.set(this, new Map([[key, hint]]));
      return;
    }
    hints.set(key, hint);
  }
  __getPivotCellRenderHint(row2, col) {
    const hints = PIVOT_RENDER_HINTS.get(this);
    if (!hints)
      return null;
    return hints.get(buildPivotCellRenderHintKey(row2, col)) ?? null;
  }
  __getPivotCellRenderHints() {
    const hints = PIVOT_RENDER_HINTS.get(this);
    if (!hints) {
      const next = new Map;
      PIVOT_RENDER_HINTS.set(this, next);
      return next;
    }
    return hints;
  }
  __findDataFieldProto(fieldIndex) {
    const pivotProto = this.#pivotProto();
    const dataFields = Array.isArray(pivotProto.dataFields) ? pivotProto.dataFields : [];
    return dataFields.find((dataField) => dataField.field === fieldIndex);
  }
  __addDataFieldProto(proto) {
    const pivotProto = this.#pivotProto();
    pivotProto.dataFields ??= [];
    pivotProto.dataFields.push(proto);
    this.#syncPivotFieldAxes();
    this.#worksheet.__queueCollaborativePublish();
  }
  __getPivotFieldProtos() {
    const pivotProto = this.#pivotProto();
    pivotProto.pivotFields ??= [];
    return pivotProto.pivotFields;
  }
  __updateLocation(update) {
    const proto = this.#pivotProto();
    proto.location ??= {
      reference: update.reference,
      firstHeaderRow: update.firstHeaderRow,
      firstDataRow: update.firstDataRow,
      firstHeaderColumn: update.firstHeaderColumn,
      firstDataColumn: update.firstDataColumn
    };
    proto.location.reference = update.reference;
    proto.location.firstHeaderRow = update.firstHeaderRow;
    proto.location.firstDataRow = update.firstDataRow;
    proto.location.firstHeaderColumn = update.firstHeaderColumn;
    proto.location.firstDataColumn = update.firstDataColumn;
    this.#worksheet.__queueCollaborativePublish();
  }
  __applyFilterForField(field, options) {
    const pivotProto = this.#pivotProto();
    pivotProto.filters ??= [];
    const index = field.__ensureIndex(pivotProto.pivotFields);
    pivotProto.filters = pivotProto.filters.filter((filter2) => filter2.field !== index);
    const { descriptor, typeToken, typeEnum } = this.#compileFilter(options);
    const filter = {
      field: index,
      type: typeToken,
      typeEnum,
      name: field.name,
      description: JSON.stringify(descriptor)
    };
    pivotProto.filters.push(filter);
    this.#worksheet.__queueCollaborativePublish();
    recomputePivotTable(this);
  }
  __clearAllFiltersForField(field) {
    const pivotProto = this.#pivotProto();
    if (!pivotProto.filters)
      return;
    const index = field.__ensureIndex(pivotProto.pivotFields);
    pivotProto.filters = pivotProto.filters.filter((filter) => filter.field !== index);
    this.#worksheet.__queueCollaborativePublish();
    recomputePivotTable(this);
  }
  #compileFilter(options) {
    const provided = [
      options.dateFilter ? "dateFilter" : null,
      options.labelFilter ? "labelFilter" : null,
      options.manualFilter ? "manualFilter" : null,
      options.valueFilter ? "valueFilter" : null
    ].filter((value) => value != null);
    if (provided.length !== 1) {
      throw new Error("Exactly one filter type must be provided");
    }
    const kind = provided[0];
    switch (kind) {
      case "dateFilter": {
        const payload = options.dateFilter;
        const descriptor = { kind, payload };
        const typeToken = compilePivotDateFilterTypeToken(payload.condition);
        return {
          descriptor,
          typeToken,
          typeEnum: 0 /* PIVOT_FILTER_TYPE_UNSPECIFIED */
        };
      }
      case "labelFilter": {
        const payload = options.labelFilter;
        const descriptor = { kind, payload };
        const typeToken = compilePivotLabelFilterTypeToken(payload.condition);
        return {
          descriptor,
          typeToken,
          typeEnum: 0 /* PIVOT_FILTER_TYPE_UNSPECIFIED */
        };
      }
      case "valueFilter": {
        const payload = options.valueFilter;
        const descriptor = { kind, payload };
        const typeToken = compilePivotValueFilterTypeToken(payload.condition);
        return {
          descriptor,
          typeToken,
          typeEnum: 0 /* PIVOT_FILTER_TYPE_UNSPECIFIED */
        };
      }
      case "manualFilter": {
        const payload = options.manualFilter;
        const descriptor = { kind, payload };
        return {
          descriptor,
          typeToken: "unknown",
          typeEnum: 0 /* PIVOT_FILTER_TYPE_UNSPECIFIED */
        };
      }
      default:
        throw new Error("Unsupported filter type");
    }
  }
  preview() {
    const pivotProto = this.#pivotProto();
    const location2 = pivotProto.location;
    const ref = location2?.reference ?? "";
    const parsed = ref ? parseRangeAddress(ref) : null;
    if (!parsed) {
      return {
        grid: [],
        header: { headerRows: 0, headerCols: 0 },
        bounds: { rowCount: 0, colCount: 0 }
      };
    }
    const range2 = this.#worksheet.getRange(parsed.ref);
    const values = range2.values;
    const rowCount = values.length;
    const colCount = values[0]?.length ?? 0;
    return {
      grid: values,
      header: {
        headerRows: Math.max(0, location2?.firstDataRow ?? 0),
        headerCols: Math.max(0, location2?.firstDataColumn ?? 0)
      },
      bounds: { rowCount, colCount }
    };
  }
  #syncPivotFieldItemsFromCache() {
    const pivotProto = this.#pivotProto();
    const cacheProto = getPivotCacheProto(this);
    const cacheFields = Array.isArray(cacheProto.fields) ? cacheProto.fields : [];
    for (let i = 0;i < pivotProto.pivotFields.length; i++) {
      const pivotField = pivotProto.pivotFields[i];
      if (!pivotField)
        continue;
      const fieldIndex = pivotField.index ?? i;
      const cacheField = cacheFields[fieldIndex];
      const sharedValues = cacheField?.sharedItems?.values ?? [];
      if (Array.isArray(pivotField.items) && pivotField.items.length > 0) {
        continue;
      }
      const seededItems = sharedValues.map((value, idx) => {
        return {
          index: idx,
          type: undefined,
          hidden: undefined,
          calculated: undefined,
          missing: undefined,
          displayName: value
        };
      });
      seededItems.sort((a, b) => {
        const aLabel = String(a.displayName ?? "");
        const bLabel = String(b.displayName ?? "");
        return aLabel.localeCompare(bLabel);
      });
      pivotField.items = seededItems;
    }
  }
  #syncPivotFieldAxes() {
    const pivotProto = this.#pivotProto();
    const pivotFields = pivotProto.pivotFields ?? [];
    for (const field of pivotFields) {
      if (!field)
        continue;
      field.axis = undefined;
      field.axisEnum = undefined;
      field.dataField = false;
    }
    const applyAxis = (hierarchies, kind) => {
      for (const hierarchy2 of hierarchies) {
        const idx = this.#hierarchyIndex(hierarchy2);
        const field = pivotFields[idx];
        if (!field)
          continue;
        field.axisEnum = compilePivotAxisEnum(kind);
        field.axis = compilePivotAxisToken(kind);
      }
    };
    applyAxis(this.#rowHierarchyOrder, "rows");
    applyAxis(this.#columnHierarchyOrder, "columns");
    applyAxis(this.#filterHierarchyOrder, "filters");
    const dataFields = Array.isArray(pivotProto.dataFields) ? pivotProto.dataFields : [];
    for (const dataField of dataFields) {
      const idx = dataField.field ?? -1;
      const field = pivotFields[idx];
      if (!field)
        continue;
      field.dataField = true;
      field.axisEnum = compilePivotAxisEnum("values");
      field.axis = compilePivotAxisToken("values");
    }
  }
}
function getPivotTableProto(pivotTable) {
  const proto = PIVOT_TABLE_PROTO.get(pivotTable);
  if (!proto) {
    throw new Error("PivotTable proto not found");
  }
  return proto;
}
function getPivotCacheProto(pivotTable) {
  const proto = PIVOT_CACHE_PROTO.get(pivotTable);
  if (!proto) {
    throw new Error("PivotCache proto not found");
  }
  return proto;
}
function getPivotSource(pivotTable) {
  const source = PIVOT_SOURCE.get(pivotTable);
  if (!source) {
    throw new Error("PivotTable source not found");
  }
  if (!source.address) {
    return source;
  }
  const refreshed = buildPivotSourceSnapshot(source);
  PIVOT_SOURCE.set(pivotTable, refreshed);
  return refreshed;
}
function getOrCreatePivotTable(options) {
  const existing = PIVOT_TABLE_WRAPPERS.get(options.pivot);
  if (existing) {
    if (options.onDelete)
      existing.addDeleteListener(options.onDelete);
    if (options.onNameChange)
      existing.addNameChangeListener(options.onNameChange);
    const existingSource = PIVOT_SOURCE.get(existing);
    if (!existingSource || shouldReplacePivotSource(existingSource, options.source)) {
      PIVOT_SOURCE.set(existing, buildPivotSourceSnapshot(options.source));
    }
    return existing;
  }
  return new PivotTable2(options);
}
function shouldReplacePivotSource(current, next) {
  if (current.address.length === 0 && next.address.length > 0)
    return true;
  if (current.headers.length === 0 && next.headers.length > 0)
    return true;
  if (current.rows.length === 0 && next.rows.length > 0)
    return true;
  if (next.headers.length > current.headers.length)
    return true;
  if (next.rows.length > current.rows.length)
    return true;
  if (current.worksheet !== next.worksheet && next.address.length > 0 && next.rows.length >= current.rows.length) {
    return true;
  }
  return false;
}
function buildPivotSourceSnapshot(source) {
  if (!source.address) {
    return {
      headers: [...source.headers],
      rows: source.rows.map((row2) => [...row2]),
      address: source.address,
      worksheet: source.worksheet
    };
  }
  const range2 = source.worksheet.getRange(source.address);
  const values = range2.values;
  const headersRaw = values[0] ?? [];
  const colCount = headersRaw.length;
  const headers = headersRaw.map((value, idx) => value != null && value !== "" ? String(value) : `Column${idx + 1}`);
  const rows = [];
  for (let i = 1;i < values.length; i++) {
    const row2 = values[i] ?? [];
    const normalized = [];
    let hasValue = false;
    for (let c = 0;c < colCount; c++) {
      const cell = row2[c];
      normalized[c] = cell ?? null;
      if (cell != null && cell !== "") {
        hasValue = true;
      }
    }
    if (hasValue)
      rows.push(normalized);
  }
  return {
    headers,
    rows,
    address: source.address,
    worksheet: source.worksheet
  };
}

// node_modules/@oai/granola/dist/models/spreadsheet/preset-style-schema.js
var TABLE_STYLE_ELEMENT_TYPES = [
  "wholeTable",
  "headerRow",
  "totalRow",
  "firstColumn",
  "lastColumn",
  "firstRowStripe",
  "secondRowStripe",
  "firstColumnStripe",
  "secondColumnStripe"
];
var PIVOT_STYLE_ELEMENT_TYPES = [
  "wholeTable",
  "headerRow",
  "totalRow",
  "firstColumn",
  "firstRowStripe",
  "secondRowStripe",
  "firstColumnStripe",
  "secondColumnStripe",
  "firstHeaderCell",
  "firstSubtotalColumn",
  "firstSubtotalRow",
  "secondSubtotalRow",
  "firstColumnSubheading",
  "secondColumnSubheading",
  "thirdColumnSubheading",
  "firstRowSubheading",
  "secondRowSubheading",
  "thirdRowSubheading",
  "pageFieldLabels",
  "pageFieldValues"
];
var BORDER_EDGE_NAMES = [
  "left",
  "right",
  "top",
  "bottom",
  "horizontal",
  "vertical"
];
var BORDER_STYLE_NAMES = [
  "thin",
  "medium",
  "double",
  "thick"
];

// node_modules/@oai/granola/dist/models/spreadsheet/preset-style-data.generated.js
var DEFAULT_XML_TABLE_STYLE_NAME = "TableStyleMedium9";
var PRESET_STYLE_COLOR_DEFS = [[9, 59999], [1], [9], [9, 79998], [9, 39998], [8, 59999], [8], [8, 79998], [8, 39998], [7, 59999], [7], [7, 79998], [7, 39998], [6, 59999], [6], [6, 79998], [6, 39998], [5, 59999], [5], [5, 79998], [5, 39998], [4, 59999], [4], [4, 79998], [4, 39998], [0, -34999], [0, -15000], [0], [9, -24998], [8, -24998], [7, -24998], [6, -24998], [5, -24998], [4, -24998], [9, -49998], [8, -49998], [7, -49998], [6, -49998], [5, -49998], [4, -49998], [1, 24998], [1, 15000], [1, 45000], [1, 49998], [0, -24998], [0, -4999], [0, -45000], [0, -49998]];
var PRESET_STYLE_FONT_DEFS = [[1, 1], [0, 1], [1, 27], [1, 28], [0, 28], [1, 29], [0, 29], [1, 30], [0, 30], [1, 31], [0, 31], [1, 32], [0, 32], [1, 33], [0, 33], [0, 27], [1, 43], [0, 43], [1, 2], [1, 6], [1, 10], [1, 14], [1, 18], [0, 22], [0, 3], [0, 7], [0, 11], [0, 15], [0, 19], [0, 23], [1, 26], [0, 26]];
var PRESET_STYLE_FILL_DEFS = [0, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 26, 2, 6, 10, 14, 18, 22, 1, 28, 34, 29, 35, 30, 36, 31, 37, 32, 38, 33, 39, 40, 41, 42, 44, 45, 43, 4, 8, 12, 16, 20, 24, 27, 46, 47];
var PRESET_STYLE_LINE_DEFS = [[1, 2], [0, 4], [1, 6], [0, 8], [1, 10], [0, 12], [1, 14], [0, 16], [1, 18], [0, 20], [1, 22], [0, 24], [1, 1], [0, 1], [2, 1], [3, 27], [0, 27], [2, 2], [2, 6], [2, 10], [2, 14], [2, 18], [2, 22], [0, 2], [0, 6], [0, 10], [0, 14], [0, 18], [0, 22], [1, 27], [0, 0], [0, 5], [0, 9], [0, 13], [0, 17], [0, 21], [0, 44], [0, 25], [0, 26], [1, 0], [0, 28], [1, 28], [1, 5], [0, 29], [1, 29], [1, 9], [0, 30], [1, 30], [1, 13], [0, 31], [1, 31], [1, 17], [0, 32], [1, 32], [1, 21], [0, 33], [1, 33], [1, 44], [1, 26], [1, 43], [0, 3], [2, 28], [0, 7], [2, 29], [0, 11], [2, 30], [0, 15], [2, 31], [0, 19], [2, 32], [0, 23], [2, 33], [0, 43], [2, 43], [0, 46], [1, 3], [1, 7], [1, 11], [1, 15], [1, 19], [1, 23], [0, 34], [0, 35], [0, 36], [0, 37], [0, 38], [0, 39]];
var PRESET_STYLE_BORDER_DEFS = [[2, 0], [0, 1, 1, 1, 2, 1, 3, 1, 5, 1, 4, 1], [2, 2], [0, 3, 1, 3, 2, 3, 3, 3, 5, 3, 4, 3], [2, 4], [0, 5, 1, 5, 2, 5, 3, 5, 5, 5, 4, 5], [2, 6], [0, 7, 1, 7, 2, 7, 3, 7, 5, 7, 4, 7], [2, 8], [0, 9, 1, 9, 2, 9, 3, 9, 5, 9, 4, 9], [2, 10], [0, 11, 1, 11, 2, 11, 3, 11, 5, 11, 4, 11], [2, 12], [0, 13, 1, 13, 2, 13, 3, 13, 5, 13, 4, 13], [2, 14], [3, 12], [2, 12, 3, 12], [0, 13, 1, 13, 2, 12, 3, 12, 5, 13, 4, 13], [2, 15], [3, 15], [5, 16, 4, 16], [2, 17], [0, 1, 1, 1, 2, 1, 3, 1, 4, 1], [2, 18], [0, 3, 1, 3, 2, 3, 3, 3, 4, 3], [2, 19], [0, 5, 1, 5, 2, 5, 3, 5, 4, 5], [2, 20], [0, 7, 1, 7, 2, 7, 3, 7, 4, 7], [2, 21], [0, 9, 1, 9, 2, 9, 3, 9, 4, 9], [2, 22], [0, 11, 1, 11, 2, 11, 3, 11, 4, 11], [0, 13, 1, 13, 2, 13, 3, 13, 4, 13], [3, 0], [0, 23, 1, 23, 2, 23, 3, 23, 5, 23, 4, 23], [3, 2], [0, 24, 1, 24, 2, 24, 3, 24, 5, 24, 4, 24], [3, 4], [0, 25, 1, 25, 2, 25, 3, 25, 5, 25, 4, 25], [3, 6], [0, 26, 1, 26, 2, 26, 3, 26, 5, 26, 4, 26], [3, 8], [0, 27, 1, 27, 2, 27, 3, 27, 5, 27, 4, 27], [3, 10], [0, 28, 1, 28, 2, 28, 3, 28, 5, 28, 4, 28], [0, 23], [2, 23], [0, 23, 1, 23, 2, 23, 3, 23], [0, 24], [2, 24], [0, 24, 1, 24, 2, 24, 3, 24], [0, 25], [2, 25], [0, 25, 1, 25, 2, 25, 3, 25], [0, 26], [2, 26], [0, 26, 1, 26, 2, 26, 3, 26], [0, 27], [2, 27], [0, 27, 1, 27, 2, 27, 3, 27], [0, 28], [2, 28], [0, 28, 1, 28, 2, 28, 3, 28], [0, 13], [2, 13], [0, 13, 1, 13, 2, 13, 3, 13], [3, 23], [2, 23, 3, 23], [3, 24], [2, 24, 3, 24], [3, 25], [2, 25, 3, 25], [3, 26], [2, 26, 3, 26], [3, 27], [2, 27, 3, 27], [3, 28], [2, 28, 3, 28], [3, 13], [2, 13, 3, 13], [0, 29], [1, 29], [2, 29], [3, 29], [3, 16], [5, 16], [3, 30], [0, 1, 1, 1, 2, 1], [0, 30, 1, 30], [2, 30, 3, 30], [0, 30, 1, 30, 5, 30], [3, 31], [0, 3, 1, 3, 2, 3], [0, 31, 1, 31], [2, 31, 3, 31], [0, 31, 1, 31, 5, 31], [3, 32], [0, 5, 1, 5, 2, 5], [0, 32, 1, 32], [2, 32, 3, 32], [0, 32, 1, 32, 5, 32], [3, 33], [0, 7, 1, 7, 2, 7], [0, 33, 1, 33], [2, 33, 3, 33], [0, 33, 1, 33, 5, 33], [3, 34], [0, 9, 1, 9, 2, 9], [0, 34, 1, 34], [2, 34, 3, 34], [0, 34, 1, 34, 5, 34], [3, 35], [0, 11, 1, 11, 2, 11], [0, 35, 1, 35], [2, 35, 3, 35], [0, 35, 1, 35, 5, 35], [3, 36], [0, 37, 1, 37, 2, 37], [0, 36, 1, 36], [2, 36, 3, 36], [0, 38, 1, 38, 5, 38], [0, 39, 1, 39, 2, 39, 3, 39], [0, 1, 1, 1], [2, 1, 3, 1, 4, 1], [2, 40, 3, 41], [2, 41], [0, 42, 1, 42, 2, 42, 3, 42], [0, 3, 1, 3], [2, 3, 3, 3, 4, 3], [2, 43, 3, 44], [2, 44], [0, 45, 1, 45, 2, 45, 3, 45], [0, 5, 1, 5], [2, 5, 3, 5, 4, 5], [2, 46, 3, 47], [2, 47], [0, 48, 1, 48, 2, 48, 3, 48], [0, 7, 1, 7], [2, 7, 3, 7, 4, 7], [2, 49, 3, 50], [2, 50], [0, 51, 1, 51, 2, 51, 3, 51], [0, 9, 1, 9], [2, 9, 3, 9, 4, 9], [2, 52, 3, 53], [2, 53], [0, 54, 1, 54, 2, 54, 3, 54], [0, 11, 1, 11], [2, 11, 3, 11, 4, 11], [2, 55, 3, 56], [2, 56], [0, 57, 1, 57, 2, 57, 3, 57], [0, 58, 1, 58], [2, 36, 3, 36, 4, 36], [2, 13, 3, 59], [2, 59], [2, 60, 3, 60], [3, 60, 4, 1], [0, 40, 1, 40], [2, 40, 3, 40, 4, 40], [2, 61], [4, 40], [4, 60], [2, 62, 3, 62], [3, 62, 4, 3], [0, 43, 1, 43], [2, 43, 3, 43, 4, 43], [2, 63], [4, 43], [4, 62], [2, 64, 3, 64], [3, 64, 4, 5], [0, 46, 1, 46], [2, 46, 3, 46, 4, 46], [2, 65], [4, 46], [4, 64], [2, 66, 3, 66], [3, 66, 4, 7], [0, 49, 1, 49], [2, 49, 3, 49, 4, 49], [2, 67], [4, 49], [4, 66], [2, 68, 3, 68], [3, 68, 4, 9], [0, 52, 1, 52], [2, 52, 3, 52, 4, 52], [2, 69], [4, 52], [4, 68], [2, 70, 3, 70], [3, 70, 4, 11], [0, 55, 1, 55], [2, 55, 3, 55, 4, 55], [2, 71], [4, 55], [4, 70], [2, 38, 3, 38], [3, 38], [3, 38, 4, 38], [0, 72, 1, 72], [2, 72, 3, 72, 4, 72], [2, 73], [4, 72], [4, 38], [2, 72, 3, 72], [0, 23, 1, 23, 2, 23, 3, 23, 5, 23], [0, 24, 1, 24, 2, 24, 3, 24, 5, 24], [0, 25, 1, 25, 2, 25, 3, 25, 5, 25], [0, 26, 1, 26, 2, 26, 3, 26, 5, 26], [0, 27, 1, 27, 2, 27, 3, 27, 5, 27], [0, 28, 1, 28, 2, 28, 3, 28, 5, 28], [0, 37, 1, 37], [2, 72], [3, 72], [0, 72, 1, 72, 2, 72, 3, 72, 5, 72], [3, 1], [2, 1], [3, 3], [2, 3], [3, 5], [2, 5], [3, 7], [2, 7], [3, 9], [2, 9], [3, 11], [2, 11], [3, 37], [2, 37], [2, 60], [0, 30, 1, 30, 2, 30, 3, 30], [1, 23], [0, 0, 1, 0, 2, 0, 3, 0], [0, 0, 1, 0, 2, 0, 3, 0, 4, 16], [2, 62], [0, 31, 1, 31, 2, 31, 3, 31], [1, 24], [0, 2, 1, 2, 2, 2, 3, 2], [0, 2, 1, 2, 2, 2, 3, 2, 4, 16], [2, 64], [0, 32, 1, 32, 2, 32, 3, 32], [1, 25], [0, 4, 1, 4, 2, 4, 3, 4], [0, 4, 1, 4, 2, 4, 3, 4, 4, 16], [2, 66], [0, 33, 1, 33, 2, 33, 3, 33], [1, 26], [0, 6, 1, 6, 2, 6, 3, 6], [0, 6, 1, 6, 2, 6, 3, 6, 4, 16], [2, 68], [0, 34, 1, 34, 2, 34, 3, 34], [1, 27], [0, 8, 1, 8, 2, 8, 3, 8], [0, 8, 1, 8, 2, 8, 3, 8, 4, 16], [2, 70], [0, 35, 1, 35, 2, 35, 3, 35], [1, 28], [0, 10, 1, 10, 2, 10, 3, 10], [0, 10, 1, 10, 2, 10, 3, 10, 4, 16], [2, 37, 3, 37], [0, 74, 1, 74, 2, 74, 3, 74], [0, 37, 1, 37, 2, 37, 3, 37], [1, 72], [0, 59, 1, 59, 2, 59, 3, 59], [0, 59, 1, 59, 2, 59, 3, 59, 4, 16], [0, 30, 1, 30, 2, 30, 3, 30, 5, 30, 4, 30], [0, 31, 1, 31, 2, 31, 3, 31, 5, 31, 4, 31], [0, 32, 1, 32, 2, 32, 3, 32, 5, 32, 4, 32], [0, 33, 1, 33, 2, 33, 3, 33, 5, 33, 4, 33], [0, 34, 1, 34, 2, 34, 3, 34, 5, 34, 4, 34], [0, 35, 1, 35, 2, 35, 3, 35, 5, 35, 4, 35], [0, 37, 1, 37, 2, 37, 3, 37, 5, 37, 4, 37], [0, 1, 1, 1, 2, 1, 3, 1], [2, 1, 3, 1], [0, 3, 1, 3, 2, 3, 3, 3], [2, 3, 3, 3], [0, 5, 1, 5, 2, 5, 3, 5], [2, 5, 3, 5], [0, 7, 1, 7, 2, 7, 3, 7], [2, 7, 3, 7], [0, 9, 1, 9, 2, 9, 3, 9], [2, 9, 3, 9], [0, 11, 1, 11, 2, 11, 3, 11], [2, 11, 3, 11], [3, 70], [1, 59, 2, 59, 3, 59], [0, 59, 2, 59, 3, 59], [3, 75], [2, 75], [3, 76], [2, 76], [3, 77], [2, 77], [3, 78], [2, 78], [3, 79], [2, 79], [3, 80], [2, 80], [3, 58], [2, 57], [0, 74, 1, 74], [4, 81], [3, 60], [0, 60, 1, 60], [3, 23, 4, 81], [4, 82], [3, 62], [0, 62, 1, 62], [3, 24, 4, 82], [4, 83], [3, 64], [0, 64, 1, 64], [3, 25, 4, 83], [4, 84], [3, 66], [0, 66, 1, 66], [3, 26, 4, 84], [4, 85], [3, 68], [0, 68, 1, 68], [3, 27, 4, 85], [4, 86], [0, 70, 1, 70], [3, 28, 4, 86], [0, 38, 1, 38], [3, 16, 4, 72]];
var PRESET_STYLE_DXF_DEFS = [[-1, 0, -1], [0, -1, -1], [0, -1, 0], [1, 1, 1], [-1, 2, -1], [0, -1, 2], [1, 3, 3], [-1, 4, -1], [0, -1, 4], [1, 5, 5], [-1, 6, -1], [0, -1, 6], [1, 7, 7], [-1, 8, -1], [0, -1, 8], [1, 9, 9], [-1, 10, -1], [0, -1, 10], [1, 11, 11], [-1, 12, -1], [0, -1, 12], [1, 13, 13], [-1, 13, -1], [2, 14, -1], [-1, -1, 14], [2, 14, 15], [1, -1, 16], [2, 15, -1], [2, 15, 15], [2, 16, -1], [2, 16, 15], [2, 17, -1], [2, 17, 15], [2, 18, -1], [2, 18, 15], [2, 19, -1], [2, 19, 15], [2, 20, -1], [2, 20, 15], [1, -1, 17], [2, 14, 18], [2, 14, 19], [1, 1, 20], [2, 15, 18], [2, 15, 19], [1, 3, 20], [2, 16, 18], [2, 16, 19], [1, 5, 20], [2, 17, 18], [2, 17, 19], [1, 7, 20], [2, 18, 18], [2, 18, 19], [1, 9, 20], [2, 19, 18], [2, 19, 19], [1, 11, 20], [2, 20, 18], [2, 20, 19], [1, 13, 20], [-1, 1, -1], [0, -1, 21], [1, -1, 22], [-1, 3, -1], [0, -1, 23], [1, -1, 24], [-1, 5, -1], [0, -1, 25], [1, -1, 26], [-1, 7, -1], [0, -1, 27], [1, -1, 28], [-1, 9, -1], [0, -1, 29], [1, -1, 30], [-1, 11, -1], [0, -1, 31], [1, -1, 32], [0, -1, 14], [1, -1, 33], [0, -1, 34], [1, -1, 35], [0, -1, 36], [1, -1, 37], [0, -1, 38], [1, -1, 39], [0, -1, 40], [1, -1, 41], [0, -1, 42], [1, -1, 43], [0, -1, 44], [1, -1, 45], [0, -1, 15], [1, -1, 13], [-1, -1, 46], [-1, -1, 47], [1, -1, 48], [-1, -1, 49], [-1, -1, 50], [1, -1, 51], [-1, -1, 52], [-1, -1, 53], [1, -1, 54], [-1, -1, 55], [-1, -1, 56], [1, -1, 57], [-1, -1, 58], [-1, -1, 59], [1, -1, 60], [-1, -1, 61], [-1, -1, 62], [1, -1, 63], [-1, -1, 64], [-1, -1, 65], [1, -1, 66], [3, -1, -1], [3, -1, 47], [3, -1, 67], [4, -1, 68], [5, -1, -1], [5, -1, 50], [5, -1, 69], [6, -1, 70], [7, -1, -1], [7, -1, 53], [7, -1, 71], [8, -1, 72], [9, -1, -1], [9, -1, 56], [9, -1, 73], [10, -1, 74], [11, -1, -1], [11, -1, 59], [11, -1, 75], [12, -1, 76], [13, -1, -1], [13, -1, 62], [13, -1, 77], [14, -1, 78], [0, -1, 65], [0, -1, 79], [1, -1, 80], [15, 14, -1], [15, 16, -1], [15, 18, -1], [15, 20, -1], [-1, 21, -1], [2, 21, 81], [2, 21, 82], [2, 22, 83], [2, 20, 84], [-1, 23, -1], [2, 23, 81], [2, 23, 82], [2, 24, 83], [15, 15, -1], [-1, 25, -1], [2, 25, 81], [2, 25, 82], [2, 26, 83], [-1, 27, -1], [2, 27, 81], [2, 27, 82], [2, 28, 83], [15, 17, -1], [-1, 29, -1], [2, 29, 81], [2, 29, 82], [2, 30, 83], [-1, 31, -1], [2, 31, 81], [2, 31, 82], [2, 32, 83], [15, 19, -1], [-1, 33, -1], [2, 33, 81], [2, 33, 82], [2, 34, 83], [15, 35, -1], [3, 0, -1], [3, -1, 85], [4, 1, 86], [5, 2, -1], [5, -1, 85], [6, 3, 86], [7, 4, -1], [7, -1, 85], [8, 5, 86], [9, 6, -1], [9, -1, 85], [10, 7, 86], [11, 8, -1], [11, -1, 85], [12, 9, 86], [13, 10, -1], [13, -1, 85], [14, 11, 86], [16, 36, -1], [-1, 36, -1], [16, -1, -1], [16, -1, 85], [17, 13, 86], [-1, -1, 80], [0, -1, 87], [1, 0, 88], [-1, 1, 89], [-1, 1, 90], [1, 1, 91], [0, -1, 92], [1, 2, 93], [-1, 3, 94], [-1, 3, 95], [1, 3, 96], [0, -1, 97], [1, 4, 98], [-1, 5, 99], [-1, 5, 100], [1, 5, 101], [0, -1, 102], [1, 6, 103], [-1, 7, 104], [-1, 7, 105], [1, 7, 106], [0, -1, 107], [1, 8, 108], [-1, 9, 109], [-1, 9, 110], [1, 9, 111], [0, -1, 112], [1, 10, 113], [-1, 11, 114], [-1, 11, 115], [1, 11, 116], [0, -1, 117], [1, 36, 118], [-1, 13, 119], [-1, 13, 120], [1, 37, 121], [0, 1, -1], [0, 0, -1], [0, -1, 122], [-1, -1, 123], [-1, -1, 124], [0, -1, 125], [2, 14, 126], [1, -1, -1], [0, 3, -1], [0, 2, -1], [0, -1, 127], [-1, -1, 128], [-1, -1, 129], [0, -1, 130], [2, 15, 131], [0, 5, -1], [0, 4, -1], [0, -1, 132], [-1, -1, 133], [-1, -1, 134], [0, -1, 135], [2, 16, 136], [0, 7, -1], [0, 6, -1], [0, -1, 137], [-1, -1, 138], [-1, -1, 139], [0, -1, 140], [2, 17, 141], [0, 9, -1], [0, 8, -1], [0, -1, 142], [-1, -1, 143], [-1, -1, 144], [0, -1, 145], [2, 18, 146], [0, 11, -1], [0, 10, -1], [0, -1, 147], [-1, -1, 148], [-1, -1, 149], [0, -1, 150], [2, 19, 151], [0, 13, -1], [0, 36, -1], [0, -1, 152], [-1, -1, 153], [-1, -1, 154], [0, -1, 155], [2, 38, 156], [-1, -1, 157], [-1, 1, 67], [15, 39, 158], [-1, -1, 87], [2, 39, -1], [2, -1, -1], [-1, -1, 159], [-1, -1, 160], [0, -1, 161], [15, 21, 162], [1, -1, 163], [-1, -1, 164], [-1, 3, 69], [15, 40, 165], [-1, -1, 92], [2, 40, -1], [-1, -1, 166], [-1, -1, 167], [0, -1, 168], [15, 23, 169], [1, -1, 170], [-1, -1, 171], [-1, 5, 71], [15, 41, 172], [-1, -1, 97], [2, 41, -1], [-1, -1, 173], [-1, -1, 174], [0, -1, 175], [15, 25, 176], [1, -1, 177], [-1, -1, 178], [-1, 7, 73], [15, 42, 179], [-1, -1, 102], [2, 42, -1], [-1, -1, 180], [-1, -1, 181], [0, -1, 182], [15, 27, 183], [1, -1, 184], [-1, -1, 185], [-1, 9, 75], [15, 43, 186], [-1, -1, 107], [2, 43, -1], [-1, -1, 187], [-1, -1, 188], [0, -1, 189], [15, 29, 190], [1, -1, 191], [-1, -1, 192], [-1, 11, 77], [15, 44, 193], [-1, -1, 112], [2, 44, -1], [-1, -1, 194], [-1, -1, 195], [0, -1, 196], [15, 31, 197], [1, -1, 198], [-1, -1, 199], [-1, 13, 200], [15, 12, 201], [-1, -1, 200], [2, 12, -1], [-1, -1, 202], [-1, -1, 203], [0, -1, 204], [15, 38, 205], [1, -1, 206], [4, -1, -1], [-1, 1, 207], [4, -1, 47], [4, -1, 67], [4, -1, 208], [6, -1, -1], [-1, 3, 207], [6, -1, 50], [6, -1, 69], [6, -1, 209], [8, -1, -1], [-1, 5, 207], [8, -1, 53], [8, -1, 71], [8, -1, 210], [10, -1, -1], [-1, 7, 207], [10, -1, 56], [10, -1, 73], [10, -1, 211], [12, -1, -1], [-1, 9, 207], [12, -1, 59], [12, -1, 75], [12, -1, 212], [14, -1, -1], [-1, 11, 207], [14, -1, 62], [14, -1, 77], [14, -1, 213], [0, -1, 214], [-1, 13, 207], [0, -1, 215], [0, -1, 216], [1, -1, 217], [-1, 1, 218], [0, -1, 218], [0, -1, 68], [0, 1, 219], [0, 1, 218], [-1, 3, 220], [0, -1, 220], [0, -1, 70], [0, 3, 221], [0, 3, 220], [-1, 5, 222], [0, -1, 222], [0, -1, 72], [0, 5, 223], [0, 5, 222], [-1, 7, 224], [0, -1, 224], [0, -1, 74], [0, 7, 225], [0, 7, 224], [-1, 9, 226], [0, -1, 226], [0, -1, 76], [0, 9, 227], [0, 9, 226], [-1, 11, 228], [0, -1, 228], [0, -1, 78], [0, 11, 229], [0, 11, 228], [-1, 13, 230], [0, -1, 230], [0, -1, 207], [0, 13, 231], [0, 13, 230], [0, 1, 85], [-1, -1, 232], [0, 1, 90], [-1, -1, 48], [-1, -1, 233], [-1, -1, 234], [0, -1, 235], [0, -1, 236], [4, -1, 163], [0, 3, 85], [-1, -1, 237], [0, 3, 95], [-1, -1, 51], [-1, -1, 238], [-1, -1, 239], [0, -1, 240], [0, -1, 241], [6, -1, 170], [0, 5, 85], [-1, -1, 242], [0, 5, 100], [-1, -1, 54], [-1, -1, 243], [-1, -1, 244], [0, -1, 245], [0, -1, 246], [8, -1, 177], [0, 7, 85], [-1, -1, 247], [0, 7, 105], [-1, -1, 57], [-1, -1, 248], [-1, -1, 249], [0, -1, 250], [0, -1, 251], [10, -1, 184], [0, 9, 85], [-1, -1, 252], [0, 9, 110], [-1, -1, 60], [-1, -1, 253], [-1, -1, 254], [0, -1, 255], [0, -1, 256], [12, -1, 191], [0, 11, 85], [-1, -1, 257], [0, 11, 115], [-1, -1, 63], [-1, -1, 258], [-1, -1, 259], [0, -1, 260], [0, -1, 261], [14, -1, 198], [0, 13, 85], [-1, -1, 231], [0, 13, 262], [-1, -1, 263], [-1, -1, 264], [-1, -1, 265], [0, -1, 266], [0, -1, 267], [-1, -1, 68], [18, -1, -1], [-1, 1, 268], [0, 45, 68], [-1, -1, 70], [19, -1, -1], [-1, 3, 269], [0, 45, 70], [-1, -1, 72], [20, -1, -1], [-1, 5, 270], [0, 45, 72], [-1, -1, 74], [21, -1, -1], [-1, 7, 271], [0, 45, 74], [-1, -1, 76], [22, -1, -1], [-1, 9, 272], [0, 45, 76], [-1, -1, 78], [23, -1, -1], [-1, 11, 273], [0, 45, 78], [-1, -1, 207], [-1, 13, 274], [-1, 13, 262], [0, 45, 207], [24, -1, -1], [-1, 39, -1], [2, -1, 83], [-1, 21, 84], [24, 14, 86], [25, -1, -1], [-1, 40, -1], [-1, 23, 84], [25, 15, 86], [26, -1, -1], [-1, 41, -1], [-1, 25, 84], [26, 16, 86], [27, -1, -1], [-1, 42, -1], [-1, 27, 84], [27, 17, 86], [28, -1, -1], [-1, 43, -1], [-1, 29, 84], [28, 18, 86], [29, -1, -1], [-1, 44, -1], [-1, 31, 84], [29, 19, 86], [-1, 38, -1], [30, -1, -1], [-1, 46, -1], [-1, 38, 84], [31, 47, 86], [2, 21, -1], [-1, -1, 218], [-1, 21, 275], [-1, -1, 276], [24, 14, -1], [2, 23, -1], [-1, -1, 220], [-1, 23, 277], [-1, -1, 278], [25, 15, -1], [2, 25, -1], [-1, -1, 222], [-1, 25, 279], [-1, -1, 280], [26, 16, -1], [2, 27, -1], [-1, -1, 224], [-1, 27, 281], [-1, -1, 282], [27, 17, -1], [2, 29, -1], [-1, -1, 226], [-1, 29, 283], [-1, -1, 284], [28, 18, -1], [2, 31, -1], [-1, -1, 228], [-1, 31, 285], [-1, -1, 286], [29, 19, -1], [2, 38, 287], [-1, -1, 230], [-1, 38, 264], [-1, -1, 119], [-1, -1, 262], [31, 46, -1], [-1, -1, 288], [-1, -1, 289], [0, 0, 290], [-1, -1, 291], [-1, -1, 90], [2, 33, -1], [1, 1, 266], [0, 2, 292], [-1, -1, 293], [-1, -1, 95], [1, 3, 266], [0, 4, 294], [-1, -1, 295], [-1, -1, 100], [1, 5, 266], [0, 6, 296], [-1, -1, 297], [-1, -1, 105], [1, 7, 266], [0, 8, 298], [-1, -1, 299], [-1, -1, 110], [1, 9, 266], [0, 10, 300], [-1, -1, 301], [-1, -1, 115], [1, 11, 266], [0, 36, 302], [-1, -1, 303], [-1, -1, 304], [-1, -1, 120], [1, 13, 266], [15, 22, 305], [2, 22, 305], [0, 1, 276], [0, -1, 306], [-1, -1, 307], [2, 22, -1], [2, 22, 308], [1, 0, 163], [15, 24, 309], [2, 24, 309], [0, 3, 278], [0, -1, 310], [-1, -1, 311], [2, 24, -1], [2, 24, 312], [1, 2, 170], [15, 26, 313], [2, 26, 313], [0, 5, 280], [0, -1, 314], [-1, -1, 315], [2, 26, -1], [2, 26, 316], [1, 4, 177], [15, 28, 317], [2, 28, 317], [0, 7, 282], [0, -1, 318], [-1, -1, 319], [2, 28, -1], [2, 28, 320], [1, 6, 184], [15, 30, 321], [2, 30, 321], [0, 9, 284], [0, -1, 322], [-1, -1, 323], [2, 30, -1], [2, 30, 324], [1, 8, 191], [15, 32, 325], [2, 32, 325], [0, 11, 286], [0, -1, 287], [-1, -1, 326], [2, 32, -1], [2, 32, 327], [1, 10, 198], [2, 38, 205], [-1, -1, 328], [2, 38, -1], [2, 38, 329], [1, 36, 206]];
var TABLE_STYLE_TEMPLATE_DEFS = [[0, 1, 2, 3, 4, 5, 7], [0, 1, 2, 3, 4, 5, 6, 7, 8]];
var PIVOT_STYLE_TEMPLATE_DEFS = [[0, 1, 2, 3, 5, 7, 10, 11, 15, 18], [0, 1, 2, 4, 6, 9, 10, 11, 15, 16, 17, 18, 19], [0, 1, 2, 4, 6, 9, 10, 11, 15, 16, 18, 19], [0, 1, 2, 4, 6, 8, 10, 11, 12, 15, 16, 18, 19], [0, 1, 2, 3, 4, 6, 9, 10, 11, 18], [1, 2, 4, 6, 9, 10, 11, 15, 16, 18, 19], [0, 1, 2, 3, 4, 6, 10, 11, 13, 14, 15, 16], [0, 1, 2, 3, 4, 6, 10, 11, 13, 15, 16], [0, 1, 2, 4, 6, 10, 11, 15, 16, 18, 19], [0, 1, 2, 3, 5, 7, 8, 10, 11, 15, 16, 18], [0, 1, 2, 4, 6, 9, 10, 12, 15, 16, 18], [0, 1, 2, 5, 6, 7, 10, 13, 14, 15, 16, 18, 19], [0, 1, 2, 5, 7, 10, 15, 16, 18, 19]];
var TABLE_STYLE_PRESET_DEFS = { TableStyleMedium28: [0, 3, 1, 2, 1, 1, 0, 0], TableStyleMedium27: [0, 6, 1, 5, 1, 1, 4, 4], TableStyleMedium26: [0, 9, 1, 8, 1, 1, 7, 7], TableStyleMedium25: [0, 12, 1, 11, 1, 1, 10, 10], TableStyleMedium24: [0, 15, 1, 14, 1, 1, 13, 13], TableStyleMedium23: [0, 18, 1, 17, 1, 1, 16, 16], TableStyleMedium22: [0, 21, 1, 20, 1, 1, 19, 19], TableStyleMedium21: [0, 26, 25, 24, 23, 23, 22, 22], TableStyleMedium20: [0, 26, 28, 24, 27, 27, 22, 22], TableStyleMedium19: [0, 26, 30, 24, 29, 29, 22, 22], TableStyleMedium18: [0, 26, 32, 24, 31, 31, 22, 22], TableStyleMedium17: [0, 26, 34, 24, 33, 33, 22, 22], TableStyleMedium16: [0, 26, 36, 24, 35, 35, 22, 22], TableStyleMedium15: [0, 39, 38, 24, 37, 37, 22, 22], TableStyleMedium14: [0, 42, 41, 40, 23, 23, 0, 0], TableStyleMedium13: [0, 45, 44, 43, 27, 27, 4, 4], TableStyleMedium12: [0, 48, 47, 46, 29, 29, 7, 7], TableStyleMedium11: [0, 51, 50, 49, 31, 31, 10, 10], TableStyleMedium10: [0, 54, 53, 52, 33, 33, 13, 13], TableStyleMedium9: [0, 57, 56, 55, 35, 35, 16, 16], TableStyleMedium8: [0, 60, 59, 58, 37, 37, 19, 19], TableStyleMedium7: [0, 63, 23, 62, 1, 1, 61, 61], TableStyleMedium6: [0, 66, 27, 65, 1, 1, 64, 64], TableStyleMedium5: [0, 69, 29, 68, 1, 1, 67, 67], TableStyleMedium4: [0, 72, 31, 71, 1, 1, 70, 70], TableStyleMedium3: [0, 75, 33, 74, 1, 1, 73, 73], TableStyleMedium2: [0, 78, 35, 77, 1, 1, 76, 76], TableStyleMedium1: [0, 80, 37, 79, 1, 1, 22, 22], TableStyleLight21: [0, 82, 81, 62, 1, 1, 61, 61], TableStyleLight20: [0, 84, 83, 65, 1, 1, 64, 64], TableStyleLight19: [0, 86, 85, 68, 1, 1, 67, 67], TableStyleLight18: [0, 88, 87, 71, 1, 1, 70, 70], TableStyleLight17: [0, 90, 89, 74, 1, 1, 73, 73], TableStyleLight16: [0, 92, 91, 77, 1, 1, 76, 76], TableStyleLight15: [0, 94, 93, 79, 1, 1, 22, 22], TableStyleLight14: [1, 97, 23, 62, 1, 1, 96, 96, 95, 95], TableStyleLight13: [1, 100, 27, 65, 1, 1, 99, 99, 98, 98], TableStyleLight12: [1, 103, 29, 68, 1, 1, 102, 102, 101, 101], TableStyleLight11: [1, 106, 31, 71, 1, 1, 105, 105, 104, 104], TableStyleLight10: [1, 109, 33, 74, 1, 1, 108, 108, 107, 107], TableStyleLight9: [1, 112, 35, 77, 1, 1, 111, 111, 110, 110], TableStyleLight8: [1, 115, 37, 79, 1, 1, 114, 114, 113, 113], TableStyleLight7: [0, 119, 118, 117, 116, 116, 61, 61], TableStyleLight6: [0, 123, 122, 121, 120, 120, 64, 64], TableStyleLight5: [0, 127, 126, 125, 124, 124, 67, 67], TableStyleLight4: [0, 131, 130, 129, 128, 128, 70, 70], TableStyleLight3: [0, 135, 134, 133, 132, 132, 73, 73], TableStyleLight2: [0, 139, 138, 137, 136, 136, 76, 76], TableStyleLight1: [0, 142, 141, 140, 1, 1, 22, 22], TableStyleDark11: [0, 64, 143, 79, 1, 1, 4, 4], TableStyleDark10: [0, 70, 144, 79, 1, 1, 10, 10], TableStyleDark9: [0, 76, 145, 79, 1, 1, 16, 16], TableStyleDark8: [0, 22, 146, 79, 1, 1, 19, 19], TableStyleDark7: [0, 143, 151, 150, 149, 148, 147, 147], TableStyleDark6: [0, 156, 151, 155, 154, 153, 152, 152], TableStyleDark5: [0, 144, 151, 160, 159, 158, 157, 157], TableStyleDark4: [0, 165, 151, 164, 163, 162, 161, 161], TableStyleDark3: [0, 145, 151, 169, 168, 167, 166, 166], TableStyleDark2: [0, 174, 151, 173, 172, 171, 170, 170], TableStyleDark1: [0, 179, 151, 178, 177, 176, 175, 175] };
var PIVOT_STYLE_PRESET_DEFS = { PivotStyleMedium28: [0, 181, 116, 180, 0, 0, 1, 1, 1, 180, -1], PivotStyleMedium27: [0, 184, 120, 183, 4, 4, 1, 1, 1, 183, -1], PivotStyleMedium26: [0, 187, 124, 186, 7, 7, 1, 1, 1, 186, -1], PivotStyleMedium25: [0, 190, 128, 189, 10, 10, 1, 1, 1, 189, -1], PivotStyleMedium24: [0, 193, 132, 192, 13, 13, 1, 1, 1, 192, -1], PivotStyleMedium23: [0, 196, 136, 195, 16, 16, 1, 1, 1, 195, -1], PivotStyleMedium22: [0, 201, 200, 198, 199, 199, 1, 1, 1, 198, -1], PivotStyleMedium21: [1, 146, 146, 207, 206, 205, 204, 200, 1, 200, 1, 203, 203, -1], PivotStyleMedium20: [1, 146, 146, 212, 211, 210, 209, 200, 1, 200, 1, 203, 203, -1], PivotStyleMedium19: [1, 146, 146, 217, 216, 215, 214, 200, 1, 200, 1, 203, 203, -1], PivotStyleMedium18: [1, 146, 146, 222, 221, 220, 219, 200, 1, 200, 1, 203, 203, -1], PivotStyleMedium17: [1, 146, 146, 227, 226, 225, 224, 200, 1, 200, 1, 203, 203, -1], PivotStyleMedium16: [1, 146, 146, 232, 231, 230, 229, 200, 1, 200, 1, 203, 203, -1], PivotStyleMedium15: [1, 146, 146, 237, 236, 235, 234, 200, 1, 200, 1, 203, 203, -1], PivotStyleMedium14: [2, 245, 244, 243, 242, 241, 240, 1, 239, 1, 61, 61, -1], PivotStyleMedium13: [2, 253, 252, 251, 250, 249, 248, 1, 247, 1, 64, 64, -1], PivotStyleMedium12: [2, 260, 259, 258, 257, 256, 255, 1, 254, 1, 67, 67, -1], PivotStyleMedium11: [2, 267, 266, 265, 264, 263, 262, 1, 261, 1, 70, 70, -1], PivotStyleMedium10: [2, 274, 273, 272, 271, 270, 269, 1, 268, 1, 73, 73, -1], PivotStyleMedium9: [2, 281, 280, 279, 278, 277, 276, 1, 275, 1, 76, 76, -1], PivotStyleMedium8: [2, 288, 287, 286, 285, 284, 283, 1, 282, 1, 22, 22, -1], PivotStyleMedium7: [3, 298, 297, 296, 295, 294, 293, 282, 292, 291, 290, 289, 289, -1], PivotStyleMedium6: [3, 308, 307, 306, 305, 294, 304, 282, 303, 302, 301, 300, 300, -1], PivotStyleMedium5: [3, 318, 317, 316, 315, 294, 314, 282, 313, 312, 311, 310, 310, -1], PivotStyleMedium4: [3, 328, 327, 326, 325, 294, 324, 282, 323, 322, 321, 320, 320, -1], PivotStyleMedium3: [3, 338, 337, 336, 335, 294, 334, 282, 333, 332, 331, 330, 330, -1], PivotStyleMedium2: [3, 348, 347, 346, 345, 294, 344, 282, 343, 342, 341, 340, 340, -1], PivotStyleMedium1: [3, 358, 357, 356, 355, 294, 354, 282, 353, 352, 351, 350, 350, -1], PivotStyleLight28: [4, 363, 362, 360, 361, 61, 360, 360, 360, 360, -1], PivotStyleLight27: [4, 368, 367, 365, 366, 64, 365, 365, 365, 365, -1], PivotStyleLight26: [4, 373, 372, 370, 371, 67, 370, 370, 370, 370, -1], PivotStyleLight25: [4, 378, 377, 375, 376, 70, 375, 375, 375, 375, -1], PivotStyleLight24: [4, 383, 382, 380, 381, 73, 380, 380, 380, 380, -1], PivotStyleLight23: [4, 388, 387, 385, 386, 76, 385, 385, 385, 385, -1], PivotStyleLight22: [4, 393, 392, 1, 391, 22, 390, 1, 1, 1, -1], PivotStyleLight21: [5, 398, 22, 236, 22, 397, 1, 396, 1, 395, 395, -1], PivotStyleLight20: [5, 403, 22, 236, 22, 402, 1, 401, 1, 400, 400, -1], PivotStyleLight19: [5, 408, 22, 236, 22, 407, 1, 406, 1, 405, 405, -1], PivotStyleLight18: [5, 413, 22, 236, 22, 412, 1, 411, 1, 410, 410, -1], PivotStyleLight17: [5, 418, 22, 236, 22, 417, 1, 416, 1, 415, 415, -1], PivotStyleLight16: [5, 423, 22, 236, 22, 422, 1, 421, 1, 420, 420, -1], PivotStyleLight15: [5, 428, 22, 236, 22, 427, 1, 426, 1, 425, 425, -1], PivotStyleLight14: [6, 437, 436, 435, 434, 433, 432, 1, 431, 431, 430, 1, -1], PivotStyleLight13: [6, 446, 445, 444, 443, 442, 441, 1, 440, 440, 439, 1, -1], PivotStyleLight12: [6, 455, 454, 453, 452, 451, 450, 1, 449, 449, 448, 1, -1], PivotStyleLight11: [6, 464, 463, 462, 461, 460, 459, 1, 458, 458, 457, 1, -1], PivotStyleLight10: [6, 473, 472, 471, 470, 469, 468, 1, 467, 467, 466, 1, -1], PivotStyleLight9: [6, 482, 481, 480, 479, 478, 477, 1, 476, 476, 475, 1, -1], PivotStyleLight8: [7, 491, 490, 489, 488, 487, 486, 1, 485, 484, 1, -1], PivotStyleLight7: [8, 397, 495, 207, 494, 1, 493, 1, 493, 492, 492, -1], PivotStyleLight6: [8, 402, 499, 212, 498, 1, 497, 1, 497, 496, 496, -1], PivotStyleLight5: [8, 407, 503, 217, 502, 1, 501, 1, 501, 500, 500, -1], PivotStyleLight4: [8, 412, 507, 222, 506, 1, 505, 1, 505, 504, 504, -1], PivotStyleLight3: [8, 417, 511, 227, 510, 1, 509, 1, 509, 508, 508, -1], PivotStyleLight2: [8, 422, 515, 232, 514, 1, 513, 1, 513, 512, 512, -1], PivotStyleLight1: [8, 427, 519, 518, 517, 1, 200, 1, 200, 516, 516, -1], PivotStyleDark28: [9, 523, 522, 147, 521, 521, 294, 520, 294, 294, 294, 147, -1], PivotStyleDark27: [9, 527, 522, 152, 526, 526, 294, 525, 294, 294, 294, 152, -1], PivotStyleDark26: [9, 531, 522, 157, 530, 530, 294, 529, 294, 294, 294, 157, -1], PivotStyleDark25: [9, 535, 522, 161, 534, 534, 294, 533, 294, 294, 294, 161, -1], PivotStyleDark24: [9, 539, 522, 166, 538, 538, 294, 537, 294, 294, 294, 166, -1], PivotStyleDark23: [9, 543, 522, 170, 542, 542, 294, 541, 294, 294, 294, 170, -1], PivotStyleDark22: [9, 548, 522, 545, 547, 547, 294, 546, 1, 294, 294, 545, -1], PivotStyleDark21: [10, 37, 37, 553, 242, 552, 294, 551, 550, 294, 294, -1], PivotStyleDark20: [10, 37, 37, 558, 250, 557, 294, 556, 555, 294, 294, -1], PivotStyleDark19: [10, 37, 37, 563, 257, 562, 294, 561, 560, 294, 294, -1], PivotStyleDark18: [10, 37, 37, 568, 264, 567, 294, 566, 565, 294, 294, -1], PivotStyleDark17: [10, 37, 37, 573, 271, 572, 294, 571, 570, 294, 294, -1], PivotStyleDark16: [10, 37, 37, 578, 278, 577, 294, 576, 575, 294, 294, -1], PivotStyleDark15: [10, 37, 37, 584, 583, 582, 294, 581, 580, 294, 294, -1], PivotStyleDark14: [11, 591, 591, 590, 242, 242, 240, 589, 589, 588, 1, 587, 586, -1], PivotStyleDark13: [11, 591, 591, 595, 250, 250, 248, 594, 594, 593, 1, 587, 586, -1], PivotStyleDark12: [11, 591, 591, 599, 257, 257, 255, 598, 598, 597, 1, 587, 586, -1], PivotStyleDark11: [11, 591, 591, 603, 264, 264, 262, 602, 602, 601, 1, 587, 586, -1], PivotStyleDark10: [11, 591, 591, 607, 271, 271, 269, 606, 606, 605, 1, 587, 586, -1], PivotStyleDark9: [11, 591, 591, 611, 278, 278, 276, 610, 610, 609, 1, 587, 586, -1], PivotStyleDark8: [11, 591, 591, 616, 615, 615, 283, 614, 614, 613, 1, 587, 586, -1], PivotStyleDark7: [12, 624, 623, 521, 622, 621, 620, 1, 619, 618, -1], PivotStyleDark6: [12, 632, 631, 526, 630, 629, 628, 1, 627, 626, -1], PivotStyleDark5: [12, 640, 639, 530, 638, 637, 636, 1, 635, 634, -1], PivotStyleDark4: [12, 648, 647, 534, 646, 645, 644, 1, 643, 642, -1], PivotStyleDark3: [12, 656, 655, 538, 654, 653, 652, 1, 651, 650, -1], PivotStyleDark2: [12, 664, 663, 542, 662, 661, 660, 1, 659, 658, -1], PivotStyleDark1: [12, 669, 668, 19, 667, 426, 486, 1, 666, 358, -1] };

// node_modules/@oai/granola/dist/models/spreadsheet/preset-style-registry.js
var NONE = -1;
var DEFAULT_RENDER_TABLE_STYLE_NAME = "TableStyleMedium2";
var DEFAULT_RENDER_PIVOT_STYLE_NAME = "PivotStyleMedium2";
var TABLE_STYLE_NAME_LOOKUP = new Map(Object.keys(TABLE_STYLE_PRESET_DEFS).map((name) => [
  normalizePresetStyleKey(name),
  name
]));
var PIVOT_STYLE_NAME_LOOKUP = new Map(Object.keys(PIVOT_STYLE_PRESET_DEFS).map((name) => [
  normalizePresetStyleKey(name),
  name
]));
var EMPTY_FILL = {
  type: 0 /* FILL_TYPE_UNSPECIFIED */,
  color: undefined,
  gradientStops: []
};
var colorCache = [];
var fillCache = [];
var fontCache = [];
var lineCache = [];
var borderCache = [];
var dxfCache = [];
function normalizePresetStyleKey(name) {
  return name.replace(/[^a-z0-9]/gi, "").toLowerCase();
}
function normalizeTableStyleName(name) {
  if (!name) {
    return;
  }
  const exact = TABLE_STYLE_PRESET_DEFS[name];
  if (exact) {
    return name;
  }
  return TABLE_STYLE_NAME_LOOKUP.get(normalizePresetStyleKey(name));
}
function normalizePivotStyleName(name) {
  if (!name) {
    return;
  }
  const exact = PIVOT_STYLE_PRESET_DEFS[name];
  if (exact) {
    return name;
  }
  return PIVOT_STYLE_NAME_LOOKUP.get(normalizePresetStyleKey(name));
}
function buildColor(colorId) {
  const cached2 = colorCache[colorId];
  if (cached2) {
    return cached2;
  }
  const colorDef = PRESET_STYLE_COLOR_DEFS[colorId];
  if (!colorDef) {
    throw new Error(`Unknown preset color id: ${colorId}`);
  }
  const [theme, tint] = colorDef;
  const color2 = {
    type: 2 /* COLOR_TYPE_SCHEME */,
    value: `theme:${theme}`,
    transform: tint === undefined ? undefined : { tint },
    lastColor: undefined
  };
  colorCache[colorId] = color2;
  return color2;
}
function buildFill(fillId) {
  if (fillId === NONE) {
    return EMPTY_FILL;
  }
  const cached2 = fillCache[fillId];
  if (cached2) {
    return cached2;
  }
  const colorId = PRESET_STYLE_FILL_DEFS[fillId];
  if (colorId === undefined) {
    throw new Error(`Unknown preset fill id: ${fillId}`);
  }
  const fill2 = {
    type: 1 /* FILL_TYPE_SOLID */,
    color: buildColor(colorId),
    gradientStops: []
  };
  fillCache[fillId] = fill2;
  return fill2;
}
function buildFont(fontId) {
  if (fontId === NONE) {
    return;
  }
  const cached2 = fontCache[fontId];
  if (cached2) {
    return cached2;
  }
  const fontDef = PRESET_STYLE_FONT_DEFS[fontId];
  if (!fontDef) {
    throw new Error(`Unknown preset font id: ${fontId}`);
  }
  const [flags, colorId] = fontDef;
  const font = {};
  if ((flags & 1) !== 0) {
    font.bold = true;
  }
  if (colorId >= 0) {
    font.fill = {
      type: 1 /* FILL_TYPE_SOLID */,
      color: buildColor(colorId),
      gradientStops: []
    };
  }
  fontCache[fontId] = font;
  return font;
}
function buildLine(lineId) {
  const cached2 = lineCache[lineId];
  if (cached2) {
    return cached2;
  }
  const lineDef = PRESET_STYLE_LINE_DEFS[lineId];
  if (!lineDef) {
    throw new Error(`Unknown preset line id: ${lineId}`);
  }
  const [styleId, colorId] = lineDef;
  const style = BORDER_STYLE_NAMES[styleId];
  if (!style) {
    throw new Error(`Unknown preset border style id: ${styleId}`);
  }
  const line = {
    style,
    color: buildColor(colorId)
  };
  lineCache[lineId] = line;
  return line;
}
function buildBorder(borderId) {
  if (borderId === NONE) {
    return;
  }
  const cached2 = borderCache[borderId];
  if (cached2) {
    return cached2;
  }
  const borderDef = PRESET_STYLE_BORDER_DEFS[borderId];
  if (!borderDef) {
    throw new Error(`Unknown preset border id: ${borderId}`);
  }
  const border = {};
  for (let i = 0;i < borderDef.length; i += 2) {
    const edgeName = BORDER_EDGE_NAMES[borderDef[i]];
    const lineId = borderDef[i + 1];
    if (!edgeName || lineId === undefined) {
      continue;
    }
    border[edgeName] = buildLine(lineId);
  }
  borderCache[borderId] = border;
  return border;
}
function hydrateDxf(dxfId) {
  const cached2 = dxfCache[dxfId];
  if (cached2) {
    return cached2;
  }
  const dxfDef = PRESET_STYLE_DXF_DEFS[dxfId];
  if (!dxfDef) {
    throw new Error(`Unknown preset dxf id: ${dxfId}`);
  }
  const [fontId, fillId, borderId] = dxfDef;
  const dxf = {
    fill: buildFill(fillId),
    font: buildFont(fontId),
    border: buildBorder(borderId)
  };
  dxfCache[dxfId] = dxf;
  return dxf;
}

class CompactPresetStyle {
  #name;
  #record;
  #templates;
  #elementNames;
  constructor(name, record2, templates, elementNames) {
    this.#name = name;
    this.#record = record2;
    this.#templates = templates;
    this.#elementNames = elementNames;
  }
  get name() {
    return this.#name;
  }
  get elementTypes() {
    return this.#template().map((elementId) => this.#elementNames[elementId]);
  }
  getElement(type) {
    const template = this.#template();
    const dxfIds = this.#dxfIds();
    for (let i = 0;i < template.length; i++) {
      const elementId = template[i];
      if (elementId === undefined) {
        continue;
      }
      if (this.#elementNames[elementId] !== type) {
        continue;
      }
      const dxfId = dxfIds[i];
      return dxfId === NONE || dxfId === undefined ? undefined : hydrateDxf(dxfId);
    }
    return;
  }
  templateAndDxfIds() {
    return {
      template: this.#template(),
      dxfIds: this.#dxfIds()
    };
  }
  #template() {
    const template = this.#templates[this.#record[0]];
    if (!template) {
      throw new Error(`Unknown preset style template id: ${this.#record[0]} for ${this.#name}`);
    }
    return template;
  }
  #dxfIds() {
    return this.#record.slice(1);
  }
}

class TablePresetStyle extends CompactPresetStyle {
  #tableStyleCache;
  get wholeTable() {
    return this.getElement("wholeTable");
  }
  get headerRow() {
    return this.getElement("headerRow");
  }
  get totalRow() {
    return this.getElement("totalRow");
  }
  get firstColumn() {
    return this.getElement("firstColumn");
  }
  get lastColumn() {
    return this.getElement("lastColumn");
  }
  get firstRowStripe() {
    return this.getElement("firstRowStripe");
  }
  get secondRowStripe() {
    return this.getElement("secondRowStripe");
  }
  get firstColumnStripe() {
    return this.getElement("firstColumnStripe");
  }
  get secondColumnStripe() {
    return this.getElement("secondColumnStripe");
  }
  toTableStyle() {
    if (this.#tableStyleCache) {
      return this.#tableStyleCache;
    }
    const { template, dxfIds } = this.templateAndDxfIds();
    const dxfs = [];
    const tableStyles = {};
    for (let i = 0;i < template.length; i++) {
      const dxfId = dxfIds[i];
      if (dxfId === NONE || dxfId === undefined) {
        continue;
      }
      const elementName = TABLE_STYLE_ELEMENT_TYPES[template[i]];
      if (!elementName) {
        continue;
      }
      tableStyles[elementName] = dxfs.push(hydrateDxf(dxfId)) - 1;
    }
    this.#tableStyleCache = {
      dxfs,
      defaultTableStyle: DEFAULT_XML_TABLE_STYLE_NAME,
      tableStyles
    };
    return this.#tableStyleCache;
  }
}

class PivotPresetStyle extends CompactPresetStyle {
  get wholeTable() {
    return this.getElement("wholeTable");
  }
  get headerRow() {
    return this.getElement("headerRow");
  }
  get totalRow() {
    return this.getElement("totalRow");
  }
  get firstColumn() {
    return this.getElement("firstColumn");
  }
  get firstRowStripe() {
    return this.getElement("firstRowStripe");
  }
  get secondRowStripe() {
    return this.getElement("secondRowStripe");
  }
  get firstColumnStripe() {
    return this.getElement("firstColumnStripe");
  }
  get secondColumnStripe() {
    return this.getElement("secondColumnStripe");
  }
  get firstHeaderCell() {
    return this.getElement("firstHeaderCell");
  }
  get firstSubtotalColumn() {
    return this.getElement("firstSubtotalColumn");
  }
  get firstSubtotalRow() {
    return this.getElement("firstSubtotalRow");
  }
  get secondSubtotalRow() {
    return this.getElement("secondSubtotalRow");
  }
  get firstColumnSubheading() {
    return this.getElement("firstColumnSubheading");
  }
  get secondColumnSubheading() {
    return this.getElement("secondColumnSubheading");
  }
  get thirdColumnSubheading() {
    return this.getElement("thirdColumnSubheading");
  }
  get firstRowSubheading() {
    return this.getElement("firstRowSubheading");
  }
  get secondRowSubheading() {
    return this.getElement("secondRowSubheading");
  }
  get thirdRowSubheading() {
    return this.getElement("thirdRowSubheading");
  }
  get pageFieldLabels() {
    return this.getElement("pageFieldLabels");
  }
  get pageFieldValues() {
    return this.getElement("pageFieldValues");
  }
}

class TablePresetStyleRegistry {
  #cache = new Map;
  getStyle(name) {
    const normalizedName = normalizeTableStyleName(name);
    if (!normalizedName) {
      return;
    }
    let style = this.#cache.get(normalizedName);
    if (style) {
      return style;
    }
    const record2 = TABLE_STYLE_PRESET_DEFS[normalizedName];
    if (!record2) {
      return;
    }
    style = new TablePresetStyle(normalizedName, record2, TABLE_STYLE_TEMPLATE_DEFS, TABLE_STYLE_ELEMENT_TYPES);
    this.#cache.set(normalizedName, style);
    return style;
  }
  names() {
    return Object.keys(TABLE_STYLE_PRESET_DEFS);
  }
}

class PivotPresetStyleRegistry {
  #cache = new Map;
  getStyle(name) {
    const normalizedName = normalizePivotStyleName(name);
    if (!normalizedName) {
      return;
    }
    let style = this.#cache.get(normalizedName);
    if (style) {
      return style;
    }
    const record2 = PIVOT_STYLE_PRESET_DEFS[normalizedName];
    if (!record2) {
      return;
    }
    style = new PivotPresetStyle(normalizedName, record2, PIVOT_STYLE_TEMPLATE_DEFS, PIVOT_STYLE_ELEMENT_TYPES);
    this.#cache.set(normalizedName, style);
    return style;
  }
  names() {
    return Object.keys(PIVOT_STYLE_PRESET_DEFS);
  }
}
var TABLE_STYLE_PRESETS = new TablePresetStyleRegistry;
var PIVOT_STYLE_PRESETS = new PivotPresetStyleRegistry;
function getTableStylePreset(name) {
  return TABLE_STYLE_PRESETS.getStyle(name);
}
function getTableStyle(name) {
  return getTableStylePreset(name)?.toTableStyle();
}
var TABLE_STYLES = new Proxy(Object.create(null), {
  get(_target2, property) {
    if (typeof property !== "string") {
      return;
    }
    return getTableStyle(property);
  },
  has(_target2, property) {
    return typeof property === "string" && getTableStyle(property) !== undefined;
  },
  ownKeys() {
    return TABLE_STYLE_PRESETS.names();
  },
  getOwnPropertyDescriptor(_target2, property) {
    if (typeof property !== "string") {
      return;
    }
    const style = getTableStyle(property);
    if (!style) {
      return;
    }
    return {
      enumerable: true,
      configurable: true,
      value: style
    };
  }
});
// node_modules/@oai/granola/dist/spreadsheet/pivot-style-rendering.js
var SPREADSHEET_COLOR_OPTIONS4 = { colorSpace: "spreadsheetml" };
function buildPivotStyleRenderCache(worksheet, themeMap) {
  const result = new Map;
  const pivots = worksheet.pivotTables.items;
  for (const pivot of pivots) {
    const pivotProto = getPivotTableProto(pivot);
    const style = PIVOT_STYLE_PRESETS.getStyle(pivotProto.styleName) ?? PIVOT_STYLE_PRESETS.getStyle(DEFAULT_RENDER_PIVOT_STYLE_NAME);
    if (!style) {
      continue;
    }
    const hints = pivot.__getPivotCellRenderHints();
    const hintKeys = new Set(hints.keys());
    for (const [key, hint] of hints.entries()) {
      const coord = parsePivotCellRenderHintKey(key);
      if (!coord)
        continue;
      result.set(key, resolveHintStyle(style.getElement(hint.type), hint, coord.row, coord.col, hintKeys, themeMap));
    }
  }
  return result;
}
function getPivotCellRenderStyle(cache, row2, col) {
  return cache.get(buildPivotCellRenderHintKey(row2, col));
}
function resolveHintStyle(dxf, hint, row2, col, hintKeys, themeMap) {
  const borders = {};
  if (dxf?.border?.top) {
    borders.top = resolveBorder(dxf.border.top, themeMap);
  }
  if (dxf?.border?.bottom) {
    borders.bottom = resolveBorder(dxf.border.bottom, themeMap);
  }
  if (dxf?.border?.left) {
    borders.left = resolveBorder(dxf.border.left, themeMap);
  }
  if (dxf?.border?.right) {
    borders.right = resolveBorder(dxf.border.right, themeMap);
  }
  if (dxf?.border?.horizontal && !borders.top) {
    const previousRowKey = buildPivotCellRenderHintKey(row2 - 1, col);
    if (hintKeys.has(previousRowKey)) {
      borders.top = resolveBorder(dxf.border.horizontal, themeMap);
    }
  }
  return {
    fillCss: dxf?.fill?.color ? resolveColor(dxf.fill.color, themeMap, SPREADSHEET_COLOR_OPTIONS4) : undefined,
    fontColor: dxf?.font?.fill?.color,
    bold: dxf?.font?.bold,
    borders,
    indentPx: Math.max(0, hint.indentLevel) * 8
  };
}
function resolveBorder(border, themeMap) {
  return {
    style: border.style ?? "thin",
    colorCss: resolveColor(border.color, themeMap, SPREADSHEET_COLOR_OPTIONS4)
  };
}

// node_modules/@oai/granola/dist/spreadsheet/resolve-cell-render-style.js
function resolveCellRenderStyle(options) {
  const baseFillCss = options.style.fill ?? null;
  const conditionalFormatting = {
    fillCss: null,
    textColor: null
  };
  if (options.cfRenderCache) {
    conditionalFormatting.fillCss = options.cfRenderCache.getFillCss(options.rowIdx, options.colIdx, options.cell);
    conditionalFormatting.textColor = options.cfRenderCache.getTextColor(options.rowIdx, options.colIdx, options.cell);
  }
  return {
    baseFillCss,
    conditionalFormatting,
    hasAnyFill: Boolean(baseFillCss || conditionalFormatting.fillCss)
  };
}

// node_modules/@oai/granola/dist/spreadsheet/draw-viewport.js
var TEXT_SCALE = 1;
var UNBOUNDED_TEXT_MEASURE_WIDTH_PX = 1e6;
var DEFAULT_UI_ACCENT_COLOR = "#60A5FA";
function parseHexColor2(value) {
  const hex4 = value.trim();
  if (!hex4.startsWith("#") || hex4.length !== 7)
    return null;
  const r = parseInt(hex4.slice(1, 3), 16);
  const g = parseInt(hex4.slice(3, 5), 16);
  const b = parseInt(hex4.slice(5, 7), 16);
  if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b))
    return null;
  return { r, g, b };
}
var SHEET_CACHE = new WeakMap;
function getSheetCache(sheet) {
  let c = SHEET_CACHE.get(sheet);
  if (!c) {
    c = {
      rowCellByColIdx: new Map,
      rowNonEmptyCols: new Map,
      textMetrics: new Map,
      mergedRowAnchorByRow: new Map,
      mergedColAnchorByCol: new Map,
      mergedAnchorsComputed: false,
      mergedAnchorsSheetRef: undefined,
      mergedRangesByRow: new Map,
      mergedHorizontalBoundariesByRow: new Map,
      mergedVerticalBoundariesByCol: new Map,
      mergedRangesComputed: false,
      mergedRangesSheetRef: undefined
    };
    SHEET_CACHE.set(sheet, c);
  }
  return c;
}
function metricsKey(r, c) {
  return r + ":" + c;
}
function invalidateRows(sheet, rows) {
  const c = SHEET_CACHE.get(sheet);
  if (!c)
    return;
  for (const r of rows) {
    c.rowCellByColIdx.delete(r);
    c.rowNonEmptyCols.delete(r);
    for (const k of c.textMetrics.keys()) {
      const idx = k.indexOf(":");
      const rr = Number(k.slice(0, idx));
      if (rr === r)
        c.textMetrics.delete(k);
    }
  }
}
function lowerBound(arr, x2) {
  let lo = 0, hi = arr.length;
  while (lo < hi) {
    const mid = lo + hi >>> 1;
    const v = arr[mid];
    if (v !== undefined && v < x2)
      lo = mid + 1;
    else
      hi = mid;
  }
  return lo;
}
function upperBound(arr, x2) {
  let lo = 0, hi = arr.length;
  while (lo < hi) {
    const mid = lo + hi >>> 1;
    const v = arr[mid];
    if (v !== undefined && v <= x2)
      lo = mid + 1;
    else
      hi = mid;
  }
  return lo;
}
var A1_REF_RE = /((?:'[^']+'|[A-Za-z0-9_.]+)!)?(\$?[A-Za-z]{1,3}\$?\d{1,7})(?::(\$?[A-Za-z]{1,3}\$?\d{1,7}))?/g;
function parseCellRef(a1) {
  let i = 0;
  if (a1[i] === "$")
    i++;
  const startLetters = i;
  while (i < a1.length && /[A-Za-z]/.test(a1[i] ?? ""))
    i++;
  const letters = a1.slice(startLetters, i);
  if (a1[i] === "$")
    i++;
  const digits = a1.slice(i);
  return { col: columnIndex(letters), row: parseInt(digits, 10) || 0 };
}
function columnIndexToLetters(index) {
  index = Math.max(1, index);
  let s = "";
  while (index > 0) {
    const rem = (index - 1) % 26;
    s = String.fromCharCode(65 + rem) + s;
    index = Math.floor((index - 1) / 26);
  }
  return s;
}
function adjustRef(a1Ref, dCol, dRow) {
  const absCol = a1Ref.startsWith("$");
  const idx = absCol ? 1 : 0;
  let lettersEnd = idx;
  while (lettersEnd < a1Ref.length && /[A-Za-z]/.test(a1Ref[lettersEnd] ?? ""))
    lettersEnd++;
  const colLetters = a1Ref.slice(idx, lettersEnd);
  let absRow = false;
  let rowStart = lettersEnd;
  if (a1Ref[rowStart] === "$") {
    absRow = true;
    rowStart++;
  }
  const rowDigits = a1Ref.slice(rowStart);
  const col = columnIndex(colLetters);
  const row2 = parseInt(rowDigits, 10) || 0;
  const newCol = absCol ? col : Math.max(1, col + dCol);
  const newRow = absRow ? row2 : Math.max(1, row2 + dRow);
  const newColLetters = columnIndexToLetters(newCol);
  const colOut = (absCol ? "$" : "") + newColLetters;
  const rowOut = (absRow ? "$" : "") + String(newRow);
  return colOut + rowOut;
}
function translateSharedFormula(base, anchor, target) {
  if (!base || !anchor || !target)
    return base;
  const { col: ac, row: ar } = parseCellRef(anchor);
  const { col: tc, row: tr } = parseCellRef(target);
  const dCol = tc - ac;
  const dRow = tr - ar;
  if (dCol === 0 && dRow === 0)
    return base;
  return base.replace(A1_REF_RE, (_m, sheet, ref1, ref2) => {
    const prefix = sheet ? String(sheet) : "";
    const adj1 = adjustRef(String(ref1), dCol, dRow);
    if (!ref2)
      return `${prefix}${adj1}`;
    const adj2 = adjustRef(String(ref2), dCol, dRow);
    return `${prefix}${adj1}:${adj2}`;
  });
}
var NUMBER_FORMAT_COLOR_KEYWORDS = {
  BLACK: 0,
  WHITE: 1,
  RED: 2,
  GREEN: 3,
  BLUE: 4,
  YELLOW: 5,
  MAGENTA: 6,
  CYAN: 7
};
function splitNumberFormatSections(code) {
  if (!code)
    return [];
  const sections = [];
  let current = "";
  let inQuotes = false;
  for (let i = 0;i < code.length; i++) {
    const ch = code[i] ?? "";
    if (ch === '"') {
      current += ch;
      inQuotes = !inQuotes;
      continue;
    }
    if (ch === "\\" && i + 1 < code.length) {
      current += ch + (code[i + 1] ?? "");
      i++;
      continue;
    }
    if (ch === ";" && !inQuotes) {
      sections.push(current);
      current = "";
      continue;
    }
    current += ch;
  }
  sections.push(current);
  return sections;
}
function pickNumberFormatSectionIndex(sectionCount, value) {
  if (sectionCount <= 0)
    return null;
  if (sectionCount === 1)
    return 0;
  if (sectionCount === 2)
    return value < 0 ? 1 : 0;
  if (sectionCount >= 3) {
    if (value > 0)
      return 0;
    if (value < 0)
      return 1;
    if (Object.is(value, -0) || value === 0)
      return 2;
  }
  return 0;
}
function colorTokenToCss(token) {
  const normalized = token.replace(/\s+/g, "").toUpperCase();
  const keywordIdx = NUMBER_FORMAT_COLOR_KEYWORDS[normalized];
  if (keywordIdx != null) {
    return excelIndexedColorToCss(keywordIdx) ?? null;
  }
  const colorMatch = normalized.match(/^COLOR(\d{1,2})$/);
  if (colorMatch) {
    const idx = Number(colorMatch[1]);
    if (!Number.isNaN(idx) && idx > 0) {
      return excelIndexedColorToCss(idx - 1) ?? null;
    }
  }
  return null;
}
function extractNumberFormatColor(section) {
  let i = 0;
  while (i < section.length && /\s/.test(section[i] ?? ""))
    i++;
  while (i < section.length && section[i] === "[") {
    const close = section.indexOf("]", i);
    if (close === -1)
      break;
    const token = section.slice(i + 1, close);
    const css = colorTokenToCss(token);
    if (css)
      return css;
    i = close + 1;
    while (i < section.length && /\s/.test(section[i] ?? ""))
      i++;
  }
  return null;
}
function rgbToWalnutColor(r, g, b) {
  const toHex = (value2) => Math.max(0, Math.min(255, Math.round(value2))).toString(16).padStart(2, "0").toUpperCase();
  const value = `FF${toHex(r)}${toHex(g)}${toHex(b)}`;
  return {
    type: 1 /* COLOR_TYPE_RGB */,
    value,
    lastColor: value,
    transform: undefined
  };
}
function cssToWalnutColor(css) {
  const hex4 = parseHexColor2(css);
  if (hex4) {
    return rgbToWalnutColor(hex4.r, hex4.g, hex4.b);
  }
  const rgb2 = rgbaToRgb(css);
  if (rgb2) {
    return rgbToWalnutColor(rgb2[0], rgb2[1], rgb2[2]);
  }
  return null;
}
function getNumberFormatColorOverride(cell, style) {
  if (!style?.numberFormatCode)
    return null;
  const isStringy = cell.dataType === 3 /* CELL_DATA_TYPE_STRING */ || cell.dataType === 1 /* CELL_DATA_TYPE_SHARED_STRING */ || cell.dataType === 2 /* CELL_DATA_TYPE_INLINE_STRING */;
  if (isStringy)
    return null;
  const num = Number(cell.value);
  if (Number.isNaN(num))
    return null;
  const sections = splitNumberFormatSections(style.numberFormatCode);
  if (sections.length === 0)
    return null;
  const sectionIdx = pickNumberFormatSectionIndex(sections.length, num);
  if (sectionIdx == null)
    return null;
  const section = sections[Math.min(sectionIdx, sections.length - 1)] ?? "";
  const css = extractNumberFormatColor(section);
  if (!css)
    return null;
  return cssToWalnutColor(css);
}
function drawViewport(ctx, granolaWorkbook, sheetName, ...rest) {
  const isLegacy = Array.isArray(rest[0]);
  let colWidths;
  let rowHeights;
  let scrollX;
  let scrollY;
  let viewportW;
  let viewportH;
  let selRow;
  let selCol;
  let zoom;
  let styleInfos;
  let highlightColors;
  let highlightAddrs;
  let unsupportedAddrs;
  let highlightFormulaCell;
  let themeMap;
  let showFormulas;
  let rowIndexRemap;
  let resolvedCharts;
  let layoutExpand;
  let options;
  let interactions;
  let textLayoutCollector;
  if (isLegacy) {
    [
      colWidths,
      rowHeights,
      scrollX,
      scrollY,
      viewportW,
      viewportH,
      selRow,
      selCol,
      zoom,
      styleInfos,
      highlightColors,
      highlightAddrs,
      unsupportedAddrs,
      highlightFormulaCell,
      themeMap,
      showFormulas,
      rowIndexRemap,
      resolvedCharts,
      layoutExpand,
      options,
      interactions,
      textLayoutCollector
    ] = rest;
  } else {
    [
      scrollX,
      scrollY,
      viewportW,
      viewportH,
      selRow,
      selCol,
      zoom,
      styleInfos,
      highlightColors,
      highlightAddrs,
      unsupportedAddrs,
      highlightFormulaCell,
      themeMap,
      showFormulas,
      rowIndexRemap,
      resolvedCharts,
      layoutExpand,
      options,
      interactions,
      textLayoutCollector
    ] = rest;
    const worksheetForLayout = granolaWorkbook.sheets.getItemOrNullObject(sheetName);
    if (worksheetForLayout.isNullObject) {
      return;
    }
    const layout = worksheetForLayout.__getViewportLayout({
      maxCols: options?.maxCols,
      maxRows: options?.maxRows,
      showFormulas,
      colWidthOverridesPx: options?.colWidthOverridesPx,
      rowHeightOverridesPx: options?.rowHeightOverridesPx
    });
    colWidths = layout.viewColWidthsPx;
    rowHeights = layout.rowHeightsPx;
  }
  const { darkMode = false, accentColor = DEFAULT_UI_ACCENT_COLOR, rowAutoHeight } = options ?? {};
  const worksheet = granolaWorkbook.sheets.getItemOrNullObject(sheetName);
  if (worksheet.isNullObject) {
    return;
  }
  const worksheetRef = worksheet;
  const worksheetName = worksheet.name;
  const sheetRows = worksheet.__getRows();
  const mergedCells = worksheet.__getMergedCells();
  const renderMetadata = worksheet.__getSpreadsheetRenderMetadata(themeMap);
  const palette = darkMode ? {
    background: "#202020",
    grid: "#4d4d4d",
    headerBg: "#1e1e1e",
    headerBorder: "#2b2b2b",
    headerText: "#f5f5f5",
    unsupportedFill: "#2b2b2b"
  } : {
    background: "#ffffff",
    grid: "#cccccc",
    headerBg: "#f5f5f5",
    headerBorder: "#cccccc",
    headerText: "#333333",
    unsupportedFill: "#eeeeee"
  };
  const backgroundColor = palette.background;
  const gridColor = palette.grid;
  const headerBgColor = palette.headerBg;
  const headerBorderColor = palette.headerBorder;
  const headerTextColor = palette.headerText;
  const unsupportedFillColor = palette.unsupportedFill;
  const defaultTextColorValue = darkMode ? "FFFFFFFF" : "FF000000";
  const pivotStyleCache = buildPivotStyleRenderCache(worksheet, themeMap);
  const zoomSafe = zoom || 1;
  const scrollXLogical = scrollX / zoomSafe;
  const scrollYLogical = scrollY / zoomSafe;
  const loggedStyleIdx = new Set;
  const sharedMap = renderMetadata.sharedFormulaMap;
  const formattedCellCache = new Map;
  const spillBoundaryCursorByRow = new Map;
  const getDisplayText = (cell, effectiveStyleIdx) => {
    if (showFormulas) {
      if (cell.formula) {
        return `= ${cell.formula}`;
      }
      if (typeof cell.sharedFormulaSi === "number") {
        const sharedFormula = sharedMap.get(cell.sharedFormulaSi);
        if (sharedFormula) {
          return `= ${translateSharedFormula(sharedFormula.base, sharedFormula.anchor, cell.address)}`;
        }
      }
    }
    return formatCell(cell, styleInfos, formattedCellCache, effectiveStyleIdx);
  };
  const isSpreadsheetNumericCell = (cell) => {
    if (showFormulas) {
      if (cell.formula)
        return false;
      if (typeof cell.sharedFormulaSi === "number" && sharedMap.has(cell.sharedFormulaSi)) {
        return false;
      }
    }
    const num = Number(cell.value);
    return cell.dataType !== 3 /* CELL_DATA_TYPE_STRING */ && !Number.isNaN(num);
  };
  const resolveCellParagraphs = (cell, displayText) => cell.paragraphs && cell.paragraphs.length > 0 ? cell.paragraphs : [
    {
      runs: [
        {
          text: displayText,
          citations: [],
          reviewMarkIds: []
        }
      ]
    }
  ];
  const createCellTextElement = ({ paragraphs, resolvedTextStyle, widthPx, heightPx }) => ({
    paragraphs,
    textStyle: resolvedTextStyle,
    bbox: {
      xEmu: 0,
      yEmu: 0,
      widthEmu: Math.round(Math.max(1, widthPx) * 9525),
      heightEmu: Math.round(Math.max(1, heightPx) * 9525)
    },
    type: 1 /* ELEMENT_TYPE_TEXT */,
    effects: [],
    children: [],
    levelsStyles: [],
    id: "",
    citations: []
  });
  const applyCellRunTextStyles = ({ element, style, tableCellStyle, pivotFontColor, pivotBold, conditionalFormattingTextColor, numberFormatColorOverride }) => {
    const styleFontColor = style.font?.color ? cssToWalnutColor(style.font.color) : null;
    for (const para of element.paragraphs ?? []) {
      for (const run of para.runs ?? []) {
        run.textStyle = run.textStyle ?? {};
        if (typeof run.textStyle.fontSize === "number" && run.textStyle.fontSize > 0 && run.textStyle.fontSize < 100) {
          run.textStyle.fontSize = Math.round(run.textStyle.fontSize * 100);
        }
        if (!(typeof run.textStyle.fontSize === "number" && run.textStyle.fontSize > 0)) {
          const px = style.font?.size;
          const pt = typeof px === "number" && px > 0 ? px * 72 / 96 : 11;
          run.textStyle.fontSize = Math.round(pt * 100);
        }
        if (run.textStyle.italic == null && style.font?.italic != null) {
          run.textStyle.italic = !!style.font.italic;
        }
        if (run.textStyle.name == null) {
          run.textStyle.name = normalizeFamilyName2(style.font?.family);
        }
        if (run.textStyle.underline == null && style.font?.underline != null) {
          run.textStyle.underline = style.font.underline ? "single" : "none";
        }
        const emphasis = resolveCellTextEmphasis({
          currentTextStyle: run.textStyle,
          baseStyle: style,
          baseStyleFontColor: styleFontColor,
          tableCellStyle,
          pivotFontColor,
          pivotBold,
          conditionalFormattingTextColor,
          numberFormatColorOverride
        });
        if (emphasis.bold != null) {
          run.textStyle.bold = emphasis.bold;
        }
        if (emphasis.fill) {
          run.textStyle.fill = emphasis.fill;
        } else if (!run.textStyle.fill) {
          run.textStyle.fill = {
            color: {
              type: 1 /* COLOR_TYPE_RGB */,
              value: defaultTextColorValue,
              transform: undefined,
              lastColor: defaultTextColorValue
            },
            type: 1 /* FILL_TYPE_SOLID */,
            gradientStops: []
          };
        }
      }
    }
  };
  const measureCellTextMetrics = ({ cell, displayText, widthPx, heightPx, paddingPx, wrapTextEnabled, style, tableCellStyle, pivotFontColor, pivotBold, numberFormatColorOverride }) => {
    const measureWidthPx = wrapTextEnabled ? Math.max(1, widthPx) : UNBOUNDED_TEXT_MEASURE_WIDTH_PX;
    const element = createCellTextElement({
      paragraphs: resolveCellParagraphs(cell, displayText),
      resolvedTextStyle: { alignment: 1 /* ALIGNMENT_TYPE_LEFT */ },
      widthPx: measureWidthPx,
      heightPx
    });
    applyCellRunTextStyles({
      element,
      style,
      tableCellStyle,
      pivotFontColor,
      pivotBold,
      conditionalFormattingTextColor: null,
      numberFormatColorOverride
    });
    const layout = layoutTextBlock(element, themeMap, {
      resolvedStyle: { alignment: 1 /* ALIGNMENT_TYPE_LEFT */ },
      bboxPx: { x: 0, y: 0, width: measureWidthPx, height: heightPx },
      paddingPx,
      textScale: TEXT_SCALE,
      wrap: wrapTextEnabled
    });
    return {
      firstLineW: layout?.lines?.[0]?.widthPx ?? 0,
      contentHeight: layout?.lines?.reduce((height, line) => height + line.heightPx, 0) ?? 0
    };
  };
  const buildCellRenderLayout = ({ cell, displayText, resolvedTextStyle, widthPx, heightPx, paddingPx, wrapTextEnabled, style, tableCellStyle, pivotFontColor, pivotBold, conditionalFormattingTextColor, numberFormatColorOverride }) => {
    const element = createCellTextElement({
      paragraphs: resolveCellParagraphs(cell, displayText),
      resolvedTextStyle,
      widthPx,
      heightPx
    });
    applyCellRunTextStyles({
      element,
      style,
      tableCellStyle,
      pivotFontColor,
      pivotBold,
      conditionalFormattingTextColor,
      numberFormatColorOverride
    });
    return {
      element,
      layout: layoutTextBlock(element, themeMap, {
        resolvedStyle: resolvedTextStyle,
        bboxPx: { x: 0, y: 0, width: Math.max(1, widthPx), height: heightPx },
        paddingPx,
        textScale: TEXT_SCALE,
        wrap: wrapTextEnabled
      })
    };
  };
  function spillWidthRightUntilBlocked(rowIdx, col) {
    const rowPresent = rowMap.get(rowIdx) != null;
    if (!rowPresent)
      return colWidths[col] ?? 0;
    ensureRowCaches(rowIdx);
    const filled = getSheetCache(worksheetRef).rowNonEmptyCols.get(rowIdx) ?? [];
    const nextIdx = upperBound(filled, col);
    let stopExclusive = filled[nextIdx] ?? colWidths.length;
    const hasDataBarAt = (rr, cc) => {
      if (!cfRenderCache)
        return false;
      const targetCell = getCellAt2(rr, cc);
      return cfRenderCache.hasDataBar(rr, cc, targetCell);
    };
    for (let cc = col + 1;cc < stopExclusive; cc++) {
      if (hasDataBarAt(rowIdx, cc)) {
        stopExclusive = cc;
        break;
      }
    }
    const startOffset = colOffsets[col] ?? 0;
    const stopOffset = colOffsets[stopExclusive] ?? startOffset;
    return Math.max(0, stopOffset - startOffset);
  }
  function spillCrossesBoundary(rowIdx, boundaryCol) {
    if (boundaryCol < 0)
      return false;
    ensureRowCaches(rowIdx);
    const nonEmpty = getSheetCache(worksheetRef).rowNonEmptyCols.get(rowIdx) ?? [];
    let cursor = spillBoundaryCursorByRow.get(rowIdx);
    if (!cursor || cursor.nonEmpty !== nonEmpty || boundaryCol < cursor.lastBoundary) {
      cursor = { nonEmpty, lastBoundary: -1, pos: -1 };
      spillBoundaryCursorByRow.set(rowIdx, cursor);
    }
    while (cursor.pos + 1 < nonEmpty.length && (nonEmpty[cursor.pos + 1] ?? Number.POSITIVE_INFINITY) <= boundaryCol) {
      cursor.pos += 1;
    }
    cursor.lastBoundary = boundaryCol;
    if (cursor.pos < 0) {
      return false;
    }
    const originCol = nonEmpty[cursor.pos] ?? -1;
    if (originCol < 0) {
      return false;
    }
    const m = getSheetCache(worksheetRef).textMetrics.get(metricsKey(rowIdx, originCol));
    if (!m || m.isNumeric) {
      return false;
    }
    const spanWidth = Math.max(0, (colOffsets[boundaryCol + 1] ?? 0) - (colOffsets[originCol] ?? 0));
    const contentW = Math.max(0, spanWidth - (m.padLeft + m.padRight));
    const EPS = 0.001;
    return m.firstLineW + EPS >= contentW;
  }
  function addrInRange(rIdx, cIdx, range2) {
    const c1 = columnIndex(range2.startAddress);
    const r1 = rowIndex(range2.startAddress);
    const c2 = columnIndex(range2.endAddress);
    const r2 = rowIndex(range2.endAddress);
    const rMin = Math.min(r1, r2);
    const rMax = Math.max(r1, r2);
    const cMin = Math.min(c1, c2);
    const cMax = Math.max(c1, c2);
    return rIdx >= rMin && rIdx <= rMax && cIdx >= cMin && cIdx <= cMax;
  }
  function getCellNumericValue(cell) {
    if (!cell)
      return null;
    const n = Number(cell.value);
    if (Number.isNaN(n))
      return null;
    return n;
  }
  function getCellHyperlink(cell) {
    if (!cell)
      return null;
    const direct = cell.hyperlink?.uri ?? cell.hyperlink?.target;
    if (direct) {
      return direct;
    }
    for (const paragraph of cell.paragraphs ?? []) {
      for (const run of paragraph.runs ?? []) {
        const candidate = run.hyperlink?.uri ?? run.hyperlink?.target;
        if (candidate) {
          return candidate;
        }
      }
    }
    return null;
  }
  const cfRenderCache = worksheetName.trim() !== "" ? granolaWorkbook.getConditionalFormattingRenderCache(worksheetName) : null;
  ctx.save();
  ctx.scale(zoom, zoom);
  const devicePixelRatio2 = typeof window === "undefined" || typeof window.devicePixelRatio !== "number" ? 1 : window.devicePixelRatio;
  const hairline = 0.5 / (devicePixelRatio2 * zoom);
  const cache = getSheetCache(worksheet);
  function getCellAt2(rowIdx, colIdx) {
    ensureRowCaches(rowIdx);
    return cache.rowCellByColIdx.get(rowIdx)?.get(colIdx);
  }
  const findMergedBoundsForCell = (rowIdx, colIdx) => {
    const ranges = cache.mergedRangesByRow.get(rowIdx);
    if (!ranges || ranges.length === 0) {
      return;
    }
    return ranges.find((bounds) => colIdx >= bounds.colMin && colIdx <= bounds.colMax);
  };
  const boundaryCrossesMergedHorizontally = (rowIdx, colIdx) => {
    const spans = cache.mergedHorizontalBoundariesByRow.get(rowIdx);
    if (!spans || spans.length === 0) {
      return false;
    }
    for (const span of spans) {
      if (colIdx >= span.colMin && colIdx <= span.colMax) {
        return true;
      }
    }
    return false;
  };
  const boundaryCrossesMergedVertically = (rowIdx, colIdx) => {
    const spans = cache.mergedVerticalBoundariesByCol.get(colIdx);
    if (!spans || spans.length === 0) {
      return false;
    }
    for (const span of spans) {
      if (rowIdx >= span.rowMin && rowIdx <= span.rowMax) {
        return true;
      }
    }
    return false;
  };
  const borderStyleWeight = {
    thin: 1,
    dashed: 2,
    dashDot: 2,
    dashDotDot: 2,
    medium: 3,
    mediumDashed: 3,
    slantDashDot: 3,
    thick: 4,
    double: 5
  };
  const weightOf = (styleName) => styleName ? borderStyleWeight[styleName] ?? 0 : 0;
  const colOffsets = [0];
  for (let i = 0;i < colWidths.length; i++)
    colOffsets[i + 1] = (colOffsets[i] ?? 0) + (colWidths[i] ?? 0);
  const rowOffsets = [0];
  for (let i = 0;i < rowHeights.length; i++)
    rowOffsets[i + 1] = (rowOffsets[i] ?? 0) + (rowHeights[i] ?? 0);
  let startCol = Math.max(0, lowerBound(colOffsets, scrollXLogical) - 1);
  const endCol = Math.min(colWidths.length - 1, lowerBound(colOffsets, scrollXLogical + viewportW / zoom) + 1);
  let startRow = Math.max(0, lowerBound(rowOffsets, scrollYLogical) - 1);
  const endRow = Math.min(rowHeights.length - 1, lowerBound(rowOffsets, scrollYLogical + viewportH / zoom) + 1);
  ensureMergedRangeCaches(cache, mergedCells);
  if (mergedCells.length > 0) {
    ensureMergedAnchorCaches(cache, mergedCells);
    let expanded = true;
    while (expanded) {
      expanded = false;
      for (let r = startRow;r <= endRow; r++) {
        const anchorRow = cache.mergedRowAnchorByRow.get(r);
        if (anchorRow != null && anchorRow < startRow) {
          startRow = Math.max(0, anchorRow);
          expanded = true;
          break;
        }
      }
      for (let c = startCol;c <= endCol; c++) {
        const anchorCol = cache.mergedColAnchorByCol.get(c);
        if (anchorCol != null && anchorCol < startCol) {
          startCol = Math.max(0, anchorCol);
          expanded = true;
          break;
        }
      }
    }
  }
  ctx.clearRect(0, 0, viewportW / zoom, viewportH / zoom);
  ctx.fillStyle = backgroundColor;
  ctx.fillRect(0, 0, viewportW / zoom, viewportH / zoom);
  const actualByIdx = new Map;
  for (const r of sheetRows)
    actualByIdx.set(r.index - 1, r);
  const rowMap = new Map;
  if (rowIndexRemap && rowIndexRemap.length > 0) {
    const N = rowHeights.length;
    for (let i = 0;i < N; i++) {
      const actualIdx = rowIndexRemap[i] ?? i;
      const row2 = actualByIdx.get(actualIdx);
      if (row2)
        rowMap.set(i, row2);
    }
  } else {
    for (const r of sheetRows)
      rowMap.set(r.index - 1, r);
  }
  const listValidationEntries = renderMetadata.listValidationEntries;
  const getListValidationForCell = (rowIdx, colIdx) => {
    for (const entry of listValidationEntries) {
      for (const range2 of entry.ranges) {
        if (addrInRange(rowIdx, colIdx, range2))
          return entry;
      }
    }
    return null;
  };
  function ensureRowCaches(rowIdx) {
    if (cache.rowCellByColIdx.has(rowIdx) && cache.rowNonEmptyCols.has(rowIdx))
      return;
    const row2 = rowMap.get(rowIdx);
    if (!row2) {
      cache.rowCellByColIdx.set(rowIdx, new Map);
      cache.rowNonEmptyCols.set(rowIdx, []);
      return;
    }
    const byCol = new Map;
    const nonEmpty = [];
    for (const cel of row2.cells) {
      const cIdx = columnIndex(cel.address);
      byCol.set(cIdx, cel);
      const hasValue = cel.value != null && String(cel.value) !== "";
      const hasRichText = !!cel.paragraphs?.some((p) => p.runs?.some((r) => (r.text ?? "").length > 0));
      if (hasValue || hasRichText || cel.formula || typeof cel.sharedFormulaSi === "number")
        nonEmpty.push(cIdx);
    }
    nonEmpty.sort((a, b) => a - b);
    cache.rowCellByColIdx.set(rowIdx, byCol);
    cache.rowNonEmptyCols.set(rowIdx, nonEmpty);
  }
  const colStyleIdxs = renderMetadata.colStyleIndices;
  const tableResolversByRow = renderMetadata.tableResolversByRow;
  const tableHorizontalBoundaries = renderMetadata.tableHorizontalBoundaries;
  const mapToActualRow = (visibleRow) => rowIndexRemap && rowIndexRemap[visibleRow] != null ? rowIndexRemap[visibleRow] : visibleRow;
  const findTableResolver = (rowIdx, colIdx) => {
    const rowResolvers = tableResolversByRow.get(rowIdx);
    if (!rowResolvers || rowResolvers.length === 0) {
      return;
    }
    return rowResolvers.find((resolver) => resolver.contains(rowIdx, colIdx));
  };
  for (let r = startRow;r <= endRow; r++) {
    const row2 = rowMap.get(r);
    const y2 = COL_HEADER_H + (rowOffsets[r] ?? 0) - scrollYLogical;
    const rowHeightPx = rowHeights[r] ?? 0;
    const rowAlreadyMeasured = !!rowAutoHeight?.hasMeasuredRow?.(r);
    const rowAutoEligible = !!rowAutoHeight && rowHeightPx > 0 && rowAutoHeight.isRowAuto(r, row2) && !rowAlreadyMeasured;
    const rowBaselineHeight = rowAutoEligible ? rowAutoHeight.getBaselineHeight?.(r, row2) ?? rowHeightPx : 0;
    let rowAutoDesiredHeight = rowAutoEligible ? rowBaselineHeight : 0;
    const pendingTextDraws = [];
    for (let c = startCol;c <= endCol; c++) {
      const x2 = ROW_HEADER_W + (colOffsets[c] ?? 0) - scrollXLogical;
      let w = colWidths[c] ?? 0;
      let h = rowHeightPx;
      const cell = getCellAt2(r, c);
      const actualRowIdx = mapToActualRow(r);
      const tableResolver = findTableResolver(actualRowIdx, c);
      const addr = `${columnLabel(c)}${r + 1}`;
      const pivotStyle = getPivotCellRenderStyle(pivotStyleCache, actualRowIdx, c);
      const tableCellStyle = tableResolver ? tableResolver.resolveCell(actualRowIdx, c) : undefined;
      const pivotIndentPx = pivotStyle?.indentPx ?? 0;
      const listValidation = listValidationEntries.length > 0 ? getListValidationForCell(r, c) : null;
      const listValidationArrowSize = listValidation != null ? getListValidationArrowSizePx(h) : 0;
      const listValidationArrowReserve = listValidation != null ? getListValidationArrowReservePx(h) : 0;
      const rowStyleIdx = row2?.styleIndex;
      const colStyleIdx = colStyleIdxs[c];
      const effectiveStyleIdx = cell?.styleIndex ?? rowStyleIdx ?? colStyleIdx ?? 0;
      const style = styleInfos[effectiveStyleIdx] ?? {};
      const wrapTextEnabled = style.wrapText === true;
      const diagColor = style.borders?.diagonal;
      const diagUp = !!style.borderDiagonalUp;
      const diagDown = !!style.borderDiagonalDown;
      const diagStyle = style.borderStyles?.diagonal;
      const numberFormatColorOverride = cell && style ? getNumberFormatColorOverride(cell, style) : null;
      if (cell) {
        const hyperlinkUrl = getCellHyperlink(cell);
        if (hyperlinkUrl && interactions?.addHyperlinkRect) {
          const hyperlinkKey = cell.address ?? `cell-${r}-${c}`;
          const hyperlinkId = `hyperlink:${hyperlinkKey}`;
          interactions.addHyperlinkRect({
            id: hyperlinkId,
            cssBounds: {
              x: x2 * zoom,
              y: y2 * zoom,
              width: w * zoom,
              height: h * zoom
            },
            url: hyperlinkUrl
          });
        }
        const basePx0 = style.font?.size ?? 11 * (96 / 72);
        const scaledBasePx0 = basePx0 * TEXT_SCALE;
        const { padLr: basePadLr0, padTb: padTb0 } = resolveCellPadding(scaledBasePx0 || 11);
        const padLeft0 = basePadLr0 + pivotIndentPx;
        const padRight0 = basePadLr0 + listValidationArrowReserve;
        const isCheckboxCell2 = !showFormulas && granolaWorkbook.__isCheckboxStyleIndex(effectiveStyleIdx);
        if (isCheckboxCell2) {
          cache.textMetrics.set(metricsKey(r, c), {
            firstLineW: 0,
            padLeft: padLeft0,
            padRight: padRight0,
            padTb: padTb0,
            isNumeric: false
          });
        } else {
          const displayText = getDisplayText(cell, effectiveStyleIdx);
          const isNumeric = isSpreadsheetNumericCell(cell);
          if (!isNumeric) {
            const metrics = measureCellTextMetrics({
              cell,
              displayText,
              widthPx: w,
              heightPx: h,
              paddingPx: {
                left: padLeft0,
                right: padRight0,
                top: padTb0,
                bottom: padTb0
              },
              wrapTextEnabled,
              style,
              tableCellStyle,
              pivotFontColor: pivotStyle?.fontColor,
              pivotBold: pivotStyle?.bold === true,
              numberFormatColorOverride
            });
            cache.textMetrics.set(metricsKey(r, c), {
              firstLineW: metrics.firstLineW,
              padLeft: padLeft0,
              padRight: padRight0,
              padTb: padTb0,
              isNumeric
            });
          } else {
            cache.textMetrics.set(metricsKey(r, c), {
              firstLineW: 0,
              padLeft: padLeft0,
              padRight: padRight0,
              padTb: padTb0,
              isNumeric
            });
          }
        }
      }
      let isMergedTopLeft = false;
      let mergedRMin = r;
      let mergedRMax = r;
      let mergedCMin = c;
      let mergedCMax = c;
      let drawBorders = style.borders ?? null;
      let drawBorderStyles = style.borderStyles ?? null;
      {
        const foundMergedBounds = findMergedBoundsForCell(r, c);
        if (foundMergedBounds) {
          mergedRMin = foundMergedBounds.rowMin;
          mergedRMax = foundMergedBounds.rowMax;
          mergedCMin = foundMergedBounds.colMin;
          mergedCMax = foundMergedBounds.colMax;
          isMergedTopLeft = r === mergedRMin && c === mergedCMin;
          if (!isMergedTopLeft) {
            continue;
          }
          w = (colOffsets[mergedCMax + 1] ?? 0) - (colOffsets[mergedCMin] ?? 0);
          h = (rowOffsets[mergedRMax + 1] ?? 0) - (rowOffsets[mergedRMin] ?? 0);
          layoutExpand?.(x2, y2, w, h, "mergedCell");
          let topPickW = 0, bottomPickW = 0, leftPickW = 0, rightPickW = 0;
          const aggBorders = {};
          const aggStyles = {};
          for (let cc = mergedCMin;cc <= mergedCMax; cc++) {
            const celTop = getCellAt2(mergedRMin, cc);
            const stTop = styleInfos[celTop?.styleIndex ?? 0] ?? {};
            const sName = stTop.borderStyles?.top;
            const wgt = weightOf(sName);
            if (stTop.borders?.top && wgt >= topPickW) {
              aggBorders.top = stTop.borders.top;
              aggStyles.top = sName;
              topPickW = wgt;
            }
          }
          for (let cc = mergedCMin;cc <= mergedCMax; cc++) {
            const celBot = getCellAt2(mergedRMax, cc);
            const stBot = styleInfos[celBot?.styleIndex ?? 0] ?? {};
            const sName = stBot.borderStyles?.bottom;
            const wgt = weightOf(sName);
            if (stBot.borders?.bottom && wgt >= bottomPickW) {
              aggBorders.bottom = stBot.borders.bottom;
              aggStyles.bottom = sName;
              bottomPickW = wgt;
            }
          }
          for (let rr2 = mergedRMin;rr2 <= mergedRMax; rr2++) {
            const celLeft = getCellAt2(rr2, mergedCMin);
            const stLeft = styleInfos[celLeft?.styleIndex ?? 0] ?? {};
            const sName = stLeft.borderStyles?.left;
            const wgt = weightOf(sName);
            if (stLeft.borders?.left && wgt >= leftPickW) {
              aggBorders.left = stLeft.borders.left;
              aggStyles.left = sName;
              leftPickW = wgt;
            }
          }
          for (let rr2 = mergedRMin;rr2 <= mergedRMax; rr2++) {
            const celRight = getCellAt2(rr2, mergedCMax);
            const stRight = styleInfos[celRight?.styleIndex ?? 0] ?? {};
            const sName = stRight.borderStyles?.right;
            const wgt = weightOf(sName);
            if (stRight.borders?.right && wgt >= rightPickW) {
              aggBorders.right = stRight.borders.right;
              aggStyles.right = sName;
              rightPickW = wgt;
            }
          }
          drawBorders = aggBorders;
          drawBorderStyles = aggStyles;
        }
      }
      if (tableResolver) {
        const tableBorderOverrides = tableResolver.resolveBorders(actualRowIdx, c);
        if (Object.keys(tableBorderOverrides).length > 0) {
          if (drawBorders && drawBorders === style.borders) {
            drawBorders = { ...drawBorders };
          }
          if (drawBorderStyles && drawBorderStyles === style.borderStyles) {
            drawBorderStyles = { ...drawBorderStyles };
          }
          if (!drawBorders)
            drawBorders = {};
          if (!drawBorderStyles)
            drawBorderStyles = {};
          const edges = [
            "top",
            "bottom",
            "left",
            "right"
          ];
          for (const edge of edges) {
            const override = tableBorderOverrides[edge];
            const cellBorderExplicit = style.borderSources?.[edge] === "cell";
            if (override && !cellBorderExplicit) {
              drawBorders[edge] = override.colorCss;
              drawBorderStyles[edge] = override.style;
            }
          }
        }
      }
      if (pivotStyle && Object.keys(pivotStyle.borders).length > 0) {
        if (drawBorders && drawBorders === style.borders) {
          drawBorders = { ...drawBorders };
        }
        if (drawBorderStyles && drawBorderStyles === style.borderStyles) {
          drawBorderStyles = { ...drawBorderStyles };
        }
        if (!drawBorders)
          drawBorders = {};
        if (!drawBorderStyles)
          drawBorderStyles = {};
        const edges = [
          "top",
          "bottom",
          "left",
          "right"
        ];
        for (const edge of edges) {
          const override = pivotStyle.borders[edge];
          if (override && !drawBorders[edge]) {
            drawBorders[edge] = override.colorCss;
            drawBorderStyles[edge] = override.style;
          }
        }
      }
      const resolvedCellStyle = resolveCellRenderStyle({
        style,
        cfRenderCache,
        rowIdx: r,
        colIdx: c,
        cell
      });
      if (tableCellStyle?.fillCss) {
        layoutExpand?.(x2, y2, w, h, "tableFill");
        ctx.fillStyle = tableCellStyle.fillCss;
        ctx.fillRect(x2, y2, w, h);
      }
      if (pivotStyle?.fillCss) {
        layoutExpand?.(x2, y2, w, h, "pivotFill");
        ctx.fillStyle = pivotStyle.fillCss;
        ctx.fillRect(x2, y2, w, h);
      }
      const baseFillCss = resolvedCellStyle.baseFillCss;
      if (baseFillCss) {
        layoutExpand?.(x2, y2, w, h, "cellFill");
        ctx.fillStyle = baseFillCss;
        ctx.fillRect(x2, y2, w, h);
      }
      const cfFill = resolvedCellStyle.conditionalFormatting.fillCss;
      const cfTextColorObj = resolvedCellStyle.conditionalFormatting.textColor;
      if (cfFill) {
        layoutExpand?.(x2, y2, w, h, "cfFill");
        ctx.fillStyle = cfFill;
        ctx.fillRect(x2, y2, w, h);
      }
      if (unsupportedAddrs.has(`${worksheetName}:${addr}`)) {
        layoutExpand?.(x2, y2, w, h, "unsupported");
        ctx.fillStyle = unsupportedFillColor;
        ctx.fillRect(x2, y2, w, h);
      }
      if (highlightFormulaCell && selRow === r && selCol === c) {
        ctx.fillStyle = "rgba(255,255,0,0.2)";
        ctx.fillRect(x2, y2, w, h);
      }
      const dataBar = cfRenderCache ? cfRenderCache.getDataBar(r, c, cell) : null;
      if (dataBar) {
        const v = getCellNumericValue(cell);
        if (v != null) {
          const innerPad = 1;
          const innerW = Math.max(0, w - innerPad * 2);
          const innerH = Math.max(0, h - innerPad * 2);
          const minV = dataBar.vMin;
          const maxV = dataBar.vMax;
          const mixedSign = minV < 0 && maxV > 0;
          if (maxV !== minV && innerW > 0 && innerH > 0) {
            let barX = x2 + innerPad;
            let barW = 0;
            let axisPx = 0;
            let growsRight = true;
            if (minV >= 0) {
              const t = Math.max(0, Math.min(1, (v - minV) / (maxV - minV)));
              barW = t * innerW;
              growsRight = true;
            } else if (maxV <= 0) {
              const t = Math.max(0, Math.min(1, (v - maxV) / (minV - maxV)));
              barW = t * innerW;
              barX = x2 + innerPad + (innerW - barW);
              growsRight = false;
            } else {
              const axis = -minV / (maxV - minV);
              axisPx = innerW * axis;
              if (v >= 0) {
                const t = Math.max(0, Math.min(1, v / maxV));
                barX = x2 + innerPad + axisPx;
                barW = t * (innerW - axisPx);
                growsRight = true;
              } else {
                const t = Math.max(0, Math.min(1, v / minV));
                barX = x2 + innerPad + axisPx - t * axisPx;
                barW = t * axisPx;
                growsRight = false;
              }
            }
            if (barW > 0.5) {
              layoutExpand?.(barX, y2 + innerPad, barW, innerH, "dataBar");
              ctx.save();
              const barColorCss = v < 0 ? dataBar.negativeColorCss ?? dataBar.colorCss : dataBar.colorCss;
              const barBorderColorCss = v < 0 ? dataBar.negativeBorderColorCss ?? (dataBar.negativeBorderColorSameAsPositive ? dataBar.borderColorCss : dataBar.border ? dataBar.negativeColorCss ?? dataBar.borderColorCss : null) : dataBar.border ? dataBar.borderColorCss ?? dataBar.colorCss : null;
              ctx.globalAlpha = 1;
              if (dataBar.gradient) {
                const fillGradient = ctx.createLinearGradient(barX, y2 + innerPad, barX + barW, y2 + innerPad);
                if (growsRight) {
                  fillGradient.addColorStop(0, barColorCss);
                  fillGradient.addColorStop(1, "rgba(255,255,255,0.92)");
                } else {
                  fillGradient.addColorStop(0, "rgba(255,255,255,0.92)");
                  fillGradient.addColorStop(1, barColorCss);
                }
                ctx.fillStyle = fillGradient;
              } else {
                ctx.fillStyle = barColorCss;
              }
              ctx.fillRect(barX, y2 + innerPad, barW, innerH);
              if (barBorderColorCss) {
                ctx.globalAlpha = 0.85;
                ctx.strokeStyle = barBorderColorCss;
                ctx.lineWidth = 1;
                ctx.strokeRect(Math.round(barX) + 0.5, Math.round(y2 + innerPad) + 0.5, Math.max(0, Math.round(barW) - 1), Math.max(0, Math.round(innerH) - 1));
              }
              ctx.restore();
            }
            if (mixedSign && dataBar.axisPosition !== "none") {
              const axisX = x2 + innerPad + axisPx;
              ctx.save();
              ctx.strokeStyle = dataBar.axisColorCss ?? "#000000";
              ctx.lineWidth = 1;
              ctx.setLineDash([2, 2]);
              ctx.beginPath();
              ctx.moveTo(axisX + 0.5, y2 + innerPad);
              ctx.lineTo(axisX + 0.5, y2 + innerPad + innerH);
              ctx.stroke();
              ctx.restore();
            }
          }
        }
      }
      if (drawBorders) {
        const b = drawBorders;
        const bs = drawBorderStyles ?? {};
        if (b.top) {
          if (bs.top === "double") {
            drawDoubleBorder(ctx, "top", b.top, x2, y2, w, h);
          } else {
            if (bs.top === "slantDashDot") {
              drawSlantDashDot(ctx, "top", b.top, x2, y2, w, h);
            } else {
              applyStrokeForBorder(ctx, bs.top, b.top);
              ctx.beginPath();
              ctx.moveTo(x2, y2);
              ctx.lineTo(x2 + w, y2);
              ctx.stroke();
              ctx.restore();
            }
          }
        }
        if (b.bottom) {
          if (bs.bottom === "double") {
            drawDoubleBorder(ctx, "bottom", b.bottom, x2, y2, w, h);
          } else {
            if (bs.bottom === "slantDashDot") {
              drawSlantDashDot(ctx, "bottom", b.bottom, x2, y2, w, h);
            } else {
              applyStrokeForBorder(ctx, bs.bottom, b.bottom);
              ctx.beginPath();
              ctx.moveTo(x2, y2 + h);
              ctx.lineTo(x2 + w, y2 + h);
              ctx.stroke();
              ctx.restore();
            }
          }
        }
        if (b.left) {
          if (bs.left === "double") {
            drawDoubleBorder(ctx, "left", b.left, x2, y2, w, h);
          } else {
            if (bs.left === "slantDashDot") {
              drawSlantDashDot(ctx, "left", b.left, x2, y2, w, h);
            } else {
              applyStrokeForBorder(ctx, bs.left, b.left);
              ctx.beginPath();
              ctx.moveTo(x2, y2);
              ctx.lineTo(x2, y2 + h);
              ctx.stroke();
              ctx.restore();
            }
          }
        }
        if (b.right) {
          if (bs.right === "double") {
            drawDoubleBorder(ctx, "right", b.right, x2, y2, w, h);
          } else {
            if (bs.right === "slantDashDot") {
              drawSlantDashDot(ctx, "right", b.right, x2, y2, w, h);
            } else {
              applyStrokeForBorder(ctx, bs.right, b.right);
              ctx.beginPath();
              ctx.moveTo(x2 + w, y2);
              ctx.lineTo(x2 + w, y2 + h);
              ctx.stroke();
              ctx.restore();
            }
          }
        }
      }
      if (worksheet.showGridLines !== false) {
        const hasAnyFill = resolvedCellStyle.hasAnyFill;
        if (!hasAnyFill) {
          ctx.strokeStyle = gridColor;
          ctx.lineWidth = hairline;
          const aboveStyle = (() => {
            const aboveCell = getCellAt2(r - 1, c);
            const sIdx = aboveCell?.styleIndex ?? 0;
            return styleInfos[sIdx] ?? {};
          })();
          const leftStyle = (() => {
            const leftCell = getCellAt2(r, c - 1);
            const sIdx = leftCell?.styleIndex ?? 0;
            return styleInfos[sIdx] ?? {};
          })();
          const hasTopBorder = !!drawBorders?.top;
          const aboveHasBottom = !!aboveStyle.borders?.bottom;
          const crossesMergedHoriz = boundaryCrossesMergedHorizontally(r, c);
          const insideTableHoriz = tableHorizontalBoundaries.has(`${r}:${c}`);
          if (!hasTopBorder && !aboveHasBottom && !crossesMergedHoriz && !insideTableHoriz) {
            ctx.beginPath();
            ctx.moveTo(x2, y2);
            ctx.lineTo(x2 + w, y2);
            ctx.stroke();
          }
          const hasLeftBorder = !!drawBorders?.left;
          const leftHasRight = !!leftStyle.borders?.right;
          const spillCoversBoundary = spillCrossesBoundary(r, c - 1);
          const crossesMergedVert = boundaryCrossesMergedVertically(r, c);
          if (!hasLeftBorder && !leftHasRight && !spillCoversBoundary && !crossesMergedVert) {
            ctx.beginPath();
            ctx.moveTo(x2, y2);
            ctx.lineTo(x2, y2 + h);
            ctx.stroke();
          }
        }
      }
      if (highlightAddrs.has(addr)) {
        const hl = highlightColors[addr];
        if (hl) {
          ctx.save();
          ctx.fillStyle = hl + "22";
          ctx.fillRect(x2, y2, w, h);
          ctx.restore();
          const neighborAddr = (rowIdx, colIdx) => `${columnLabel(colIdx)}${rowIdx + 1}`;
          ctx.save();
          ctx.strokeStyle = hl;
          ctx.lineWidth = 2;
          const topAddr = r > 0 ? neighborAddr(r - 1, c) : null;
          if (!topAddr || !highlightAddrs.has(topAddr)) {
            ctx.beginPath();
            ctx.moveTo(x2, y2);
            ctx.lineTo(x2 + w, y2);
            ctx.stroke();
          }
          const bottomAddr = neighborAddr(r + 1, c);
          if (!highlightAddrs.has(bottomAddr)) {
            ctx.beginPath();
            ctx.moveTo(x2, y2 + h);
            ctx.lineTo(x2 + w, y2 + h);
            ctx.stroke();
          }
          const leftAddr = c > 0 ? neighborAddr(r, c - 1) : null;
          if (!leftAddr || !highlightAddrs.has(leftAddr)) {
            ctx.beginPath();
            ctx.moveTo(x2, y2);
            ctx.lineTo(x2, y2 + h);
            ctx.stroke();
          }
          const rightAddr = neighborAddr(r, c + 1);
          if (!highlightAddrs.has(rightAddr)) {
            ctx.beginPath();
            ctx.moveTo(x2 + w, y2);
            ctx.lineTo(x2 + w, y2 + h);
            ctx.stroke();
          }
          ctx.restore();
        }
      }
      if (listValidation) {
        if (interactions?.addDataValidationTarget) {
          const sheetName2 = worksheetName || "sheet";
          interactions.addDataValidationTarget({
            id: `dv:${sheetName2}:${addr}`,
            addr,
            sheetName: sheetName2,
            cssBounds: {
              x: (x2 + Math.max(0, w - listValidationArrowReserve)) * zoom,
              y: y2 * zoom,
              width: listValidationArrowReserve * zoom,
              height: h * zoom
            }
          });
        }
      }
      const isCheckboxCell = !!cell && !listValidation && !showFormulas && granolaWorkbook.__isCheckboxStyleIndex(effectiveStyleIdx);
      const checkboxInfo = cell ? getCheckboxRenderInfo({
        cell,
        isCheckbox: isCheckboxCell,
        x: x2,
        y: y2,
        w,
        h,
        zoom
      }) : null;
      const baseFontPxForIcon = style.font?.size ?? 10 * (96 / 72);
      const iconSetInfo = cell && !listValidation && !checkboxInfo && cfRenderCache ? cfRenderCache.getIconSet(r, c, cell) : null;
      const iconLayout = iconSetInfo && cell ? getConditionalFormattingIconLayout({
        x: x2,
        y: y2,
        width: w,
        height: h,
        fontSizePx: baseFontPxForIcon,
        iconSetName: iconSetInfo.iconSetName,
        showValue: iconSetInfo.showValue
      }) : null;
      if (checkboxInfo) {
        if (interactions?.addCheckboxTarget) {
          interactions.addCheckboxTarget({
            id: `checkbox:${addr}`,
            address: addr,
            checked: checkboxInfo.checked,
            cssBounds: checkboxInfo.cssBounds
          });
        }
        pendingTextDraws.push(() => {
          drawCheckbox(ctx, checkboxInfo, { accentColor, darkMode });
          if (diagColor && (diagUp || diagDown)) {
            applyStrokeForBorder(ctx, diagStyle, diagColor);
            if (diagDown) {
              ctx.beginPath();
              ctx.moveTo(x2, y2);
              ctx.lineTo(x2 + w, y2 + h);
              ctx.stroke();
            }
            if (diagUp) {
              ctx.beginPath();
              ctx.moveTo(x2, y2 + h);
              ctx.lineTo(x2 + w, y2);
              ctx.stroke();
            }
            ctx.restore();
          }
        });
      }
      if (cell && !checkboxInfo) {
        const hideCellValueForIcon = !!iconSetInfo && !iconSetInfo.showValue;
        const displayText = hideCellValueForIcon ? "" : getDisplayText(cell, effectiveStyleIdx);
        const isNumeric = isSpreadsheetNumericCell(cell);
        const resolved = {
          anchor: style.verticalAlign ?? 3 /* ANCHOR_TYPE_BOTTOM */,
          alignment: style.align === "center" ? 2 /* ALIGNMENT_TYPE_CENTER */ : style.align === "right" ? 3 /* ALIGNMENT_TYPE_RIGHT */ : style.align === "left" ? 1 /* ALIGNMENT_TYPE_LEFT */ : isNumeric ? 3 /* ALIGNMENT_TYPE_RIGHT */ : 1 /* ALIGNMENT_TYPE_LEFT */
        };
        const pivotFontColor = pivotStyle?.fontColor;
        const pivotFontBold = pivotStyle?.bold === true;
        if (typeof cell.styleIndex === "number" && !loggedStyleIdx.has(cell.styleIndex) && loggedStyleIdx.size < 12) {
          loggedStyleIdx.add(cell.styleIndex);
        }
        const spillW = spillWidthRightUntilBlocked(r, c);
        const basePx = style.font?.size ?? 10 * (96 / 72);
        const scaledBasePx = basePx * TEXT_SCALE;
        const { padLr: basePadLr, padTb } = resolveCellPadding(scaledBasePx || 11);
        const iconPadLeft = iconLayout?.reservedWidth ?? 0;
        const padLeft = basePadLr + pivotIndentPx + iconPadLeft;
        const padRight = basePadLr + listValidationArrowReserve;
        const firstLineWExact = cache.textMetrics.get(metricsKey(r, c))?.firstLineW ?? 0;
        cache.textMetrics.set(metricsKey(r, c), {
          firstLineW: firstLineWExact,
          padLeft,
          padRight,
          padTb,
          isNumeric
        });
        const contentW = Math.max(0, w - (padLeft + padRight));
        const actuallySpills = !wrapTextEnabled && !isNumeric && firstLineWExact > contentW;
        const measuredW = Math.max(w, firstLineWExact + (padLeft + padRight));
        const capW = isMergedTopLeft && (mergedCMax > mergedCMin || mergedRMax > mergedRMin) ? w : spillW;
        const drawW = actuallySpills ? Math.min(capW, measuredW) : w;
        const resolvedForSpill = actuallySpills ? { ...resolved, alignment: 1 /* ALIGNMENT_TYPE_LEFT */ } : resolved;
        const { element: drawElement, layout: drawLayout } = hideCellValueForIcon && displayText === "" ? { element: null, layout: null } : buildCellRenderLayout({
          cell,
          displayText,
          resolvedTextStyle: resolvedForSpill,
          widthPx: drawW,
          heightPx: h,
          paddingPx: {
            left: padLeft,
            right: padRight,
            top: padTb,
            bottom: padTb
          },
          wrapTextEnabled,
          style,
          tableCellStyle,
          pivotFontColor,
          pivotBold: pivotFontBold,
          conditionalFormattingTextColor: cfTextColorObj,
          numberFormatColorOverride
        });
        if (rowAutoEligible && mergedRMin === mergedRMax) {
          const measuredTextHeight = drawLayout?.lines?.reduce((height, line) => height + line.heightPx, 0) ?? 0;
          if (measuredTextHeight > rowAutoDesiredHeight) {
            rowAutoDesiredHeight = measuredTextHeight;
          }
        }
        const performDraw = () => {
          if (iconLayout && iconSetInfo) {
            drawConditionalFormattingIcon(ctx, {
              iconSetName: iconSetInfo.iconSetName,
              iconIndex: iconSetInfo.iconIndex,
              x: iconLayout.x,
              y: iconLayout.y,
              width: iconLayout.width,
              height: iconLayout.height
            });
          }
          if (hideCellValueForIcon && displayText === "") {
            return;
          }
          ctx.save();
          ctx.beginPath();
          ctx.rect(x2, y2, drawW, h);
          ctx.clip();
          if (drawLayout && drawElement) {
            renderTextBlock(drawElement, drawLayout, ctx, undefined, {
              resolvedStyle: resolvedForSpill,
              bboxPx: { x: x2, y: y2, width: drawW, height: h },
              paddingPx: {
                left: padLeft,
                right: padRight,
                top: padTb,
                bottom: padTb
              }
            });
          }
          ctx.restore();
        };
        pendingTextDraws.push(() => {
          layoutExpand?.(x2, y2, drawW, h, `text:addr=${addr} r=${r} c=${c} firstLine=${Math.round(firstLineWExact)} content=${Math.round(contentW)} draw=${Math.round(drawW)} spills=${actuallySpills}`);
          performDraw();
          if (listValidation && listValidationArrowSize > 0) {
            const arrowX = x2 + w - listValidationArrowSize - DATA_VALIDATION_ARROW_INSET_PX;
            const arrowY = y2 + (h - listValidationArrowSize) / 2;
            ctx.save();
            ctx.fillStyle = "rgba(107, 114, 128, 0.9)";
            ctx.beginPath();
            ctx.moveTo(arrowX, arrowY + 2);
            ctx.lineTo(arrowX + listValidationArrowSize, arrowY + 2);
            ctx.lineTo(arrowX + listValidationArrowSize / 2, arrowY + listValidationArrowSize);
            ctx.closePath();
            ctx.fill();
            ctx.restore();
          }
          if (diagColor && (diagUp || diagDown)) {
            applyStrokeForBorder(ctx, diagStyle, diagColor);
            if (diagDown) {
              ctx.beginPath();
              ctx.moveTo(x2, y2);
              ctx.lineTo(x2 + w, y2 + h);
              ctx.stroke();
            }
            if (diagUp) {
              ctx.beginPath();
              ctx.moveTo(x2, y2 + h);
              ctx.lineTo(x2 + w, y2);
              ctx.stroke();
            }
            ctx.restore();
          }
        });
      }
    }
    for (const fn of pendingTextDraws)
      fn();
    if (rowAutoEligible) {
      const currentHeight = rowHeightPx;
      const targetHeight = Math.max(rowBaselineHeight, rowAutoDesiredHeight);
      if (targetHeight > 0 && Math.abs(targetHeight - currentHeight) > 0.5) {
        rowAutoHeight.requestUpdate(r, targetHeight);
      }
      rowAutoHeight.markRowMeasured?.(r);
    }
  }
  drawSheetImages(ctx, worksheet, granolaWorkbook, colOffsets, rowOffsets, scrollXLogical, scrollYLogical, viewportW / zoom, viewportH / zoom, interactions?.addImageTarget, zoom);
  const sparklineSpecs = worksheet.sparklineGroups.renderContext;
  drawSparklineGroups(ctx, sparklineSpecs, colOffsets, rowOffsets, scrollXLogical, scrollYLogical, viewportW / zoom, viewportH / zoom, themeMap);
  drawSheetShapes(ctx, worksheet, colOffsets, rowOffsets, scrollXLogical, scrollYLogical, viewportW / zoom, viewportH / zoom, themeMap, layoutExpand, interactions?.addShapeTarget, zoom, textLayoutCollector);
  const chartHoverTargets = interactions?.setChartHoverTargets ? [] : null;
  drawSheetCharts(ctx, worksheet, granolaWorkbook, colOffsets, rowOffsets, scrollXLogical, scrollYLogical, viewportW / zoom, viewportH / zoom, themeMap, resolvedCharts, textLayoutCollector, chartHoverTargets ?? undefined, options?.mapCtx, options?.onMapViewport);
  if (chartHoverTargets) {
    interactions?.setChartHoverTargets?.(chartHoverTargets);
  }
  const emuToPx2 = (emu) => emu / 9525;
  const chartItems = worksheet.charts.items;
  if ((layoutExpand || interactions?.addChartTarget) && chartItems.length > 0) {
    for (const [chartIndex, chart2] of chartItems.entries()) {
      const d = chart2.toDrawingProto();
      if (!d.chart || !d.fromAnchor)
        continue;
      const fromCol = Number(d.fromAnchor.colId);
      const fromRow = Number(d.fromAnchor.rowId);
      const fromColOffset = colOffsets[fromCol];
      const fromRowOffset = rowOffsets[fromRow];
      if (fromColOffset == null || fromRowOffset == null)
        continue;
      const baseX = ROW_HEADER_W + fromColOffset + emuToPx2(Number(d.fromAnchor.colOffset)) - scrollXLogical;
      const baseY = COL_HEADER_H + fromRowOffset + emuToPx2(Number(d.fromAnchor.rowOffset)) - scrollYLogical;
      let w = null;
      let h = null;
      let usesTwoCellAnchor = false;
      if (d.toAnchor) {
        usesTwoCellAnchor = true;
        const toCol = Number(d.toAnchor.colId);
        const toRow = Number(d.toAnchor.rowId);
        const toColOffset = colOffsets[toCol];
        const toRowOffset = rowOffsets[toRow];
        if (toColOffset == null || toRowOffset == null)
          continue;
        const x1 = ROW_HEADER_W + toColOffset + emuToPx2(Number(d.toAnchor.colOffset)) - scrollXLogical;
        const y1 = COL_HEADER_H + toRowOffset + emuToPx2(Number(d.toAnchor.rowOffset)) - scrollYLogical;
        w = x1 - baseX;
        h = y1 - baseY;
      } else if (d.extentCx && d.extentCy) {
        w = emuToPx2(Number(d.extentCx));
        h = emuToPx2(Number(d.extentCy));
      }
      if (w == null || h == null || w <= 0 || h <= 0)
        continue;
      layoutExpand?.(baseX, baseY, w, h, "chart");
      const chartId = d.chart?.id || chart2.id || `chart-${chartIndex}`;
      if (interactions?.addChartTarget) {
        interactions.addChartTarget({
          id: chartId,
          logicalBounds: { x: baseX, y: baseY, width: w, height: h },
          cssBounds: {
            x: baseX * zoom,
            y: baseY * zoom,
            width: w * zoom,
            height: h * zoom
          },
          drawing: d,
          usesTwoCellAnchor
        });
      }
    }
  }
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.font = "12px sans-serif";
  for (let c = startCol;c <= endCol; c++) {
    const x2 = ROW_HEADER_W + (colOffsets[c] ?? 0) - scrollXLogical;
    const w = colWidths[c] ?? 0;
    ctx.fillStyle = headerBgColor;
    ctx.fillRect(x2, 0, w, COL_HEADER_H);
    ctx.strokeStyle = headerBorderColor;
    ctx.lineWidth = hairline;
    ctx.strokeRect(x2, 0, w, COL_HEADER_H);
    ctx.fillStyle = headerTextColor;
    ctx.fillText(columnLabel(c), x2 + w / 2, COL_HEADER_H / 2);
  }
  for (let r = startRow;r <= endRow; r++) {
    const y2 = COL_HEADER_H + (rowOffsets[r] ?? 0) - scrollYLogical;
    const h = rowHeights[r] ?? 0;
    if (h <= 0)
      continue;
    ctx.fillStyle = headerBgColor;
    ctx.fillRect(0, y2, ROW_HEADER_W, h);
    ctx.strokeStyle = headerBorderColor;
    ctx.lineWidth = hairline;
    ctx.strokeRect(0, y2, ROW_HEADER_W, h);
    ctx.fillStyle = headerTextColor;
    ctx.fillText((r + 1).toString(), ROW_HEADER_W / 2, y2 + h / 2);
  }
  ctx.fillStyle = headerBgColor;
  ctx.fillRect(0, 0, ROW_HEADER_W, COL_HEADER_H);
  ctx.strokeStyle = headerBorderColor;
  ctx.lineWidth = hairline;
  ctx.strokeRect(0, 0, ROW_HEADER_W, COL_HEADER_H);
  const markers = getHiddenHeaderMarkersCached({
    worksheet,
    rowHeights,
    colWidths,
    rowIndexRemap
  });
  if (markers) {
    const markerColor = accentColor;
    const zoomSafe2 = zoom || 1;
    const markerThickness = 2 / zoomSafe2;
    for (const boundary of markers.colBoundaries) {
      if (boundary < startCol || boundary >= endCol)
        continue;
      const xCenter = ROW_HEADER_W + (colOffsets[boundary + 1] ?? 0) - scrollXLogical;
      const x2 = xCenter - markerThickness / 2;
      if (x2 + markerThickness < 0 || x2 > viewportW / zoomSafe2)
        continue;
      ctx.fillStyle = markerColor;
      ctx.fillRect(x2, 0, markerThickness, COL_HEADER_H);
    }
    for (const boundary of markers.rowBoundaries) {
      if (boundary < startRow || boundary >= endRow)
        continue;
      const yCenter = COL_HEADER_H + (rowOffsets[boundary + 1] ?? 0) - scrollYLogical;
      const y2 = yCenter - markerThickness / 2;
      if (y2 + markerThickness < 0 || y2 > viewportH / zoomSafe2)
        continue;
      ctx.fillStyle = markerColor;
      ctx.fillRect(0, y2, ROW_HEADER_W, markerThickness);
    }
  }
  ctx.restore();
}
// node_modules/@oai/granola/dist/models/workbook-export/build-auto-render-metrics.js
init_address_utils();

// node_modules/@oai/granola/dist/models/workbook-export/build-column-widths-for-export.js
function buildColumnWidthsForExport(sheet, maxCols) {
  const defaultWidth = typeof sheet.defaultColWidth === "number" && sheet.defaultColWidth > 0 ? colWidthToPx(sheet.defaultColWidth) : colWidthToPx(12.71);
  const widths = Array(Math.max(1, maxCols)).fill(defaultWidth);
  for (const col of sheet.columns ?? []) {
    const isNoopDefaultColumn = !col.hidden && col.customWidth !== true && (!(typeof col.width === "number" && Number.isFinite(col.width)) || col.width <= 0);
    if (isNoopDefaultColumn) {
      continue;
    }
    const min3 = Math.max(0, (col.min ?? 1) - 1);
    const max4 = Math.max(min3, (col.max ?? col.min ?? 1) - 1);
    const px = colWidthToPx(col.width);
    for (let idx = min3;idx <= max4 && idx < widths.length; idx += 1) {
      widths[idx] = px;
    }
  }
  return widths;
}

// node_modules/@oai/granola/dist/models/workbook-export/build-row-heights-for-export.js
function buildRowHeightsForExport(sheet, maxRows) {
  const defaultPt = sheet.defaultRowHeight && sheet.defaultRowHeight !== 0 ? sheet.defaultRowHeight : undefined;
  const heights = Array(Math.max(1, maxRows)).fill(pointsToPx(defaultPt));
  for (const row2 of sheet.rows ?? []) {
    if (!row2 || row2.index == null)
      continue;
    if ((row2.customHeight || row2.height !== 0) && row2.height != null) {
      const idx = row2.index - 1;
      if (idx >= 0 && idx < heights.length) {
        heights[idx] = pointsToPx(row2.height);
      }
    }
  }
  return heights;
}

// node_modules/@oai/granola/dist/models/workbook-export/compute-offsets.js
function computeOffsets(lengths) {
  const offsets = [0];
  for (let i = 0;i < lengths.length; i += 1) {
    offsets[i + 1] = (offsets[i] ?? 0) + (lengths[i] ?? 0);
  }
  return offsets;
}

// node_modules/@oai/granola/dist/models/workbook-export/create-export-canvas.js
function createExportCanvas(widthPx, heightPx) {
  const targetWidth = Math.max(1, Math.round(widthPx));
  const targetHeight = Math.max(1, Math.round(heightPx));
  if (typeof OffscreenCanvas !== "undefined") {
    return new OffscreenCanvas(targetWidth, targetHeight);
  }
  throw new Error("OffscreenCanvas API is not available for sheet export.");
}

// node_modules/@oai/granola/dist/models/workbook-export/get-used-range-for-sheet.js
function getUsedRangeForSheet(sheet) {
  let maxC = -1;
  let maxR = -1;
  for (const row2 of sheet.rows ?? []) {
    for (const cell of row2.cells ?? []) {
      if (cell.value !== "" && cell.value != null) {
        if (!cell.address)
          continue;
        const c = columnIndex(cell.address);
        const r = rowIndex(cell.address);
        if (c > maxC)
          maxC = c;
        if (r > maxR)
          maxR = r;
      }
    }
  }
  if (maxC < 0 || maxR < 0)
    return null;
  const endColLetters = columnLabel(maxC);
  return `A1:${endColLetters}${maxR + 1}`;
}

// node_modules/@oai/granola/dist/models/workbook-export/build-auto-render-metrics.js
var SPILL_COL_ALLOWANCE = 50;
var SPILL_ROW_ALLOWANCE = 200;
var MAX_AUTO_CANVAS_PX = 20000;
function buildAutoRenderMetrics(options) {
  const { sheet, styleInfos, themeMap, scale, granolaWorkbook } = options;
  const autoCrop = options.autoCrop ?? "all";
  let maxCol = 0;
  let maxRow = 0;
  const used = getUsedRangeForSheet(sheet);
  if (used) {
    const parsed = parseRangeAddress(used);
    if (parsed) {
      maxCol = Math.max(maxCol, parsed.bounds.endCol + 1);
      maxRow = Math.max(maxRow, parsed.bounds.endRow + 1);
    }
  }
  for (const merge2 of sheet.mergedCells ?? []) {
    const startAddress = merge2.startAddress;
    if (!startAddress)
      continue;
    const endAddress = merge2.endAddress ?? startAddress;
    const c1 = columnIndex(startAddress);
    const r1 = rowIndex(startAddress);
    const c2 = columnIndex(endAddress);
    const r2 = rowIndex(endAddress);
    maxCol = Math.max(maxCol, Math.max(c1, c2) + 1);
    maxRow = Math.max(maxRow, Math.max(r1, r2) + 1);
  }
  for (const table2 of sheet.tables ?? []) {
    if (!table2.ref)
      continue;
    const [refStart, refEnd] = table2.ref.split(":");
    if (refStart) {
      const sc = columnIndex(refStart);
      const sr = rowIndex(refStart);
      const ec = refEnd ? columnIndex(refEnd) : sc;
      const er = refEnd ? rowIndex(refEnd) : sr;
      maxCol = Math.max(maxCol, Math.max(sc, ec) + 1);
      maxRow = Math.max(maxRow, Math.max(sr, er) + 1);
    }
  }
  for (const drawing of sheet.drawings ?? []) {
    if (!drawing.toAnchor)
      continue;
    const toC = Number(drawing.toAnchor.colId);
    const toR = Number(drawing.toAnchor.rowId);
    if (Number.isFinite(toC))
      maxCol = Math.max(maxCol, toC + 1);
    if (Number.isFinite(toR))
      maxRow = Math.max(maxRow, toR + 1);
  }
  const maxCols = Math.max(1, maxCol + SPILL_COL_ALLOWANCE);
  const maxRows = Math.max(1, maxRow + SPILL_ROW_ALLOWANCE);
  const colWidths = buildColumnWidthsForExport(sheet, maxCols);
  const rowHeights = buildRowHeightsForExport(sheet, maxRows);
  const colOffsets = computeOffsets(colWidths);
  const rowOffsets = computeOffsets(rowHeights);
  const layoutCanvas = createExportCanvas(1, 1);
  const layoutCtx = layoutCanvas.getContext("2d");
  if (!layoutCtx) {
    throw new Error("Canvas 2D context unavailable for sheet export.");
  }
  if (scale !== 1) {
    layoutCtx.scale(scale, scale);
  }
  const acc = {
    xMin: Number.POSITIVE_INFINITY,
    yMin: Number.POSITIVE_INFINITY,
    xMax: Number.NEGATIVE_INFINITY,
    yMax: Number.NEGATIVE_INFINITY
  };
  const expand = (x2, y2, w, h, tag) => {
    if (autoCrop === "charts" && tag !== "chart") {
      return;
    }
    if (!Number.isFinite(x2) || !Number.isFinite(y2))
      return;
    if (!(w > 0 && h > 0))
      return;
    const dataX2 = x2 - ROW_HEADER_W;
    const dataY2 = y2 - COL_HEADER_H;
    acc.xMin = Math.min(acc.xMin, dataX2);
    acc.yMin = Math.min(acc.yMin, dataY2);
    acc.xMax = Math.max(acc.xMax, dataX2 + w);
    acc.yMax = Math.max(acc.yMax, dataY2 + h);
  };
  const fullW = colOffsets[colOffsets.length - 1] ?? 0;
  const fullH = rowOffsets[rowOffsets.length - 1] ?? 0;
  drawViewport(layoutCtx, granolaWorkbook, sheet.name ?? "", colWidths, rowHeights, 0, 0, fullW, fullH, null, null, 1, styleInfos, {}, new Set, new Set, false, themeMap, false, undefined, undefined, expand, undefined);
  let dataX = 0;
  let dataY = 0;
  let dataW = 1;
  let dataH = 1;
  if (Number.isFinite(acc.xMin) && Number.isFinite(acc.yMin)) {
    dataX = Math.max(0, Math.floor(acc.xMin));
    dataY = Math.max(0, Math.floor(acc.yMin));
    dataW = Math.max(1, Math.ceil(acc.xMax - acc.xMin));
    dataH = Math.max(1, Math.ceil(acc.yMax - acc.yMin));
  } else {
    const fallback = getUsedRangeForSheet(sheet) ?? "A1:A1";
    const parsed = parseRangeAddress(fallback);
    const bounds = parsed?.bounds ?? {
      startRow: 0,
      startCol: 0,
      endRow: 0,
      endCol: 0
    };
    const cMin = Math.max(0, Math.min(bounds.startCol, bounds.endCol));
    const rMin = Math.max(0, Math.min(bounds.startRow, bounds.endRow));
    const cMax = Math.max(bounds.startCol, bounds.endCol);
    const rMax = Math.max(bounds.startRow, bounds.endRow);
    dataX = colOffsets[cMin] ?? 0;
    dataY = rowOffsets[rMin] ?? 0;
    dataW = Math.max(1, (colOffsets[cMax + 1] ?? 0) - dataX);
    dataH = Math.max(1, (rowOffsets[rMax + 1] ?? 0) - dataY);
  }
  const canvasW = Math.max(1, Math.round((dataW + ROW_HEADER_W) * scale));
  const canvasH = Math.max(1, Math.round((dataH + COL_HEADER_H) * scale));
  if (canvasW > MAX_AUTO_CANVAS_PX || canvasH > MAX_AUTO_CANVAS_PX) {
    throw new Error(`Auto render too large: ${canvasW}x${canvasH}px. Try specifying range or center.`);
  }
  return {
    colWidths,
    rowHeights,
    scrollX: dataX,
    scrollY: dataY,
    dataW,
    dataH
  };
}
// node_modules/@oai/granola/dist/models/workbook-export/crop-export-headers.js
function cropExportHeaders(canvas, scale) {
  const headerWidth = ROW_HEADER_W * scale;
  const headerHeight = COL_HEADER_H * scale;
  const width = Math.max(1, Math.round(canvas.width - headerWidth));
  const height = Math.max(1, Math.round(canvas.height - headerHeight));
  const cropped = createExportCanvas(width, height);
  const ctx = cropped.getContext("2d");
  if (!ctx) {
    throw new Error("Canvas 2D context unavailable for sheet export.");
  }
  ctx.drawImage(canvas, -headerWidth, -headerHeight);
  return cropped;
}

// node_modules/@oai/granola/dist/models/workbook-export/export-canvas-to-blob.js
function exportCanvasToBlob(canvas, format2, quality) {
  const mime = format2 === "jpeg" ? "image/jpeg" : "image/png";
  const normalizedQuality = typeof quality === "number" && quality >= 0 && quality <= 1 ? quality : undefined;
  if (typeof canvas.convertToBlob !== "function") {
    throw new Error("OffscreenCanvas.convertToBlob is required for export.");
  }
  return canvas.convertToBlob({ type: mime, quality: normalizedQuality });
}

// node_modules/@oai/granola/dist/models/workbook-export/resolve-center-coords.js
init_address_utils();
function resolveCenterCoords(center, sheetName) {
  const trimmed = center.trim();
  if (!trimmed) {
    throw new Error("Center cell cannot be empty.");
  }
  const { sheetName: centerSheet, ref } = splitSheetAddress(trimmed);
  if (centerSheet && centerSheet !== sheetName) {
    throw new Error(`Center sheet "${centerSheet}" does not match "${sheetName}"`);
  }
  const parsed = parseRangeAddress(ref);
  if (!parsed) {
    throw new Error(`Invalid center address "${center}"`);
  }
  return { row: parsed.bounds.startRow, col: parsed.bounds.startCol };
}

// node_modules/@oai/granola/dist/models/workbook-export/resolve-export-sheet-target.js
function resolveExportSheetTarget(options, workbookProto, activeSheetName) {
  const { sheet, sheetName, sheetIndex } = options;
  const targetCount = [
    sheet !== undefined,
    sheetName != null,
    sheetIndex != null
  ].filter(Boolean).length;
  if (targetCount > 1) {
    throw new Error("Provide only one of sheet, sheetName, or sheetIndex.");
  }
  const sheets = workbookProto.sheets ?? [];
  let resolvedName;
  let resolvedIndex;
  if (sheet !== undefined) {
    if (typeof sheet === "string") {
      resolvedName = sheet;
    } else if (typeof sheet === "number") {
      resolvedIndex = sheet;
    } else {
      resolvedName = sheet.name?.trim();
      if (!resolvedName && Number.isFinite(sheet.index)) {
        resolvedIndex = sheet.index;
      }
    }
  } else if (sheetName) {
    resolvedName = sheetName;
  } else if (typeof sheetIndex === "number") {
    resolvedIndex = sheetIndex;
  } else {
    if (sheets.length === 0) {
      throw new Error("Cannot export workbook without any sheets.");
    }
    resolvedName = activeSheetName ?? sheets[0]?.name ?? "";
  }
  const normalizedName = resolvedName?.trim();
  if (normalizedName) {
    const index = sheets.findIndex((entry) => entry?.name === normalizedName);
    if (index < 0) {
      throw new Error(`Sheet "${normalizedName}" not found`);
    }
    const sheetProto = sheets[index];
    if (!sheetProto) {
      throw new Error(`Sheet "${normalizedName}" not found`);
    }
    return {
      sheet: sheetProto,
      sheetName: sheetProto.name ?? normalizedName,
      sheetIndex: index
    };
  }
  if (resolvedIndex != null) {
    if (!Number.isInteger(resolvedIndex) || resolvedIndex < 0) {
      throw new Error(`Invalid worksheet index ${resolvedIndex}`);
    }
    const sheetProto = sheets[resolvedIndex];
    if (!sheetProto) {
      throw new Error(`Worksheet index ${resolvedIndex} not found`);
    }
    return {
      sheet: sheetProto,
      sheetName: sheetProto.name ?? `Sheet${resolvedIndex + 1}`,
      sheetIndex: resolvedIndex
    };
  }
  throw new Error("Unable to resolve sheet for export.");
}

// node_modules/@oai/granola/dist/models/workbook-export/resolve-range-bounds.js
init_address_utils();
function resolveRangeBounds(range2, sheetName) {
  const trimmed = range2.trim();
  if (!trimmed) {
    throw new Error("Range cannot be empty.");
  }
  const { sheetName: rangeSheet, ref } = splitSheetAddress(trimmed);
  if (rangeSheet && rangeSheet !== sheetName) {
    throw new Error(`Range sheet "${rangeSheet}" does not match "${sheetName}"`);
  }
  const parsed = parseRangeAddress(ref);
  if (!parsed) {
    throw new Error(`Invalid range "${range2}"`);
  }
  return parsed.bounds;
}

// node_modules/@oai/granola/dist/models/workbook-export/workbook-export.js
function renderWorkbook(workbook, options = {}) {
  const format2 = options.format ?? "png";
  return exportWorkbook(workbook, { ...options, format: format2 });
}
function exportWorkbook(workbook, options = {}) {
  if (options.range && options.center) {
    throw new Error("Provide either range or center, not both.");
  }
  if (options.center && (!options.width || !options.height)) {
    throw new Error("Center rendering requires width and height in pixels.");
  }
  const format2 = options.format ?? "png";
  const scale = typeof options.scale === "number" && Number.isFinite(options.scale) && options.scale > 0 ? options.scale : 1;
  const headers = options.headers !== false;
  workbook.recalculate();
  const workbookProto = workbook.toProto();
  const activeSheetName = (workbookProto.sheets?.length ?? 0) > 0 ? workbook.worksheets.getActiveWorksheet().name : undefined;
  const { sheet, sheetName } = resolveExportSheetTarget(options, workbookProto, activeSheetName);
  const styleInfos = buildStyleMaps(workbookProto);
  const themeMap = buildWorkbookThemeMap(workbookProto.theme);
  let metrics;
  if (options.range) {
    const bounds = resolveRangeBounds(options.range, sheetName);
    const cMin = Math.max(0, Math.min(bounds.startCol, bounds.endCol));
    const cMax = Math.max(bounds.startCol, bounds.endCol);
    const rMin = Math.max(0, Math.min(bounds.startRow, bounds.endRow));
    const rMax = Math.max(bounds.startRow, bounds.endRow);
    const colWidths2 = buildColumnWidthsForExport(sheet, Math.max(cMax + 1, 1));
    const rowHeights2 = buildRowHeightsForExport(sheet, Math.max(rMax + 1, 1));
    const colOffsets = computeOffsets(colWidths2);
    const rowOffsets = computeOffsets(rowHeights2);
    metrics = {
      colWidths: colWidths2,
      rowHeights: rowHeights2,
      scrollX: colOffsets[cMin] ?? 0,
      scrollY: rowOffsets[rMin] ?? 0,
      dataW: (colOffsets[cMax + 1] ?? 0) - (colOffsets[cMin] ?? 0),
      dataH: (rowOffsets[rMax + 1] ?? 0) - (rowOffsets[rMin] ?? 0)
    };
  } else if (options.center) {
    const width = options.width ?? 0;
    const height = options.height ?? 0;
    if (!Number.isFinite(width) || width <= 0 || !Number.isFinite(height) || height <= 0) {
      throw new Error("Center rendering requires width and height in pixels.");
    }
    const { col, row: row2 } = resolveCenterCoords(options.center, sheetName);
    const maxCols = Math.max(500, col + 50);
    const maxRows = Math.max(500, row2 + 200);
    const colWidths2 = buildColumnWidthsForExport(sheet, maxCols);
    const rowHeights2 = buildRowHeightsForExport(sheet, maxRows);
    const colOffsets = computeOffsets(colWidths2);
    const rowOffsets = computeOffsets(rowHeights2);
    const cellCenterX = (colOffsets[col] ?? 0) + (colWidths2[col] ?? 0) / 2;
    const cellCenterY = (rowOffsets[row2] ?? 0) + (rowHeights2[row2] ?? 0) / 2;
    const dataW2 = Math.max(1, Math.round(width));
    const dataH2 = Math.max(1, Math.round(height));
    const scrollX2 = Math.max(0, Math.round(cellCenterX - dataW2 / 2));
    const scrollY2 = Math.max(0, Math.round(cellCenterY - dataH2 / 2));
    metrics = {
      colWidths: colWidths2,
      rowHeights: rowHeights2,
      scrollX: scrollX2,
      scrollY: scrollY2,
      dataW: dataW2,
      dataH: dataH2
    };
  } else {
    metrics = buildAutoRenderMetrics({
      sheet,
      styleInfos,
      themeMap,
      scale,
      granolaWorkbook: workbook,
      autoCrop: options.autoCrop
    });
  }
  const { colWidths, rowHeights, scrollX, scrollY, dataW, dataH } = metrics;
  const canvasW = Math.max(1, Math.round((dataW + ROW_HEADER_W) * scale));
  const canvasH = Math.max(1, Math.round((dataH + COL_HEADER_H) * scale));
  const canvas = createExportCanvas(canvasW, canvasH);
  const ctx = canvas.getContext("2d");
  if (!ctx) {
    throw new Error("Canvas 2D context unavailable for sheet export.");
  }
  if (scale !== 1) {
    ctx.scale(scale, scale);
  }
  ctx.save();
  ctx.fillStyle = "#ffffff";
  ctx.fillRect(0, 0, canvasW / scale, canvasH / scale);
  ctx.restore();
  drawViewport(ctx, workbook, sheetName ?? "", colWidths, rowHeights, scrollX, scrollY, dataW, dataH, null, null, 1, styleInfos, {}, new Set, new Set, false, themeMap, false, undefined, undefined, undefined, undefined);
  const outputCanvas = headers ? canvas : cropExportHeaders(canvas, scale);
  return exportCanvasToBlob(outputCanvas, format2, options.quality);
}

// node_modules/@oai/granola/dist/plugins/workbook-export.js
function installWorkbookExport() {
  registerWorkbookExportProvider({
    exportWorkbook,
    renderWorkbook
  });
}

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/api/chart-help.js
var CHARTS_API_HELP = [
  {
    kind: "api",
    name: "charts",
    summary: "Chart objects anchored to cells.",
    notes: [
      "Use worksheet.charts.add(...) to create charts.",
      "Use worksheet.charts.deleteAll() (or .clear()) to remove charts.",
      "Use chart.delete() to remove a single chart.",
      "Charts are anchored with 0-based row/col positions and px offsets.",
      "Charts support title.text, setPosition, width/height, and axes.valueAxis/categoryAxis.",
      "Passing a multi-cell range to setPosition reserves that rectangle (from/to anchors)."
    ]
  },
  {
    kind: "api",
    name: "worksheet.charts.add",
    summary: "Add a chart using a config object.",
    notes: [
      "Prefer passing a single config object to worksheet.charts.add(...) or assigning chart.xAxis/chart.yAxis/chart.legend/chart.dataLabels/chart.dataTable with compact config objects.",
      "Config assignment merges; omitted fields keep their existing values (useful for incremental edits).",
      "Skip noisy defaults in configs (e.g. text color is already theme text). Set only what changes the output.",
      "Use either manual anchors ({ from, to/extent }) or the compat range overload.",
      "Common chart types used in specs: 'bar', 'line', 'scatter'.",
      "Config props used in specs: title, titleTextStyle, categories, series, hasLegend, legend, barOptions, xAxis, yAxis, dataLabels, dataTable.",
      "Charts use 0-based row/col anchors for manual positioning.",
      "Charts support title.text, setPosition, width/height, and axes.valueAxis/categoryAxis."
    ],
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const sheet = workbook.worksheets.add('Charts');",
              "const chart = sheet.charts.add('line', {",
              "  title: 'Milky Way Star Birth Rate',",
              "  titleTextStyle: { fontSize: 18, bold: true },",
              "  categories: ['2020', '2021', '2022'],",
              "  series: [",
              "    { name: 'Milky Way', values: [1.8, 1.9, 2.0] },",
              "  ],",
              "  hasLegend: true,",
              "  legend: { position: 'top' },",
              "  barOptions: { direction: 'column', grouping: 'stacked', gapWidth: 120 },",
              "  dataLabels: { showValue: false },",
              "  from: { row: 1, col: 1 },",
              "  extent: { widthPx: 520, heightPx: 280 },",
              "});"
            ].join(`
`),
            summary: "Create a chart with a manual anchor"
          },
          {
            code: [
              "const sheet = workbook.worksheets.getItem('Charts');",
              "const range = sheet.getRange('A2:B5');",
              "const chart = sheet.charts.add('ColumnClustered', range, 'Auto');",
              "chart.title.text = 'Stock Prices and Market Caps';",
              "chart.setPosition(sheet.getRange('F2:M10'));",
              "chart.width = 500;",
              "chart.height = 300;",
              "chart.axes.valueAxis.majorGridlines.format.line.color = '#CCCCCC';"
            ].join(`
`),
            summary: "Compat range-anchored chart API"
          }
        ]
      },
      python: {
        functionName: "worksheet.charts.add",
        examples: [
          {
            code: [
              "sheet = workbook.worksheets.add('Charts')",
              "chart = sheet.charts.add('line', {",
              "  'from': {'row': 1, 'col': 1},",
              "  'extent': {'widthPx': 520, 'heightPx': 280},",
              "})",
              "chart.title = 'Milky Way Star Birth Rate'",
              "chart.categories = ['2020', '2021', '2022']",
              "series = chart.series.add('Milky Way')",
              "series.values = [1.8, 1.9, 2.0]",
              "series.categories = chart.categories"
            ].join(`
`),
            summary: "Create a chart with a manual anchor"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "charts.add",
    summary: "Alias for worksheet.charts.add.",
    notes: ["Use worksheet.charts.add for the full signature and examples."]
  },
  {
    kind: "api",
    name: "chart data table",
    summary: "Chart data table visibility and styling.",
    languages: {
      javascript: {
        examples: [
          {
            summary: "Data table with optional legend keys",
            code: [
              "chart.dataTable = { visible: true, showLegendKey: true, textStyle: { fontSize: 10 } };",
              "chart.dataTable = { visible: true, showLegendKey: false };"
            ].join(`
`)
          }
        ]
      },
      python: {
        functionName: "chart.data_table",
        examples: [
          {
            code: [
              "chart.data_table = {'visible': True, 'showLegendKey': True, 'textStyle': {'fontSize': 10}}",
              "chart.data_table = {'visible': True, 'showLegendKey': False}"
            ].join(`
`),
            summary: "Data table with optional legend keys"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "chart series",
    summary: "Series data, styling, and trendlines for worksheet charts.",
    notes: [
      "Use chart.series.add(name) then set categories/values.",
      "Trendlines are configured on a series via series.trendlines.add(...)."
    ],
    languages: {
      javascript: {
        examples: [
          {
            summary: "Series + moving-average trendline",
            code: [
              "const sheet = workbook.worksheets.add('Trendlines');",
              "const chart = sheet.charts.add('line', { from: { row: 1, col: 1 }, extent: { widthPx: 420, heightPx: 240 } });",
              "chart.categories = ['Q1', 'Q2', 'Q3', 'Q4'];",
              "const series = chart.series.add('Revenue');",
              "series.values = [10, 14, 13, 17];",
              "series.categories = chart.categories;",
              "series.trendlines.add('movingAverage', { movingAveragePeriod: 3 });"
            ].join(`
`)
          }
        ]
      },
      python: {
        functionName: "chart.series.add",
        examples: [
          {
            code: [
              "sheet = workbook.worksheets.add('Trendlines')",
              "chart = sheet.charts.add('line', {'from': {'row': 1, 'col': 1}, 'extent': {'widthPx': 420, 'heightPx': 240}})",
              "chart.categories = ['Q1', 'Q2', 'Q3', 'Q4']",
              "series = chart.series.add('Revenue')",
              "series.values = [10, 14, 13, 17]",
              "series.categories = chart.categories",
              "series.trendlines.add('movingAverage', {'movingAveragePeriod': 3})"
            ].join(`
`),
            summary: "Series + moving-average trendline"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "chart title",
    summary: "Chart title text, placement, and text style.",
    languages: {
      javascript: {
        examples: [
          {
            summary: "Compact title edits",
            code: [
              "chart.title = '';",
              "chart.titlePlacement = 'none';",
              "chart.title = 'Sales Data';",
              "chart.titlePlacement = 'aboveChart';",
              "chart.titlePlacement = 'centeredOverlay';",
              "chart.titleTextStyle.bold = true;",
              "chart.titleTextStyle.fontSize = 18;"
            ].join(`
`)
          }
        ]
      },
      python: {
        functionName: "chart.title",
        examples: [
          {
            code: [
              "chart.title = ''",
              "chart.title_placement = 'none'",
              "chart.title = 'Sales Data'",
              "chart.title_placement = 'aboveChart'",
              "chart.title_placement = 'centeredOverlay'",
              "chart.title_text_style = {'bold': True, 'fontSize': 18}"
            ].join(`
`),
            summary: "Compact title edits"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "chart fills",
    summary: "Chart and plot area fills (including pattern fills).",
    languages: {
      javascript: {
        examples: [
          {
            summary: "Pattern fills (+ Office.js-style aliases)",
            code: [
              "chart.chartFill = { type: 'solid', color: 'background1', pattern: { type: 'percent10', color: 'accent1' } };",
              "chart.plotAreaFill = { type: 'solid', color: 'background1', pattern: { type: 'diagonalCross', color: 'accent2' } };",
              "",
              "// Office.js-style aliases (map to chartFill/plotAreaFill + chartLine/plotAreaLine):",
              "chart.chartArea.format.fill = { type: 'solid', color: 'background1' };",
              "chart.plotArea.format.fill.setSolidColor('accent2');",
              "chart.plotArea.format.line.visible = false;"
            ].join(`
`)
          }
        ]
      },
      python: {
        functionName: "chart.chart_fill",
        examples: [
          {
            code: [
              "chart.chart_fill = {'type': 'solid', 'color': 'background1', 'pattern': {'type': 'percent10', 'color': 'accent1'}}",
              "chart.plot_area_fill = {'type': 'solid', 'color': 'background1', 'pattern': {'type': 'diagonalCross', 'color': 'accent2'}}",
              "chart.chart_area.format.fill = {'type': 'solid', 'color': 'background1'}",
              "chart.plot_area.format.fill.set_solid_color('accent2')",
              "chart.plot_area.format.line.visible = False"
            ].join(`
`),
            summary: "Pattern fills (+ Office.js-style aliases)"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "chart legend",
    summary: "Legend visibility, position, and styling.",
    languages: {
      javascript: {
        examples: [
          {
            summary: "Legend on/off + position + style",
            code: [
              "chart.hasLegend = false;",
              "chart.hasLegend = true; chart.legend = { position: 'bottom', textStyle: { fontSize: 11 }, fill: { type: 'solid', color: 'background1', pattern: { type: 'zigZag', color: 'accent2' } }, stroke: { fill: 'accent2', style: 'solid', width: 1 } };"
            ].join(`
`)
          }
        ]
      },
      python: {
        functionName: "chart.legend",
        examples: [
          {
            code: [
              "chart.has_legend = False",
              "chart.has_legend = True",
              "chart.legend = {'position': 'bottom', 'textStyle': {'fontSize': 11}, 'fill': {'type': 'solid', 'color': 'background1', 'pattern': {'type': 'zigZag', 'color': 'accent2'}}, 'stroke': {'fill': 'accent2', 'style': 'solid', 'width': 1}}"
            ].join(`
`),
            summary: "Legend on/off + position + style"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "chart barOptions",
    summary: "Bar/column chart layout options.",
    languages: {
      javascript: {
        examples: [
          {
            summary: "Column chart spacing + overlap",
            code: [
              "chart.barOptions.direction = 'column';",
              "chart.barOptions.grouping = 'clustered';",
              "chart.barOptions.gapWidth = 100;",
              "chart.barOptions.overlap = -20;",
              "chart.barOptions.direction = 'column';",
              "chart.barOptions.grouping = 'stacked';",
              "chart.barOptions.gapWidth = 120;"
            ].join(`
`)
          }
        ]
      },
      python: {
        functionName: "chart.bar_options",
        examples: [
          {
            code: [
              "chart.bar_options = {'direction': 'column', 'grouping': 'clustered', 'gapWidth': 100, 'overlap': -20}",
              "chart.bar_options = {'direction': 'column', 'grouping': 'stacked', 'gapWidth': 120}"
            ].join(`
`),
            summary: "Column chart spacing + overlap"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "chart axes",
    summary: "Axis config (type, position, titles, ticks, gridlines, formats, and styling).",
    notes: [
      "Use chart.xAxis and chart.yAxis to configure the primary axes.",
      "Axis config setters merge; apply small patches without resetting other axis fields."
    ],
    languages: {
      javascript: {
        examples: [
          {
            summary: "Axis type + presence",
            code: [
              "chart.xAxis = { axisType: 'textAxis' };",
              "chart.xAxis = { axisType: 'dateAxis' };",
              "chart.xAxis = { deleted: true, title: 'Years' };",
              "chart.yAxis = { deleted: true, title: 'Revenue' };"
            ].join(`
`)
          },
          {
            summary: "Axis titles + text styles (avoid redundant defaults)",
            code: [
              "chart.xAxis = { title: { text: 'Category', textStyle: { fontSize: 14, bold: true } } };",
              "chart.yAxis = { title: { text: 'Value', textStyle: { fontSize: 12, italic: true, fill: 'accent1' } } };"
            ].join(`
`)
          },
          {
            summary: "Axis ordering + crossing",
            code: [
              "chart.xAxis = { position: 'bottom', orientation: 'maxMin' };",
              "chart.yAxis = { position: 'left', crossBetween: 'between' };",
              "chart.yAxis = { crosses: 'autoZero' };",
              "chart.yAxis = { crossesAt: 2 };",
              "chart.yAxis = { crosses: 'max' };"
            ].join(`
`)
          },
          {
            summary: "Tick labels",
            code: [
              "chart.xAxis = { tickLabelPosition: 'nextTo' };",
              "chart.xAxis = { tickLabelPosition: 'high' };",
              "chart.xAxis = { tickLabelPosition: 'low' };",
              "chart.xAxis = { tickLabelPosition: 'none', tickLabelInterval: 2, tickLabelDistanceFromAxis: 10 };"
            ].join(`
`)
          },
          {
            summary: "Tick marks + units",
            code: [
              "chart.xAxis = { majorUnit: 5, minorUnit: 1 };",
              "chart.xAxis = { majorTickMark: 'outside', minorTickMark: 'inside' };",
              "chart.yAxis = { majorTickMark: 'cross', minorTickMark: 'none' };"
            ].join(`
`)
          },
          {
            summary: "Gridlines + axis lines",
            code: [
              "chart.yAxis = { majorGridlines: { fill: 'background2', style: 'dashed', width: 1 }, minorGridlines: { fill: 'background2', style: 'dotted', width: 0.5 } };",
              "chart.xAxis = { majorGridlines: { fill: 'background2', style: 'solid', width: 1 }, minorGridlines: { fill: 'background2', style: 'dotted', width: 0.5 } };",
              "chart.xAxis = { line: { fill: 'background2', style: 'solid', width: 1 } };",
              "chart.yAxis = { line: { fill: 'background2', style: 'solid', width: 1 } };",
              "",
              "// Hide gridlines:",
              "chart.yAxis = { majorGridlines: null, minorGridlines: null };",
              "chart.xAxis = { majorGridlines: null, minorGridlines: null };"
            ].join(`
`)
          },
          {
            summary: "Number formats",
            code: [
              "chart.xAxis = { numberFormatCode: '0', numberFormatSourceLinked: true };"
            ].join(`
`)
          },
          {
            summary: "Axis text style",
            code: [
              "chart.xAxis = { textStyle: { fontSize: 10 } };",
              "chart.yAxis = { textStyle: { fontSize: 1, fill: 'background1' } };"
            ].join(`
`)
          }
        ]
      },
      python: {
        functionName: "chart.x_axis",
        examples: [
          {
            code: [
              "chart.x_axis = {'axisType': 'textAxis'}",
              "chart.x_axis = {'axisType': 'dateAxis'}",
              "chart.x_axis = {'deleted': True, 'title': 'Years'}",
              "chart.y_axis = {'deleted': True, 'title': 'Revenue'}"
            ].join(`
`),
            summary: "Axis type + presence"
          },
          {
            code: [
              "chart.x_axis = {'title': {'text': 'Category', 'textStyle': {'fontSize': 14, 'bold': True}}}",
              "chart.y_axis = {'title': {'text': 'Value', 'textStyle': {'fontSize': 12, 'italic': True, 'fill': 'accent1'}}}"
            ].join(`
`),
            summary: "Axis titles + text styles (avoid redundant defaults)"
          },
          {
            code: [
              "chart.x_axis = {'position': 'bottom', 'orientation': 'maxMin'}",
              "chart.y_axis = {'position': 'left', 'crossBetween': 'between'}",
              "chart.y_axis = {'crosses': 'autoZero'}",
              "chart.y_axis = {'crossesAt': 2}",
              "chart.y_axis = {'crosses': 'max'}"
            ].join(`
`),
            summary: "Axis ordering + crossing"
          },
          {
            code: [
              "chart.x_axis = {'tickLabelPosition': 'nextTo'}",
              "chart.x_axis = {'tickLabelPosition': 'high'}",
              "chart.x_axis = {'tickLabelPosition': 'low'}",
              "chart.x_axis = {'tickLabelPosition': 'none', 'tickLabelInterval': 2, 'tickLabelDistanceFromAxis': 10}"
            ].join(`
`),
            summary: "Tick labels"
          },
          {
            code: [
              "chart.x_axis = {'majorUnit': 5, 'minorUnit': 1}",
              "chart.x_axis = {'majorTickMark': 'outside', 'minorTickMark': 'inside'}",
              "chart.y_axis = {'majorTickMark': 'cross', 'minorTickMark': 'none'}"
            ].join(`
`),
            summary: "Tick marks + units"
          },
          {
            code: [
              "chart.y_axis = {'majorGridlines': {'fill': 'background2', 'style': 'dashed', 'width': 1}, 'minorGridlines': {'fill': 'background2', 'style': 'dotted', 'width': 0.5}}",
              "chart.x_axis = {'majorGridlines': {'fill': 'background2', 'style': 'solid', 'width': 1}, 'minorGridlines': {'fill': 'background2', 'style': 'dotted', 'width': 0.5}}",
              "chart.x_axis = {'line': {'fill': 'background2', 'style': 'solid', 'width': 1}}",
              "chart.y_axis = {'line': {'fill': 'background2', 'style': 'solid', 'width': 1}}",
              "chart.y_axis = {'majorGridlines': None, 'minorGridlines': None}",
              "chart.x_axis = {'majorGridlines': None, 'minorGridlines': None}"
            ].join(`
`),
            summary: "Gridlines + axis lines"
          },
          {
            code: [
              "chart.x_axis = {'numberFormatCode': '0', 'numberFormatSourceLinked': True}"
            ].join(`
`),
            summary: "Number formats"
          },
          {
            code: [
              "chart.x_axis = {'textStyle': {'fontSize': 10}}",
              "chart.y_axis = {'textStyle': {'fontSize': 1, 'fill': 'background1'}}"
            ].join(`
`),
            summary: "Axis text style"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "categoryAxis",
    summary: "Alias for the chart category axis. In Granola, this maps to chart.xAxis.",
    notes: [
      "Prefer chart.xAxis = { ... } for config-style edits.",
      "Also available as chart.axes.categoryAxis."
    ],
    languages: {
      javascript: {
        examples: [
          {
            summary: "Show category axis tick labels",
            code: [
              "chart.xAxis = { deleted: false, tickLabelPosition: 'nextToAxis' };"
            ].join(`
`)
          }
        ]
      },
      python: {
        functionName: "chart.x_axis",
        examples: [
          {
            code: [
              "chart.x_axis = {'deleted': False, 'tickLabelPosition': 'nextToAxis'}"
            ].join(`
`),
            summary: "Show category axis tick labels"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "valueAxis",
    summary: "Alias for the chart value axis. In Granola, this maps to chart.yAxis.",
    notes: [
      "Prefer chart.yAxis = { ... } for config-style edits.",
      "Also available as chart.axes.valueAxis."
    ],
    languages: {
      javascript: {
        examples: [
          {
            summary: "Format value axis gridlines",
            code: [
              "chart.yAxis = { majorGridlines: { fill: 'background2', style: 'dashed', width: 1 } };"
            ].join(`
`)
          }
        ]
      },
      python: {
        functionName: "chart.y_axis",
        examples: [
          {
            code: [
              "chart.y_axis = {'majorGridlines': {'fill': 'background2', 'style': 'dashed', 'width': 1}}"
            ].join(`
`),
            summary: "Format value axis gridlines"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "chart.xAxis",
    summary: "Primary x-axis (category axis) config setter.",
    notes: [
      "Assign a config object: chart.xAxis = { ... }. Omitted fields keep current values.",
      "Compat name: categoryAxis."
    ],
    languages: {
      javascript: {
        examples: [
          {
            summary: "Make x-axis labels visible",
            code: [
              "chart.xAxis = { visible: true, tickLabelPosition: 'nextToAxis' };"
            ].join(`
`)
          }
        ]
      },
      python: {
        functionName: "chart.x_axis",
        examples: [
          {
            code: [
              "chart.x_axis = {'visible': True, 'tickLabelPosition': 'nextToAxis'}"
            ].join(`
`),
            summary: "Make x-axis labels visible"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "chart.yAxis",
    summary: "Primary y-axis (value axis) config setter.",
    notes: [
      "Assign a config object: chart.yAxis = { ... }. Omitted fields keep current values.",
      "Compat name: valueAxis."
    ],
    languages: {
      javascript: {
        examples: [
          {
            summary: "Set y-axis title",
            code: ["chart.yAxis = { title: { text: 'Revenue' } };"].join(`
`)
          }
        ]
      },
      python: {
        functionName: "chart.y_axis",
        examples: [
          {
            code: ["chart.y_axis = {'title': {'text': 'Revenue'}}"].join(`
`),
            summary: "Set y-axis title"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "chart dataLabels",
    summary: "Chart-level data labels (including callouts and pattern fills).",
    notes: [
      "Use chart.dataLabels for defaults applied to all series/points.",
      "For per-point customization, use series.dataLabelOverrides (see separate help entry)."
    ],
    languages: {
      javascript: {
        examples: [
          {
            summary: "Positions + minimal style",
            code: [
              "chart.dataLabels = { showValue: false, position: undefined };",
              "chart.dataLabels = { showValue: true, position: 'center', textStyle: { fontSize: 9 } };",
              "chart.dataLabels = { showValue: true, position: 'inEnd' };",
              "chart.dataLabels = { showValue: true, position: 'inBase' };",
              "chart.dataLabels = { showValue: true, position: 'outEnd', textStyle: { bold: true, fontSize: 10 } };"
            ].join(`
`)
          },
          {
            summary: "Data callout styling (fill + stroke)",
            code: [
              "chart.dataLabels = { showValue: true, position: 'dataCallout', fill: { type: 'solid', color: 'background1', pattern: { type: 'percent20', color: 'accent1' } }, stroke: { fill: 'accent1', style: 'solid', width: 1 } };"
            ].join(`
`)
          }
        ]
      },
      python: {
        functionName: "chart.data_labels",
        examples: [
          {
            code: [
              "chart.data_labels = {'showValue': False, 'position': None}",
              "chart.data_labels = {'showValue': True, 'position': 'center', 'textStyle': {'fontSize': 9}}",
              "chart.data_labels = {'showValue': True, 'position': 'inEnd'}",
              "chart.data_labels = {'showValue': True, 'position': 'inBase'}",
              "chart.data_labels = {'showValue': True, 'position': 'outEnd', 'textStyle': {'bold': True, 'fontSize': 10}}"
            ].join(`
`),
            summary: "Positions + minimal style"
          },
          {
            code: [
              "chart.data_labels = {'showValue': True, 'position': 'dataCallout', 'fill': {'type': 'solid', 'color': 'background1', 'pattern': {'type': 'percent20', 'color': 'accent1'}}, 'stroke': {'fill': 'accent1', 'style': 'solid', 'width': 1}}"
            ].join(`
`),
            summary: "Data callout styling (fill + stroke)"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "chart dataTable",
    summary: "Chart data table visibility and styling.",
    languages: {
      javascript: {
        examples: [
          {
            summary: "Data table with optional legend keys",
            code: [
              "chart.dataTable = { visible: true, showLegendKey: true, textStyle: { fontSize: 10 }, fill: { type: 'solid', color: 'background1', pattern: { type: 'smallGrid', color: 'accent3' } } };",
              "chart.dataTable = { visible: true, showLegendKey: false };"
            ].join(`
`)
          }
        ]
      },
      python: {
        functionName: "chart.data_table",
        examples: [
          {
            code: [
              "chart.data_table = {'visible': True, 'showLegendKey': True, 'textStyle': {'fontSize': 10}, 'fill': {'type': 'solid', 'color': 'background1', 'pattern': {'type': 'smallGrid', 'color': 'accent3'}}}",
              "chart.data_table = {'visible': True, 'showLegendKey': False}"
            ].join(`
`),
            summary: "Data table with optional legend keys"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "chart series",
    summary: "Series data, styling, number formats, error bars, trendlines, and label overrides.",
    languages: {
      javascript: {
        examples: [
          {
            summary: "Series styling via worksheet.charts.add config",
            code: [
              "const chart = worksheet.charts.add('bar', { categories: ['Q1','Q2'], series: [{ name: '2025', values: [18, 14], line: { fill: '#7c3aed', style: 'solid', width: 2 }, fill: { type: 'solid', color: '#ede9fe', pattern: { type: 'smallCheck', color: '#8b5cf6' } } }, { name: '2026', values: [21, 17], line: { fill: '#d97706', style: 'solid', width: 2 }, fill: { type: 'solid', color: '#fef3c7', pattern: { type: 'dottedDiamond', color: '#f59e0b' } } }] });"
            ].join(`
`)
          },
          {
            summary: "Scatter series with xValues (config)",
            code: [
              "const chart = worksheet.charts.add('scatter', { series: [{ name: 'S1', xValues: [1, 2, 3, 4], values: [2, 4, 3, 5] }] });"
            ].join(`
`)
          },
          {
            summary: "Create a series and set categories/values (one-liners)",
            code: [
              "chart.categories = ['A', 'B', 'C'];",
              "const series = chart.series.add('S1'); series.categories = chart.categories; series.values = [1, 2, 3];"
            ].join(`
`)
          },
          {
            summary: "Series value number format code",
            code: ["chart.series.items[0]!.valuesFormatCode = '$0.00';"].join(`
`)
          },
          {
            summary: "Error bars",
            code: [
              "const series = chart.series.items[0]!;",
              "series.errorBars = { type: 'standardError', line: { fill: 'accent1', style: 'solid', width: 1 } };",
              "series.errorBars = { type: 'percentage', value: 5 };",
              "series.errorBars = { type: 'standardDeviation' };"
            ].join(`
`)
          },
          {
            summary: "Trendlines",
            code: [
              "const series = chart.series.items[0]!;",
              "series.trendlines.add('linear', { forecastForward: 2, forecastBackward: 1, intercept: 0, displayEquation: true, displayRSquared: true, stroke: { fill: 'accent1', style: 'dashed', width: 1 } });",
              "series.trendlines.add('polynomial', { polynomialOrder: 3 });",
              "series.trendlines.add('movingAverage', { movingAveragePeriod: 5 });",
              "series.trendlines.add('exponential');",
              "series.trendlines.clear();"
            ].join(`
`)
          },
          {
            summary: "Trendline styling (label fill + line alias)",
            code: [
              "const trend = series.trendlines.add('linear', { line: { fill: 'accent5', style: 'dashed', width: 1 }, label: { fill: { type: 'solid', color: 'background1', pattern: { type: 'smallCheck', color: 'accent6' } } } });"
            ].join(`
`)
          },
          {
            summary: "Per-point data label overrides",
            code: [
              "const series = chart.series.items[1]!;",
              "const label0 = series.dataLabelOverrides.add(0);",
              "label0.showValue = true;",
              "label0.position = 'inEnd';",
              "label0.textStyle.bold = true;",
              "label0.textStyle.fontSize = 10;"
            ].join(`
`)
          },
          {
            summary: "Series styling after creation (one-liners)",
            code: [
              "chart.series.items[0]!.line = { fill: '#3b82f6', style: 'solid', width: 2 };",
              "chart.series.items[0]!.fill = { type: 'solid', color: '#60a5fa' };"
            ].join(`
`)
          },
          {
            summary: "Outline-only bars (no fill + visible stroke)",
            code: [
              "const series = chart.series.items[0]!;",
              "series.fill = { type: 'none' };",
              "series.stroke = { color: 'accent5', style: 'solid', weight: 1.5 };",
              "",
              "// Equivalent format-style surface (useful for agent code):",
              "series.format.fill.clear();",
              "series.format.line = { color: 'accent5', style: 'solid', weight: 1.5 };"
            ].join(`
`)
          }
        ]
      },
      python: {
        functionName: "chart.series",
        examples: [
          {
            code: [
              "chart = worksheet.charts.add('bar', {'categories': ['Q1', 'Q2'], 'series': [{'name': '2025', 'values': [18, 14], 'line': {'fill': '#7c3aed', 'style': 'solid', 'width': 2}, 'fill': {'type': 'solid', 'color': '#ede9fe', 'pattern': {'type': 'smallCheck', 'color': '#8b5cf6'}}}, {'name': '2026', 'values': [21, 17], 'line': {'fill': '#d97706', 'style': 'solid', 'width': 2}, 'fill': {'type': 'solid', 'color': '#fef3c7', 'pattern': {'type': 'dottedDiamond', 'color': '#f59e0b'}}}]})"
            ].join(`
`),
            summary: "Series styling via worksheet.charts.add config"
          },
          {
            code: [
              "chart = worksheet.charts.add('scatter', {'series': [{'name': 'S1', 'xValues': [1, 2, 3, 4], 'values': [2, 4, 3, 5]}]})"
            ].join(`
`),
            summary: "Scatter series with xValues (config)"
          },
          {
            code: [
              "chart.categories = ['A', 'B', 'C']",
              "series = chart.series.add('S1')",
              "series.categories = chart.categories",
              "series.values = [1, 2, 3]"
            ].join(`
`),
            summary: "Create a series and set categories/values (one-liners)"
          },
          {
            code: ["chart.series.items[0].values_format_code = '$0.00'"].join(`
`),
            summary: "Series value number format code"
          },
          {
            code: [
              "series = chart.series.items[0]",
              "series.error_bars = {'type': 'standardError', 'line': {'fill': 'accent1', 'style': 'solid', 'width': 1}}",
              "series.error_bars = {'type': 'percentage', 'value': 5}",
              "series.error_bars = {'type': 'standardDeviation'}"
            ].join(`
`),
            summary: "Error bars"
          },
          {
            code: [
              "series = chart.series.items[0]",
              "series.trendlines.add('linear', {'forecastForward': 2, 'forecastBackward': 1, 'intercept': 0, 'displayEquation': True, 'displayRSquared': True, 'stroke': {'fill': 'accent1', 'style': 'dashed', 'width': 1}})",
              "series.trendlines.add('polynomial', {'polynomialOrder': 3})",
              "series.trendlines.add('movingAverage', {'movingAveragePeriod': 5})",
              "series.trendlines.add('exponential')",
              "series.trendlines.clear()"
            ].join(`
`),
            summary: "Trendlines"
          },
          {
            code: [
              "trend = series.trendlines.add('linear', {'line': {'fill': 'accent5', 'style': 'dashed', 'width': 1}, 'label': {'fill': {'type': 'solid', 'color': 'background1', 'pattern': {'type': 'smallCheck', 'color': 'accent6'}}}})"
            ].join(`
`),
            summary: "Trendline styling (label fill + line alias)"
          },
          {
            code: [
              "series = chart.series.items[1]",
              "label0 = series.data_label_overrides.add(0)",
              "label0.show_value = True",
              "label0.position = 'inEnd'",
              "label0.text_style.bold = True",
              "label0.text_style.font_size = 10"
            ].join(`
`),
            summary: "Per-point data label overrides"
          },
          {
            code: [
              "chart.series.items[0].line = {'fill': '#3b82f6', 'style': 'solid', 'width': 2}",
              "chart.series.items[0].fill = {'type': 'solid', 'color': '#60a5fa'}"
            ].join(`
`),
            summary: "Series styling after creation (one-liners)"
          },
          {
            code: [
              "series = chart.series.items[0]",
              "series.fill = {'type': 'none'}",
              "series.stroke = {'color': 'accent5', 'style': 'solid', 'weight': 1.5}",
              "series.format.fill.clear()",
              "series.format.line = {'color': 'accent5', 'style': 'solid', 'weight': 1.5}"
            ].join(`
`),
            summary: "Outline-only bars (no fill + visible stroke)"
          }
        ]
      }
    }
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/api/sparklines-help.js
var SPARKLINES_API_HELP = [
  {
    kind: "api",
    name: "sparklines",
    summary: "Sparkline groups for compact trend visuals.",
    notes: [
      "Use worksheet.sparklines.add({ type, targetRange, sourceData }).",
      "Use worksheet.sparklines.getAll() to list groups.",
      "Use worksheet.sparklines.deleteAll() to remove all groups (safe no-op when empty).",
      "worksheet.sparklines is an alias for worksheet.sparklineGroups."
    ]
  },
  {
    kind: "api",
    name: "worksheet.sparklines.add",
    summary: "Create a sparkline group for a target range.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "sheet.getRange('A1:A6').values = [[1],[2],[3],[2],[4],[6]];",
              "const group = sheet.sparklines.add({",
              "  type: 'line',",
              "  sourceData: sheet.getRange('A1:A6'),",
              "  targetRange: sheet.getRange('B1:B6'),",
              "});",
              "group.displayXAxis = true;"
            ].join(`
`),
            summary: "Add a line sparkline group"
          }
        ]
      },
      python: {
        functionName: "worksheet.sparklines.add",
        examples: [
          {
            code: [
              "sheet.get_range('A1:A6').values = [[1], [2], [3], [2], [4], [6]]",
              "group = sheet.sparklines.add({",
              "  'type': 'line',",
              "  'sourceData': sheet.get_range('A1:A6'),",
              "  'targetRange': sheet.get_range('B1:B6'),",
              "})",
              "group.display_x_axis = True"
            ].join(`
`),
            summary: "Add a line sparkline group"
          }
        ]
      }
    },
    notes: [
      "targetRange and sourceData accept a Range or an A1 string address.",
      "Use worksheet.sparklines.deleteAll() to clear everything."
    ]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/api/formulas-help.js
var FORMULAS_API_HELP = [
  {
    kind: "api",
    name: "formulas",
    summary: "Formula authoring and calculation.",
    tags: ["spreadsheet", "formulas"],
    notes: [
      "Write formulas via range.formulas (2D string array).",
      `range.values accepts strings starting with '=' as formulas; use "'=..." for literal text.`,
      "Call workbook.recalculate() before reading computed values.",
      "If a newer Excel function appears unsupported in your runtime, replace it with compatible patterns (example: AVERAGEIFS -> SUMIFS/COUNTIFS)."
    ],
    languages: {
      javascript: {
        examples: [
          {
            code: [
              'const sheet = workbook.worksheets.add("Sheet1");',
              'const range = sheet.getRange("A1:A2");',
              'range.formulas = [["=1+1"], ["=SUM(2,3)"]];',
              "workbook.recalculate();",
              "const values = range.values;"
            ].join(`
`)
          }
        ],
        notes: []
      },
      python: {
        functionName: "range.formulas",
        examples: [
          {
            code: [
              'sheet = workbook.worksheets.add("Sheet1")',
              'range = sheet.get_range("A1:A2")',
              'range.formulas = [["=1+1"], ["=SUM(2,3)"]]',
              "workbook.recalculate()",
              "values = range.values"
            ].join(`
`)
          }
        ],
        notes: []
      }
    }
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/api/workbook-help.js
var CORE_WORKBOOK_API_HELP = [
  {
    kind: "api",
    name: "workbook",
    summary: "Workbook lifecycle and entry points.",
    notes: [
      "Create with Workbook.create() or Workbook.load().",
      "Access sheets via workbook.worksheets.",
      "Call workbook.recalculate() before reading formula results.",
      "Export with workbook.render(...) or workbook.toProto()."
    ]
  },
  {
    kind: "api",
    name: "workbook.render",
    summary: "Render worksheet previews as PNG/JPEG.",
    notes: [
      "Use workbook.render({ sheetName, range, format, scale, headers }).",
      "range is A1 notation; center requires width and height.",
      "Provide only one of sheet, sheetName, or sheetIndex.",
      "Use range or center (with width and height)."
    ],
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const png = await workbook.render({",
              "  sheetName: 'Summary',",
              "  range: 'A1:D12',",
              "  format: 'png',",
              "});"
            ].join(`
`),
            summary: "Render a range preview"
          }
        ]
      },
      python: {
        functionName: "workbook.render",
        examples: [
          {
            code: [
              "png = workbook.render({",
              "  'sheetName': 'Summary',",
              "  'range': 'A1:D12',",
              "  'format': 'png',",
              "})"
            ].join(`
`),
            summary: "Render a range preview"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "workbook.help",
    summary: "Return NDJSON help about workbook APIs via query and regex search",
    notes: [
      "Tip: query matches entry names, not example bodies. ",
      "To find an API by keyword, use query='*' to grep across the help index and search=<regex>",
      "Search uses regex matching; for multiple terms use pipes (example: freeze|pane|freeze_panes).",
      "Use `include` param to control payload size.",
      "Formula metadata is exposed under fx.<NAME> entries (ex: fx.LET).",
      "Enums are listed under enum.<Name> (ex: enum.ShapeGeometry)."
    ],
    examples: [
      {
        code: [
          "workbook.help(",
          "  'enum.ShapeGeometry',",
          "  { include: ['index','notes'] },",
          ")"
        ].join(`
`),
        summary: "Get help for a specific enums"
      },
      {
        code: [
          "workbook.help(",
          "  'enum.*',",
          "  { search: 'ShapeGeometry|LineStyle', include: ['index'] },",
          ")"
        ].join(`
`),
        summary: "Get help for multiple enums"
      },
      {
        code: [
          "workbook.help({query: '*', search: 'trendline|trendlines', include: ['index','examples']})."
        ].join(`
`),
        summary: "Get help on specific features by regex search"
      },
      {
        query: "ranges",
        include: ["index", "examples"],
        search: null,
        maxChars: 1200,
        summary: "Range addressing and value/formula basics"
      },
      {
        query: "styles",
        include: ["index", "examples"],
        search: null,
        maxChars: 1200,
        summary: "Formatting ranges (fills, fonts, borders, number formats)"
      },
      {
        query: "*",
        include: ["index", "examples", "notes"],
        search: "tables|sparklines|charts|images|render|validation|conditional|freeze|data_validation",
        maxChars: 2000,
        summary: "Grep for feature namespaces"
      },
      {
        query: "fx.*",
        include: ["index", "examples", "notes"],
        search: "LET|LAMBDA|XLOOKUP|MAP|BYROW",
        maxChars: 2000,
        summary: "Browse formula metadata entries"
      }
    ]
  },
  {
    kind: "api",
    name: "workbook.resolve",
    summary: "Resolve anchored ids from inspect output.",
    examples: [
      { id: "ws/<sheetId>" },
      { id: "th/<threadId>" },
      { id: "ch/<sheetRef>.<chartId>" }
    ],
    notes: [
      "Worksheet anchors: ws/<sheetRef> where sheetRef can be a worksheet name, worksheet id, or sheetId.",
      "Thread anchors: th/<threadId>.",
      "Chart anchors: ch/<sheetRef>.<chartId> (sheetRef can be a worksheet name, worksheet id, or sheetId; chartId is the chart.id)."
    ]
  },
  {
    kind: "api",
    name: "workbook.recalculate",
    summary: "Recalculate formulas and computed values.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const sheet = workbook.worksheets.getItem('Sheet1');",
              "sheet.getRange('A1:A2').values = [[1], [2]];",
              "sheet.getRange('B1').formulas = [['=SUM(A:A)']];",
              "const total = sheet.getRange('B1').values[0]?.[0];"
            ].join(`
`),
            summary: "Recalculate after writing formulas"
          }
        ]
      },
      python: {
        functionName: "workbook.recalculate",
        examples: [
          {
            code: [
              "sheet = workbook.worksheets.get_item('Sheet1')",
              "sheet.get_range('A1:A2').values = [[1], [2]]",
              "sheet.get_range('B1').formulas = [['=SUM(A:A)']]",
              "total = sheet.get_range('B1').values[0][0]"
            ].join(`
`),
            summary: "Recalculate after writing formulas"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "workbook.worksheets.add",
    summary: "Add a worksheet by name.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const sheet = workbook.worksheets.add('DogHealth');",
              "sheet.getRange('A1').values = [['Date']];"
            ].join(`
`),
            summary: "Create a worksheet and write values"
          }
        ]
      },
      python: {
        functionName: "workbook.worksheets.add",
        examples: [
          {
            code: [
              "sheet = workbook.worksheets.add('DogHealth')",
              "sheet.get_range('A1').values = [['Date']]"
            ].join(`
`),
            summary: "Create a worksheet and write values"
          }
        ]
      }
    },
    notes: [
      "If the name already exists, the existing worksheet is returned.",
      "Use workbook.worksheets.getItem to access existing sheets by name."
    ]
  },
  {
    kind: "api",
    name: "workbook.worksheets.getItem",
    summary: "Get a worksheet by name.",
    tags: ["worksheets"],
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const sheet = workbook.worksheets.getItem('Sheet1');",
              "sheet.getRange('A1').values = [['Hello']];"
            ].join(`
`),
            summary: "Fetch a sheet and write a cell"
          }
        ]
      },
      python: {
        functionName: "workbook.worksheets.get_item",
        examples: [
          {
            code: [
              "sheet = workbook.worksheets.get_item('Sheet1')",
              "sheet.get_range('A1').values = [['Hello']]"
            ].join(`
`),
            summary: "Fetch a sheet and write a cell"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "workbook.worksheets.getActiveWorksheet",
    summary: "Return the active worksheet.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const sheet = workbook.worksheets.getActiveWorksheet();",
              "sheet.getRange('A1').values = [['Active sheet']];"
            ].join(`
`),
            summary: "Write to the active sheet"
          }
        ]
      },
      python: {
        functionName: "workbook.worksheets.get_active_worksheet",
        examples: [
          {
            code: [
              "sheet = workbook.worksheets.get_active_worksheet()",
              "sheet.get_range('A1').values = [['Active sheet']]"
            ].join(`
`),
            summary: "Write to the active sheet"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "workbook.setColorScheme",
    summary: "Update the workbook theme color palette (accent1..6, bg/tx, dk/lt, hyperlinks).",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "// Prefer updating the theme palette over repainting every range.",
              "// Theme tokens like 'accent1' will automatically pick up the new palette.",
              "workbook.setColorScheme({",
              "  name: 'Brand',",
              "  themeColors: {",
              "    accent1: '#1F6FEB',",
              "    accent2: '#F97316',",
              "    accent3: '#16A34A',",
              "    dk1: '#0B0F19',",
              "    lt1: '#FFFFFF',",
              "    lt2: '#E5E7EB',",
              "    hlink: '#2563EB',",
              "    folHlink: '#7C3AED',",
              "  },",
              "});"
            ].join(`
`),
            summary: "Swap the workbook theme palette"
          },
          {
            code: [
              "// Then use theme tokens for styling:",
              "const sheet = workbook.worksheets.getItem('Sheet1');",
              "const header = sheet.getRange('A1:D1');",
              "header.format.fill = 'accent1';",
              "header.format.font = { color: 'lt1', bold: true };"
            ].join(`
`),
            summary: "Style with theme tokens (accent slots)"
          }
        ]
      },
      python: {
        functionName: "workbook.set_color_scheme",
        examples: [
          {
            code: [
              "# Prefer updating the theme palette over repainting every range.",
              "# Theme tokens like 'accent1' automatically pick up the new palette.",
              "workbook.set_color_scheme({",
              "  'name': 'Brand',",
              "  'themeColors': {",
              "    'accent1': '#1F6FEB',",
              "    'accent2': '#F97316',",
              "    'accent3': '#16A34A',",
              "    'dk1': '#0B0F19',",
              "    'lt1': '#FFFFFF',",
              "    'lt2': '#E5E7EB',",
              "    'hlink': '#2563EB',",
              "    'folHlink': '#7C3AED',",
              "  },",
              "})"
            ].join(`
`),
            summary: "Swap the workbook theme palette"
          },
          {
            code: [
              "# Then use theme tokens for styling:",
              "sheet = workbook.worksheets.get_item('Sheet1')",
              "header = sheet.get_range('A1:D1')",
              "header.format.fill = 'accent1'",
              "header.format.font = {'color': 'lt1', 'bold': True}"
            ].join(`
`),
            summary: "Style with theme tokens (accent slots)"
          }
        ]
      }
    },
    notes: [
      "Theme slots: accent1..accent6, bg1/bg2, tx1/tx2, dk1/lt1/dk2/lt2, hlink, folHlink.",
      "Use theme tokens in styling APIs (fills, fonts, borders, charts) so global re-theming works.",
      "Hex colors are fine for special needs, but tokens are the best default for dashboards and consistent styling."
    ]
  },
  {
    kind: "api",
    name: "workbook.utils",
    summary: "Small helpers for building formulas and addresses.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              'workbook.utils.columnToLetter(1); // "A"',
              'workbook.utils.columnToLetter(27); // "AA"',
              "workbook.utils.letterToColumn('AA'); // 27",
              "workbook.utils.toA1String(1, 2); // 'B1'",
              "workbook.utils.toA1String(1, 2, 3, 4); // 'B1:D3'"
            ].join(`
`),
            summary: "Convert between 1-based columns and letters"
          }
        ]
      },
      python: {
        functionName: "workbook.utils.to_a1_string",
        examples: [
          {
            code: [
              "column_a = workbook.utils.column_to_letter(1)  # 'A'",
              "column_aa = workbook.utils.column_to_letter(27)  # 'AA'",
              "column_index = workbook.utils.letter_to_column('AA')  # 27",
              "single_cell_a1 = workbook.utils.to_a1_string(1, 2)  # 'B1'",
              "range_a1 = workbook.utils.to_a1_string(1, 2, 3, 4)  # 'B1:D3'"
            ].join(`
`),
            summary: "Convert between 1-based columns and letters"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "workbook.awareness",
    summary: "Presence selections plus comment and note operations.",
    notes: [
      "Ops include comments.self.set, thread.add, thread.reply, note.add (comment.add alias).",
      "Comment/note ops require a comment author; call comments.self.set once or pass an author."
    ]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/api/drawings-help.js
var DRAWINGS_API_HELP = [
  {
    kind: "api",
    name: "drawings",
    summary: "Charts, shapes, and images anchored to cells.",
    notes: [
      "Use worksheet.charts, worksheet.shapes, and worksheet.images.",
      "Anchors use 0-based row/col indices with px offsets.",
      "Clearing cells does not remove drawings; delete drawings explicitly."
    ]
  },
  {
    kind: "api",
    name: "worksheet.deleteAllDrawings",
    summary: "Remove all charts, shapes, and images from a worksheet.",
    languages: {
      javascript: {
        examples: [
          {
            code: "sheet.deleteAllDrawings();",
            summary: "Clear drawings before rebuilding a dashboard"
          }
        ]
      },
      python: {
        functionName: "worksheet.delete_all_drawings",
        examples: [
          {
            code: "sheet.delete_all_drawings()",
            summary: "Clear drawings before rebuilding a dashboard"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "worksheet.autoLayoutDrawings",
    summary: "Lay out charts/shapes/images deterministically in a frame.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const items = sheet.charts.items;",
              "sheet.autoLayoutDrawings(items, {",
              "  direction: 'vertical',",
              "  frame: { startCell: 'A8', width: 1200, height: 800 },",
              "  gap: 24,",
              "  padding: 32,",
              "});"
            ].join(`
`),
            summary: "Stack charts vertically in a dashboard frame"
          }
        ]
      },
      python: {
        functionName: "worksheet.auto_layout_drawings",
        examples: [
          {
            code: [
              "items = sheet.charts.items",
              "sheet.auto_layout_drawings(items, {",
              "  'direction': 'vertical',",
              "  'frame': {'startCell': 'A8', 'width': 1200, 'height': 800},",
              "  'gap': 24,",
              "  'padding': 32,",
              "})"
            ].join(`
`),
            summary: "Stack charts vertically in a dashboard frame"
          }
        ]
      }
    },
    notes: [
      "Layout inputs are pixels; items keep their existing sizes.",
      "Pass charts, shapes, or images (or any mix)."
    ]
  },
  {
    kind: "api",
    name: "shapes",
    summary: "Shapes anchored to cells.",
    notes: [
      "Use worksheet.shapes.add(...) to create shapes.",
      "Shapes use 0-based row/col anchors and px offsets."
    ]
  },
  {
    kind: "api",
    name: "worksheet.shapes.add",
    summary: "Add a shape anchored to worksheet cells.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const sheet = workbook.worksheets.getItem('Shapes');",
              "sheet.shapes.add({",
              "  geometry: 'rect',",
              "  anchor: {",
              "    from: { row: 2, col: 3 },",
              "    extent: { widthPx: 260, heightPx: 140 },",
              "  },",
              "  fill: 'accent1',",
              "  line: { style: 'dashed', fill: 'accent4', width: 1 },",
              "});"
            ].join(`
`),
            summary: "Create a rectangle with an explicit extent anchor"
          },
          {
            code: [
              "const sheet = workbook.worksheets.getItem('Shapes');",
              "const star = sheet.shapes.add('Star5', sheet.getRange('G2:L10'));",
              "star.name = 'Star';",
              "star.fill.color = '#FFD966';",
              "star.line.color = '#C09000';"
            ].join(`
`),
            summary: "Compat add with a range anchor"
          }
        ]
      },
      python: {
        functionName: "worksheet.shapes.add",
        examples: [
          {
            code: [
              "sheet = workbook.worksheets.get_item('Shapes')",
              "sheet.shapes.add({",
              "  'geometry': 'rect',",
              "  'anchor': {",
              "    'from': {'row': 2, 'col': 3},",
              "    'extent': {'widthPx': 260, 'heightPx': 140},",
              "  },",
              "  'fill': 'accent1',",
              "  'line': {'style': 'dashed', 'fill': 'accent4', 'width': 1},",
              "})"
            ].join(`
`),
            summary: "Create a rectangle with an explicit extent anchor"
          },
          {
            code: [
              "sheet = workbook.worksheets.get_item('Shapes')",
              "star = sheet.shapes.add('Star5', sheet.get_range('G2:L10'))",
              "star.name = 'Star'",
              "star.fill.color = '#FFD966'",
              "star.line.color = '#C09000'"
            ].join(`
`),
            summary: "Compat add with a range anchor"
          }
        ]
      }
    },
    notes: [
      "geometry values are listed under enum.ShapeGeometry.",
      "geometry names are case-insensitive and accept common aliases like rectangle and rightTriangle.",
      "anchor accepts { from, to/extent } or a range like 'A1:D6'."
    ]
  },
  {
    kind: "api",
    name: "shapes.add",
    summary: "Alias for worksheet.shapes.add.",
    notes: ["Use worksheet.shapes.add for the full signature and examples."]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/api/names-help.js
var NAMES_API_HELP = [
  {
    kind: "api",
    name: "defined-names",
    summary: "Defined names and custom functions.",
    notes: [
      "Use workbook.names.add(name, refersTo) to create a named range (refersTo can be a Range or a string).",
      "Use workbook.names.getItem(name) / getItemOrNullObject(name) to access existing names.",
      "Use workbook.names.items to iterate, and namedItem.delete() to remove.",
      "Use workbook.names.addRange(name, formula, options) and workbook.names.addFunction(...) as legacy helpers.",
      "Compatibility alias: workbook.definedNames points to workbook.names."
    ]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/api/images-help.js
var IMAGES_API_HELP = [
  {
    kind: "api",
    name: "images",
    summary: "Worksheet image objects anchored to cells.",
    notes: [
      "Use worksheet.images.add(...) to place an image.",
      "Anchors use 0-based row/col indices with px offsets."
    ]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/api/inspect-help.js
var INSPECT_API_HELP = [
  {
    kind: "api",
    name: "workbook.inspect",
    summary: "Return NDJSON snapshot records for the workbook.",
    examples: [
      {
        target: null,
        kind: "sheet,table",
        include: null,
        exclude: null,
        search: "Revenue",
        maxChars: 1200,
        searchTerm: null,
        sheetId: null,
        range: null,
        offset: null,
        options: null,
        summary: "Inspect sheets/tables matching Revenue"
      },
      {
        target: null,
        kind: "region",
        include: null,
        exclude: null,
        search: null,
        maxChars: 2000,
        tableMaxRows: 5,
        tableMaxCols: 6,
        tableMaxCellChars: 80,
        searchTerm: null,
        sheetId: "ws/<sheetId>",
        range: null,
        offset: null,
        options: null,
        summary: "List data regions with previews for a sheet"
      },
      {
        target: null,
        kind: "table",
        include: "values",
        exclude: null,
        search: null,
        maxChars: 2000,
        tableMaxRows: 5,
        tableMaxCols: 6,
        tableMaxCellChars: 80,
        searchTerm: null,
        sheetId: "ws/<sheetId>",
        range: "A1:D20",
        offset: null,
        options: null,
        summary: "Preview table values for a range"
      },
      {
        target: null,
        kind: "conditionalFormatting",
        include: null,
        exclude: null,
        search: "top10",
        maxChars: 2000,
        tableMaxRows: 5,
        tableMaxCols: 6,
        tableMaxCellChars: 80,
        searchTerm: null,
        sheetId: "ws/<sheetId>",
        range: "B2:B20",
        offset: null,
        options: null,
        summary: "List conditional formatting rules for a range"
      },
      {
        target: { id: "ws/<sheetId>", beforeLines: 1, afterLines: 4 },
        kind: null,
        include: null,
        exclude: null,
        search: null,
        maxChars: 2000,
        searchTerm: null,
        sheetId: null,
        range: null,
        offset: null,
        options: null,
        summary: "Window around a sheet record"
      },
      {
        target: null,
        kind: null,
        include: null,
        exclude: null,
        search: null,
        maxChars: 3000,
        searchTerm: "Age",
        sheetId: null,
        range: null,
        offset: 0,
        options: {
          matchCase: null,
          matchEntireCell: null,
          useRegex: null,
          matchFormulas: true,
          ignoreDiacritics: null,
          maxResults: 20
        },
        summary: "Find cells matching Age (values or formulas)"
      }
    ],
    notes: [
      "Use search and maxChars to keep output focused.",
      "include/exclude select record properties (not cell addresses). Use search for A1-like addresses.",
      "Use searchTerm to return match records with sheet + address.",
      "range + sheetId scope table/formula/style output to a specific range.",
      "Use kind=conditionalFormatting (alias cf) to inspect rule families and params like text, timePeriod, top10, aboveAverage, and iconSet fields such as thresholds/showValue/reverse/percent.",
      "tableMaxRows/tableMaxCols/tableMaxCellChars control table preview sizes when values would be too large.",
      "Use kind=definedName to list workbook or sheet-scoped defined names."
    ]
  }
];

// node_modules/@oai/granola/dist/models/presentation/color.zod.js
var ColorNameSchema = exports_external.enum([
  "accent1",
  "accent2",
  "accent3",
  "accent4",
  "accent5",
  "accent6",
  "bg1",
  "bg2",
  "tx1",
  "tx2",
  "dk1",
  "lt1",
  "dk2",
  "lt2",
  "hlink",
  "folHlink"
]);
var ColorTransformSchema = exports_external.object({
  opacity: exports_external.number().optional(),
  lighten: exports_external.number().optional(),
  darken: exports_external.number().optional()
}).strict();
var ColorConfigSchema = exports_external.union([
  exports_external.string(),
  exports_external.object({
    type: exports_external.literal("rgb"),
    value: exports_external.string(),
    transform: ColorTransformSchema.optional()
  }).strict(),
  exports_external.object({
    type: exports_external.literal("theme"),
    value: ColorNameSchema,
    transform: ColorTransformSchema.optional()
  }).strict()
]);

// node_modules/@oai/granola/dist/models/presentation/pattern.zod.js
var patternNames = Object.keys(PATTERN_NAME_TO_TYPE_MAP);
var PatternNameSchema = exports_external.enum(patternNames);
var PatternConfigSchema = exports_external.object({
  type: PatternNameSchema,
  color: ColorConfigSchema
}).strict();

// node_modules/@oai/granola/dist/models/presentation/fill.zod.js
var FillToRectSchema = exports_external.object({
  l: exports_external.number().optional(),
  t: exports_external.number().optional(),
  r: exports_external.number().optional(),
  b: exports_external.number().optional()
}).strict();
var ImageReferenceSchema = exports_external.object({
  id: exports_external.string()
}).strict();
var GradientStopSchema = exports_external.object({
  offset: exports_external.number(),
  color: ColorConfigSchema
}).strict();
var GradientKindSchema = exports_external.enum(["linear", "path"]);
var SolidFillSchema = exports_external.object({
  type: exports_external.literal("solid"),
  color: ColorConfigSchema,
  pattern: PatternConfigSchema.optional()
}).strict();
var GradientFillSchema = exports_external.object({
  type: exports_external.literal("gradient"),
  stops: exports_external.array(GradientStopSchema),
  angleDeg: exports_external.number().optional(),
  gradientKind: GradientKindSchema.optional()
}).strict();
var ImageFillSchema = exports_external.object({
  type: exports_external.literal("image"),
  imageReference: ImageReferenceSchema,
  alphaModFix: exports_external.number().optional(),
  stretchFillRect: FillToRectSchema.optional(),
  fillRect: FillToRectSchema.optional(),
  pathType: exports_external.number().optional(),
  srcRect: FillToRectSchema.optional()
}).strict();
var NoneFillSchema = exports_external.object({
  type: exports_external.literal("none")
}).strict();
var FillConfigSchema = exports_external.union([
  exports_external.string(),
  NoneFillSchema,
  SolidFillSchema,
  GradientFillSchema,
  ImageFillSchema
]);

// node_modules/@oai/granola/dist/models/presentation/line.zod.js
var CanonicalLineStyleSchema = exports_external.enum([
  "solid",
  "dashed",
  "dotted",
  "dash-dot",
  "dash-dot-dot"
]);
var LineStyleValues = CanonicalLineStyleSchema.options;
var normalizeLineStyle = (value) => {
  if (typeof value !== "string") {
    return value;
  }
  const trimmed = value.trim();
  if (!trimmed) {
    return value;
  }
  const normalized = trimmed.toLowerCase().replace(/[^a-z]+/g, "");
  switch (normalized) {
    case "solid":
      return "solid";
    case "dash":
    case "dashed":
      return "dashed";
    case "dot":
    case "dotted":
      return "dotted";
    case "dashdot":
      return "dash-dot";
    case "dashdotdot":
      return "dash-dot-dot";
    default:
      return value;
  }
};
var LineStyleSchema = exports_external.preprocess(normalizeLineStyle, CanonicalLineStyleSchema);
var LineConfigSchema = exports_external.object({
  fill: FillConfigSchema.optional(),
  width: exports_external.number().optional(),
  color: FillConfigSchema.optional(),
  weight: exports_external.number().optional(),
  style: LineStyleSchema
}).strict();

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/enums-help.js
var WORKBOOK_ENUM_HELP = [
  {
    kind: "enum",
    name: "enum.ChartType",
    summary: "Supported chart types for worksheet charts.",
    values: Object.keys(CHART_TYPE_TO_PROTO),
    notes: [
      "Map charts currently render country-level data only. Use country names or ISO-3166-1 alpha-2/alpha-3 codes (e.g. USA, CAN, MEX)."
    ]
  },
  {
    kind: "enum",
    name: "enum.ShapeGeometry",
    summary: "Supported shape geometry tokens for worksheet shapes.",
    values: Object.keys(SHAPE_GEOMETRY_NAME_TO_PROTO)
  },
  {
    kind: "enum",
    name: "enum.LineStyle",
    summary: "Supported line styles for shape and chart strokes.",
    values: [...LineStyleValues]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/engine/metadata/compatibility.json
var compatibility_default = [
  {
    name: "STDEV",
    category: "compatibility",
    id: 13,
    description: "This function is available for compatibility with Excel 2007 and earlier. Estimates standard deviation based on a sample (ignores logical values and text in the sample)",
    example: "=STDEV(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numbers corresponding to a sample of a population and can be numbers or references that contain numbers",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "VAR",
    category: "compatibility",
    id: 47,
    description: "This function is available for compatibility with Excel 2007 and earlier. Estimates variance based on a sample (ignores logical values and text in the sample)",
    example: "=VAR(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numeric arguments corresponding to a sample of a population",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "STDEVP",
    category: "compatibility",
    id: 123,
    description: "This function is available for compatibility with Excel 2007 and earlier. Calculates standard deviation based on the entire population given as arguments (ignores logical values and text)",
    example: "=STDEVP(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numbers corresponding to a population and can be numbers or references that contain numbers",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "VARP",
    category: "compatibility",
    id: 124,
    description: "This function is available for compatibility with Excel 2007 and earlier. Calculates variance based on the entire population (ignores logical values and text in the population)",
    example: "=VARP(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numeric arguments corresponding to a population",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "RANK",
    category: "compatibility",
    id: 132,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the rank of a number in a list of numbers: its size relative to other values in the list",
    example: "=RANK(10, A1, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the number for which you want to find the rank",
        type: "number|range",
        optional: false
      },
      {
        name: "ref",
        description: "Is an array of, or a reference to, a list of numbers. Nonnumeric values are ignored",
        type: "value|range",
        optional: false
      },
      {
        name: "order",
        description: "Is a number: rank in the list sorted descending = 0 or omitted; rank in the list sorted ascending = any nonzero value",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "BETADIST",
    category: "compatibility",
    id: 150,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the cumulative beta probability density function",
    example: "=BETADIST(A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value between A and B at which to evaluate the function",
        type: "value|range",
        optional: false
      },
      {
        name: "alpha",
        description: "Is a parameter to the distribution and must be greater than 0",
        type: "value|range",
        optional: false
      },
      {
        name: "beta",
        description: "Is a parameter to the distribution and must be greater than 0",
        type: "value|range",
        optional: false
      },
      {
        name: "a",
        description: "Is an optional lower bound to the interval of x. If omitted, A = 0",
        type: "value|range",
        optional: true
      },
      {
        name: "b",
        description: "Is an optional upper bound to the interval of x. If omitted, B = 1",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "BETAINV",
    category: "compatibility",
    id: 152,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the inverse of the cumulative beta probability density function (BETADIST)",
    example: "=BETAINV(A1, A1, A1)",
    parameters: [
      {
        name: "probability",
        description: "Is a probability associated with the beta distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "alpha",
        description: "Is a parameter to the distribution and must be greater than 0",
        type: "value|range",
        optional: false
      },
      {
        name: "beta",
        description: "Is a parameter to the distribution and must be greater than 0",
        type: "value|range",
        optional: false
      },
      {
        name: "a",
        description: "Is an optional lower bound to the interval of x. If omitted, A = 0",
        type: "value|range",
        optional: true
      },
      {
        name: "b",
        description: "Is an optional upper bound to the interval of x. If omitted, B = 1",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "BINOMDIST",
    category: "compatibility",
    id: 153,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the individual term binomial distribution probability",
    example: "=BINOMDIST(10, A1, A1, A1)",
    parameters: [
      {
        name: "numberS",
        description: "Is the number of successes in trials",
        type: "number|range",
        optional: false
      },
      {
        name: "trials",
        description: "Is the number of independent trials",
        type: "value|range",
        optional: false
      },
      {
        name: "probabilityS",
        description: "Is the probability of success on each trial",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value: for the cumulative distribution function, use TRUE; for the probability mass function, use FALSE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CHIDIST",
    category: "compatibility",
    id: 154,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the right-tailed probability of the chi-squared distribution",
    example: "=CHIDIST(A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value at which you want to evaluate the distribution, a nonnegative number",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom",
        description: "Is the number of degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CHIINV",
    category: "compatibility",
    id: 155,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the inverse of the right-tailed probability of the chi-squared distribution",
    example: "=CHIINV(A1, A1)",
    parameters: [
      {
        name: "probability",
        description: "Is a probability associated with the chi-squared distribution, a value between 0 and 1 inclusive",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom",
        description: "Is the number of degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CONFIDENCE",
    category: "compatibility",
    id: 157,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the confidence interval for a population mean, using a normal distribution",
    example: "=CONFIDENCE(A1, A1, A1)",
    parameters: [
      {
        name: "alpha",
        description: "Is the significance level used to compute the confidence level, a number greater than 0 and less than 1",
        type: "value|range",
        optional: false
      },
      {
        name: "standardDev",
        description: "Is the population standard deviation for the data range and is assumed to be known. Standard_dev must be greater than 0",
        type: "value|range",
        optional: false
      },
      {
        name: "size",
        description: "Is the sample size",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CRITBINOM",
    category: "compatibility",
    id: 158,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the smallest value for which the cumulative binomial distribution is greater than or equal to a criterion value",
    example: "=CRITBINOM(A1, A1, A1)",
    parameters: [
      {
        name: "trials",
        description: "Is the number of Bernoulli trials",
        type: "value|range",
        optional: false
      },
      {
        name: "probabilityS",
        description: "Is the probability of success on each trial, a number between 0 and 1 inclusive",
        type: "value|range",
        optional: false
      },
      {
        name: "alpha",
        description: "Is the criterion value, a number between 0 and 1 inclusive",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "EXPONDIST",
    category: "compatibility",
    id: 160,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the exponential distribution",
    example: "=EXPONDIST(A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value of the function, a nonnegative number",
        type: "value|range",
        optional: false
      },
      {
        name: "lambda",
        description: "Is the parameter value, a positive number",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value for the function to return: the cumulative distribution function = TRUE; the probability density function = FALSE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "FDIST",
    category: "compatibility",
    id: 161,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the (right-tailed) F probability distribution (degree of diversity) for two data sets",
    example: "=FDIST(A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value at which to evaluate the function, a nonnegative number",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom1",
        description: "Is the numerator degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom2",
        description: "Is the denominator degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "FINV",
    category: "compatibility",
    id: 162,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the inverse of the (right-tailed) F probability distribution: if p = FDIST(x,...), then FINV(p,...) = x",
    example: "=FINV(A1, A1, A1)",
    parameters: [
      {
        name: "probability",
        description: "Is a probability associated with the F cumulative distribution, a number between 0 and 1 inclusive",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom1",
        description: "Is the numerator degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom2",
        description: "Is the denominator degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "FLOOR",
    category: "compatibility",
    id: 165,
    description: "Rounds a number down to the nearest multiple of significance",
    example: "=FLOOR(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the numeric value you want to round",
        type: "number|range",
        optional: false
      },
      {
        name: "significance",
        description: "Is the multiple to which you want to round. Number and Significance must either both be positive or both be negative",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "GAMMADIST",
    category: "compatibility",
    id: 166,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the gamma distribution",
    example: "=GAMMADIST(A1, A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value at which you want to evaluate the distribution, a nonnegative number",
        type: "value|range",
        optional: false
      },
      {
        name: "alpha",
        description: "Is a parameter to the distribution, a positive number",
        type: "value|range",
        optional: false
      },
      {
        name: "beta",
        description: "Is a parameter to the distribution, a positive number. If beta = 1, GAMMADIST returns the standard gamma distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value: return the cumulative distribution function = TRUE; return the probability mass function = FALSE or omitted",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "GAMMAINV",
    category: "compatibility",
    id: 167,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the inverse of the gamma cumulative distribution: if p = GAMMADIST(x,...), then GAMMAINV(p,...) = x",
    example: "=GAMMAINV(A1, A1, A1)",
    parameters: [
      {
        name: "probability",
        description: "Is the probability associated with the gamma distribution, a number between 0 and 1, inclusive",
        type: "value|range",
        optional: false
      },
      {
        name: "alpha",
        description: "Is a parameter to the distribution, a positive number",
        type: "value|range",
        optional: false
      },
      {
        name: "beta",
        description: "Is a parameter to the distribution, a positive number. If beta = 1, GAMMAINV returns the inverse of the standard gamma distribution",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CEILING",
    category: "compatibility",
    id: 168,
    description: "Rounds a number up, to the nearest multiple of significance",
    example: "=CEILING(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the value you want to round",
        type: "number|range",
        optional: false
      },
      {
        name: "significance",
        description: "Is the multiple to which you want to round",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "HYPGEOMDIST",
    category: "compatibility",
    id: 169,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the hypergeometric distribution",
    example: "=HYPGEOMDIST(A1, 10, A1, 10)",
    parameters: [
      {
        name: "sampleS",
        description: "Is the number of successes in the sample",
        type: "value|range",
        optional: false
      },
      {
        name: "numberSample",
        description: "Is the size of the sample",
        type: "number|range",
        optional: false
      },
      {
        name: "populationS",
        description: "Is the number of successes in the population",
        type: "value|range",
        optional: false
      },
      {
        name: "numberPop",
        description: "Is the population size",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "LOGNORMDIST",
    category: "compatibility",
    id: 170,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the cumulative lognormal distribution of x, where ln(x) is normally distributed with parameters Mean and Standard_dev",
    example: "=LOGNORMDIST(A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value at which to evaluate the function, a positive number",
        type: "value|range",
        optional: false
      },
      {
        name: "mean",
        description: "Is the mean of ln(x)",
        type: "value|range",
        optional: false
      },
      {
        name: "standardDev",
        description: "Is the standard deviation of ln(x), a positive number",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "LOGINV",
    category: "compatibility",
    id: 171,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the inverse of the lognormal cumulative distribution function of x, where ln(x) is normally distributed with parameters Mean and Standard_dev",
    example: "=LOGINV(A1, A1, A1)",
    parameters: [
      {
        name: "probability",
        description: "Is a probability associated with the lognormal distribution, a number between 0 and 1, inclusive",
        type: "value|range",
        optional: false
      },
      {
        name: "mean",
        description: "Is the mean of ln(x)",
        type: "value|range",
        optional: false
      },
      {
        name: "standardDev",
        description: "Is the standard deviation of ln(x), a positive number",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "NEGBINOMDIST",
    category: "compatibility",
    id: 172,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the negative binomial distribution, the probability that there will be Number_f failures before the Number_s-th success, with Probability_s probability of a success",
    example: "=NEGBINOMDIST(10, 10, A1)",
    parameters: [
      {
        name: "numberF",
        description: "Is the number of failures",
        type: "number|range",
        optional: false
      },
      {
        name: "numberS",
        description: "Is the threshold number of successes",
        type: "number|range",
        optional: false
      },
      {
        name: "probabilityS",
        description: "Is the probability of a success; a number between 0 and 1",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "NORMDIST",
    category: "compatibility",
    id: 173,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the normal cumulative distribution for the specified mean and standard deviation",
    example: "=NORMDIST(A1, A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value for which you want the distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "mean",
        description: "Is the arithmetic mean of the distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "standardDev",
        description: "Is the standard deviation of the distribution, a positive number",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value: for the cumulative distribution function, use TRUE; for the probability density function, use FALSE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "NORMSDIST",
    category: "compatibility",
    id: 174,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the standard normal cumulative distribution (has a mean of zero and a standard deviation of one)",
    example: "=NORMSDIST(A1)",
    parameters: [
      {
        name: "z",
        description: "Is the value for which you want the distribution",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "NORMINV",
    category: "compatibility",
    id: 175,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation",
    example: "=NORMINV(A1, A1, A1)",
    parameters: [
      {
        name: "probability",
        description: "Is a probability corresponding to the normal distribution, a number between 0 and 1 inclusive",
        type: "value|range",
        optional: false
      },
      {
        name: "mean",
        description: "Is the arithmetic mean of the distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "standardDev",
        description: "Is the standard deviation of the distribution, a positive number",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "NORMSINV",
    category: "compatibility",
    id: 176,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the inverse of the standard normal cumulative distribution (has a mean of zero and a standard deviation of one)",
    example: "=NORMSINV(A1)",
    parameters: [
      {
        name: "probability",
        description: "Is a probability corresponding to the normal distribution, a number between 0 and 1 inclusive",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "POISSON",
    category: "compatibility",
    id: 180,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the Poisson distribution",
    example: "=POISSON(A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the number of events",
        type: "value|range",
        optional: false
      },
      {
        name: "mean",
        description: "Is the expected numeric value, a positive number",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value: for the cumulative Poisson probability, use TRUE; for the Poisson probability mass function, use FALSE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "TDIST",
    category: "compatibility",
    id: 181,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the Student's t-distribution",
    example: "=TDIST(A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the numeric value at which to evaluate the distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom",
        description: "Is an integer indicating the number of degrees of freedom that characterize the distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "tails",
        description: "Specifies the number of distribution tails to return: one-tailed distribution = 1; two-tailed distribution = 2",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "WEIBULL",
    category: "compatibility",
    id: 182,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the Weibull distribution",
    example: "=WEIBULL(A1, A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value at which to evaluate the function, a nonnegative number",
        type: "value|range",
        optional: false
      },
      {
        name: "alpha",
        description: "Is a parameter to the distribution, a positive number",
        type: "value|range",
        optional: false
      },
      {
        name: "beta",
        description: "Is a parameter to the distribution, a positive number",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value: for the cumulative distribution function, use TRUE; for the probability mass function, use FALSE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CHITEST",
    category: "compatibility",
    id: 186,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the test for independence: the value from the chi-squared distribution for the statistic and the appropriate degrees of freedom",
    example: "=CHITEST(A1:A5, A1:A5)",
    parameters: [
      {
        name: "actualRange",
        description: "Is the range of data that contains observations to test against expected values",
        type: "range",
        optional: false
      },
      {
        name: "expectedRange",
        description: "Is the range of data that contains the ratio of the product of row totals and column totals to the grand total",
        type: "range",
        optional: false
      }
    ]
  },
  {
    name: "COVAR",
    category: "compatibility",
    id: 188,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns covariance, the average of the products of deviations for each data point pair in two data sets",
    example: "=COVAR({1,2;3,4}, {1,2;3,4})",
    parameters: [
      {
        name: "array1",
        description: "Is the first cell range of integers and must be numbers, arrays, or references that contain numbers",
        type: "array",
        optional: false
      },
      {
        name: "array2",
        description: "Is the second cell range of integers and must be numbers, arrays, or references that contain numbers",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "FORECAST",
    category: "compatibility",
    id: 189,
    description: "This function is available for compatibility with Excel 2013 and earlier. Calculates, or predicts, a future value along a linear trend by using existing values",
    example: "=FORECAST(A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the data point for which you want to predict a value and must be a numeric value",
        type: "value|range",
        optional: false
      },
      {
        name: "knownYs",
        description: "Is the dependent array or range of numeric data",
        type: "value|range",
        optional: false
      },
      {
        name: "knownXs",
        description: "Is the independent array or range of numeric data. The variance of Known_x's must not be zero",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "FTEST",
    category: "compatibility",
    id: 190,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the result of an F-test, the two-tailed probability that the variances in Array1 and Array2 are not significantly different",
    example: "=FTEST({1,2;3,4}, {1,2;3,4})",
    parameters: [
      {
        name: "array1",
        description: "Is the first array or range of data and can be numbers or names, arrays, or references that contain numbers (blanks are ignored)",
        type: "array",
        optional: false
      },
      {
        name: "array2",
        description: "Is the second array or range of data and can be numbers or names, arrays, or references that contain numbers (blanks are ignored)",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "TTEST",
    category: "compatibility",
    id: 196,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the probability associated with a Student's t-Test",
    example: "=TTEST({1,2;3,4}, {1,2;3,4}, A1, A1)",
    parameters: [
      {
        name: "array1",
        description: "Is the first data set",
        type: "array",
        optional: false
      },
      {
        name: "array2",
        description: "Is the second data set",
        type: "array",
        optional: false
      },
      {
        name: "tails",
        description: "Specifies the number of distribution tails to return: one-tailed distribution = 1; two-tailed distribution = 2",
        type: "value|range",
        optional: false
      },
      {
        name: "typeParam",
        description: "Is the kind of t-test: paired = 1, two-sample equal variance (homoscedastic) = 2, two-sample unequal variance = 3",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "ZTEST",
    category: "compatibility",
    id: 204,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the one-tailed P-value of a z-test",
    example: "=ZTEST({1,2;3,4}, A1, A1)",
    parameters: [
      {
        name: "array",
        description: "Is the array or range of data against which to test X",
        type: "array",
        optional: false
      },
      {
        name: "x",
        description: "Is the value to test",
        type: "value|range",
        optional: false
      },
      {
        name: "sigma",
        description: "Is the population (known) standard deviation. If omitted, the sample standard deviation is used",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "QUARTILE",
    category: "compatibility",
    id: 207,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the quartile of a data set",
    example: "=QUARTILE({1,2;3,4}, A1)",
    parameters: [
      {
        name: "array",
        description: "Is the array or cell range of numeric values for which you want the quartile value",
        type: "array",
        optional: false
      },
      {
        name: "quart",
        description: "Is a number: minimum value = 0; 1st quartile = 1; median value = 2; 3rd quartile = 3; maximum value = 4",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "PERCENTILE",
    category: "compatibility",
    id: 208,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the k-th percentile of values in a range",
    example: "=PERCENTILE({1,2;3,4}, A1)",
    parameters: [
      {
        name: "array",
        description: "Is the array or range of data that defines relative standing",
        type: "array",
        optional: false
      },
      {
        name: "k",
        description: "Is the percentile value that is between 0 through 1, inclusive",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "PERCENTRANK",
    category: "compatibility",
    id: 209,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the rank of a value in a data set as a percentage of the data set",
    example: "=PERCENTRANK({1,2;3,4}, A1, A1)",
    parameters: [
      {
        name: "array",
        description: "Is the array or range of data with numeric values that defines relative standing",
        type: "array",
        optional: false
      },
      {
        name: "x",
        description: "Is the value for which you want to know the rank",
        type: "value|range",
        optional: false
      },
      {
        name: "significance",
        description: "Is an optional value that identifies the number of significant digits for the returned percentage, three digits if omitted (0.xxx%)",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "MODE",
    category: "compatibility",
    id: 210,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the most frequently occurring, or repetitive, value in an array or range of data",
    example: "=MODE(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numbers, or names, arrays, or references that contain numbers for which you want the mode",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "TINV",
    category: "compatibility",
    id: 212,
    description: "This function is available for compatibility with Excel 2007 and earlier. Returns the two-tailed inverse of the Student's t-distribution",
    example: "=TINV(A1, A1)",
    parameters: [
      {
        name: "probability",
        description: "Is the probability associated with the two-tailed Student's t-distribution, a number between 0 and 1 inclusive",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom",
        description: "Is a positive integer indicating the number of degrees of freedom to characterize the distribution",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CONCATENATE",
    category: "compatibility",
    id: 213,
    description: "Joins several text strings into one text string",
    example: '=CONCATENATE("text1", C1:C5, "text2", C1:C5)',
    parameters: [
      {
        name: "text1",
        description: "Are 1 to 255 text strings to be joined into a single text string and can be text strings, numbers, or single-cell references",
        type: "string",
        optional: false
      },
      {
        name: "text2",
        description: "Text string.",
        type: "string",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/engine/metadata/cube.json
var cube_default = [
  {
    name: "CUBEVALUE",
    category: "cube",
    id: 233,
    description: "Returns an aggregated value from the cube.",
    example: "=CUBEVALUE(A1, C1:C5, A1, C1:C5)",
    parameters: [
      {
        name: "connection",
        description: "Is the name of a connection to an OLAP cube",
        type: "value|range",
        optional: false
      },
      {
        name: "memberExpression1",
        description: "Is a slicer that determines the portion of the OLAP cube for which the aggregated value is to be retrieved",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CUBEMEMBER",
    category: "cube",
    id: 234,
    description: "Returns a member or tuple from the cube.",
    example: "=CUBEMEMBER(A1, A1, A1)",
    parameters: [
      {
        name: "connection",
        description: "Is the name of a connection to an OLAP cube",
        type: "value|range",
        optional: false
      },
      {
        name: "memberExpression",
        description: "Is the expression representing the name of a member or tuple in the OLAP cube",
        type: "value|range",
        optional: false
      },
      {
        name: "caption",
        description: "Is the caption to be displayed in the cell",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "CUBEMEMBERPROPERTY",
    category: "cube",
    id: 235,
    description: "Returns the value of a member property from the cube.",
    example: "=CUBEMEMBERPROPERTY(A1, A1, A1)",
    parameters: [
      {
        name: "connection",
        description: "Is the name of a connection to an OLAP cube",
        type: "value|range",
        optional: false
      },
      {
        name: "memberExpression",
        description: "Is the expression representing the name of a member in the OLAP cube",
        type: "value|range",
        optional: false
      },
      {
        name: "property",
        description: "Is the property name",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CUBERANKEDMEMBER",
    category: "cube",
    id: 236,
    description: "Returns the nth, or ranked, member in a set.",
    example: "=CUBERANKEDMEMBER(A1, A1, A1)",
    parameters: [
      {
        name: "connection",
        description: "Is the name of a connection to an OLAP cube",
        type: "value|range",
        optional: false
      },
      {
        name: "setExpression",
        description: "Is the set from which the element is to be retrieved",
        type: "value|range",
        optional: false
      },
      {
        name: "rank",
        description: "Is the rank of the element to be retrieved",
        type: "value|range",
        optional: false
      },
      {
        name: "caption",
        description: "Is the caption to be displayed in the cell",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "CUBEKPIMEMBER",
    category: "cube",
    id: 329,
    description: "Returns a key performance indicator (KPI) property and displays the KPI name in the cell.",
    example: "=CUBEKPIMEMBER(A1, A1, A1)",
    parameters: [
      {
        name: "connection",
        description: "Is the name of a connection to an OLAP cube",
        type: "value|range",
        optional: false
      },
      {
        name: "kpiName",
        description: "Is the KPI name",
        type: "value|range",
        optional: false
      },
      {
        name: "kpiProperty",
        description: "Is the KPI property",
        type: "value|range",
        optional: false
      },
      {
        name: "caption",
        description: "Is the caption to be displayed in the cell",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "CUBESET",
    category: "cube",
    id: 330,
    description: "Defines a calculated set of members or tuples by sending a set expression to the cube on the server, which creates the set, and then returns that set to Microsoft Excel.",
    example: "=CUBESET(A1, A1, A1)",
    parameters: [
      {
        name: "connection",
        description: "Is the name of a connection to an OLAP cube",
        type: "value|range",
        optional: false
      },
      {
        name: "setExpression",
        description: "Is the expression for the set",
        type: "value|range",
        optional: false
      },
      {
        name: "caption",
        description: "Is the caption to be displayed in the cell",
        type: "value|range",
        optional: true
      },
      {
        name: "sortOrder",
        description: "Is the sort order",
        type: "value|range",
        optional: true
      },
      {
        name: "sortBy",
        description: "Is the sort by",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "CUBESETCOUNT",
    category: "cube",
    id: 331,
    description: "Returns the number of items in a set.",
    example: "=CUBESETCOUNT(A1)",
    parameters: [
      {
        name: "setParam",
        description: "Is the set whose elements are to be counted",
        type: "value|range",
        optional: false
      }
    ]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/engine/metadata/database.json
var database_default = [
  {
    name: "DCOUNT",
    category: "database",
    id: 41,
    description: "Counts the cells containing numbers in the field (column) of records in the database that match the conditions you specify",
    example: '=DCOUNT(A1, A1, ">0")',
    parameters: [
      {
        name: "database",
        description: "Is the range of cells that makes up the list or database. A database is a list of related data",
        type: "value|range",
        optional: false
      },
      {
        name: "field",
        description: "Is either the label of the column in double quotation marks or a number that represents the column's position in the list",
        type: "value|range",
        optional: false
      },
      {
        name: "criteria",
        description: "Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition",
        type: "criteria",
        optional: false
      }
    ]
  },
  {
    name: "DSUM",
    category: "database",
    id: 42,
    description: "Adds the numbers in the field (column) of records in the database that match the conditions you specify",
    example: '=DSUM(A1, A1, ">0")',
    parameters: [
      {
        name: "database",
        description: "Is the range of cells that makes up the list or database. A database is a list of related data",
        type: "value|range",
        optional: false
      },
      {
        name: "field",
        description: "Is either the label of the column in double quotation marks or a number that represents the column's position in the list",
        type: "value|range",
        optional: false
      },
      {
        name: "criteria",
        description: "Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition",
        type: "criteria",
        optional: false
      }
    ]
  },
  {
    name: "DAVERAGE",
    category: "database",
    id: 43,
    description: "Returns the average of the values in a database field after filtering rows with a criteria table.",
    example: '=DAVERAGE(A1:C10, "Sales", E1:F2)',
    parameters: [
      {
        name: "database",
        description: "Structured table (including headers) that holds the records to query.",
        type: "range",
        optional: false
      },
      {
        name: "field",
        description: 'Column to average, specified by header name ("Sales") or column index.',
        type: "string|number",
        optional: false
      },
      {
        name: "criteria",
        description: "Criteria range with column labels and the filters to apply to the database.",
        type: "range",
        optional: false
      }
    ]
  },
  {
    name: "DMIN",
    category: "database",
    id: 44,
    description: "Returns the smallest number in the field (column) of records in the database that match the conditions you specify",
    example: '=DMIN(A1, A1, ">0")',
    parameters: [
      {
        name: "database",
        description: "Is the range of cells that makes up the list or database. A database is a list of related data",
        type: "value|range",
        optional: false
      },
      {
        name: "field",
        description: "Is either the label of the column in double quotation marks or a number that represents the column's position in the list",
        type: "value|range",
        optional: false
      },
      {
        name: "criteria",
        description: "Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition",
        type: "criteria",
        optional: false
      }
    ]
  },
  {
    name: "DMAX",
    category: "database",
    id: 45,
    description: "Returns the largest number in the field (column) of records in the database that match the conditions you specify",
    example: '=DMAX(A1, A1, ">0")',
    parameters: [
      {
        name: "database",
        description: "Is the range of cells that makes up the list or database. A database is a list of related data",
        type: "value|range",
        optional: false
      },
      {
        name: "field",
        description: "Is either the label of the column in double quotation marks or a number that represents the column's position in the list",
        type: "value|range",
        optional: false
      },
      {
        name: "criteria",
        description: "Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition",
        type: "criteria",
        optional: false
      }
    ]
  },
  {
    name: "DSTDEV",
    category: "database",
    id: 46,
    description: "Estimates the standard deviation based on a sample from selected database entries",
    example: '=DSTDEV(A1, A1, ">0")',
    parameters: [
      {
        name: "database",
        description: "Is the range of cells that makes up the list or database. A database is a list of related data",
        type: "value|range",
        optional: false
      },
      {
        name: "field",
        description: "Is either the label of the column in double quotation marks or a number that represents the column's position in the list",
        type: "value|range",
        optional: false
      },
      {
        name: "criteria",
        description: "Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition",
        type: "criteria",
        optional: false
      }
    ]
  },
  {
    name: "DVAR",
    category: "database",
    id: 48,
    description: "Estimates variance based on a sample from selected database entries",
    example: '=DVAR(A1, A1, ">0")',
    parameters: [
      {
        name: "database",
        description: "Is the range of cells that makes up the list or database. A database is a list of related data",
        type: "value|range",
        optional: false
      },
      {
        name: "field",
        description: "Is either the label of the column in double quotation marks or a number that represents the column's position in the list",
        type: "value|range",
        optional: false
      },
      {
        name: "criteria",
        description: "Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition",
        type: "criteria",
        optional: false
      }
    ]
  },
  {
    name: "DPRODUCT",
    category: "database",
    id: 121,
    description: "Multiplies the values in the field (column) of records in the database that match the conditions you specify",
    example: '=DPRODUCT(A1, A1, ">0")',
    parameters: [
      {
        name: "database",
        description: "Is the range of cells that makes up the list or database. A database is a list of related data",
        type: "value|range",
        optional: false
      },
      {
        name: "field",
        description: "Is either the label of the column in double quotation marks or a number that represents the column's position in the list",
        type: "value|range",
        optional: false
      },
      {
        name: "criteria",
        description: "Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition",
        type: "criteria",
        optional: false
      }
    ]
  },
  {
    name: "DSTDEVP",
    category: "database",
    id: 125,
    description: "Calculates the standard deviation based on the entire population of selected database entries",
    example: '=DSTDEVP(A1, A1, ">0")',
    parameters: [
      {
        name: "database",
        description: "Is the range of cells that makes up the list or database. A database is a list of related data",
        type: "value|range",
        optional: false
      },
      {
        name: "field",
        description: "Is either the label of the column in double quotation marks or a number that represents the column's position in the list",
        type: "value|range",
        optional: false
      },
      {
        name: "criteria",
        description: "Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition",
        type: "criteria",
        optional: false
      }
    ]
  },
  {
    name: "DVARP",
    category: "database",
    id: 126,
    description: "Calculates variance based on the entire population of selected database entries",
    example: '=DVARP(A1, A1, ">0")',
    parameters: [
      {
        name: "database",
        description: "Is the range of cells that makes up the list or database. A database is a list of related data",
        type: "value|range",
        optional: false
      },
      {
        name: "field",
        description: "Is either the label of the column in double quotation marks or a number that represents the column's position in the list",
        type: "value|range",
        optional: false
      },
      {
        name: "criteria",
        description: "Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition",
        type: "criteria",
        optional: false
      }
    ]
  },
  {
    name: "DCOUNTA",
    category: "database",
    id: 129,
    description: "Counts nonblank cells in the field (column) of records in the database that match the conditions you specify",
    example: '=DCOUNTA(A1, A1, ">0")',
    parameters: [
      {
        name: "database",
        description: "Is the range of cells that makes up the list or database. A database is a list of related data",
        type: "value|range",
        optional: false
      },
      {
        name: "field",
        description: "Is either the label of the column in double quotation marks or a number that represents the column's position in the list",
        type: "value|range",
        optional: false
      },
      {
        name: "criteria",
        description: "Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition",
        type: "criteria",
        optional: false
      }
    ]
  },
  {
    name: "DGET",
    category: "database",
    id: 145,
    description: "Extracts from a database a single record that matches the conditions you specify",
    example: '=DGET(A1, A1, ">0")',
    parameters: [
      {
        name: "database",
        description: "Is the range of cells that makes up the list or database. A database is a list of related data",
        type: "value|range",
        optional: false
      },
      {
        name: "field",
        description: "Is either the label of the column in double quotation marks or a number that represents the column's position in the list",
        type: "value|range",
        optional: false
      },
      {
        name: "criteria",
        description: "Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition",
        type: "criteria",
        optional: false
      }
    ]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/engine/metadata/date-time.json
var date_time_default = [
  {
    name: "DATE",
    category: "date-time",
    id: 63,
    description: "Returns the number that represents the date in Microsoft Excel date-time code",
    example: "=DATE(A1, A1, A1)",
    parameters: [
      {
        name: "year",
        description: "Is a number from 1900 or 1904 (depending on the workbook's date system) to 9999",
        type: "value|range",
        optional: false
      },
      {
        name: "month",
        description: "Is a number from 1 to 12 representing the month of the year",
        type: "value|range",
        optional: false
      },
      {
        name: "day",
        description: "Is a number from 1 to 31 representing the day of the month",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "TIME",
    category: "date-time",
    id: 64,
    description: "Converts hours, minutes, and seconds given as numbers to an Excel serial number, formatted with a time format",
    example: "=TIME(A1, A1, A1)",
    parameters: [
      {
        name: "hour",
        description: "Is a number from 0 to 23 representing the hour",
        type: "value|range",
        optional: false
      },
      {
        name: "minute",
        description: "Is a number from 0 to 59 representing the minute",
        type: "value|range",
        optional: false
      },
      {
        name: "second",
        description: "Is a number from 0 to 59 representing the second",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "DAY",
    category: "date-time",
    id: 65,
    description: "Returns the day of the month, a number from 1 to 31.",
    example: "=DAY(10)",
    parameters: [
      {
        name: "serialNumber",
        description: "Is a number in the date-time code used by Microsoft Excel",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "MONTH",
    category: "date-time",
    id: 66,
    description: "Returns the month, a number from 1 (January) to 12 (December).",
    example: "=MONTH(10)",
    parameters: [
      {
        name: "serialNumber",
        description: "Is a number in the date-time code used by Microsoft Excel",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "YEAR",
    category: "date-time",
    id: 67,
    description: "Returns the year of a date, an integer in the range 1900 - 9999.",
    example: "=YEAR(10)",
    parameters: [
      {
        name: "serialNumber",
        description: "Is a number in the date-time code used by Microsoft Excel",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "WEEKDAY",
    category: "date-time",
    id: 68,
    description: "Returns a number from 1 to 7 identifying the day of the week of a date.",
    example: "=WEEKDAY(10, A1)",
    parameters: [
      {
        name: "serialNumber",
        description: "Is a number that represents a date",
        type: "number|range",
        optional: false
      },
      {
        name: "returnType",
        description: "Is a number: for Sunday=1 through Saturday=7, use 1; for Monday=1 through Sunday=7, use 2; for Monday=0 through Sunday=6, use 3",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "HOUR",
    category: "date-time",
    id: 69,
    description: "Returns the hour as a number from 0 (12:00 A.M.) to 23 (11:00 P.M.).",
    example: "=HOUR(10)",
    parameters: [
      {
        name: "serialNumber",
        description: "Is a number in the date-time code used by Microsoft Excel, or text in time format, such as 16:48:00 or 4:48:00 PM",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "MINUTE",
    category: "date-time",
    id: 70,
    description: "Returns the minute, a number from 0 to 59.",
    example: "=MINUTE(10)",
    parameters: [
      {
        name: "serialNumber",
        description: "Is a number in the date-time code used by Microsoft Excel or text in time format, such as 16:48:00 or 4:48:00 PM",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "SECOND",
    category: "date-time",
    id: 71,
    description: "Returns the second, a number from 0 to 59.",
    example: "=SECOND(10)",
    parameters: [
      {
        name: "serialNumber",
        description: "Is a number in the date-time code used by Microsoft Excel or text in time format, such as 16:48:23 or 4:48:47 PM",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "NOW",
    category: "date-time",
    id: 72,
    description: "Returns the current date and time formatted as a date and time.",
    example: "=NOW()",
    parameters: []
  },
  {
    name: "DATEVALUE",
    category: "date-time",
    id: 106,
    description: "Converts a date in the form of text to a number that represents the date in Microsoft Excel date-time code",
    example: "=DATEVALUE(DATE(2024, 1, 1))",
    parameters: [
      {
        name: "dateText",
        description: "Is text that represents a date in a Microsoft Excel date format, between 1/1/1900 or 1/1/1904 (depending on the workbook's date system) and 12/31/9999",
        type: "string",
        optional: false
      }
    ]
  },
  {
    name: "TIMEVALUE",
    category: "date-time",
    id: 107,
    description: "Converts a text time to an Excel serial number for a time, a number from 0 (12:00:00 AM) to 0.999988426 (11:59:59 PM). Format the number with a time format after entering the formula",
    example: "=TIMEVALUE(TIME(9, 0, 0))",
    parameters: [
      {
        name: "timeText",
        description: "Is a text string that gives a time in any one of the Microsoft Excel time formats (date information in the string is ignored)",
        type: "string",
        optional: false
      }
    ]
  },
  {
    name: "DAYS360",
    category: "date-time",
    id: 134,
    description: "Returns the number of days between two dates based on a 360-day year (twelve 30-day months)",
    example: "=DAYS360(DATE(2024, 1, 1), DATE(2024, 1, 1), A1)",
    parameters: [
      {
        name: "startDate",
        description: "Start_date and end_date are the two dates between which you want to know the number of days",
        type: "date",
        optional: false
      },
      {
        name: "endDate",
        description: "Start_date and end_date are the two dates between which you want to know the number of days",
        type: "date",
        optional: false
      },
      {
        name: "method",
        description: "Is a logical value specifying the calculation method: U.S. (NASD) = FALSE or omitted; European = TRUE.",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "TODAY",
    category: "date-time",
    id: 135,
    description: "Returns the current date formatted as a date.",
    example: "=TODAY()",
    parameters: []
  },
  {
    name: "EDATE",
    category: "date-time",
    id: 302,
    description: "Returns the serial number of the date that is the indicated number of months before or after the start date",
    example: "=EDATE(DATE(2024, 1, 1), A1)",
    parameters: [
      {
        name: "startDate",
        description: "Is a serial date number that represents the start date",
        type: "date",
        optional: false
      },
      {
        name: "months",
        description: "Is the number of months before or after start_date",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "EOMONTH",
    category: "date-time",
    id: 303,
    description: "Returns the serial number of the last day of the month before or after a specified number of months",
    example: "=EOMONTH(DATE(2024, 1, 1), A1)",
    parameters: [
      {
        name: "startDate",
        description: "Is a serial date number that represents the start date",
        type: "date",
        optional: false
      },
      {
        name: "months",
        description: "Is the number of months before or after the start_date",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "YEARFRAC",
    category: "date-time",
    id: 304,
    description: "Returns the year fraction representing the number of whole days between start_date and end_date",
    example: "=YEARFRAC(DATE(2024, 1, 1), DATE(2024, 1, 1), A1)",
    parameters: [
      {
        name: "startDate",
        description: "Is a serial date number that represents the start date",
        type: "date",
        optional: false
      },
      {
        name: "endDate",
        description: "Is a serial date number that represents the end date",
        type: "date",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "WEEKNUM",
    category: "date-time",
    id: 318,
    description: "Returns the week number in the year",
    example: "=WEEKNUM(10, A1)",
    parameters: [
      {
        name: "serialNumber",
        description: "Is the date-time code used by Microsoft Excel for date and time calculation",
        type: "number|range",
        optional: false
      },
      {
        name: "returnType",
        description: "Is a number (1 or 2) that determines the type of the return value",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "WORKDAY",
    category: "date-time",
    id: 323,
    description: "Returns the serial number of the date before or after a specified number of workdays",
    example: "=WORKDAY(DATE(2024, 1, 1), A1, A1)",
    parameters: [
      {
        name: "startDate",
        description: "Is a serial date number that represents the start date",
        type: "date",
        optional: false
      },
      {
        name: "days",
        description: "Is the number of nonweekend and non-holiday days before or after start_date",
        type: "value|range",
        optional: false
      },
      {
        name: "holidays",
        description: "Is an optional array of one or more serial date numbers to exclude from the working calendar, such as state and federal holidays and floating holidays",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "NETWORKDAYS",
    category: "date-time",
    id: 324,
    description: "Returns the number of whole workdays between two dates",
    example: "=NETWORKDAYS(DATE(2024, 1, 1), DATE(2024, 1, 1), A1)",
    parameters: [
      {
        name: "startDate",
        description: "Is a serial date number that represents the start date",
        type: "date",
        optional: false
      },
      {
        name: "endDate",
        description: "Is a serial date number that represents the end date",
        type: "date",
        optional: false
      },
      {
        name: "holidays",
        description: "Is an optional set of one or more serial date numbers to exclude from the working calendar, such as state and federal holidays and floating holidays",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "NETWORKDAYS.INTL",
    category: "date-time",
    id: 372,
    description: "Returns the number of whole workdays between two dates with custom weekend parameters",
    example: "=NETWORKDAYS.INTL(DATE(2024, 1, 1), DATE(2024, 1, 1), A1)",
    parameters: [
      {
        name: "startDate",
        description: "Is a serial date number that represents the start date",
        type: "date",
        optional: false
      },
      {
        name: "endDate",
        description: "Is a serial date number that represents the end date",
        type: "date",
        optional: false
      },
      {
        name: "weekend",
        description: "Is a number or string specifying when weekends occur",
        type: "value|range",
        optional: true
      },
      {
        name: "holidays",
        description: "Is an optional set of one or more serial date numbers to exclude from the working calendar, such as state and federal holidays and floating holidays",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "WORKDAY.INTL",
    category: "date-time",
    id: 373,
    description: "Returns the serial number of the date before or after a specified number of workdays with custom weekend parameters",
    example: "=WORKDAY.INTL(DATE(2024, 1, 1), A1, A1)",
    parameters: [
      {
        name: "startDate",
        description: "Is a serial date number that represents the start date",
        type: "date",
        optional: false
      },
      {
        name: "days",
        description: "Is the number of nonweekend and non-holiday days before or after start_date",
        type: "value|range",
        optional: false
      },
      {
        name: "weekend",
        description: "Is a number or string specifying when weekends occur",
        type: "value|range",
        optional: true
      },
      {
        name: "holidays",
        description: "Is an optional array of one or more serial date numbers to exclude from the working calendar, such as state and federal holidays and floating holidays",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "DAYS",
    category: "date-time",
    id: 420,
    description: "Returns the number of days between the two dates.",
    example: "=DAYS(DATE(2024, 1, 1), DATE(2024, 1, 1))",
    parameters: [
      {
        name: "endDate",
        description: "Start_date and end_date are the two dates between which you want to know the number of days",
        type: "date",
        optional: false
      },
      {
        name: "startDate",
        description: "Start_date and end_date are the two dates between which you want to know the number of days",
        type: "date",
        optional: false
      }
    ]
  },
  {
    name: "ISOWEEKNUM",
    category: "date-time",
    id: 431,
    description: "Returns the ISO week number in the year for a given date",
    example: "=ISOWEEKNUM(DATE(2024, 1, 1))",
    parameters: [
      {
        name: "date",
        description: "Is the date-time code used by Microsoft Excel for date and time calculation",
        type: "date",
        optional: false
      }
    ]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/engine/metadata/engineering.json
var engineering_default = [
  {
    name: "HEX2BIN",
    category: "engineering",
    id: 237,
    description: "Converts a Hexadecimal number to binary",
    example: "=HEX2BIN(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the hexadecimal number you want to convert",
        type: "number|range",
        optional: false
      },
      {
        name: "places",
        description: "Is the number of characters to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "HEX2DEC",
    category: "engineering",
    id: 238,
    description: "Converts a hexadecimal number to decimal",
    example: "=HEX2DEC(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the hexadecimal number you want to convert",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "HEX2OCT",
    category: "engineering",
    id: 239,
    description: "Converts a hexadecimal number to octal",
    example: "=HEX2OCT(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the hexadecimal number you want to convert",
        type: "number|range",
        optional: false
      },
      {
        name: "places",
        description: "Is the number of characters to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "DEC2BIN",
    category: "engineering",
    id: 240,
    description: "Converts a decimal number to binary",
    example: "=DEC2BIN(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the decimal integer you want to convert",
        type: "number|range",
        optional: false
      },
      {
        name: "places",
        description: "Is the number of characters to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "DEC2HEX",
    category: "engineering",
    id: 241,
    description: "Converts a decimal number to hexadecimal",
    example: "=DEC2HEX(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the decimal integer you want to convert",
        type: "number|range",
        optional: false
      },
      {
        name: "places",
        description: "Is the number of characters to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "DEC2OCT",
    category: "engineering",
    id: 242,
    description: "Converts a decimal number to octal",
    example: "=DEC2OCT(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the decimal integer you want to convert",
        type: "number|range",
        optional: false
      },
      {
        name: "places",
        description: "Is the number of characters to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "OCT2BIN",
    category: "engineering",
    id: 243,
    description: "Converts an octal number to binary",
    example: "=OCT2BIN(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the octal number you want to convert",
        type: "number|range",
        optional: false
      },
      {
        name: "places",
        description: "Is the number of characters to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "OCT2HEX",
    category: "engineering",
    id: 244,
    description: "Converts an octal number to hexadecimal",
    example: "=OCT2HEX(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the octal number you want to convert",
        type: "number|range",
        optional: false
      },
      {
        name: "places",
        description: "Is the number of characters to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "OCT2DEC",
    category: "engineering",
    id: 245,
    description: "Converts an octal number to decimal",
    example: "=OCT2DEC(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the octal number you want to convert",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "BIN2DEC",
    category: "engineering",
    id: 246,
    description: "Converts a binary number to decimal",
    example: "=BIN2DEC(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the binary number you want to convert",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "BIN2OCT",
    category: "engineering",
    id: 247,
    description: "Converts a binary number to octal",
    example: "=BIN2OCT(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the binary number you want to convert",
        type: "number|range",
        optional: false
      },
      {
        name: "places",
        description: "Is the number of characters to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "BIN2HEX",
    category: "engineering",
    id: 248,
    description: "Converts a binary number to hexadecimal",
    example: "=BIN2HEX(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the binary number you want to convert",
        type: "number|range",
        optional: false
      },
      {
        name: "places",
        description: "Is the number of characters to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "IMSUB",
    category: "engineering",
    id: 249,
    description: "Returns the difference of two complex numbers",
    example: "=IMSUB(10, 10)",
    parameters: [
      {
        name: "inumber1",
        description: "Is the complex number from which to subtract inumber2",
        type: "number|range",
        optional: false
      },
      {
        name: "inumber2",
        description: "Is the complex number to subtract from inumber1",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMDIV",
    category: "engineering",
    id: 250,
    description: "Returns the quotient of two complex numbers",
    example: "=IMDIV(10, 10)",
    parameters: [
      {
        name: "inumber1",
        description: "Is the complex numerator or dividend",
        type: "number|range",
        optional: false
      },
      {
        name: "inumber2",
        description: "Is the complex denominator or divisor",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMPOWER",
    category: "engineering",
    id: 251,
    description: "Returns a complex number raised to an integer power",
    example: "=IMPOWER(10, 10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number you want to raise to a power",
        type: "number|range",
        optional: false
      },
      {
        name: "numberParam",
        description: "Is the power to which you want to raise the complex number",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMABS",
    category: "engineering",
    id: 252,
    description: "Returns the absolute value (modulus) of a complex number",
    example: "=IMABS(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the absolute value",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMSQRT",
    category: "engineering",
    id: 253,
    description: "Returns the square root of a complex number",
    example: "=IMSQRT(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the square root",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMLN",
    category: "engineering",
    id: 254,
    description: "Returns the natural logarithm of a complex number",
    example: "=IMLN(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the natural logarithm",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMLOG2",
    category: "engineering",
    id: 255,
    description: "Returns the base-2 logarithm of a complex number",
    example: "=IMLOG2(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the base-2 logarithm",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMLOG10",
    category: "engineering",
    id: 256,
    description: "Returns the base-10 logarithm of a complex number",
    example: "=IMLOG10(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the common logarithm",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMSIN",
    category: "engineering",
    id: 257,
    description: "Returns the sine of a complex number",
    example: "=IMSIN(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the sine",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMCOS",
    category: "engineering",
    id: 258,
    description: "Returns the cosine of a complex number",
    example: "=IMCOS(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the cosine",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMEXP",
    category: "engineering",
    id: 259,
    description: "Returns the exponential of a complex number",
    example: "=IMEXP(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the exponential",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMARGUMENT",
    category: "engineering",
    id: 260,
    description: "Returns the argument q, an angle expressed in radians",
    example: "=IMARGUMENT(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the argument",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMCONJUGATE",
    category: "engineering",
    id: 261,
    description: "Returns the complex conjugate of a complex number",
    example: "=IMCONJUGATE(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the conjugate",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMAGINARY",
    category: "engineering",
    id: 262,
    description: "Returns the imaginary coefficient of a complex number",
    example: "=IMAGINARY(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the imaginary coefficient",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMREAL",
    category: "engineering",
    id: 263,
    description: "Returns the real coefficient of a complex number",
    example: "=IMREAL(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the real coefficient",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "COMPLEX",
    category: "engineering",
    id: 264,
    description: "Converts real and imaginary coefficients into a complex number",
    example: "=COMPLEX(A1, A1, A1)",
    parameters: [
      {
        name: "realNum",
        description: "Is the real coefficient of the complex number",
        type: "value|range",
        optional: false
      },
      {
        name: "iNum",
        description: "Is the imaginary coefficient of the complex number",
        type: "value|range",
        optional: false
      },
      {
        name: "suffix",
        description: "Is the suffix for the imaginary component of the complex number",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "IMSUM",
    category: "engineering",
    id: 265,
    description: "Returns the sum of complex numbers",
    example: "=IMSUM(10, C1:C5, 10, C1:C5)",
    parameters: [
      {
        name: "inumber1",
        description: "Are from 1 to 255 complex numbers to add",
        type: "number|range",
        optional: false
      },
      {
        name: "inumber2",
        description: "Number or reference.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "IMPRODUCT",
    category: "engineering",
    id: 266,
    description: "Returns the product of 1 to 255 complex numbers",
    example: "=IMPRODUCT(10, C1:C5, 10, C1:C5)",
    parameters: [
      {
        name: "inumber1",
        description: "Inumber1, Inumber2,... are from 1 to 255 complex numbers to multiply.",
        type: "number|range",
        optional: false
      },
      {
        name: "inumber2",
        description: "Number or reference.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "DELTA",
    category: "engineering",
    id: 271,
    description: "Tests whether two numbers are equal",
    example: "=DELTA(10, 20)",
    parameters: [
      {
        name: "number1",
        description: "Is the first number",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Is the second number",
        type: "number|range",
        optional: true
      }
    ]
  },
  {
    name: "GESTEP",
    category: "engineering",
    id: 272,
    description: "Tests whether a number is greater than a threshold value",
    example: "=GESTEP(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the value to test against step",
        type: "number|range",
        optional: false
      },
      {
        name: "step",
        description: "Is the threshold value",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "ERF",
    category: "engineering",
    id: 276,
    description: "Returns the error function",
    example: "=ERF(A1, A1)",
    parameters: [
      {
        name: "lowerLimit",
        description: "Is the lower bound for integrating ERF",
        type: "value|range",
        optional: false
      },
      {
        name: "upperLimit",
        description: "Is the upper bound for integrating ERF",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "ERFC",
    category: "engineering",
    id: 277,
    description: "Returns the complementary error function",
    example: "=ERFC(A1)",
    parameters: [
      {
        name: "x",
        description: "Is the lower bound for integrating ERF",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "BESSELJ",
    category: "engineering",
    id: 278,
    description: "Returns the Bessel function Jn(x)",
    example: "=BESSELJ(A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value at which to evaluate the function",
        type: "value|range",
        optional: false
      },
      {
        name: "n",
        description: "Is the order of the Bessel function",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "BESSELK",
    category: "engineering",
    id: 279,
    description: "Returns the modified Bessel function Kn(x)",
    example: "=BESSELK(A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value at which to evaluate the function",
        type: "value|range",
        optional: false
      },
      {
        name: "n",
        description: "Is the order of the function",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "BESSELY",
    category: "engineering",
    id: 280,
    description: "Returns the Bessel function Yn(x)",
    example: "=BESSELY(A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value at which to evaluate the function",
        type: "value|range",
        optional: false
      },
      {
        name: "n",
        description: "Is the order of the function",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "BESSELI",
    category: "engineering",
    id: 281,
    description: "Returns the modified Bessel function In(x)",
    example: "=BESSELI(A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value at which to evaluate the function",
        type: "value|range",
        optional: false
      },
      {
        name: "n",
        description: "Is the order of the Bessel function",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CONVERT",
    category: "engineering",
    id: 320,
    description: "Converts a number from one measurement system to another",
    example: "=CONVERT(10, A1, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the value in from_units to convert",
        type: "number|range",
        optional: false
      },
      {
        name: "fromUnit",
        description: "Is the units for number",
        type: "value|range",
        optional: false
      },
      {
        name: "toUnit",
        description: "Is the units for the result",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "ERF.PRECISE",
    category: "engineering",
    id: 392,
    description: "Returns the error function",
    example: "=ERF.PRECISE(A1)",
    parameters: [
      {
        name: "x",
        description: "Is the lower bound for integrating ERF.PRECISE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "ERFC.PRECISE",
    category: "engineering",
    id: 393,
    description: "Returns the complementary error function",
    example: "=ERFC.PRECISE(A1)",
    parameters: [
      {
        name: "x",
        description: "Is the lower bound for integrating ERFC.PRECISE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "IMTAN",
    category: "engineering",
    id: 403,
    description: "Returns the tangent of a complex number",
    example: "=IMTAN(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the tangent",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMCOT",
    category: "engineering",
    id: 404,
    description: "Returns the cotangent of a complex number",
    example: "=IMCOT(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the cotangent",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMCSC",
    category: "engineering",
    id: 405,
    description: "Returns the cosecant of a complex number",
    example: "=IMCSC(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the cosecant",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMCSCH",
    category: "engineering",
    id: 406,
    description: "Returns the hyperbolic cosecant of a complex number",
    example: "=IMCSCH(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the hyperbolic cosecant",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMSEC",
    category: "engineering",
    id: 407,
    description: "Returns the secant of a complex number",
    example: "=IMSEC(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the secant",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMSECH",
    category: "engineering",
    id: 408,
    description: "Returns the hyperbolic secant of a complex number",
    example: "=IMSECH(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the hyperbolic secant",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "BITAND",
    category: "engineering",
    id: 409,
    description: "Returns a bitwise 'And' of two numbers",
    example: "=BITAND(10, 20)",
    parameters: [
      {
        name: "number1",
        description: "Is the decimal representation of the binary number you want to evaluate",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Is the decimal representation of the binary number you want to evaluate",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "BITOR",
    category: "engineering",
    id: 410,
    description: "Returns a bitwise 'Or' of two numbers",
    example: "=BITOR(10, 20)",
    parameters: [
      {
        name: "number1",
        description: "Is the decimal representation of the binary number you want to evaluate",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Is the decimal representation of the binary number you want to evaluate",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "BITXOR",
    category: "engineering",
    id: 411,
    description: "Returns a bitwise 'Exclusive Or' of two numbers",
    example: "=BITXOR(10, 20)",
    parameters: [
      {
        name: "number1",
        description: "Is the decimal representation of the binary number you want to evaluate",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Is the decimal representation of the binary number you want to evaluate",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "BITLSHIFT",
    category: "engineering",
    id: 412,
    description: "Returns a number shifted left by shift_amount bits",
    example: "=BITLSHIFT(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the decimal representation of the binary number you want to evaluate",
        type: "number|range",
        optional: false
      },
      {
        name: "shiftAmount",
        description: "Is the number of bits that you want to shift Number left by",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "BITRSHIFT",
    category: "engineering",
    id: 413,
    description: "Returns a number shifted right by shift_amount bits",
    example: "=BITRSHIFT(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the decimal representation of the binary number you want to evaluate",
        type: "number|range",
        optional: false
      },
      {
        name: "shiftAmount",
        description: "Is the number of bits that you want to shift Number right by",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "IMSINH",
    category: "engineering",
    id: 440,
    description: "Returns the hyperbolic sine of a complex number",
    example: "=IMSINH(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the hyperbolic sine",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "IMCOSH",
    category: "engineering",
    id: 441,
    description: "Returns the hyperbolic cosine of a complex number",
    example: "=IMCOSH(10)",
    parameters: [
      {
        name: "inumber",
        description: "Is a complex number for which you want the hyperbolic cosine",
        type: "number|range",
        optional: false
      }
    ]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/engine/metadata/financial.json
var financial_default = [
  {
    name: "NPV",
    category: "financial",
    id: 12,
    description: "Returns the net present value of an investment based on a discount rate and a series of future payments (negative values) and income (positive values)",
    example: "=NPV(A1, A1:A5, C1:C5, C1:C5)",
    parameters: [
      {
        name: "rate",
        description: "Is the rate of discount over the length of one period",
        type: "value|range",
        optional: false
      },
      {
        name: "value1",
        description: "Are 1 to 254 payments and income, equally spaced in time and occurring at the end of each period",
        type: "value|range",
        optional: false
      },
      {
        name: "value2",
        description: "Value argument for the calculation.",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "PV",
    category: "financial",
    id: 54,
    description: "Returns the present value of an investment: the total amount that a series of future payments is worth now",
    example: "=PV(A1, A1, A1)",
    parameters: [
      {
        name: "rate",
        description: "Is the interest rate per period. For example, use 6%/4 for quarterly payments at 6% APR",
        type: "value|range",
        optional: false
      },
      {
        name: "nper",
        description: "Is the total number of payment periods in an investment",
        type: "value|range",
        optional: false
      },
      {
        name: "pmt",
        description: "Is the payment made each period and cannot change over the life of the investment",
        type: "value|range",
        optional: false
      },
      {
        name: "fv",
        description: "Is the future value, or a cash balance you want to attain after the last payment is made",
        type: "value|range",
        optional: true
      },
      {
        name: "typeParam",
        description: "Is a logical value: payment at the beginning of the period = 1; payment at the end of the period = 0 or omitted",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "FV",
    category: "financial",
    id: 55,
    description: "Returns the future value of an investment based on periodic, constant payments and a constant interest rate",
    example: "=FV(A1, A1, A1)",
    parameters: [
      {
        name: "rate",
        description: "Is the interest rate per period. For example, use 6%/4 for quarterly payments at 6% APR",
        type: "value|range",
        optional: false
      },
      {
        name: "nper",
        description: "Is the total number of payment periods in the investment",
        type: "value|range",
        optional: false
      },
      {
        name: "pmt",
        description: "Is the payment made each period; it cannot change over the life of the investment",
        type: "value|range",
        optional: false
      },
      {
        name: "pv",
        description: "Is the present value, or the lump-sum amount that a series of future payments is worth now. If omitted, Pv = 0",
        type: "value|range",
        optional: true
      },
      {
        name: "typeParam",
        description: "Is a value representing the timing of payment: payment at the beginning of the period = 1; payment at the end of the period = 0 or omitted",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "NPER",
    category: "financial",
    id: 56,
    description: "Returns the number of periods for an investment based on periodic, constant payments and a constant interest rate",
    example: "=NPER(A1, A1, A1)",
    parameters: [
      {
        name: "rate",
        description: "Is the interest rate per period. For example, use 6%/4 for quarterly payments at 6% APR",
        type: "value|range",
        optional: false
      },
      {
        name: "pmt",
        description: "Is the payment made each period; it cannot change over the life of the investment",
        type: "value|range",
        optional: false
      },
      {
        name: "pv",
        description: "Is the present value, or the lump-sum amount that a series of future payments is worth now",
        type: "value|range",
        optional: false
      },
      {
        name: "fv",
        description: "Is the future value, or a cash balance you want to attain after the last payment is made. If omitted, zero is used",
        type: "value|range",
        optional: true
      },
      {
        name: "typeParam",
        description: "Is a logical value: payment at the beginning of the period = 1; payment at the end of the period = 0 or omitted",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "PMT",
    category: "financial",
    id: 57,
    description: "Calculates the payment for a loan based on constant payments and a constant interest rate",
    example: "=PMT(A1, A1, A1)",
    parameters: [
      {
        name: "rate",
        description: "Is the interest rate per period for the loan. For example, use 6%/4 for quarterly payments at 6% APR",
        type: "value|range",
        optional: false
      },
      {
        name: "nper",
        description: "Is the total number of payments for the loan",
        type: "value|range",
        optional: false
      },
      {
        name: "pv",
        description: "Is the present value: the total amount that a series of future payments is worth now",
        type: "value|range",
        optional: false
      },
      {
        name: "fv",
        description: "Is the future value, or a cash balance you want to attain after the last payment is made, 0 (zero) if omitted",
        type: "value|range",
        optional: true
      },
      {
        name: "typeParam",
        description: "Is a logical value: payment at the beginning of the period = 1; payment at the end of the period = 0 or omitted",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "RATE",
    category: "financial",
    id: 58,
    description: "Returns the interest rate per period of a loan or an investment. For example, use 6%/4 for quarterly payments at 6% APR",
    example: "=RATE(A1, A1, A1)",
    parameters: [
      {
        name: "nper",
        description: "Is the total number of payment periods for the loan or investment",
        type: "value|range",
        optional: false
      },
      {
        name: "pmt",
        description: "Is the payment made each period and cannot change over the life of the loan or investment",
        type: "value|range",
        optional: false
      },
      {
        name: "pv",
        description: "Is the present value: the total amount that a series of future payments is worth now",
        type: "value|range",
        optional: false
      },
      {
        name: "fv",
        description: "Is the future value, or a cash balance you want to attain after the last payment is made. If omitted, uses Fv = 0",
        type: "value|range",
        optional: true
      },
      {
        name: "typeParam",
        description: "Is a logical value: payment at the beginning of the period = 1; payment at the end of the period = 0 or omitted",
        type: "value|range",
        optional: true
      },
      {
        name: "guess",
        description: "Is your guess for what the rate will be; if omitted, Guess = 0.1 (10 percent)",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "MIRR",
    category: "financial",
    id: 59,
    description: "Returns the internal rate of return for a series of periodic cash flows, considering both cost of investment and interest on reinvestment of cash",
    example: "=MIRR(A1:A5, A1, A1)",
    parameters: [
      {
        name: "values",
        description: "Is an array or a reference to cells that contain numbers that represent a series of payments (negative) and income (positive) at regular periods",
        type: "value|range",
        optional: false
      },
      {
        name: "financeRate",
        description: "Is the interest rate you pay on the money used in the cash flows",
        type: "value|range",
        optional: false
      },
      {
        name: "reinvestRate",
        description: "Is the interest rate you receive on the cash flows as you reinvest them",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "IRR",
    category: "financial",
    id: 60,
    description: "Returns the internal rate of return for a series of cash flows",
    example: "=IRR(A1:A5, A1)",
    parameters: [
      {
        name: "values",
        description: "Is an array or a reference to cells that contain numbers for which you want to calculate the internal rate of return",
        type: "value|range",
        optional: false
      },
      {
        name: "guess",
        description: "Is a number that you guess is close to the result of IRR; 0.1 (10 percent) if omitted",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "SLN",
    category: "financial",
    id: 108,
    description: "Returns the straight-line depreciation of an asset for one period",
    example: "=SLN(A1, A1, A1)",
    parameters: [
      {
        name: "cost",
        description: "Is the initial cost of the asset",
        type: "value|range",
        optional: false
      },
      {
        name: "salvage",
        description: "Is the salvage value at the end of the life of the asset",
        type: "value|range",
        optional: false
      },
      {
        name: "life",
        description: "Is the number of periods over which the asset is being depreciated (sometimes called the useful life of the asset)",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "SYD",
    category: "financial",
    id: 109,
    description: "Returns the sum-of-years' digits depreciation of an asset for a specified period",
    example: "=SYD(A1, A1, A1, A1)",
    parameters: [
      {
        name: "cost",
        description: "Is the initial cost of the asset",
        type: "value|range",
        optional: false
      },
      {
        name: "salvage",
        description: "Is the salvage value at the end of the life of the asset",
        type: "value|range",
        optional: false
      },
      {
        name: "life",
        description: "Is the number of periods over which the asset is being depreciated (sometimes called the useful life of the asset)",
        type: "value|range",
        optional: false
      },
      {
        name: "per",
        description: "Is the period and must use the same units as Life",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "DDB",
    category: "financial",
    id: 110,
    description: "Returns the depreciation of an asset for a specified period using the double-declining balance method or some other method you specify",
    example: "=DDB(A1, A1, A1, A1)",
    parameters: [
      {
        name: "cost",
        description: "Is the initial cost of the asset",
        type: "value|range",
        optional: false
      },
      {
        name: "salvage",
        description: "Is the salvage value at the end of the life of the asset",
        type: "value|range",
        optional: false
      },
      {
        name: "life",
        description: "Is the number of periods over which the asset is being depreciated (sometimes called the useful life of the asset)",
        type: "value|range",
        optional: false
      },
      {
        name: "period",
        description: "Is the period for which you want to calculate the depreciation. Period must use the same units as Life",
        type: "value|range",
        optional: false
      },
      {
        name: "factor",
        description: "Is the rate at which the balance declines. If Factor is omitted, it is assumed to be 2 (the double-declining balance method)",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "IPMT",
    category: "financial",
    id: 116,
    description: "Returns the interest payment for a given period for an investment, based on periodic, constant payments and a constant interest rate",
    example: "=IPMT(A1, A1, A1, A1)",
    parameters: [
      {
        name: "rate",
        description: "Is the interest rate per period. For example, use 6%/4 for quarterly payments at 6% APR",
        type: "value|range",
        optional: false
      },
      {
        name: "per",
        description: "Is the period for which you want to find the interest and must be in the range 1 to Nper",
        type: "value|range",
        optional: false
      },
      {
        name: "nper",
        description: "Is the total number of payment periods in an investment",
        type: "value|range",
        optional: false
      },
      {
        name: "pv",
        description: "Is the present value, or the lump-sum amount that a series of future payments is worth now",
        type: "value|range",
        optional: false
      },
      {
        name: "fv",
        description: "Is the future value, or a cash balance you want to attain after the last payment is made. If omitted, Fv = 0",
        type: "value|range",
        optional: true
      },
      {
        name: "typeParam",
        description: "Is a logical value representing the timing of payment: at the end of the period = 0 or omitted, at the beginning of the period = 1",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "PPMT",
    category: "financial",
    id: 117,
    description: "Returns the payment on the principal for a given investment based on periodic, constant payments and a constant interest rate",
    example: "=PPMT(A1, A1, A1, A1)",
    parameters: [
      {
        name: "rate",
        description: "Is the interest rate per period. For example, use 6%/4 for quarterly payments at 6% APR",
        type: "value|range",
        optional: false
      },
      {
        name: "per",
        description: "Specifies the period and must be in the range 1 to nper",
        type: "value|range",
        optional: false
      },
      {
        name: "nper",
        description: "Is the total number of payment periods in an investment",
        type: "value|range",
        optional: false
      },
      {
        name: "pv",
        description: "Is the present value: the total amount that a series of future payments is worth now",
        type: "value|range",
        optional: false
      },
      {
        name: "fv",
        description: "Is the future value, or cash balance you want to attain after the last payment is made",
        type: "value|range",
        optional: true
      },
      {
        name: "typeParam",
        description: "Is a logical value: payment at the beginning of the period = 1; payment at the end of the period = 0 or omitted",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "VDB",
    category: "financial",
    id: 136,
    description: "Returns the depreciation of an asset for any period you specify, including partial periods, using the double-declining balance method or some other method you specify",
    example: "=VDB(A1, A1, A1, A1)",
    parameters: [
      {
        name: "cost",
        description: "Is the initial cost of the asset",
        type: "value|range",
        optional: false
      },
      {
        name: "salvage",
        description: "Is the salvage value at the end of the life of the asset",
        type: "value|range",
        optional: false
      },
      {
        name: "life",
        description: "Is the number of periods over which the asset is being depreciated (sometimes called the useful life of the asset)",
        type: "value|range",
        optional: false
      },
      {
        name: "startPeriod",
        description: "Is the starting period for which you want to calculate the depreciation, in the same units as Life",
        type: "value|range",
        optional: false
      },
      {
        name: "endPeriod",
        description: "Is the ending period for which you want to calculate the depreciation, in the same units as Life",
        type: "value|range",
        optional: false
      },
      {
        name: "factor",
        description: "Is the rate at which the balance declines, 2 (double-declining balance) if omitted",
        type: "value|range",
        optional: true
      },
      {
        name: "noSwitch",
        description: "Switch to straight-line depreciation when depreciation is greater than the declining balance = FALSE or omitted; do not switch = TRUE",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "DB",
    category: "financial",
    id: 146,
    description: "Returns the depreciation of an asset for a specified period using the fixed-declining balance method",
    example: "=DB(A1, A1, A1, A1)",
    parameters: [
      {
        name: "cost",
        description: "Is the initial cost of the asset",
        type: "value|range",
        optional: false
      },
      {
        name: "salvage",
        description: "Is the salvage value at the end of the life of the asset",
        type: "value|range",
        optional: false
      },
      {
        name: "life",
        description: "Is the number of periods over which the asset is being depreciated (sometimes called the useful life of the asset)",
        type: "value|range",
        optional: false
      },
      {
        name: "period",
        description: "Is the period for which you want to calculate the depreciation. Period must use the same units as Life",
        type: "value|range",
        optional: false
      },
      {
        name: "month",
        description: "Is the number of months in the first year. If month is omitted, it is assumed to be 12",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "ISPMT",
    category: "financial",
    id: 221,
    description: "Returns the interest paid during a specific period of an investment",
    example: "=ISPMT(A1, A1, A1, A1)",
    parameters: [
      {
        name: "rate",
        description: "Interest rate per period. For example, use 6%/4 for quarterly payments at 6% APR",
        type: "value|range",
        optional: false
      },
      {
        name: "per",
        description: "Period for which you want to find the interest",
        type: "value|range",
        optional: false
      },
      {
        name: "nper",
        description: "Number of payment periods in an investment",
        type: "value|range",
        optional: false
      },
      {
        name: "pv",
        description: "Lump sum amount that a series of future payments is right now",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "XIRR",
    category: "financial",
    id: 282,
    description: "Returns the internal rate of return for a schedule of cash flows",
    example: "=XIRR(A1:A5, DATE(2024, 1, 1), A1)",
    parameters: [
      {
        name: "values",
        description: "Is a series of cash flows that correspond to a schedule of payments in dates",
        type: "value|range",
        optional: false
      },
      {
        name: "dates",
        description: "Is a schedule of payment dates that corresponds to the cash flow payments",
        type: "date",
        optional: false
      },
      {
        name: "guess",
        description: "Is a number that you guess is close to the result of XIRR",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "XNPV",
    category: "financial",
    id: 283,
    description: "Returns the net present value for a schedule of cash flows",
    example: "=XNPV(A1, A1:A5, DATE(2024, 1, 1))",
    parameters: [
      {
        name: "rate",
        description: "Is the discount rate to apply to the cash flows",
        type: "value|range",
        optional: false
      },
      {
        name: "values",
        description: "Is a series of cash flows that correspond to a schedule of payments in dates",
        type: "value|range",
        optional: false
      },
      {
        name: "dates",
        description: "Is a schedule of payment dates that corresponds to the cash flow payments",
        type: "date",
        optional: false
      }
    ]
  },
  {
    name: "PRICEMAT",
    category: "financial",
    id: 284,
    description: "Returns the price per $100 face value of a security that pays interest at maturity",
    example: "=PRICEMAT(A1, A1, TRUE, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "issue",
        description: "Is the security's issue date, expressed as a serial date number",
        type: "boolean",
        optional: false
      },
      {
        name: "rate",
        description: "Is the security's interest rate at date of issue",
        type: "value|range",
        optional: false
      },
      {
        name: "yld",
        description: "Is the security's annual yield",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "YIELDMAT",
    category: "financial",
    id: 285,
    description: "Returns the annual yield of a security that pays interest at maturity",
    example: "=YIELDMAT(A1, A1, TRUE, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "issue",
        description: "Is the security's issue date, expressed as a serial date number",
        type: "boolean",
        optional: false
      },
      {
        name: "rate",
        description: "Is the security's interest rate at date of issue",
        type: "value|range",
        optional: false
      },
      {
        name: "pr",
        description: "Is the security's price per $100 face value",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "INTRATE",
    category: "financial",
    id: 286,
    description: "Returns the interest rate for a fully invested security",
    example: "=INTRATE(A1, A1, A1, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "investment",
        description: "Is the amount invested in the security",
        type: "value|range",
        optional: false
      },
      {
        name: "redemption",
        description: "Is the amount to be received at maturity",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "RECEIVED",
    category: "financial",
    id: 287,
    description: "Returns the amount received at maturity for a fully invested security",
    example: "=RECEIVED(A1, A1, A1, 10)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "investment",
        description: "Is the amount invested in the security",
        type: "value|range",
        optional: false
      },
      {
        name: "discount",
        description: "Is the security's discount rate",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "DISC",
    category: "financial",
    id: 288,
    description: "Returns the discount rate for a security",
    example: "=DISC(A1, A1, A1, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "pr",
        description: "Is the security's price per $100 face value",
        type: "value|range",
        optional: false
      },
      {
        name: "redemption",
        description: "Is the security's redemption value per $100 face value",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "PRICEDISC",
    category: "financial",
    id: 289,
    description: "Returns the price per $100 face value of a discounted security",
    example: "=PRICEDISC(A1, A1, 10, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "discount",
        description: "Is the security's discount rate",
        type: "value|range",
        optional: false
      },
      {
        name: "redemption",
        description: "Is the security's redemption value per $100 face value",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "YIELDDISC",
    category: "financial",
    id: 290,
    description: "Returns the annual yield for a discounted security. For example, a treasury bill",
    example: "=YIELDDISC(A1, A1, A1, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "pr",
        description: "Is the security's price per $100 face value",
        type: "value|range",
        optional: false
      },
      {
        name: "redemption",
        description: "Is the security's redemption value per $100 face value",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "TBILLEQ",
    category: "financial",
    id: 291,
    description: "Returns the bond-equivalent yield for a treasury bill",
    example: "=TBILLEQ(A1, A1, 10)",
    parameters: [
      {
        name: "settlement",
        description: "Is the Treasury bill's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the Treasury bill's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "discount",
        description: "Is the Treasury bill's discount rate",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "TBILLPRICE",
    category: "financial",
    id: 292,
    description: "Returns the price per $100 face value for a treasury bill",
    example: "=TBILLPRICE(A1, A1, 10)",
    parameters: [
      {
        name: "settlement",
        description: "Is the Treasury bill's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the Treasury bill's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "discount",
        description: "Is the Treasury bill's discount rate",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "TBILLYIELD",
    category: "financial",
    id: 293,
    description: "Returns the yield for a treasury bill",
    example: "=TBILLYIELD(A1, A1, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the Treasury bill's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the Treasury bill's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "pr",
        description: "Is the Treasury Bill's price per $100 face value",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "PRICE",
    category: "financial",
    id: 294,
    description: "Returns the price per $100 face value of a security that pays periodic interest",
    example: "=PRICE(A1, A1, A1, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "rate",
        description: "Is the security's annual coupon rate",
        type: "value|range",
        optional: false
      },
      {
        name: "yld",
        description: "Is the security's annual yield",
        type: "value|range",
        optional: false
      },
      {
        name: "redemption",
        description: "Is the security's redemption value per $100 face value",
        type: "value|range",
        optional: false
      },
      {
        name: "frequency",
        description: "Is the number of coupon payments per year",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "YIELD",
    category: "financial",
    id: 295,
    description: "Returns the yield on a security that pays periodic interest",
    example: "=YIELD(A1, A1, A1, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "rate",
        description: "Is the security's annual coupon rate",
        type: "value|range",
        optional: false
      },
      {
        name: "pr",
        description: "Is the security's price per $100 face value",
        type: "value|range",
        optional: false
      },
      {
        name: "redemption",
        description: "Is the security's redemption value per $100 face value",
        type: "value|range",
        optional: false
      },
      {
        name: "frequency",
        description: "Is the number of coupon payments per year",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "DOLLARDE",
    category: "financial",
    id: 296,
    description: "Converts a dollar price, expressed as a fraction, into a dollar price, expressed as a decimal number",
    example: "=DOLLARDE(A1, A1)",
    parameters: [
      {
        name: "fractionalDollar",
        description: "Is a number expressed as a fraction",
        type: "value|range",
        optional: false
      },
      {
        name: "fraction",
        description: "Is the integer to use in the denominator of the fraction",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "DOLLARFR",
    category: "financial",
    id: 297,
    description: "Converts a dollar price, expressed as a decimal number, into a dollar price, expressed as a fraction",
    example: "=DOLLARFR(A1, A1)",
    parameters: [
      {
        name: "decimalDollar",
        description: "Is a decimal number",
        type: "value|range",
        optional: false
      },
      {
        name: "fraction",
        description: "Is the integer to use in the denominator of a fraction",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "NOMINAL",
    category: "financial",
    id: 298,
    description: "Returns the annual nominal interest rate",
    example: "=NOMINAL(A1, A1)",
    parameters: [
      {
        name: "effectRate",
        description: "Is the effective interest rate",
        type: "value|range",
        optional: false
      },
      {
        name: "npery",
        description: "Is the number of compounding periods per year",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "EFFECT",
    category: "financial",
    id: 299,
    description: "Returns the effective annual interest rate",
    example: "=EFFECT(A1, A1)",
    parameters: [
      {
        name: "nominalRate",
        description: "Is the nominal interest rate",
        type: "value|range",
        optional: false
      },
      {
        name: "npery",
        description: "Is the number of compounding periods per year",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CUMPRINC",
    category: "financial",
    id: 300,
    description: "Returns the cumulative principal paid on a loan between two periods",
    example: "=CUMPRINC(A1, A1, A1, A1)",
    parameters: [
      {
        name: "rate",
        description: "Is the interest rate",
        type: "value|range",
        optional: false
      },
      {
        name: "nper",
        description: "Is the total number of payment periods",
        type: "value|range",
        optional: false
      },
      {
        name: "pv",
        description: "Is the present value",
        type: "value|range",
        optional: false
      },
      {
        name: "startPeriod",
        description: "Is the first period in the calculation",
        type: "value|range",
        optional: false
      },
      {
        name: "endPeriod",
        description: "Is the last period in the calculation",
        type: "value|range",
        optional: false
      },
      {
        name: "typeParam",
        description: "Is the timing of the payment",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CUMIPMT",
    category: "financial",
    id: 301,
    description: "Returns the cumulative interest paid between two periods",
    example: "=CUMIPMT(A1, A1, A1, A1)",
    parameters: [
      {
        name: "rate",
        description: "Is the interest rate",
        type: "value|range",
        optional: false
      },
      {
        name: "nper",
        description: "Is the total number of payment periods",
        type: "value|range",
        optional: false
      },
      {
        name: "pv",
        description: "Is the present value",
        type: "value|range",
        optional: false
      },
      {
        name: "startPeriod",
        description: "Is the first period in the calculation",
        type: "value|range",
        optional: false
      },
      {
        name: "endPeriod",
        description: "Is the last period in the calculation",
        type: "value|range",
        optional: false
      },
      {
        name: "typeParam",
        description: "Is the timing of the payment",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "COUPDAYBS",
    category: "financial",
    id: 305,
    description: "Returns the number of days from the beginning of the coupon period to the settlement date",
    example: "=COUPDAYBS(A1, A1, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "frequency",
        description: "Is the number of coupon payments per year",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "COUPDAYS",
    category: "financial",
    id: 306,
    description: "Returns the number of days in the coupon period that contains the settlement date",
    example: "=COUPDAYS(A1, A1, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "frequency",
        description: "Is the number of coupon payments per year",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "COUPDAYSNC",
    category: "financial",
    id: 307,
    description: "Returns the number of days from the settlement date to the next coupon date",
    example: "=COUPDAYSNC(A1, A1, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "frequency",
        description: "Is the number of coupon payments per year",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "COUPNCD",
    category: "financial",
    id: 308,
    description: "Returns the next coupon date after the settlement date",
    example: "=COUPNCD(A1, A1, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "frequency",
        description: "Is the number of coupon payments per year",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "COUPNUM",
    category: "financial",
    id: 309,
    description: "Returns the number of coupons payable between the settlement date and maturity date",
    example: "=COUPNUM(A1, A1, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "frequency",
        description: "Is the number of coupon payments per year",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "COUPPCD",
    category: "financial",
    id: 310,
    description: "Returns the previous coupon date before the settlement date",
    example: "=COUPPCD(A1, A1, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "frequency",
        description: "Is the number of coupon payments per year",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "DURATION",
    category: "financial",
    id: 311,
    description: "Returns the annual duration of a security with periodic interest payments",
    example: "=DURATION(A1, A1, A1, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "coupon",
        description: "Is the security's annual coupon rate",
        type: "value|range",
        optional: false
      },
      {
        name: "yld",
        description: "Is the security's annual yield",
        type: "value|range",
        optional: false
      },
      {
        name: "frequency",
        description: "Is the number of coupon payments per year",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "MDURATION",
    category: "financial",
    id: 312,
    description: "Returns the Macauley modified duration for a security with an assumed par value of $100",
    example: "=MDURATION(A1, A1, A1, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "coupon",
        description: "Is the security's annual coupon rate",
        type: "value|range",
        optional: false
      },
      {
        name: "yld",
        description: "Is the security's annual yield",
        type: "value|range",
        optional: false
      },
      {
        name: "frequency",
        description: "Is the number of coupon payments per year",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "ODDLPRICE",
    category: "financial",
    id: 313,
    description: "Returns the price per $100 face value of a security with an odd last period",
    example: "=ODDLPRICE(A1, A1, A1, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "lastInterest",
        description: "Is the security's last coupon date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "rate",
        description: "Is the security's interest rate",
        type: "value|range",
        optional: false
      },
      {
        name: "yld",
        description: "Is the security's annual yield",
        type: "value|range",
        optional: false
      },
      {
        name: "redemption",
        description: "Is the security's redemption value per $100 face value",
        type: "value|range",
        optional: false
      },
      {
        name: "frequency",
        description: "Is the number of coupon payments per year",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "ODDLYIELD",
    category: "financial",
    id: 314,
    description: "Returns the yield of a security with an odd last period",
    example: "=ODDLYIELD(A1, A1, A1, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "lastInterest",
        description: "Is the security's last coupon date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "rate",
        description: "Is the security's interest rate",
        type: "value|range",
        optional: false
      },
      {
        name: "pr",
        description: "Is the security's price",
        type: "value|range",
        optional: false
      },
      {
        name: "redemption",
        description: "Is the security's redemption value per $100 face value",
        type: "value|range",
        optional: false
      },
      {
        name: "frequency",
        description: "Is the number of coupon payments per year",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "ODDFPRICE",
    category: "financial",
    id: 315,
    description: "Returns the price per $100 face value of a security with an odd first period",
    example: "=ODDFPRICE(A1, A1, TRUE, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "issue",
        description: "Is the security's issue date, expressed as a serial date number",
        type: "boolean",
        optional: false
      },
      {
        name: "firstCoupon",
        description: "Is the security's first coupon date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "rate",
        description: "Is the security's interest rate",
        type: "value|range",
        optional: false
      },
      {
        name: "yld",
        description: "Is the security's annual yield",
        type: "value|range",
        optional: false
      },
      {
        name: "redemption",
        description: "Is the security's redemption value per $100 face value",
        type: "value|range",
        optional: false
      },
      {
        name: "frequency",
        description: "Is the number of coupon payments per year",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "ODDFYIELD",
    category: "financial",
    id: 316,
    description: "Returns the yield of a security with an odd first period",
    example: "=ODDFYIELD(A1, A1, TRUE, A1)",
    parameters: [
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "maturity",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "issue",
        description: "Is the security's issue date, expressed as a serial date number",
        type: "boolean",
        optional: false
      },
      {
        name: "firstCoupon",
        description: "Is the security's first coupon date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "rate",
        description: "Is the security's interest rate",
        type: "value|range",
        optional: false
      },
      {
        name: "pr",
        description: "Is the security's price",
        type: "value|range",
        optional: false
      },
      {
        name: "redemption",
        description: "Is the security's redemption value per $100 face value",
        type: "value|range",
        optional: false
      },
      {
        name: "frequency",
        description: "Is the number of coupon payments per year",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "AMORLINC",
    category: "financial",
    id: 319,
    description: "Returns the prorated linear depreciation of an asset for each accounting period.",
    example: "=AMORLINC(A1, DATE(2024, 1, 1), A1, A1)",
    parameters: [
      {
        name: "cost",
        description: "Is the cost of the asset",
        type: "value|range",
        optional: false
      },
      {
        name: "datePurchased",
        description: "Is the date the asset is purchased",
        type: "date",
        optional: false
      },
      {
        name: "firstPeriod",
        description: "Is the date of the end of the first period",
        type: "value|range",
        optional: false
      },
      {
        name: "salvage",
        description: "Is the salvage value at the end of life of the asset.",
        type: "value|range",
        optional: false
      },
      {
        name: "period",
        description: "Is the period",
        type: "value|range",
        optional: false
      },
      {
        name: "rate",
        description: "Is the rate of depreciation",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Year_basis : 0 for year of 360 days, 1 for actual, 3 for year of 365 days.",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "ACCRINT",
    category: "financial",
    id: 321,
    description: "Returns the accrued interest for a security that pays periodic interest.",
    example: "=ACCRINT(TRUE, A1, A1, A1)",
    parameters: [
      {
        name: "issue",
        description: "Is the security's issue date, expressed as a serial date number",
        type: "boolean",
        optional: false
      },
      {
        name: "firstInterest",
        description: "Is the security's first interest date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "settlement",
        description: "Is the security's settlement date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "rate",
        description: "Is the security's annual coupon rate",
        type: "value|range",
        optional: false
      },
      {
        name: "par",
        description: "Is the security's par value",
        type: "value|range",
        optional: false
      },
      {
        name: "frequency",
        description: "Is the number of coupon payments per year",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      },
      {
        name: "_calcMethod",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "ACCRINTM",
    category: "financial",
    id: 322,
    description: "Returns the accrued interest for a security that pays interest at maturity",
    example: "=ACCRINTM(TRUE, A1, A1, A1)",
    parameters: [
      {
        name: "issue",
        description: "Is the security's issue date, expressed as a serial date number",
        type: "boolean",
        optional: false
      },
      {
        name: "settlement",
        description: "Is the security's maturity date, expressed as a serial date number",
        type: "value|range",
        optional: false
      },
      {
        name: "rate",
        description: "Is the security's annual coupon rate",
        type: "value|range",
        optional: false
      },
      {
        name: "par",
        description: "Is the security's par value",
        type: "value|range",
        optional: false
      },
      {
        name: "basis",
        description: "Is the type of day count basis to use",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "FVSCHEDULE",
    category: "financial",
    id: 328,
    description: "Returns the future value of an initial principal after applying a series of compound interest rates",
    example: "=FVSCHEDULE(A1, A1)",
    parameters: [
      {
        name: "principal",
        description: "Is the present value",
        type: "value|range",
        optional: false
      },
      {
        name: "schedule",
        description: "Is an array of interest rates to apply",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "PDURATION",
    category: "financial",
    id: 417,
    description: "Returns the number of periods required by an investment to reach a specified value",
    example: "=PDURATION(A1, A1, A1)",
    parameters: [
      {
        name: "rate",
        description: "Is the interest rate per period.",
        type: "value|range",
        optional: false
      },
      {
        name: "pv",
        description: "Is the present value of the investment",
        type: "value|range",
        optional: false
      },
      {
        name: "fv",
        description: "Is the desired future value of the investment",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "RRI",
    category: "financial",
    id: 426,
    description: "Returns an equivalent interest rate for the growth of an investment",
    example: "=RRI(A1, A1, A1)",
    parameters: [
      {
        name: "nper",
        description: "Is the number of periods for the investment",
        type: "value|range",
        optional: false
      },
      {
        name: "pv",
        description: "Is the present value of the investment",
        type: "value|range",
        optional: false
      },
      {
        name: "fv",
        description: "Is the future value of the investment",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "STOCKHISTORY",
    category: "financial",
    id: 461,
    description: "Returns an array of historical quote data for a symbol and date range you specify.",
    example: "=STOCKHISTORY(A1, DATE(2024, 1, 1), C1:C5, C1:C5)",
    parameters: [
      {
        name: "stock",
        description: "Symbol of financial instrument to be considered or a Stock data type.",
        type: "value|range",
        optional: false
      },
      {
        name: "startDate",
        description: "First date to return data from.",
        type: "date",
        optional: false
      },
      {
        name: "endDate",
        description: "Last date to return data from.",
        type: "date",
        optional: true
      },
      {
        name: "interval",
        description: "A number indicating the granularity of the data; 0 - Daily, 1 - Weekly, 2 - Monthly",
        type: "value|range",
        optional: true
      },
      {
        name: "headers",
        description: "A logical value to add column header data; 0 - No column header, 1 - Show column header, 2 - Show instrument identifier and column header",
        type: "value|range",
        optional: true
      },
      {
        name: "properties1",
        description: "A number indicating which column of data to return; 0 through 5",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/engine/metadata/information.json
var information_default = [
  {
    name: "ISNA",
    category: "information",
    id: 3,
    description: "Checks whether a value is #N/A, and returns TRUE or FALSE",
    example: "=ISNA(A1:A5)",
    parameters: [
      {
        name: "value",
        description: "Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "ISERROR",
    category: "information",
    id: 4,
    description: "Checks whether a value is an error, and returns TRUE or FALSE",
    example: "=ISERROR(A1:A5)",
    parameters: [
      {
        name: "value",
        description: "Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "NA",
    category: "information",
    id: 11,
    description: "Returns the error value #N/A (value not available)",
    example: "=NA()",
    parameters: []
  },
  {
    name: "TYPE",
    category: "information",
    id: 79,
    description: "Returns an integer representing the data type of a value: number = 1; text = 2; logical value = 4; error value = 16; array = 64; compound data = 128",
    example: "=TYPE(A1:A5)",
    parameters: [
      {
        name: "value",
        description: "Can be any value",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "ISREF",
    category: "information",
    id: 86,
    description: "Checks whether a value is a reference, and returns TRUE or FALSE",
    example: "=ISREF(A1:A5)",
    parameters: [
      {
        name: "value",
        description: "Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "ISERR",
    category: "information",
    id: 100,
    description: "Checks whether a value is an error other than #N/A, and returns TRUE or FALSE",
    example: "=ISERR(A1:A5)",
    parameters: [
      {
        name: "value",
        description: "Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "ISTEXT",
    category: "information",
    id: 101,
    description: "Checks whether a value is text, and returns TRUE or FALSE",
    example: "=ISTEXT(A1:A5)",
    parameters: [
      {
        name: "value",
        description: "Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "ISNUMBER",
    category: "information",
    id: 102,
    description: "Checks whether a value is a number, and returns TRUE or FALSE",
    example: "=ISNUMBER(A1:A5)",
    parameters: [
      {
        name: "value",
        description: "Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "ISBLANK",
    category: "information",
    id: 103,
    description: "Checks whether a reference is to an empty cell, and returns TRUE or FALSE",
    example: "=ISBLANK(A1:A5)",
    parameters: [
      {
        name: "value",
        description: "Is the cell or a name that refers to the cell you want to test",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "N",
    category: "information",
    id: 105,
    description: "Converts non-number value to a number, dates to serial numbers, TRUE to 1, anything else to 0 (zero)",
    example: "=N(A1:A5)",
    parameters: [
      {
        name: "value",
        description: "Is the value you want converted",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "ISNONTEXT",
    category: "information",
    id: 122,
    description: "Checks whether a value is not text (blank cells are not text), and returns TRUE or FALSE",
    example: "=ISNONTEXT(A1:A5)",
    parameters: [
      {
        name: "value",
        description: "Is the value you want tested: a cell; a formula; or a name referring to a cell, formula, or value",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "ISLOGICAL",
    category: "information",
    id: 128,
    description: "Checks whether a value is a logical value (TRUE or FALSE), and returns TRUE or FALSE",
    example: "=ISLOGICAL(A1:A5)",
    parameters: [
      {
        name: "value",
        description: "Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "ERROR.TYPE",
    category: "information",
    id: 148,
    description: "Returns a number matching an error value.",
    example: "=ERROR.TYPE(A1)",
    parameters: [
      {
        name: "errorVal",
        description: "Is the error value for which you want the identifying number, and can be an actual error value or a reference to a cell containing an error value",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "ISEVEN",
    category: "information",
    id: 273,
    description: "Returns TRUE if the number is even",
    example: "=ISEVEN(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the value to test",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "ISODD",
    category: "information",
    id: 274,
    description: "Returns TRUE if the number is odd",
    example: "=ISODD(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the value to test",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "SHEET",
    category: "information",
    id: 433,
    description: "Returns the sheet number of the referenced sheet",
    example: "=SHEET(A1:A5)",
    parameters: [
      {
        name: "value",
        description: "Is the name of a sheet or a reference that you want the sheet number of. If omitted the number of the sheet containing the function is returned",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "SHEETS",
    category: "information",
    id: 434,
    description: "Returns the number of sheets in a reference",
    example: "=SHEETS(A1:A5)",
    parameters: [
      {
        name: "reference",
        description: "Is a reference for which you want to know the number of sheets it contains. If omitted the number of sheets in the workbook containing the function is returned",
        type: "range",
        optional: true
      }
    ]
  },
  {
    name: "ISFORMULA",
    category: "information",
    id: 436,
    description: "Checks whether a reference is to a cell containing a formula, and returns TRUE or FALSE",
    example: "=ISFORMULA(A1:A5)",
    parameters: [
      {
        name: "reference",
        description: "Is a reference to the cell you want to test. Reference can be a cell reference, a formula, or name that refers to a cell",
        type: "range",
        optional: false
      }
    ]
  },
  {
    name: "ISOMITTED",
    category: "information",
    id: 481,
    description: "Checks whether the value is omitted, and returns TRUE or FALSE",
    example: "=ISOMITTED(A1)",
    parameters: [
      {
        name: "argument",
        description: "Is the value you want to test, such as a LAMBDA parameter",
        type: "value|range",
        optional: false
      }
    ]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/engine/metadata/logical.json
var logical_default = [
  {
    name: "IF",
    category: "logical",
    id: 2,
    description: "Checks whether a condition is met, and returns one value if TRUE, and another value if FALSE",
    example: "=IF(TRUE, A1:A5)",
    parameters: [
      {
        name: "logicalTest",
        description: "Is any value or expression that can be evaluated to TRUE or FALSE",
        type: "boolean",
        optional: false
      },
      {
        name: "valueIfTrue",
        description: "Is the value that is returned if Logical_test is TRUE. If omitted, TRUE is returned. You can nest up to seven IF functions",
        type: "value|range",
        optional: true
      },
      {
        name: "valueIfFalse",
        description: "Is the value that is returned if Logical_test is FALSE. If omitted, FALSE is returned",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "TRUE",
    category: "logical",
    id: 35,
    description: "Returns the logical value TRUE",
    example: "=TRUE()",
    parameters: []
  },
  {
    name: "FALSE",
    category: "logical",
    id: 36,
    description: "Returns the logical value FALSE",
    example: "=FALSE()",
    parameters: []
  },
  {
    name: "AND",
    category: "logical",
    id: 37,
    description: "Checks whether all arguments are TRUE, and returns TRUE if all arguments are TRUE",
    example: "=AND(TRUE, C1:C5, TRUE, C1:C5)",
    parameters: [
      {
        name: "logical1",
        description: "Are 1 to 255 conditions you want to test that can be either TRUE or FALSE and can be logical values, arrays, or references",
        type: "boolean",
        optional: false
      },
      {
        name: "logical2",
        description: "TRUE or FALSE.",
        type: "boolean",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "OR",
    category: "logical",
    id: 38,
    description: "Checks whether any of the arguments are TRUE, and returns TRUE or FALSE. Returns FALSE only if all arguments are FALSE",
    example: "=OR(TRUE, C1:C5, TRUE, C1:C5)",
    parameters: [
      {
        name: "logical1",
        description: "Are 1 to 255 conditions that you want to test that can be either TRUE or FALSE",
        type: "boolean",
        optional: false
      },
      {
        name: "logical2",
        description: "TRUE or FALSE.",
        type: "boolean",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "NOT",
    category: "logical",
    id: 39,
    description: "Changes FALSE to TRUE, or TRUE to FALSE",
    example: "=NOT(TRUE)",
    parameters: [
      {
        name: "logical",
        description: "Is a value or expression that can be evaluated to TRUE or FALSE",
        type: "boolean",
        optional: false
      }
    ]
  },
  {
    name: "IFERROR",
    category: "logical",
    id: 332,
    description: "Returns value_if_error if expression is an error and the value of the expression itself otherwise",
    example: "=IFERROR(A1:A5, A1:A5)",
    parameters: [
      {
        name: "value",
        description: "Is any value or expression or reference",
        type: "value|range",
        optional: false
      },
      {
        name: "valueIfError",
        description: "Is any value or expression or reference",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "XOR",
    category: "logical",
    id: 416,
    description: "Returns a logical 'Exclusive Or' of all arguments",
    example: "=XOR(TRUE, C1:C5, TRUE, C1:C5)",
    parameters: [
      {
        name: "logical1",
        description: "Are 1 to 254 conditions you want to test that can be either TRUE or FALSE and can be logical values, arrays, or references",
        type: "boolean",
        optional: false
      },
      {
        name: "logical2",
        description: "TRUE or FALSE.",
        type: "boolean",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "IFNA",
    category: "logical",
    id: 437,
    description: "Returns the value you specify if the expression resolves to #N/A, otherwise returns the result of the expression",
    example: "=IFNA(A1:A5, A1:A5)",
    parameters: [
      {
        name: "value",
        description: "Is any value or expression or reference",
        type: "value|range",
        optional: false
      },
      {
        name: "valueIfNa",
        description: "Is any value or expression or reference",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "IFS",
    category: "logical",
    id: 447,
    description: "Checks whether one or more conditions are met and returns a value corresponding to the first TRUE condition",
    example: "=IFS(TRUE, A1:A5, C1:C5, C1:C5)",
    parameters: [
      {
        name: "logicalTest",
        description: "Is any value or expression that can be evaluated to TRUE or FALSE",
        type: "boolean",
        optional: false
      },
      {
        name: "valueIfTrue",
        description: "Is the value returned if Logical_test is TRUE",
        type: "value|range",
        optional: false
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "SWITCH",
    category: "logical",
    id: 448,
    description: "Evaluates an expression against a list of values and returns the result corresponding to the first matching value. If there is no match, an optional default value is returned",
    example: "=SWITCH(A1, A1:A5, A1, C1:C5)",
    parameters: [
      {
        name: "expression",
        description: "Is an expression to be evaluated",
        type: "value|range",
        optional: false
      },
      {
        name: "value1",
        description: "Is a value to be compared with expression",
        type: "value|range",
        optional: false
      },
      {
        name: "result1",
        description: "Is a result to be returned if the corresponding value matches expression",
        type: "value|range",
        optional: false
      },
      {
        name: "defaultOrValue2",
        description: "Value argument for the calculation.",
        type: "value|range",
        optional: true
      },
      {
        name: "result2",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "LET",
    category: "logical",
    id: 467,
    description: "Assigns calculation results to names. Useful for storing intermediate calculations and values by defining names inside a formula. These names only apply within the scope of the LET function.",
    example: "=LET(A1, A1, A1, C1:C5)",
    parameters: [
      {
        name: "name1",
        description: "The name, or a calculation which can make use of all names within the LET. Names must start with a letter, cannot be the output of a formula, or conflict with range syntax.",
        type: "value|range",
        optional: false
      },
      {
        name: "nameValue1",
        description: "The value associated with the name.",
        type: "value|range",
        optional: false
      },
      {
        name: "calculationOrName2",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      },
      {
        name: "nameValue2",
        description: "Value argument for the calculation.",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "LAMBDA",
    category: "logical",
    id: 468,
    description: "Creates a function value, which can be called within formulas",
    example: "=LAMBDA(A1, C1:C5, C1:C5)",
    parameters: [
      {
        name: "parameterOrCalculation",
        description: "A parameter, or calculation, calculating the result of the function. Parameters cannot be calculated. The last argument to LAMBDA must always be a calculation. The calculation, which may use the parameters, will return a function that can then be called.",
        type: "value|range",
        optional: false
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "MAKEARRAY",
    category: "logical",
    id: 469,
    description: "Returns a calculated array of a specified row and column size, by applying a LAMBDA function.",
    example: "=MAKEARRAY(A1, A1, A1)",
    parameters: [
      {
        name: "rows",
        description: "Is the number of rows in the array. Must be greater than zero.",
        type: "value|range",
        optional: false
      },
      {
        name: "columns",
        description: "Is the number of columns in the array. Must be greater than zero.",
        type: "value|range",
        optional: false
      },
      {
        name: "functionParam",
        description: "Is a LAMBDA that is called to create the array. The LAMBDA takes two parameters, row index and column index.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "MAP",
    category: "logical",
    id: 476,
    description: "Returns an array formed by 'mapping' each value in the array(s) to a new value by applying a lambda to create a new value.",
    example: "=MAP({1,2;3,4}, {1,2;3,4}, C1:C5, C1:C5)",
    parameters: [
      {
        name: "array",
        description: "Is an array to be mapped",
        type: "array",
        optional: false
      },
      {
        name: "lambdaOrArray2",
        description: "Is a LAMBDA which must be the last argument and must have a parameter for each array passed, or another array to be mapped",
        type: "array",
        optional: false
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "REDUCE",
    category: "logical",
    id: 477,
    description: "Reduces an array to an accumulated value by applying a LAMBDA function to each value and returning the total value in the accumulator.",
    example: "=REDUCE(A1, {1,2;3,4}, A1)",
    parameters: [
      {
        name: "initialValue",
        description: "Is the starting value for the accumulator",
        type: "value|range",
        optional: false
      },
      {
        name: "array",
        description: "Is an array to be reduced",
        type: "array",
        optional: false
      },
      {
        name: "functionParam",
        description: "Is a LAMBDA that is called to reduce the array. The LAMBDA takes two parameters, accumulator and value.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "SCAN",
    category: "logical",
    id: 478,
    description: "Scans an array by applying a LAMBDA function to each value and returns an array that has each intermediate value",
    example: "=SCAN(A1, {1,2;3,4}, A1)",
    parameters: [
      {
        name: "initialValue",
        description: "Is the the starting value for the accumulator",
        type: "value|range",
        optional: false
      },
      {
        name: "array",
        description: "Is an array to be scanned",
        type: "array",
        optional: false
      },
      {
        name: "functionParam",
        description: "Is a LAMBDA that is called to scan the array. The LAMBDA takes two parameters, accumulator and value.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "BYROW",
    category: "logical",
    id: 479,
    description: "Applies a LAMBDA function to each row and returns an array of the results.",
    example: "=BYROW({1,2;3,4}, A1)",
    parameters: [
      {
        name: "array",
        description: "Is an array to be separated by row",
        type: "array",
        optional: false
      },
      {
        name: "functionParam",
        description: "Is a LAMBDA that is called to scan the array. The LAMBDA takes two parameters, accumulator and value.",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "BYCOL",
    category: "logical",
    id: 480,
    description: "Applies a LAMBDA function to each column and returns an array of the results.",
    example: "=BYCOL({1,2;3,4}, A1)",
    parameters: [
      {
        name: "array",
        description: "Is an array to be separated by column",
        type: "array",
        optional: false
      },
      {
        name: "functionParam",
        description: "Is a LAMBDA that is called to scan the array. The LAMBDA takes two parameters, accumulator and value.",
        type: "value|range",
        optional: true
      }
    ]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/engine/metadata/lookup-reference.json
var lookup_reference_default = [
  {
    name: "ROW",
    category: "lookup-reference",
    id: 9,
    description: "Returns the row number of a reference",
    example: "=ROW(A1:A5)",
    parameters: [
      {
        name: "reference",
        description: "Is the cell or a single range of cells for which you want the row number; if omitted, returns the cell containing the ROW function",
        type: "range",
        optional: true
      }
    ]
  },
  {
    name: "COLUMN",
    category: "lookup-reference",
    id: 10,
    description: "Returns the column number of a reference",
    example: "=COLUMN(A1:A5)",
    parameters: [
      {
        name: "reference",
        description: "Is the cell or range of contiguous cells for which you want the column number. If omitted, the cell containing the COLUMN function is used",
        type: "range",
        optional: true
      }
    ]
  },
  {
    name: "LOOKUP",
    category: "lookup-reference",
    id: 29,
    description: "Looks up a value either from a one-row or one-column range or from an array. Provided for backward compatibility",
    example: "=LOOKUP(A2:A10, A2:A10, A2:A10, {1,2;3,4})",
    parameters: [
      {
        name: "lookupValue",
        description: "Is a value that LOOKUP searches for in Lookup_vector and can be a number, text, a logical value, or a name or reference to a value",
        type: "value|range",
        optional: false
      },
      {
        name: "lookupVector",
        description: "Is a range that contains only one row or one column of text, numbers, or logical values, placed in ascending order",
        type: "value|range",
        optional: false
      },
      {
        name: "resultVectorLookupValue",
        description: "Is a range that contains only one row or column, the same size as Lookup_vector",
        type: "value|range",
        optional: false
      },
      {
        name: "array",
        description: "Is a value that LOOKUP searches for in Array and can be a number, text, a logical value, or a name or reference to a value is a range of cells that contain text, number, or logical values that you want to compare with Lookup_value",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "INDEX",
    category: "lookup-reference",
    id: 30,
    description: "Returns a value or reference of the cell at the intersection of a particular row and column, in a given range",
    example: "=INDEX({1,2;3,4}, A1, A1:A5, A1)",
    parameters: [
      {
        name: "array",
        description: "Is a range of cells or an array constant.",
        type: "array",
        optional: false
      },
      {
        name: "rowNum",
        description: "Selects the row in Array or Reference from which to return a value. If omitted, Column_num is required",
        type: "value|range",
        optional: false
      },
      {
        name: "columnNumReference",
        description: "Selects the column in Array or Reference from which to return a value. If omitted, Row_num is required",
        type: "range",
        optional: false
      },
      {
        name: "rowNum2",
        description: "Is a reference to one or more cell ranges",
        type: "value|range",
        optional: false
      },
      {
        name: "columnNum",
        description: "Selects the row in Array or Reference from which to return a value. If omitted, Column_num is required",
        type: "value|range",
        optional: true
      },
      {
        name: "areaNum",
        description: "Selects the column in Array or Reference from which to return a value. If omitted, Row_num is required selects a range in Reference from which to return a value. The first area selected or entered is area 1, the second area is area 2, and so on",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "MATCH",
    category: "lookup-reference",
    id: 62,
    description: "Returns the relative position of an item in an array that matches a specified value in a specified order",
    example: "=MATCH(A2:A10, {1,2;3,4}, A1)",
    parameters: [
      {
        name: "lookupValue",
        description: "Is the value you use to find the value you want in the array, a number, text, or logical value, or a reference to one of these",
        type: "value|range",
        optional: false
      },
      {
        name: "lookupArray",
        description: "Is a contiguous range of cells containing possible lookup values, an array of values, or a reference to an array",
        type: "array",
        optional: false
      },
      {
        name: "matchType",
        description: "Is a number 1, 0, or -1 indicating which value to return.",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "AREAS",
    category: "lookup-reference",
    id: 73,
    description: "Returns the number of areas in a reference. An area is a range of contiguous cells or a single cell",
    example: "=AREAS(A1:A5)",
    parameters: [
      {
        name: "reference",
        description: "Is a reference to a cell or range of cells and can refer to multiple areas",
        type: "range",
        optional: false
      }
    ]
  },
  {
    name: "ROWS",
    category: "lookup-reference",
    id: 74,
    description: "Returns the number of rows in a reference or array",
    example: "=ROWS({1,2;3,4})",
    parameters: [
      {
        name: "array",
        description: "Is an array, an array formula, or a reference to a range of cells for which you want the number of rows",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "COLUMNS",
    category: "lookup-reference",
    id: 75,
    description: "Returns the number of columns in an array or reference",
    example: "=COLUMNS({1,2;3,4})",
    parameters: [
      {
        name: "array",
        description: "Is an array or array formula, or a reference to a range of cells for which you want the number of columns",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "OFFSET",
    category: "lookup-reference",
    id: 76,
    description: "Returns a reference to a range that is a given number of rows and columns from a given reference",
    example: "=OFFSET(A1:A5, A1, A1)",
    parameters: [
      {
        name: "reference",
        description: "Is the reference from which you want to base the offset, a reference to a cell or range of adjacent cells",
        type: "range",
        optional: false
      },
      {
        name: "rows",
        description: "Is the number of rows, up or down, that you want the upper-left cell of the result to refer to",
        type: "value|range",
        optional: false
      },
      {
        name: "cols",
        description: "Is the number of columns, to the left or right, that you want the upper-left cell of the result to refer to",
        type: "value|range",
        optional: false
      },
      {
        name: "height",
        description: "Is the height, in number of rows, that you want the result to be, the same height as Reference if omitted",
        type: "value|range",
        optional: true
      },
      {
        name: "width",
        description: "Is the width, in number of columns, that you want the result to be, the same width as Reference if omitted",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "TRANSPOSE",
    category: "lookup-reference",
    id: 78,
    description: "Converts a vertical range of cells to a horizontal range, or vice versa",
    example: "=TRANSPOSE({1,2;3,4})",
    parameters: [
      {
        name: "array",
        description: "Is a range of cells on a worksheet or an array of values that you want to transpose",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "CHOOSE",
    category: "lookup-reference",
    id: 83,
    description: "Chooses a value or action to perform from a list of values, based on an index number",
    example: "=CHOOSE(A1, A1:A5, C1:C5, C1:C5)",
    parameters: [
      {
        name: "indexNum",
        description: "Specifies which value argument is selected. Index_num must be between 1 and 254, or a formula or a reference to a number between 1 and 254",
        type: "value|range",
        optional: false
      },
      {
        name: "value1",
        description: "Are 1 to 254 numbers, cell references, defined names, formulas, functions, or text arguments from which CHOOSE selects",
        type: "value|range",
        optional: false
      },
      {
        name: "value2",
        description: "Value argument for the calculation.",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "HLOOKUP",
    category: "lookup-reference",
    id: 84,
    description: "Looks for a value in the top row of a table or array of values and returns the value in the same column from a row you specify",
    example: "=HLOOKUP(A2:A10, {1,2;3,4}, A1)",
    parameters: [
      {
        name: "lookupValue",
        description: "Is the value to be found in the first row of the table and can be a value, a reference, or a text string",
        type: "value|range",
        optional: false
      },
      {
        name: "tableArray",
        description: "Is a table of text, numbers, or logical values in which data is looked up. Table_array can be a reference to a range or a range name",
        type: "array",
        optional: false
      },
      {
        name: "rowIndexNum",
        description: "Is the row number in table_array from which the matching value should be returned. The first row of values in the table is row 1",
        type: "value|range",
        optional: false
      },
      {
        name: "rangeLookup",
        description: "Is a logical value: to find the closest match in the top row (sorted in ascending order) = TRUE or omitted; find an exact match = FALSE",
        type: "range",
        optional: true
      }
    ]
  },
  {
    name: "VLOOKUP",
    category: "lookup-reference",
    id: 85,
    description: "Looks for a value in the leftmost column of a table, and then returns a value in the same row from a column you specify. By default, the table must be sorted in an ascending order",
    example: "=VLOOKUP(A2:A10, {1,2;3,4}, A1)",
    parameters: [
      {
        name: "lookupValue",
        description: "Is the value to be found in the first column of the table, and can be a value, a reference, or a text string",
        type: "value|range",
        optional: false
      },
      {
        name: "tableArray",
        description: "Is a table of text, numbers, or logical values, in which data is retrieved. Table_array can be a reference to a range or a range name",
        type: "array",
        optional: false
      },
      {
        name: "colIndexNum",
        description: "Is the column number in table_array from which the matching value should be returned. The first column of values in the table is column 1",
        type: "value|range",
        optional: false
      },
      {
        name: "rangeLookup",
        description: "Is a logical value: to find the closest match in the first column (sorted in ascending order) = TRUE or omitted; find an exact match = FALSE",
        type: "range",
        optional: true
      }
    ]
  },
  {
    name: "INDIRECT",
    category: "lookup-reference",
    id: 111,
    description: "Returns the reference specified by a text string",
    example: '=INDIRECT("text", A1)',
    parameters: [
      {
        name: "refText",
        description: "Is a reference to a cell that contains an A1- or R1C1-style reference, a name defined as a reference, or a reference to a cell as a text string",
        type: "string",
        optional: false
      },
      {
        name: "a1",
        description: "Is a logical value that specifies the type of reference in Ref_text: R1C1-style = FALSE; A1-style = TRUE or omitted",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "ADDRESS",
    category: "lookup-reference",
    id: 133,
    description: "Creates a cell reference as text, given specified row and column numbers",
    example: "=ADDRESS(A1, A1, A1)",
    parameters: [
      {
        name: "rowNum",
        description: "Is the row number to use in the cell reference: Row_number = 1 for row 1",
        type: "value|range",
        optional: false
      },
      {
        name: "columnNum",
        description: "Is the column number to use in the cell reference. For example, Column_number = 4 for column D",
        type: "value|range",
        optional: false
      },
      {
        name: "absNum",
        description: "Specifies the reference type: absolute = 1; absolute row/relative column = 2; relative row/absolute column = 3; relative = 4",
        type: "value|range",
        optional: true
      },
      {
        name: "a1",
        description: "Is a logical value that specifies the reference style: A1 style = 1 or TRUE; R1C1 style = 0 or FALSE",
        type: "value|range",
        optional: true
      },
      {
        name: "sheetText",
        description: "Is text specifying the name of the worksheet to be used as the external reference",
        type: "string",
        optional: true
      }
    ]
  },
  {
    name: "GETPIVOTDATA",
    category: "lookup-reference",
    id: 223,
    description: "Extracts data stored in a PivotTable.",
    example: "=GETPIVOTDATA(A1, A1, C1:C5, C1:C5)",
    parameters: [
      {
        name: "dataField",
        description: "Is the name of the data field to extract data from",
        type: "value|range",
        optional: false
      },
      {
        name: "pivotTable",
        description: "Is a reference to a cell or range of cells in the PivotTable that contains the data you want to retrieve",
        type: "value|range",
        optional: false
      },
      {
        name: "field",
        description: "Field to refer to",
        type: "value|range",
        optional: true
      },
      {
        name: "item",
        description: "Field item to refer to",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "HYPERLINK",
    category: "lookup-reference",
    id: 224,
    description: "Creates a shortcut or jump that opens a document stored on your hard drive, a network server, or on the Internet",
    example: "=HYPERLINK(A1, A1)",
    parameters: [
      {
        name: "linkLocation",
        description: "Is the text giving the path and file name to the document to be opened, a hard drive location, UNC address, or URL path",
        type: "value|range",
        optional: false
      },
      {
        name: "friendlyName",
        description: "Is text or a number that is displayed in the cell. If omitted, the cell displays the Link_location text",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "FORMULATEXT",
    category: "lookup-reference",
    id: 435,
    description: "Returns a formula as a string",
    example: "=FORMULATEXT(A1:A5)",
    parameters: [
      {
        name: "reference",
        description: "Is a reference to a formula",
        type: "range",
        optional: false
      }
    ]
  },
  {
    name: "FIELDVALUE",
    category: "lookup-reference",
    id: 449,
    description: "Extracts a value from a field of a given record",
    example: "=FIELDVALUE(A1:A5, A1)",
    parameters: [
      {
        name: "value",
        description: "The record from which you want to extract the field",
        type: "value|range",
        optional: false
      },
      {
        name: "fieldName",
        description: "The names of the field or fields that you want to extract",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "FILTER",
    category: "lookup-reference",
    id: 450,
    description: "Filter a range or array",
    example: "=FILTER({1,2;3,4}, A1, A1)",
    parameters: [
      {
        name: "array",
        description: "The range or array to filter",
        type: "array",
        optional: false
      },
      {
        name: "include",
        description: "An array of booleans where TRUE represents a row or column to retain",
        type: "value|range",
        optional: false
      },
      {
        name: "ifEmpty",
        description: "Returned if no items are retained",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "SORT",
    category: "lookup-reference",
    id: 451,
    description: "Sorts a range or array",
    example: "=SORT({1,2;3,4}, A1)",
    parameters: [
      {
        name: "array",
        description: "The range or array to sort",
        type: "array",
        optional: false
      },
      {
        name: "sortIndex",
        description: "A number indicating the row or column to sort by",
        type: "value|range",
        optional: true
      },
      {
        name: "sortOrder",
        description: "A number indicating the desired sort order; 1 for ascending order (default), -1 for descending order",
        type: "value|range",
        optional: true
      },
      {
        name: "byCol",
        description: "A logical value indicating the desired sort direction: FALSE to sort by row (default), TRUE to sort by column",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "UNIQUE",
    category: "lookup-reference",
    id: 452,
    description: "Returns the unique values from a range or array.",
    example: "=UNIQUE({1,2;3,4}, A1)",
    parameters: [
      {
        name: "array",
        description: "The range or array from which to return unique rows or columns",
        type: "array",
        optional: false
      },
      {
        name: "byCol",
        description: "Is a logical value: compare rows against each other and return the unique rows = FALSE or omitted; compare columns against each other and return the unique columns = TRUE",
        type: "value|range",
        optional: true
      },
      {
        name: "exactlyOnce",
        description: "Is a logical value: return rows or columns that occur exactly once from the array = TRUE; return all distinct rows or columns from the array = FALSE or omitted",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "XMATCH",
    category: "lookup-reference",
    id: 456,
    description: "Returns the relative position of an item in an array. By default, an exact match is required",
    example: "=XMATCH(A2:A10, {1,2;3,4}, A1)",
    parameters: [
      {
        name: "lookupValue",
        description: "Is the value to search for",
        type: "value|range",
        optional: false
      },
      {
        name: "lookupArray",
        description: "Is the array or range to search",
        type: "array",
        optional: false
      },
      {
        name: "matchMode",
        description: "Specify how to match the lookup_value against the values in lookup_array",
        type: "value|range",
        optional: true
      },
      {
        name: "searchMode",
        description: "Specify the search mode to use. By default, a first to last search will be used",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "XLOOKUP",
    category: "lookup-reference",
    id: 457,
    description: "Searches a range or an array for a match and returns the corresponding item from a second range or array. By default, an exact match is used",
    example: "=XLOOKUP(A2:A10, {1,2;3,4}, {1,2;3,4})",
    parameters: [
      {
        name: "lookupValue",
        description: "Is the value to search for",
        type: "value|range",
        optional: false
      },
      {
        name: "lookupArray",
        description: "Is the array or range to search",
        type: "array",
        optional: false
      },
      {
        name: "returnArray",
        description: "Is the array or range to return",
        type: "array",
        optional: false
      },
      {
        name: "ifNotFound",
        description: "Returned if no match is found",
        type: "value|range",
        optional: true
      },
      {
        name: "matchMode",
        description: "Specify how to match lookup_value against the values in lookup_array",
        type: "value|range",
        optional: true
      },
      {
        name: "searchMode",
        description: "Specify the search mode to use. By default, a first to last search will be used",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "SORTBY",
    category: "lookup-reference",
    id: 458,
    description: "Sorts a range or array based on the values in a corresponding range or array",
    example: "=SORTBY({1,2;3,4}, {1,2;3,4}, C1:C5, C1:C5)",
    parameters: [
      {
        name: "array",
        description: "The range or array to sort",
        type: "array",
        optional: false
      },
      {
        name: "byArray",
        description: "The range or array to sort on",
        type: "array",
        optional: false
      },
      {
        name: "sortOrder",
        description: "A number indicating the desired sort order; 1 for ascending order (default), -1 for descending order",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "WRAPROWS",
    category: "lookup-reference",
    id: 462,
    description: "Wraps a row or column vector after a specified number of values.",
    example: "=WRAPROWS(A1, 10, A1)",
    parameters: [
      {
        name: "vector",
        description: "The vector or reference to wrap.",
        type: "value|range",
        optional: false
      },
      {
        name: "wrapCount",
        description: "The maximum number of values per row.",
        type: "value|range",
        optional: false
      },
      {
        name: "padWith",
        description: "The value with which to pad. The default is #N/A.",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "VSTACK",
    category: "lookup-reference",
    id: 463,
    description: "Vertically stacks arrays into one array.",
    example: "=VSTACK({1,2;3,4}, C1:C5, {1,2;3,4}, C1:C5)",
    parameters: [
      {
        name: "array1",
        description: "An array or reference to be stacked.",
        type: "array",
        optional: false
      },
      {
        name: "array2",
        description: "Array or spill range input.",
        type: "array",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "HSTACK",
    category: "lookup-reference",
    id: 464,
    description: "Horizontally stacks arrays into one array.",
    example: "=HSTACK({1,2;3,4}, C1:C5, {1,2;3,4}, C1:C5)",
    parameters: [
      {
        name: "array1",
        description: "An array or reference to be stacked.",
        type: "array",
        optional: false
      },
      {
        name: "array2",
        description: "Array or spill range input.",
        type: "array",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CHOOSEROWS",
    category: "lookup-reference",
    id: 465,
    description: "Returns rows from an array or reference.",
    example: "=CHOOSEROWS({1,2;3,4}, A1, C1:C5, C1:C5)",
    parameters: [
      {
        name: "array",
        description: "The array or reference containing the rows to be returned.",
        type: "array",
        optional: false
      },
      {
        name: "rowNum1",
        description: "The number of the row to be returned.",
        type: "value|range",
        optional: false
      },
      {
        name: "rowNum2",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CHOOSECOLS",
    category: "lookup-reference",
    id: 466,
    description: "Returns columns from an array or reference.",
    example: "=CHOOSECOLS({1,2;3,4}, A1, C1:C5, C1:C5)",
    parameters: [
      {
        name: "array",
        description: "The array or reference containing the columns to be returned.",
        type: "array",
        optional: false
      },
      {
        name: "colNum1",
        description: "The number of the column to be returned.",
        type: "value|range",
        optional: false
      },
      {
        name: "colNum2",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "TOCOL",
    category: "lookup-reference",
    id: 473,
    description: "Returns the array as one column.",
    example: "=TOCOL({1,2;3,4}, A1)",
    parameters: [
      {
        name: "array",
        description: "The array or reference to return as a column.",
        type: "array",
        optional: false
      },
      {
        name: "ignore",
        description: "Whether to ignore certain types of values. By default, no values are ignored.",
        type: "value|range",
        optional: true
      },
      {
        name: "scanByColumn",
        description: "Scan the array by column. By default, the array is scanned by row.",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "TOROW",
    category: "lookup-reference",
    id: 474,
    description: "Returns the array as one row.",
    example: "=TOROW({1,2;3,4}, A1)",
    parameters: [
      {
        name: "array",
        description: "The array or reference to return as a row.",
        type: "array",
        optional: false
      },
      {
        name: "ignore",
        description: "Whether to ignore certain types of values. By default, no values are ignored.",
        type: "value|range",
        optional: true
      },
      {
        name: "scanByColumn",
        description: "Scan the array by column. By default, the array is scanned by row.",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "WRAPCOLS",
    category: "lookup-reference",
    id: 475,
    description: "Wraps a row or column vector after a specified number of values.",
    example: "=WRAPCOLS(A1, 10, A1)",
    parameters: [
      {
        name: "vector",
        description: "The vector or reference to wrap.",
        type: "value|range",
        optional: false
      },
      {
        name: "wrapCount",
        description: "The maximum number of values per column.",
        type: "value|range",
        optional: false
      },
      {
        name: "padWith",
        description: "The value with which to pad. The default is #N/A.",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "EXPAND",
    category: "lookup-reference",
    id: 482,
    description: "Expands an array to the specified dimensions.",
    example: "=EXPAND({1,2;3,4}, A1, A1)",
    parameters: [
      {
        name: "array",
        description: "The array to expand.",
        type: "array",
        optional: false
      },
      {
        name: "rows",
        description: "The number of rows in the expanded array. If missing, rows will not be expanded.",
        type: "value|range",
        optional: false
      },
      {
        name: "columns",
        description: "The number of columns in the expanded array. If missing, columns will not be expanded.",
        type: "value|range",
        optional: true
      },
      {
        name: "padWith",
        description: "The value with which to pad. The default is #N/A.",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "TAKE",
    category: "lookup-reference",
    id: 483,
    description: "Returns rows or columns from array start or end.",
    example: "=TAKE({1,2;3,4}, A1, A1)",
    parameters: [
      {
        name: "array",
        description: "The array from which to take rows or columns.",
        type: "array",
        optional: false
      },
      {
        name: "rows",
        description: "The number of rows to take. A negative value takes from the end of the array.",
        type: "value|range",
        optional: false
      },
      {
        name: "columns",
        description: "The number of columns to take. A negative value takes from the end of the array.",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "DROP",
    category: "lookup-reference",
    id: 484,
    description: "Drops rows or columns from array start or end.",
    example: "=DROP({1,2;3,4}, A1)",
    parameters: [
      {
        name: "array",
        description: "The array from which to drop rows or columns.",
        type: "array",
        optional: false
      },
      {
        name: "rows",
        description: "The number of rows to drop. A negative value drops from the end of the array.",
        type: "value|range",
        optional: true
      },
      {
        name: "columns",
        description: "The number of columns to drop. A negative value drops from the end of the array.",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "PY",
    category: "lookup-reference",
    id: 485,
    description: "Executes Python code that returns a value into the cell (not yet supported in Granola).",
    example: "=PY(A1)",
    parameters: [
      {
        name: "useCtrlEnterToCommitPythonCodeCreatesPythonFormulas",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "IMAGE",
    category: "lookup-reference",
    id: 486,
    description: "Returns an image from a given source",
    example: '=IMAGE(A1, "text")',
    parameters: [
      {
        name: "source",
        description: "The path of the source that points to the image",
        type: "value|range",
        optional: false
      },
      {
        name: "altText",
        description: "The alternative text that describes the image for accessibility",
        type: "string",
        optional: true
      },
      {
        name: "sizing",
        description: "The setting that determines the dimensions in which the image will be rendered in the cell",
        type: "value|range",
        optional: true
      },
      {
        name: "height",
        description: "The custom height of the image in pixels",
        type: "value|range",
        optional: true
      },
      {
        name: "width",
        description: "The custom width of the image in pixels",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "GROUPBY",
    category: "lookup-reference",
    id: 487,
    description: "Aggregate values by row fields",
    example: "=GROUPBY(A1, A1:A5, A1)",
    parameters: [
      {
        name: "rowFields",
        description: "The range or array containing the row fields",
        type: "value|range",
        optional: false
      },
      {
        name: "values",
        description: "The range or array containing the values to aggregate",
        type: "value|range",
        optional: false
      },
      {
        name: "functionParam",
        description: "The function used to do the aggregations",
        type: "value|range",
        optional: false
      },
      {
        name: "fieldHeaders",
        description: "A number between 0 and 3 that specifies whether the field data has headers and whether field headers should be returned in the results",
        type: "value|range",
        optional: true
      },
      {
        name: "totalDepth",
        description: "Show totals for the row fields. 0 for none, 1 for grand totals, 2 for grand total and first level subtotals, etc",
        type: "value|range",
        optional: true
      },
      {
        name: "sortOrder",
        description: "The column index to sort the row fields on. A negative index will sort in reverse order",
        type: "value|range",
        optional: true
      },
      {
        name: "filterArray",
        description: "An array of booleans where TRUE represents a row to retain",
        type: "array",
        optional: true
      },
      {
        name: "fieldRelationship",
        description: "The relationship of fields when multiple columns are supplied to the row_fields argument",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "PIVOTBY",
    category: "lookup-reference",
    id: 488,
    description: "Aggregate values by rows and columns",
    example: "=PIVOTBY(A1, A1, A1:A5, A1)",
    parameters: [
      {
        name: "rowFields",
        description: "The range or array containing the row fields",
        type: "value|range",
        optional: false
      },
      {
        name: "colFields",
        description: "The range or array containing the column fields",
        type: "value|range",
        optional: false
      },
      {
        name: "values",
        description: "The range or array containing the values to aggregate",
        type: "value|range",
        optional: false
      },
      {
        name: "functionParam",
        description: "The function used to do the aggregations",
        type: "value|range",
        optional: false
      },
      {
        name: "fieldHeaders",
        description: "A number between 0 and 3 that specifies whether the field data has headers and whether field headers should be returned in the results",
        type: "value|range",
        optional: true
      },
      {
        name: "rowTotalDepth",
        description: "Show totals for the row fields. 0 for none, 1 for grand totals, 2 for grand total and first level subtotals, etc",
        type: "value|range",
        optional: true
      },
      {
        name: "rowSortOrder",
        description: "The column index to sort the row fields on. A negative index will sort in reverse order",
        type: "value|range",
        optional: true
      },
      {
        name: "colTotalDepth",
        description: "Show totals for the column fields. 0 for none, 1 for grand totals, 2 for grand total and first level subtotals, etc",
        type: "value|range",
        optional: true
      },
      {
        name: "colSortOrder",
        description: "The column index to sort the column fields on. A negative index will sort in reverse order",
        type: "value|range",
        optional: true
      },
      {
        name: "filterArray",
        description: "An array of booleans where TRUE represents a row to retain",
        type: "array",
        optional: true
      },
      {
        name: "relativeTo",
        description: "Defines what PERCENTOF is calculated relative to. This",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "TRIMRANGE",
    category: "lookup-reference",
    id: 494,
    description: "Trims a range to the last used cell in any direction.",
    example: "=TRIMRANGE(A1:A5, A1)",
    parameters: [
      {
        name: "range",
        description: "The range to be trimmed",
        type: "range",
        optional: false
      },
      {
        name: "rowTrimMode",
        description: "Row trim direction",
        type: "value|range",
        optional: true
      },
      {
        name: "colTrimMode",
        description: "Column trim direction",
        type: "value|range",
        optional: true
      }
    ]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/engine/metadata/math-trig.json
var math_trig_default = [
  {
    name: "SUM",
    category: "math-trig",
    id: 5,
    description: "Adds all the numbers in a range of cells",
    example: "=SUM(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numbers to sum. Logical values and text are ignored in cells, included if typed as arguments",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "SIN",
    category: "math-trig",
    id: 16,
    description: "Returns the sine of an angle",
    example: "=SIN(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the angle in radians for which you want the sine. Degrees * PI()/180 = radians",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "COS",
    category: "math-trig",
    id: 17,
    description: "Returns the cosine of an angle",
    example: "=COS(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the angle in radians for which you want the cosine",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "TAN",
    category: "math-trig",
    id: 18,
    description: "Returns the tangent of an angle",
    example: "=TAN(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the angle in radians for which you want the tangent. Degrees * PI()/180 = radians",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "ATAN",
    category: "math-trig",
    id: 19,
    description: "Returns the arctangent of a number in radians, in the range -Pi/2 to Pi/2",
    example: "=ATAN(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the tangent of the angle you want",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "PI",
    category: "math-trig",
    id: 20,
    description: "Returns the value of Pi, 3.14159265358979, accurate to 15 digits",
    example: "=PI()",
    parameters: []
  },
  {
    name: "SQRT",
    category: "math-trig",
    id: 21,
    description: "Returns the square root of a number",
    example: "=SQRT(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the number for which you want the square root",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "EXP",
    category: "math-trig",
    id: 22,
    description: "Returns e raised to the power of a given number",
    example: "=EXP(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the exponent applied to the base e. The constant e equals 2.71828182845904, the base of the natural logarithm",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "LN",
    category: "math-trig",
    id: 23,
    description: "Returns the natural logarithm of a number",
    example: "=LN(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the positive real number for which you want the natural logarithm",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "LOG10",
    category: "math-trig",
    id: 24,
    description: "Returns the base-10 logarithm of a number",
    example: "=LOG10(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the positive real number for which you want the base-10 logarithm",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "ABS",
    category: "math-trig",
    id: 25,
    description: "Returns the absolute value of a number, a number without its sign",
    example: "=ABS(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the real number for which you want the absolute value",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "INT",
    category: "math-trig",
    id: 26,
    description: "Rounds a number down to the nearest integer",
    example: "=INT(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the real number you want to round down to an integer",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "SIGN",
    category: "math-trig",
    id: 27,
    description: "Returns the sign of a number: 1 if the number is positive, zero if the number is zero, or -1 if the number is negative",
    example: "=SIGN(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is any real number",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "ROUND",
    category: "math-trig",
    id: 28,
    description: "Rounds a number to a specified number of digits",
    example: "=ROUND(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the number you want to round",
        type: "number|range",
        optional: false
      },
      {
        name: "numDigits",
        description: "Is the number of digits to which you want to round. Negative rounds to the left of the decimal point; zero to the nearest integer",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "MOD",
    category: "math-trig",
    id: 40,
    description: "Returns the remainder after a number is divided by a divisor",
    example: "=MOD(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the number for which you want to find the remainder after the division is performed",
        type: "number|range",
        optional: false
      },
      {
        name: "divisor",
        description: "Is the number by which you want to divide Number",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "RAND",
    category: "math-trig",
    id: 61,
    description: "Returns a random number greater than or equal to 0 and less than 1, evenly distributed (changes on recalculation)",
    example: "=RAND()",
    parameters: []
  },
  {
    name: "ATAN2",
    category: "math-trig",
    id: 80,
    description: "Returns the arctangent of the specified x- and y- coordinates, in radians between -Pi and Pi, excluding -Pi",
    example: "=ATAN2(A1, A1)",
    parameters: [
      {
        name: "xNum",
        description: "Is the x-coordinate of the point",
        type: "value|range",
        optional: false
      },
      {
        name: "yNum",
        description: "Is the y-coordinate of the point",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "ASIN",
    category: "math-trig",
    id: 81,
    description: "Returns the arcsine of a number in radians, in the range -Pi/2 to Pi/2",
    example: "=ASIN(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the sine of the angle you want and must be from -1 to 1",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "ACOS",
    category: "math-trig",
    id: 82,
    description: "Returns the arccosine of a number, in radians in the range 0 to Pi. The arccosine is the angle whose cosine is Number",
    example: "=ACOS(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the cosine of the angle you want and must be from -1 to 1",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "LOG",
    category: "math-trig",
    id: 87,
    description: "Returns the logarithm of a number to the base you specify",
    example: "=LOG(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the positive real number for which you want the logarithm",
        type: "number|range",
        optional: false
      },
      {
        name: "base",
        description: "Is the base of the logarithm; 10 if omitted",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "MDETERM",
    category: "math-trig",
    id: 113,
    description: "Returns the matrix determinant of an array",
    example: "=MDETERM({1,2;3,4})",
    parameters: [
      {
        name: "array",
        description: "Is a numeric array with an equal number of rows and columns, either a cell range or an array constant",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "MINVERSE",
    category: "math-trig",
    id: 114,
    description: "Returns the inverse matrix for the matrix stored in an array",
    example: "=MINVERSE({1,2;3,4})",
    parameters: [
      {
        name: "array",
        description: "Is a numeric array with an equal number of rows and columns, either a cell range or an array constant",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "MMULT",
    category: "math-trig",
    id: 115,
    description: "Returns the matrix product of two arrays, an array with the same number of rows as array1 and columns as array2",
    example: "=MMULT({1,2;3,4}, {1,2;3,4})",
    parameters: [
      {
        name: "array1",
        description: "Is the first array of numbers to multiply and must have the same number of columns as Array2 has rows",
        type: "array",
        optional: false
      },
      {
        name: "array2",
        description: "Array or spill range input.",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "PRODUCT",
    category: "math-trig",
    id: 119,
    description: "Multiplies all the numbers given as arguments",
    example: "=PRODUCT(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numbers, logical values, or text representations of numbers that you want to multiply",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "FACT",
    category: "math-trig",
    id: 120,
    description: "Returns the factorial of a number, equal to 1*2*3*...* Number",
    example: "=FACT(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the nonnegative number you want the factorial of",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "TRUNC",
    category: "math-trig",
    id: 127,
    description: "Truncates a number to an integer by removing the decimal, or fractional, part of the number",
    example: "=TRUNC(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the number you want to truncate",
        type: "number|range",
        optional: false
      },
      {
        name: "numDigits",
        description: "Is a number specifying the precision of the truncation, 0 (zero) if omitted",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "ROUNDUP",
    category: "math-trig",
    id: 130,
    description: "Rounds a number up, away from zero",
    example: "=ROUNDUP(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is any real number that you want rounded up",
        type: "number|range",
        optional: false
      },
      {
        name: "numDigits",
        description: "Is the number of digits to which you want to round. Negative rounds to the left of the decimal point; zero or omitted, to the nearest integer",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "ROUNDDOWN",
    category: "math-trig",
    id: 131,
    description: "Rounds a number down, toward zero",
    example: "=ROUNDDOWN(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is any real number that you want rounded down",
        type: "number|range",
        optional: false
      },
      {
        name: "numDigits",
        description: "Is the number of digits to which you want to round. Negative rounds to the left of the decimal point; zero or omitted, to the nearest integer",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "SUMPRODUCT",
    category: "math-trig",
    id: 138,
    description: "Returns the sum of the products of corresponding ranges or arrays",
    example: "=SUMPRODUCT({1,2;3,4}, C1:C5, C1:C5)",
    parameters: [
      {
        name: "array1",
        description: "Are 2 to 255 arrays for which you want to multiply and then add components. All arrays must have the same dimensions",
        type: "array",
        optional: false
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "SINH",
    category: "math-trig",
    id: 139,
    description: "Returns the hyperbolic sine of a number",
    example: "=SINH(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is any real number",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "COSH",
    category: "math-trig",
    id: 140,
    description: "Returns the hyperbolic cosine of a number",
    example: "=COSH(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is any real number",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "TANH",
    category: "math-trig",
    id: 141,
    description: "Returns the hyperbolic tangent of a number",
    example: "=TANH(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is any real number",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "ASINH",
    category: "math-trig",
    id: 142,
    description: "Returns the inverse hyperbolic sine of a number",
    example: "=ASINH(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is any real number equal to or greater than 1",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "ACOSH",
    category: "math-trig",
    id: 143,
    description: "Returns the inverse hyperbolic cosine of a number",
    example: "=ACOSH(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is any real number equal to or greater than 1",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "ATANH",
    category: "math-trig",
    id: 144,
    description: "Returns the inverse hyperbolic tangent of a number",
    example: "=ATANH(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is any real number between -1 and 1 excluding -1 and 1",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "COMBIN",
    category: "math-trig",
    id: 156,
    description: "Returns the number of combinations for a given number of items",
    example: "=COMBIN(10, 10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the total number of items",
        type: "number|range",
        optional: false
      },
      {
        name: "numberChosen",
        description: "Is the number of items in each combination",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "EVEN",
    category: "math-trig",
    id: 159,
    description: "Rounds a positive number up and negative number down to the nearest even integer",
    example: "=EVEN(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the value to round",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "ODD",
    category: "math-trig",
    id: 178,
    description: "Rounds a positive number up and negative number down to the nearest odd integer",
    example: "=ODD(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the value to round",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "SUMXMY2",
    category: "math-trig",
    id: 183,
    description: "Sums the squares of the differences in two corresponding ranges or arrays",
    example: "=SUMXMY2({1,2;3,4}, {1,2;3,4})",
    parameters: [
      {
        name: "arrayX",
        description: "Is the first range or array of values and can be a number or name, array, or reference that contains numbers",
        type: "array",
        optional: false
      },
      {
        name: "arrayY",
        description: "Is the second range or array of values and can be a number or name, array, or reference that contains numbers",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "SUMX2MY2",
    category: "math-trig",
    id: 184,
    description: "Sums the differences between the squares of two corresponding ranges or arrays",
    example: "=SUMX2MY2({1,2;3,4}, {1,2;3,4})",
    parameters: [
      {
        name: "arrayX",
        description: "Is the first range or array of numbers and can be a number or name, array, or reference that contains numbers",
        type: "array",
        optional: false
      },
      {
        name: "arrayY",
        description: "Is the second range or array of numbers and can be a number or name, array, or reference that contains numbers",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "SUMX2PY2",
    category: "math-trig",
    id: 185,
    description: "Returns the sum total of the sums of squares of numbers in two corresponding ranges or arrays",
    example: "=SUMX2PY2({1,2;3,4}, {1,2;3,4})",
    parameters: [
      {
        name: "arrayX",
        description: "Is the first range or array of numbers and can be a number or name, array, or reference that contains numbers",
        type: "array",
        optional: false
      },
      {
        name: "arrayY",
        description: "Is the second range or array of numbers and can be a number or name, array, or reference that contains numbers",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "SUMSQ",
    category: "math-trig",
    id: 201,
    description: "Returns the sum of the squares of the arguments. The arguments can be numbers, arrays, names, or references to cells that contain numbers",
    example: "=SUMSQ(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numbers, arrays, names, or references to arrays for which you want the sum of the squares",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "POWER",
    category: "math-trig",
    id: 214,
    description: "Returns the result of a number raised to a power",
    example: "=POWER(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the base number, any real number",
        type: "number|range",
        optional: false
      },
      {
        name: "power",
        description: "Is the exponent, to which the base number is raised",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "RADIANS",
    category: "math-trig",
    id: 215,
    description: "Converts degrees to radians",
    example: "=RADIANS(A1)",
    parameters: [
      {
        name: "angle",
        description: "Is an angle in degrees that you want to convert",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "DEGREES",
    category: "math-trig",
    id: 216,
    description: "Converts radians to degrees",
    example: "=DEGREES(A1)",
    parameters: [
      {
        name: "angle",
        description: "Is the angle in radians that you want to convert",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "SUBTOTAL",
    category: "math-trig",
    id: 217,
    description: "Returns a subtotal in a list or database",
    example: "=SUBTOTAL(A1, A1, C1:C5, C1:C5)",
    parameters: [
      {
        name: "functionNum",
        description: "Is the number 1 to 11 that specifies the summary function for the subtotal.",
        type: "value|range",
        optional: false
      },
      {
        name: "ref1",
        description: "Are 1 to 254 ranges or references for which you want the subtotal",
        type: "value|range",
        optional: false
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "SUMIF",
    category: "math-trig",
    id: 218,
    description: "Adds the cells specified by a given condition or criteria",
    example: '=SUMIF(A1:A5, ">0", A1:A5)',
    parameters: [
      {
        name: "range",
        description: "Is the range of cells you want evaluated",
        type: "range",
        optional: false
      },
      {
        name: "criteria",
        description: "Is the condition or criteria in the form of a number, expression, or text that defines which cells will be added",
        type: "criteria",
        optional: false
      },
      {
        name: "sumRange",
        description: "Are the actual cells to sum. If omitted, the cells in range are used",
        type: "range",
        optional: true
      }
    ]
  },
  {
    name: "ROMAN",
    category: "math-trig",
    id: 222,
    description: "Converts an Arabic numeral to Roman, as text",
    example: "=ROMAN(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the Arabic numeral you want to convert",
        type: "number|range",
        optional: false
      },
      {
        name: "form",
        description: "Is the number specifying the type of Roman numeral you want.",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "SERIESSUM",
    category: "math-trig",
    id: 267,
    description: "Returns the sum of a power series based on the formula",
    example: "=SERIESSUM(A1, A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the input value to the power series",
        type: "value|range",
        optional: false
      },
      {
        name: "n",
        description: "Is the initial power to which you want to raise x",
        type: "value|range",
        optional: false
      },
      {
        name: "m",
        description: "Is the step by which to increase n for each term in the series",
        type: "value|range",
        optional: false
      },
      {
        name: "coefficients",
        description: "Is a set of coefficients by which each successive power of x is multiplied",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "FACTDOUBLE",
    category: "math-trig",
    id: 268,
    description: "Returns the double factorial of a number",
    example: "=FACTDOUBLE(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the value for which to return the double factorial",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "SQRTPI",
    category: "math-trig",
    id: 269,
    description: "Returns the square root of (number * Pi)",
    example: "=SQRTPI(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the number by which p is multiplied",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "QUOTIENT",
    category: "math-trig",
    id: 270,
    description: "Returns the integer portion of a division",
    example: "=QUOTIENT(A1, A1)",
    parameters: [
      {
        name: "numerator",
        description: "Is the dividend",
        type: "value|range",
        optional: false
      },
      {
        name: "denominator",
        description: "Is the divisor",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "MROUND",
    category: "math-trig",
    id: 275,
    description: "Returns a number rounded to the desired multiple",
    example: "=MROUND(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the value to round",
        type: "number|range",
        optional: false
      },
      {
        name: "multiple",
        description: "Is the multiple to which you want to round number",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "RANDBETWEEN",
    category: "math-trig",
    id: 317,
    description: "Returns a random number between the numbers you specify",
    example: "=RANDBETWEEN(A1, A1)",
    parameters: [
      {
        name: "bottom",
        description: "Is the smallest integer RANDBETWEEN will return",
        type: "value|range",
        optional: false
      },
      {
        name: "top",
        description: "Is the largest integer RANDBETWEEN will return",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "GCD",
    category: "math-trig",
    id: 325,
    description: "Returns the greatest common divisor",
    example: "=GCD(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 values",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "MULTINOMIAL",
    category: "math-trig",
    id: 326,
    description: "Returns the multinomial of a set of numbers",
    example: "=MULTINOMIAL(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 values for which you want the multinomial",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "LCM",
    category: "math-trig",
    id: 327,
    description: "Returns the least common multiple",
    example: "=LCM(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 values for which you want the least common multiple",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "SUMIFS",
    category: "math-trig",
    id: 334,
    description: "Adds the cells specified by a given set of conditions or criteria",
    example: '=SUMIFS(A1:A5, A1:A5, ">0", C1:C5)',
    parameters: [
      {
        name: "sumRange",
        description: "Are the actual cells to sum.",
        type: "range",
        optional: false
      },
      {
        name: "criteriaRange",
        description: "Is the range of cells you want evaluated for the particular condition",
        type: "range",
        optional: false
      },
      {
        name: "criteria",
        description: "Is the condition or criteria in the form of a number, expression, or text that defines which cells will be added",
        type: "criteria",
        optional: false
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "AGGREGATE",
    category: "math-trig",
    id: 337,
    description: "",
    example: "=AGGREGATE(A1, A1, A1, C1:C5)",
    parameters: [
      {
        name: "functionNum",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      },
      {
        name: "options",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      },
      {
        name: "ref1",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "ACOT",
    category: "math-trig",
    id: 395,
    description: "Returns the arccotangent of a number, in radians in the range 0 to Pi.",
    example: "=ACOT(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the cotangent of the angle you want",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "ACOTH",
    category: "math-trig",
    id: 396,
    description: "Returns the inverse hyperbolic cotangent of a number",
    example: "=ACOTH(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the hyperbolic cotangent of the angle that you want",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "COT",
    category: "math-trig",
    id: 397,
    description: "Returns the cotangent of an angle",
    example: "=COT(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the angle in radians for which you want the cotangent",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "COTH",
    category: "math-trig",
    id: 398,
    description: "Returns the hyperbolic cotangent of a number",
    example: "=COTH(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the angle in radians for which you want the hyperbolic cotangent",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "CSC",
    category: "math-trig",
    id: 399,
    description: "Returns the cosecant of an angle",
    example: "=CSC(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the angle in radians for which you want the cosecant",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "CSCH",
    category: "math-trig",
    id: 400,
    description: "Returns the hyperbolic cosecant of an angle",
    example: "=CSCH(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the angle in radians for which you want the hyperbolic cosecant",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "SEC",
    category: "math-trig",
    id: 401,
    description: "Returns the secant of an angle",
    example: "=SEC(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the angle in radians for which you want the secant",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "SECH",
    category: "math-trig",
    id: 402,
    description: "Returns the hyperbolic secant of an angle",
    example: "=SECH(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the angle in radians for which you want the hyperbolic secant",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "COMBINA",
    category: "math-trig",
    id: 415,
    description: "Returns the number of combinations with repetitions for a given number of items",
    example: "=COMBINA(10, 10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the total number of items",
        type: "number|range",
        optional: false
      },
      {
        name: "numberChosen",
        description: "Is the number of items in each combination",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "BASE",
    category: "math-trig",
    id: 418,
    description: "Converts a number into a text representation with the given radix (base)",
    example: "=BASE(10, A1, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the number that you want to convert",
        type: "number|range",
        optional: false
      },
      {
        name: "radix",
        description: "Is the base Radix that you want to convert the number into",
        type: "value|range",
        optional: false
      },
      {
        name: "minLength",
        description: "Is the minimum length of the returned string. If omitted leading zeros are not added",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "DECIMAL",
    category: "math-trig",
    id: 419,
    description: "Converts a text representation of a number in a given base into a decimal number",
    example: "=DECIMAL(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the number that you want to convert",
        type: "number|range",
        optional: false
      },
      {
        name: "radix",
        description: "Is the base Radix of the number you are converting",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "MUNIT",
    category: "math-trig",
    id: 429,
    description: "Returns the unit matrix for the specified dimension",
    example: "=MUNIT(A1)",
    parameters: [
      {
        name: "dimension",
        description: "Is an integer specifying the dimension of the unit matrix that you want to return",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "ARABIC",
    category: "math-trig",
    id: 430,
    description: "Converts a Roman numeral to Arabic",
    example: '=ARABIC("text")',
    parameters: [
      {
        name: "text",
        description: "Is the Roman numeral you want to convert",
        type: "string",
        optional: false
      }
    ]
  },
  {
    name: "CEILING.MATH",
    category: "math-trig",
    id: 438,
    description: "Rounds a number up, to the nearest integer or to the nearest multiple of significance",
    example: "=CEILING.MATH(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the value you want to round",
        type: "number|range",
        optional: false
      },
      {
        name: "significance",
        description: "Is the multiple to which you want to round",
        type: "value|range",
        optional: true
      },
      {
        name: "mode",
        description: "When given and nonzero this function will round away from zero",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "FLOOR.MATH",
    category: "math-trig",
    id: 439,
    description: "Rounds a number down, to the nearest integer or to the nearest multiple of significance",
    example: "=FLOOR.MATH(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the value you want to round",
        type: "number|range",
        optional: false
      },
      {
        name: "significance",
        description: "Is the multiple to which you want to round",
        type: "value|range",
        optional: true
      },
      {
        name: "mode",
        description: "When given and nonzero this function will round towards zero",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "RANDARRAY",
    category: "math-trig",
    id: 459,
    description: "Returns an array of random numbers",
    example: "=RANDARRAY(A1)",
    parameters: [
      {
        name: "rows",
        description: "The number of rows in the returned array",
        type: "value|range",
        optional: true
      },
      {
        name: "columns",
        description: "The number of columns in the returned array",
        type: "value|range",
        optional: true
      },
      {
        name: "min",
        description: "The minimum number you would like returned",
        type: "value|range",
        optional: true
      },
      {
        name: "max",
        description: "The maximum number you would like returned",
        type: "value|range",
        optional: true
      },
      {
        name: "integer",
        description: "Return an integer or a decimal value. TRUE for an integer, FALSE for a decimal number",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "SEQUENCE",
    category: "math-trig",
    id: 460,
    description: "Returns a sequence of numbers",
    example: "=SEQUENCE(A1, A1)",
    parameters: [
      {
        name: "rows",
        description: "The number of rows to return",
        type: "value|range",
        optional: false
      },
      {
        name: "columns",
        description: "The number of columns to return",
        type: "value|range",
        optional: true
      },
      {
        name: "start",
        description: "The first number in the sequence",
        type: "value|range",
        optional: true
      },
      {
        name: "step",
        description: "The amount to increment each subsequent value in the sequence",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "PERCENTOF",
    category: "math-trig",
    id: 470,
    description: "Returns the percentage of a subset of a given data set",
    example: "=PERCENTOF(A1, A1)",
    parameters: [
      {
        name: "dataSubset",
        description: "Is the subset",
        type: "value|range",
        optional: false
      },
      {
        name: "dataAll",
        description: "Is the data set",
        type: "value|range",
        optional: false
      }
    ]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/engine/metadata/statistical.json
var statistical_default = [
  {
    name: "COUNT",
    category: "statistical",
    id: 1,
    description: "Counts the number of cells in a range that contain numbers",
    example: "=COUNT(A1:A5, C1:C5, B1:B5, C1:C5)",
    parameters: [
      {
        name: "value1",
        description: "Are 1 to 255 arguments that can contain or refer to a variety of different types of data, but only numbers are counted",
        type: "value|range",
        optional: false
      },
      {
        name: "value2",
        description: "Value argument for the calculation.",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "AVERAGE",
    category: "statistical",
    id: 6,
    description: "Returns the arithmetic mean of the supplied numbers, ignoring text and empty cells.",
    example: "=AVERAGE(A2:A6, 10, 12)",
    parameters: [
      {
        name: "number1",
        description: "First number, reference, or range that contains values to average.",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, reference, or range to include in the mean.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Optional extra arguments (up to 255 total) supplied as numbers or ranges.",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "MIN",
    category: "statistical",
    id: 7,
    description: "Returns the smallest numeric value from the supplied numbers or ranges, ignoring text, logical values, and blanks.",
    example: "=MIN(A2:A10, 0, C2:C4)",
    parameters: [
      {
        name: "number1",
        description: "First number, reference, or range that contains values to compare.",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Optional additional number, reference, or range.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Optional extra numbers or ranges (up to 255 total arguments).",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "MAX",
    category: "statistical",
    id: 8,
    description: "Returns the largest numeric value from the supplied numbers or ranges, ignoring text, logical values, and blanks.",
    example: "=MAX(A2:A10, 0, C2:C4)",
    parameters: [
      {
        name: "number1",
        description: "First number, reference, or range that contains values to compare.",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Optional additional number, reference, or range.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Optional extra numbers or ranges (up to 255 total arguments).",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "LINEST",
    category: "statistical",
    id: 50,
    description: "Returns statistics that describe a linear trend matching known data points, by fitting a straight line using the least squares method",
    example: "=LINEST(A1, A1)",
    parameters: [
      {
        name: "knownYs",
        description: "Is the set of y-values you already know in the relationship y = mx + b",
        type: "value|range",
        optional: false
      },
      {
        name: "knownXs",
        description: "Is an optional set of x-values that you may already know in the relationship y = mx + b",
        type: "value|range",
        optional: true
      },
      {
        name: "constParam",
        description: "Is a logical value: the constant b is calculated normally if Const = TRUE or omitted; b is set equal to 0 if Const = FALSE",
        type: "value|range",
        optional: true
      },
      {
        name: "stats",
        description: "Is a logical value: return additional regression statistics = TRUE; return m-coefficients and the constant b = FALSE or omitted",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "TREND",
    category: "statistical",
    id: 51,
    description: "Returns numbers in a linear trend matching known data points, using the least squares method",
    example: "=TREND(A1, A1)",
    parameters: [
      {
        name: "knownYs",
        description: "Is a range or array of y-values you already know in the relationship y = mx + b",
        type: "value|range",
        optional: false
      },
      {
        name: "knownXs",
        description: "Is an optional range or array of x-values that you know in the relationship y = mx + b, an array the same size as Known_y's",
        type: "value|range",
        optional: true
      },
      {
        name: "newXs",
        description: "Is a range or array of new x-values for which you want TREND to return corresponding y-values",
        type: "value|range",
        optional: true
      },
      {
        name: "constParam",
        description: "Is a logical value: the constant b is calculated normally if Const = TRUE or omitted; b is set equal to 0 if Const = FALSE",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "LOGEST",
    category: "statistical",
    id: 52,
    description: "Returns statistics that describe an exponential curve matching known data points",
    example: "=LOGEST(A1, A1)",
    parameters: [
      {
        name: "knownYs",
        description: "Is the set of y-values you already know in the relationship y = b*m^x",
        type: "value|range",
        optional: false
      },
      {
        name: "knownXs",
        description: "Is an optional set of x-values that you may already know in the relationship y = b*m^x",
        type: "value|range",
        optional: true
      },
      {
        name: "constParam",
        description: "Is a logical value: the constant b is calculated normally if Const = TRUE or omitted; b is set equal to 1 if Const = FALSE",
        type: "value|range",
        optional: true
      },
      {
        name: "stats",
        description: "Is a logical value: return additional regression statistics = TRUE; return m-coefficients and the constant b = FALSE or omitted",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "GROWTH",
    category: "statistical",
    id: 53,
    description: "Returns numbers in an exponential growth trend matching known data points",
    example: "=GROWTH(A1, A1)",
    parameters: [
      {
        name: "knownYs",
        description: "Is the set of y-values you already know in the relationship y = b*m^x, an array or range of positive numbers",
        type: "value|range",
        optional: false
      },
      {
        name: "knownXs",
        description: "Is an optional set of x-values that you may already know in the relationship y = b*m^x, an array or range the same size as Known_y's",
        type: "value|range",
        optional: true
      },
      {
        name: "newXs",
        description: "Are new x-values for which you want GROWTH to return corresponding y-values",
        type: "value|range",
        optional: true
      },
      {
        name: "constParam",
        description: "Is a logical value: the constant b is calculated normally if Const = TRUE; b is set equal to 1 if Const = FALSE or omitted",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "COUNTA",
    category: "statistical",
    id: 118,
    description: "Counts the number of cells in a range that are not empty",
    example: "=COUNTA(A1:A5, C1:C5, B1:B5, C1:C5)",
    parameters: [
      {
        name: "value1",
        description: "Are 1 to 255 arguments representing the values and cells you want to count. Values can be any type of information",
        type: "value|range",
        optional: false
      },
      {
        name: "value2",
        description: "Value argument for the calculation.",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "MEDIAN",
    category: "statistical",
    id: 137,
    description: "Returns the median, or the number in the middle of the set of given numbers",
    example: "=MEDIAN(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numbers or names, arrays, or references that contain numbers for which you want the median",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "FREQUENCY",
    category: "statistical",
    id: 147,
    description: "Calculates how often values occur within a range of values and then returns a vertical array of numbers having one more element than Bins_array",
    example: "=FREQUENCY({1,2;3,4}, {1,2;3,4})",
    parameters: [
      {
        name: "dataArray",
        description: "Is an array of or reference to a set of values for which you want to count frequencies (blanks and text are ignored)",
        type: "array",
        optional: false
      },
      {
        name: "binsArray",
        description: "Is an array of or reference to intervals into which you want to group the values in data_array",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "AVEDEV",
    category: "statistical",
    id: 149,
    description: "Returns the average of the absolute deviations of data points from their mean. Arguments can be numbers or names, arrays, or references that contain numbers",
    example: "=AVEDEV(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 arguments for which you want the average of the absolute deviations",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "GAMMALN",
    category: "statistical",
    id: 151,
    description: "Returns the natural logarithm of the gamma function",
    example: "=GAMMALN(A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value for which you want to calculate GAMMALN, a positive number",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "FISHER",
    category: "statistical",
    id: 163,
    description: "Returns the Fisher transformation",
    example: "=FISHER(A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value for which you want the transformation, a number between -1 and 1, excluding -1 and 1",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "FISHERINV",
    category: "statistical",
    id: 164,
    description: "Returns the inverse of the Fisher transformation: if y = FISHER(x), then FISHERINV(y) = x",
    example: "=FISHERINV(A1)",
    parameters: [
      {
        name: "y",
        description: "Is the value for which you want to perform the inverse of the transformation",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "STANDARDIZE",
    category: "statistical",
    id: 177,
    description: "Returns a normalized value from a distribution characterized by a mean and standard deviation",
    example: "=STANDARDIZE(A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value you want to normalize",
        type: "value|range",
        optional: false
      },
      {
        name: "mean",
        description: "Is the arithmetic mean of the distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "standardDev",
        description: "Is the standard deviation of the distribution, a positive number",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "PERMUT",
    category: "statistical",
    id: 179,
    description: "Returns the number of permutations for a given number of objects that can be selected from the total objects",
    example: "=PERMUT(10, 10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the total number of objects",
        type: "number|range",
        optional: false
      },
      {
        name: "numberChosen",
        description: "Is the number of objects in each permutation",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "CORREL",
    category: "statistical",
    id: 187,
    description: "Returns the correlation coefficient between two data sets",
    example: "=CORREL({1,2;3,4}, {1,2;3,4})",
    parameters: [
      {
        name: "array1",
        description: "Is a cell range of values. The values should be numbers, names, arrays, or references that contain numbers",
        type: "array",
        optional: false
      },
      {
        name: "array2",
        description: "Is a second cell range of values. The values should be numbers, names, arrays, or references that contain numbers",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "INTERCEPT",
    category: "statistical",
    id: 191,
    description: "Calculates the point at which a line will intersect the y-axis by using a best-fit regression line plotted through the known x-values and y-values",
    example: "=INTERCEPT(A1, A1)",
    parameters: [
      {
        name: "knownYs",
        description: "Is the dependent set of observations or data and can be numbers or names, arrays, or references that contain numbers",
        type: "value|range",
        optional: false
      },
      {
        name: "knownXs",
        description: "Is the independent set of observations or data and can be numbers or names, arrays, or references that contain numbers",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "PEARSON",
    category: "statistical",
    id: 192,
    description: "Returns the Pearson product moment correlation coefficient, r",
    example: "=PEARSON({1,2;3,4}, {1,2;3,4})",
    parameters: [
      {
        name: "array1",
        description: "Is a set of independent values",
        type: "array",
        optional: false
      },
      {
        name: "array2",
        description: "Is a set of dependent values",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "RSQ",
    category: "statistical",
    id: 193,
    description: "Returns the square of the Pearson product moment correlation coefficient through the given data points",
    example: "=RSQ(A1, A1)",
    parameters: [
      {
        name: "knownYs",
        description: "Is an array or range of data points and can be numbers or names, arrays, or references that contain numbers",
        type: "value|range",
        optional: false
      },
      {
        name: "knownXs",
        description: "Is an array or range of data points and can be numbers or names, arrays, or references that contain numbers",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "STEYX",
    category: "statistical",
    id: 194,
    description: "Returns the standard error of the predicted y-value for each x in a regression",
    example: "=STEYX(A1, A1)",
    parameters: [
      {
        name: "knownYs",
        description: "Is an array or range of dependent data points and can be numbers or names, arrays, or references that contain numbers",
        type: "value|range",
        optional: false
      },
      {
        name: "knownXs",
        description: "Is an array or range of independent data points and can be numbers or names, arrays, or references that contain numbers",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "SLOPE",
    category: "statistical",
    id: 195,
    description: "Returns the slope of the linear regression line through the given data points",
    example: "=SLOPE(A1, A1)",
    parameters: [
      {
        name: "knownYs",
        description: "Is an array or cell range of numeric dependent data points and can be numbers or names, arrays, or references that contain numbers",
        type: "value|range",
        optional: false
      },
      {
        name: "knownXs",
        description: "Is the set of independent data points and can be numbers or names, arrays, or references that contain numbers",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "PROB",
    category: "statistical",
    id: 197,
    description: "Returns the probability that values in a range are between two limits or equal to a lower limit",
    example: "=PROB(A1:A5, A1:A5, A1)",
    parameters: [
      {
        name: "xRange",
        description: "Is the range of numeric values of x with which there are associated probabilities",
        type: "range",
        optional: false
      },
      {
        name: "probRange",
        description: "Is the set of probabilities associated with values in X_range, values between 0 and 1 and excluding 0",
        type: "range",
        optional: false
      },
      {
        name: "lowerLimit",
        description: "Is the lower bound on the value for which you want a probability",
        type: "value|range",
        optional: false
      },
      {
        name: "upperLimit",
        description: "Is the optional upper bound on the value. If omitted, PROB returns the probability that X_range values are equal to Lower_limit",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "DEVSQ",
    category: "statistical",
    id: 198,
    description: "Returns the sum of squares of deviations of data points from their sample mean",
    example: "=DEVSQ(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 arguments, or an array or array reference, on which you want DEVSQ to calculate",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "GEOMEAN",
    category: "statistical",
    id: 199,
    description: "Returns the geometric mean of an array or range of positive numeric data",
    example: "=GEOMEAN(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numbers or names, arrays, or references that contain numbers for which you want the mean",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "HARMEAN",
    category: "statistical",
    id: 200,
    description: "Returns the harmonic mean of a data set of positive numbers: the reciprocal of the arithmetic mean of reciprocals",
    example: "=HARMEAN(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numbers or names, arrays, or references that contain numbers for which you want the harmonic mean",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "KURT",
    category: "statistical",
    id: 202,
    description: "Returns the kurtosis of a data set",
    example: "=KURT(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numbers or names, arrays, or references that contain numbers for which you want the kurtosis",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "SKEW",
    category: "statistical",
    id: 203,
    description: "Returns the skewness of a distribution: a characterization of the degree of asymmetry of a distribution around its mean",
    example: "=SKEW(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numbers or names, arrays, or references that contain numbers for which you want the skewness",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "LARGE",
    category: "statistical",
    id: 205,
    description: "Returns the k-th largest value in a data set. For example, the fifth largest number",
    example: "=LARGE({1,2;3,4}, A1)",
    parameters: [
      {
        name: "array",
        description: "Is the array or range of data for which you want to determine the k-th largest value",
        type: "array",
        optional: false
      },
      {
        name: "k",
        description: "Is the position (from the largest) in the array or cell range of the value to return",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "SMALL",
    category: "statistical",
    id: 206,
    description: "Returns the k-th smallest value in a data set. For example, the fifth smallest number",
    example: "=SMALL({1,2;3,4}, A1)",
    parameters: [
      {
        name: "array",
        description: "Is an array or range of numerical data for which you want to determine the k-th smallest value",
        type: "array",
        optional: false
      },
      {
        name: "k",
        description: "Is the position (from the smallest) in the array or range of the value to return",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "TRIMMEAN",
    category: "statistical",
    id: 211,
    description: "Returns the mean of the interior portion of a set of data values",
    example: "=TRIMMEAN({1,2;3,4}, A1)",
    parameters: [
      {
        name: "array",
        description: "Is the range or array of values to trim and average",
        type: "array",
        optional: false
      },
      {
        name: "percent",
        description: "Is the fractional number of data points to exclude from the top and bottom of the data set",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "COUNTIF",
    category: "statistical",
    id: 219,
    description: "Counts the number of cells within a range that meet the given condition",
    example: '=COUNTIF(A1:A5, ">0")',
    parameters: [
      {
        name: "range",
        description: "Is the range of cells from which you want to count nonblank cells",
        type: "range",
        optional: false
      },
      {
        name: "criteria",
        description: "Is the condition in the form of a number, expression, or text that defines which cells will be counted",
        type: "criteria",
        optional: false
      }
    ]
  },
  {
    name: "COUNTBLANK",
    category: "statistical",
    id: 220,
    description: "Counts the number of empty cells in a specified range of cells",
    example: "=COUNTBLANK(A1:A5)",
    parameters: [
      {
        name: "range",
        description: "Is the range from which you want to count the empty cells",
        type: "range",
        optional: false
      }
    ]
  },
  {
    name: "AVERAGEA",
    category: "statistical",
    id: 225,
    description: "Returns the arithmetic mean while treating TRUE as 1, FALSE or text as 0, and numbers as-is.",
    example: '=AVERAGEA(A2:A5, TRUE, "5")',
    parameters: [
      {
        name: "value1",
        description: "First value, reference, or range to evaluate (text and logical values are counted).",
        type: "value|range",
        optional: false
      },
      {
        name: "value2",
        description: "Additional value, reference, or range to include in the average.",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Optional extra arguments (up to 255 total).",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "MAXA",
    category: "statistical",
    id: 226,
    description: "Returns the largest value while treating TRUE as 1, FALSE or text as 0, and numbers as-is.",
    example: '=MAXA(A2:A6, TRUE, "5")',
    parameters: [
      {
        name: "value1",
        description: "First value, reference, or range to evaluate (text/logical values are counted).",
        type: "value|range",
        optional: false
      },
      {
        name: "value2",
        description: "Optional additional value, reference, or range.",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Optional extra arguments (up to 255 total).",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "MINA",
    category: "statistical",
    id: 227,
    description: "Returns the smallest value while treating TRUE as 1, FALSE or text as 0, and numbers as-is.",
    example: '=MINA(A2:A6, FALSE, "5")',
    parameters: [
      {
        name: "value1",
        description: "First value, reference, or range to evaluate (text/logical values are counted).",
        type: "value|range",
        optional: false
      },
      {
        name: "value2",
        description: "Optional additional value, reference, or range.",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Optional extra arguments (up to 255 total).",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "STDEVPA",
    category: "statistical",
    id: 228,
    description: "Calculates standard deviation based on an entire population, including logical values and text. Text and the logical value FALSE have the value 0; the logical value TRUE has the value 1",
    example: "=STDEVPA(A1:A5, C1:C5, B1:B5, C1:C5)",
    parameters: [
      {
        name: "value1",
        description: "Are 1 to 255 values corresponding to a population and can be values, names, arrays, or references that contain values",
        type: "value|range",
        optional: false
      },
      {
        name: "value2",
        description: "Value argument for the calculation.",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "VARPA",
    category: "statistical",
    id: 229,
    description: "Calculates variance based on the entire population, including logical values and text. Text and the logical value FALSE have the value 0; the logical value TRUE has the value 1",
    example: "=VARPA(A1:A5, C1:C5, B1:B5, C1:C5)",
    parameters: [
      {
        name: "value1",
        description: "Are 1 to 255 value arguments corresponding to a population",
        type: "value|range",
        optional: false
      },
      {
        name: "value2",
        description: "Value argument for the calculation.",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "STDEVA",
    category: "statistical",
    id: 230,
    description: "Estimates standard deviation based on a sample, including logical values and text. Text and the logical value FALSE have the value 0; the logical value TRUE has the value 1",
    example: "=STDEVA(A1:A5, C1:C5, B1:B5, C1:C5)",
    parameters: [
      {
        name: "value1",
        description: "Are 1 to 255 values corresponding to a sample of a population and can be values or names or references to values",
        type: "value|range",
        optional: false
      },
      {
        name: "value2",
        description: "Value argument for the calculation.",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "VARA",
    category: "statistical",
    id: 231,
    description: "Estimates variance based on a sample, including logical values and text. Text and the logical value FALSE have the value 0; the logical value TRUE has the value 1",
    example: "=VARA(A1:A5, C1:C5, B1:B5, C1:C5)",
    parameters: [
      {
        name: "value1",
        description: "Are 1 to 255 value arguments corresponding to a sample of a population",
        type: "value|range",
        optional: false
      },
      {
        name: "value2",
        description: "Value argument for the calculation.",
        type: "value|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "COUNTIFS",
    category: "statistical",
    id: 333,
    description: "Counts the number of cells specified by a given set of conditions or criteria",
    example: '=COUNTIFS(A1:A5, ">0", C1:C5, C1:C5)',
    parameters: [
      {
        name: "criteriaRange",
        description: "Is the range of cells you want evaluated for the particular condition",
        type: "range",
        optional: false
      },
      {
        name: "criteria",
        description: "Is the condition in the form of a number, expression, or text that defines which cells will be counted",
        type: "criteria",
        optional: false
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "AVERAGEIF",
    category: "statistical",
    id: 335,
    description: "Calculates the mean of cells in a range that satisfy a single condition.",
    example: '=AVERAGEIF(A2:A10, ">100", B2:B10)',
    parameters: [
      {
        name: "range",
        description: "Cells that are tested against the criteria.",
        type: "range",
        optional: false
      },
      {
        name: "criteria",
        description: 'Condition such as ">0" or "apples" that determines which cells qualify.',
        type: "criteria",
        optional: false
      },
      {
        name: "averageRange",
        description: "Optional cells to average when they differ from range; range is used when omitted.",
        type: "range",
        optional: true
      }
    ]
  },
  {
    name: "AVERAGEIFS",
    category: "statistical",
    id: 336,
    description: "Calculates the mean of cells that satisfy multiple range/criteria pairs.",
    example: '=AVERAGEIFS(B2:B10, A2:A10, "=West", C2:C10, ">0")',
    parameters: [
      {
        name: "averageRange",
        description: "Cells whose values are averaged when every criteria pair is satisfied.",
        type: "range",
        optional: false
      },
      {
        name: "criteriaRange1",
        description: "Cells evaluated against the first criteria.",
        type: "range",
        optional: false
      },
      {
        name: "criteria1",
        description: 'First condition, such as "=North" or ">0".',
        type: "criteria",
        optional: false
      },
      {
        name: "rest",
        description: "Optional additional pairs supplied as criteria_range2, criteria2, criteria_range3, criteria3, and so on.",
        type: "range|criteria",
        optional: false
      }
    ]
  },
  {
    name: "BINOM.DIST",
    category: "statistical",
    id: 338,
    description: "Returns the individual term binomial distribution probability",
    example: "=BINOM.DIST(10, A1, A1, A1)",
    parameters: [
      {
        name: "numberS",
        description: "Is the number of successes in trials",
        type: "number|range",
        optional: false
      },
      {
        name: "trials",
        description: "Is the number of independent trials",
        type: "value|range",
        optional: false
      },
      {
        name: "probabilityS",
        description: "Is the probability of success on each trial",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value: for the cumulative distribution function, use TRUE; for the probability mass function, use FALSE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "BINOM.INV",
    category: "statistical",
    id: 339,
    description: "Returns the smallest value for which the cumulative binomial distribution is greater than or equal to a criterion value",
    example: "=BINOM.INV(A1, A1, A1)",
    parameters: [
      {
        name: "trials",
        description: "Is the number of Bernoulli trials",
        type: "value|range",
        optional: false
      },
      {
        name: "probabilityS",
        description: "Is the probability of success on each trial, a number between 0 and 1 inclusive",
        type: "value|range",
        optional: false
      },
      {
        name: "alpha",
        description: "Is the criterion value, a number between 0 and 1 inclusive",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CONFIDENCE.NORM",
    category: "statistical",
    id: 340,
    description: "Returns the confidence interval for a population mean, using a normal distribution",
    example: "=CONFIDENCE.NORM(A1, A1, A1)",
    parameters: [
      {
        name: "alpha",
        description: "Is the significance level used to compute the confidence level, a number greater than 0 and less than 1",
        type: "value|range",
        optional: false
      },
      {
        name: "standardDev",
        description: "Is the population standard deviation for the data range and is assumed to be known. Standard_dev must be greater than 0",
        type: "value|range",
        optional: false
      },
      {
        name: "size",
        description: "Is the sample size",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CONFIDENCE.T",
    category: "statistical",
    id: 341,
    description: "Returns the confidence interval for a population mean, using a Student's T distribution",
    example: "=CONFIDENCE.T(A1, A1, A1)",
    parameters: [
      {
        name: "alpha",
        description: "Is the significance level used to compute the confidence level, a number greater than 0 and less than 1",
        type: "value|range",
        optional: false
      },
      {
        name: "standardDev",
        description: "Is the population standard deviation for the data range and is assumed to be known. Standard_dev must be greater than 0",
        type: "value|range",
        optional: false
      },
      {
        name: "size",
        description: "Is the sample size",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CHISQ.TEST",
    category: "statistical",
    id: 342,
    description: "Returns the test for independence: the value from the chi-squared distribution for the statistic and the appropriate degrees of freedom",
    example: "=CHISQ.TEST(A1:A5, A1:A5)",
    parameters: [
      {
        name: "actualRange",
        description: "Is the range of data that contains observations to test against expected values",
        type: "range",
        optional: false
      },
      {
        name: "expectedRange",
        description: "Is the range of data that contains the ratio of the product of row totals and column totals to the grand total",
        type: "range",
        optional: false
      }
    ]
  },
  {
    name: "F.TEST",
    category: "statistical",
    id: 343,
    description: "Returns the result of an F-test, the two-tailed probability that the variances in Array1 and Array2 are not significantly different",
    example: "=F.TEST({1,2;3,4}, {1,2;3,4})",
    parameters: [
      {
        name: "array1",
        description: "Is the first array or range of data and can be numbers or names, arrays, or references that contain numbers (blanks are ignored)",
        type: "array",
        optional: false
      },
      {
        name: "array2",
        description: "Is the second array or range of data and can be numbers or names, arrays, or references that contain numbers (blanks are ignored)",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "COVARIANCE.P",
    category: "statistical",
    id: 344,
    description: "Returns population covariance, the average of the products of deviations for each data point pair in two data sets",
    example: "=COVARIANCE.P({1,2;3,4}, {1,2;3,4})",
    parameters: [
      {
        name: "array1",
        description: "Is the first cell range of integers and must be numbers, arrays, or references that contain numbers",
        type: "array",
        optional: false
      },
      {
        name: "array2",
        description: "Is the second cell range of integers and must be numbers, arrays, or references that contain numbers",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "COVARIANCE.S",
    category: "statistical",
    id: 345,
    description: "Returns sample covariance, the average of the products of deviations for each data point pair in two data sets",
    example: "=COVARIANCE.S({1,2;3,4}, {1,2;3,4})",
    parameters: [
      {
        name: "array1",
        description: "Is the first cell range of integers and must be numbers, arrays, or references that contain numbers",
        type: "array",
        optional: false
      },
      {
        name: "array2",
        description: "Is the second cell range of integers and must be numbers, arrays, or references that contain numbers",
        type: "array",
        optional: false
      }
    ]
  },
  {
    name: "EXPON.DIST",
    category: "statistical",
    id: 346,
    description: "Returns the exponential distribution",
    example: "=EXPON.DIST(A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value of the function, a nonnegative number",
        type: "value|range",
        optional: false
      },
      {
        name: "lambda",
        description: "Is the parameter value, a positive number",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value for the function to return: the cumulative distribution function = TRUE; the probability density function = FALSE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "GAMMA.DIST",
    category: "statistical",
    id: 347,
    description: "Returns the gamma distribution",
    example: "=GAMMA.DIST(A1, A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value at which you want to evaluate the distribution, a nonnegative number",
        type: "value|range",
        optional: false
      },
      {
        name: "alpha",
        description: "Is a parameter to the distribution, a positive number",
        type: "value|range",
        optional: false
      },
      {
        name: "beta",
        description: "Is a parameter to the distribution, a positive number. If beta = 1, GAMMA.DIST returns the standard gamma distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value: return the cumulative distribution function = TRUE; return the probability mass function = FALSE or omitted",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "GAMMA.INV",
    category: "statistical",
    id: 348,
    description: "Returns the inverse of the gamma cumulative distribution: if p = GAMMA.DIST(x,...), then GAMMA.INV(p,...) = x",
    example: "=GAMMA.INV(A1, A1, A1)",
    parameters: [
      {
        name: "probability",
        description: "Is the probability associated with the gamma distribution, a number between 0 and 1, inclusive",
        type: "value|range",
        optional: false
      },
      {
        name: "alpha",
        description: "Is a parameter to the distribution, a positive number",
        type: "value|range",
        optional: false
      },
      {
        name: "beta",
        description: "Is a parameter to the distribution, a positive number. If beta = 1, GAMMA.INV returns the inverse of the standard gamma distribution",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "MODE.MULT",
    category: "statistical",
    id: 349,
    description: "Returns a vertical array of the most frequently occurring, or repetitive, values in an array or range of data. For a horizontal array, use =TRANSPOSE(MODE.MULT(number1,number2,...))",
    example: "=MODE.MULT(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numbers, or names, arrays, or references that contain numbers for which you want the mode",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "MODE.SNGL",
    category: "statistical",
    id: 350,
    description: "Returns the most frequently occurring, or repetitive, value in an array or range of data",
    example: "=MODE.SNGL(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numbers, or names, arrays, or references that contain numbers for which you want the mode",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "NORM.DIST",
    category: "statistical",
    id: 351,
    description: "Returns the normal distribution for the specified mean and standard deviation",
    example: "=NORM.DIST(A1, A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value for which you want the distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "mean",
        description: "Is the arithmetic mean of the distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "standardDev",
        description: "Is the standard deviation of the distribution, a positive number",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value: for the cumulative distribution function, use TRUE; for the probability density function, use FALSE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "NORM.INV",
    category: "statistical",
    id: 352,
    description: "Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation",
    example: "=NORM.INV(A1, A1, A1)",
    parameters: [
      {
        name: "probability",
        description: "Is a probability corresponding to the normal distribution, a number between 0 and 1 inclusive",
        type: "value|range",
        optional: false
      },
      {
        name: "mean",
        description: "Is the arithmetic mean of the distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "standardDev",
        description: "Is the standard deviation of the distribution, a positive number",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "PERCENTILE.EXC",
    category: "statistical",
    id: 353,
    description: "Returns the k-th percentile of values in a range, where k is in the range 0..1, exclusive",
    example: "=PERCENTILE.EXC({1,2;3,4}, A1)",
    parameters: [
      {
        name: "array",
        description: "Is the array or range of data that defines relative standing",
        type: "array",
        optional: false
      },
      {
        name: "k",
        description: "Is the percentile value that is between 0 through 1, inclusive",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "PERCENTILE.INC",
    category: "statistical",
    id: 354,
    description: "Returns the k-th percentile of values in a range, where k is in the range 0..1, inclusive",
    example: "=PERCENTILE.INC({1,2;3,4}, A1)",
    parameters: [
      {
        name: "array",
        description: "Is the array or range of data that defines relative standing",
        type: "array",
        optional: false
      },
      {
        name: "k",
        description: "Is the percentile value that is between 0 through 1, inclusive",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "PERCENTRANK.EXC",
    category: "statistical",
    id: 355,
    description: "Returns the rank of a value in a data set as a percentage (0..1, exclusive) of the data set",
    example: "=PERCENTRANK.EXC({1,2;3,4}, A1, A1)",
    parameters: [
      {
        name: "array",
        description: "Is the array or range of data with numeric values that defines relative standing",
        type: "array",
        optional: false
      },
      {
        name: "x",
        description: "Is the value for which you want to know the rank",
        type: "value|range",
        optional: false
      },
      {
        name: "significance",
        description: "Is an optional value that identifies the number of significant digits for the returned percentage, three digits if omitted (0.xxx%)",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "PERCENTRANK.INC",
    category: "statistical",
    id: 356,
    description: "Returns the rank of a value in a data set as a percentage (0..1, inclusive) of the data set",
    example: "=PERCENTRANK.INC({1,2;3,4}, A1, A1)",
    parameters: [
      {
        name: "array",
        description: "Is the array or range of data with numeric values that defines relative standing",
        type: "array",
        optional: false
      },
      {
        name: "x",
        description: "Is the value for which you want to know the rank",
        type: "value|range",
        optional: false
      },
      {
        name: "significance",
        description: "Is an optional value that identifies the number of significant digits for the returned percentage, three digits if omitted (0.xxx%)",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "POISSON.DIST",
    category: "statistical",
    id: 357,
    description: "Returns the Poisson distribution",
    example: "=POISSON.DIST(A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the number of events",
        type: "value|range",
        optional: false
      },
      {
        name: "mean",
        description: "Is the expected numeric value, a positive number",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value: for the cumulative Poisson probability, use TRUE; for the Poisson probability mass function, use FALSE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "QUARTILE.EXC",
    category: "statistical",
    id: 358,
    description: "Returns the quartile of a data set, based on percentile values from 0..1, exclusive",
    example: "=QUARTILE.EXC({1,2;3,4}, A1)",
    parameters: [
      {
        name: "array",
        description: "Is the array or cell range of numeric values for which you want the quartile value",
        type: "array",
        optional: false
      },
      {
        name: "quart",
        description: "Is a number: minimum value = 0; 1st quartile = 1; median value = 2; 3rd quartile = 3; maximum value = 4",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "QUARTILE.INC",
    category: "statistical",
    id: 359,
    description: "Returns the quartile of a data set, based on percentile values from 0..1, inclusive",
    example: "=QUARTILE.INC({1,2;3,4}, A1)",
    parameters: [
      {
        name: "array",
        description: "Is the array or cell range of numeric values for which you want the quartile value",
        type: "array",
        optional: false
      },
      {
        name: "quart",
        description: "Is a number: minimum value = 0; 1st quartile = 1; median value = 2; 3rd quartile = 3; maximum value = 4",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "RANK.AVG",
    category: "statistical",
    id: 360,
    description: "Returns the rank of a number in a list of numbers: its size relative to other values in the list; if more than one value has the same rank, the average rank is returned",
    example: "=RANK.AVG(10, A1, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the number for which you want to find the rank",
        type: "number|range",
        optional: false
      },
      {
        name: "ref",
        description: "Is an array of, or a reference to, a list of numbers. Nonnumeric values are ignored",
        type: "value|range",
        optional: false
      },
      {
        name: "order",
        description: "Is a number: rank in the list sorted descending = 0 or omitted; rank in the list sorted ascending = any nonzero value",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "RANK.EQ",
    category: "statistical",
    id: 361,
    description: "Returns the rank of a number in a list of numbers: its size relative to other values in the list; if more than one value has the same rank, the top rank of that set of values is returned",
    example: "=RANK.EQ(10, A1, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the number for which you want to find the rank",
        type: "number|range",
        optional: false
      },
      {
        name: "ref",
        description: "Is an array of, or a reference to, a list of numbers. Nonnumeric values are ignored",
        type: "value|range",
        optional: false
      },
      {
        name: "order",
        description: "Is a number: rank in the list sorted descending = 0 or omitted; rank in the list sorted ascending = any nonzero value",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "STDEV.S",
    category: "statistical",
    id: 362,
    description: "Estimates standard deviation based on a sample (ignores logical values and text in the sample)",
    example: "=STDEV.S(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numbers corresponding to a sample of a population and can be numbers or references that contain numbers",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "STDEV.P",
    category: "statistical",
    id: 363,
    description: "Calculates standard deviation based on the entire population given as arguments (ignores logical values and text)",
    example: "=STDEV.P(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numbers corresponding to a population and can be numbers or references that contain numbers",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "T.DIST",
    category: "statistical",
    id: 364,
    description: "Returns the left-tailed Student's t-distribution",
    example: "=T.DIST(A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the numeric value at which to evaluate the distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom",
        description: "Is an integer indicating the number of degrees of freedom that characterize the distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value: for the cumulative distribution function, use TRUE; for the probability density function, use FALSE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "T.DIST.2T",
    category: "statistical",
    id: 365,
    description: "Returns the two-tailed Student's t-distribution",
    example: "=T.DIST.2T(A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the numeric value at which to evaluate the distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom",
        description: "Is an integer indicating the number of degrees of freedom that characterize the distribution",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "T.DIST.RT",
    category: "statistical",
    id: 366,
    description: "Returns the right-tailed Student's t-distribution",
    example: "=T.DIST.RT(A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the numeric value at which to evaluate the distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom",
        description: "Is an integer indicating the number of degrees of freedom that characterize the distribution",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "T.INV",
    category: "statistical",
    id: 367,
    description: "Returns the left-tailed inverse of the Student's t-distribution",
    example: "=T.INV(A1, A1)",
    parameters: [
      {
        name: "probability",
        description: "Is the probability associated with the two-tailed Student's t-distribution, a number between 0 and 1 inclusive",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom",
        description: "Is a positive integer indicating the number of degrees of freedom to characterize the distribution",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "T.INV.2T",
    category: "statistical",
    id: 368,
    description: "Returns the two-tailed inverse of the Student's t-distribution",
    example: "=T.INV.2T(A1, A1)",
    parameters: [
      {
        name: "probability",
        description: "Is the probability associated with the two-tailed Student's t-distribution, a number between 0 and 1 inclusive",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom",
        description: "Is a positive integer indicating the number of degrees of freedom to characterize the distribution",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "VAR.S",
    category: "statistical",
    id: 369,
    description: "Estimates variance based on a sample (ignores logical values and text in the sample)",
    example: "=VAR.S(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numeric arguments corresponding to a sample of a population",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "VAR.P",
    category: "statistical",
    id: 370,
    description: "Calculates variance based on the entire population (ignores logical values and text in the population)",
    example: "=VAR.P(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 255 numeric arguments corresponding to a population",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "WEIBULL.DIST",
    category: "statistical",
    id: 371,
    description: "Returns the Weibull distribution",
    example: "=WEIBULL.DIST(A1, A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value at which to evaluate the function, a nonnegative number",
        type: "value|range",
        optional: false
      },
      {
        name: "alpha",
        description: "Is a parameter to the distribution, a positive number",
        type: "value|range",
        optional: false
      },
      {
        name: "beta",
        description: "Is a parameter to the distribution, a positive number",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value: for the cumulative distribution function, use TRUE; for the probability mass function, use FALSE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "BETA.DIST",
    category: "statistical",
    id: 374,
    description: "Returns the beta probability distribution function",
    example: "=BETA.DIST(A1, A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value between A and B at which to evaluate the function",
        type: "value|range",
        optional: false
      },
      {
        name: "alpha",
        description: "Is a parameter to the distribution and must be greater than 0",
        type: "value|range",
        optional: false
      },
      {
        name: "beta",
        description: "Is a parameter to the distribution and must be greater than 0",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value: for the cumulative distribution function, use TRUE; for the probability density function, use FALSE",
        type: "value|range",
        optional: false
      },
      {
        name: "a",
        description: "Is an optional lower bound to the interval of x. If omitted, A = 0",
        type: "value|range",
        optional: true
      },
      {
        name: "b",
        description: "Is an optional upper bound to the interval of x. If omitted, B = 1",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "BETA.INV",
    category: "statistical",
    id: 375,
    description: "Returns the inverse of the cumulative beta probability density function (BETA.DIST)",
    example: "=BETA.INV(A1, A1, A1)",
    parameters: [
      {
        name: "probability",
        description: "Is a probability associated with the beta distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "alpha",
        description: "Is a parameter to the distribution and must be greater than 0",
        type: "value|range",
        optional: false
      },
      {
        name: "beta",
        description: "Is a parameter to the distribution and must be greater than 0",
        type: "value|range",
        optional: false
      },
      {
        name: "a",
        description: "Is an optional lower bound to the interval of x. If omitted, A = 0",
        type: "value|range",
        optional: true
      },
      {
        name: "b",
        description: "Is an optional upper bound to the interval of x. If omitted, B = 1",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "CHISQ.DIST",
    category: "statistical",
    id: 376,
    description: "Returns the left-tailed probability of the chi-squared distribution",
    example: "=CHISQ.DIST(A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value at which you want to evaluate the distribution, a nonnegative number",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom",
        description: "Is the number of degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value for the function to return: the cumulative distribution function = TRUE; the probability density function = FALSE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CHISQ.DIST.RT",
    category: "statistical",
    id: 377,
    description: "Returns the right-tailed probability of the chi-squared distribution",
    example: "=CHISQ.DIST.RT(A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value at which you want to evaluate the distribution, a nonnegative number",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom",
        description: "Is the number of degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CHISQ.INV",
    category: "statistical",
    id: 378,
    description: "Returns the inverse of the left-tailed probability of the chi-squared distribution",
    example: "=CHISQ.INV(A1, A1)",
    parameters: [
      {
        name: "probability",
        description: "Is a probability associated with the chi-squared distribution, a value between 0 and 1 inclusive",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom",
        description: "Is the number of degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CHISQ.INV.RT",
    category: "statistical",
    id: 379,
    description: "Returns the inverse of the right-tailed probability of the chi-squared distribution",
    example: "=CHISQ.INV.RT(A1, A1)",
    parameters: [
      {
        name: "probability",
        description: "Is a probability associated with the chi-squared distribution, a value between 0 and 1 inclusive",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom",
        description: "Is the number of degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "F.DIST",
    category: "statistical",
    id: 380,
    description: "Returns the (left-tailed) F probability distribution (degree of diversity) for two data sets",
    example: "=F.DIST(A1, A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value at which to evaluate the function, a nonnegative number",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom1",
        description: "Is the numerator degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom2",
        description: "Is the denominator degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value for the function to return: the cumulative distribution function = TRUE; the probability density function = FALSE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "F.DIST.RT",
    category: "statistical",
    id: 381,
    description: "Returns the (right-tailed) F probability distribution (degree of diversity) for two data sets",
    example: "=F.DIST.RT(A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value at which to evaluate the function, a nonnegative number",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom1",
        description: "Is the numerator degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom2",
        description: "Is the denominator degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "F.INV",
    category: "statistical",
    id: 382,
    description: "Returns the inverse of the (left-tailed) F probability distribution: if p = F.DIST(x,...), then F.INV(p,...) = x",
    example: "=F.INV(A1, A1, A1)",
    parameters: [
      {
        name: "probability",
        description: "Is a probability associated with the F cumulative distribution, a number between 0 and 1 inclusive",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom1",
        description: "Is the numerator degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom2",
        description: "Is the denominator degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "F.INV.RT",
    category: "statistical",
    id: 383,
    description: "Returns the inverse of the (right-tailed) F probability distribution: if p = F.DIST.RT(x,...), then F.INV.RT(p,...) = x",
    example: "=F.INV.RT(A1, A1, A1)",
    parameters: [
      {
        name: "probability",
        description: "Is a probability associated with the F cumulative distribution, a number between 0 and 1 inclusive",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom1",
        description: "Is the numerator degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      },
      {
        name: "degFreedom2",
        description: "Is the denominator degrees of freedom, a number between 1 and 10^10, excluding 10^10",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "HYPGEOM.DIST",
    category: "statistical",
    id: 384,
    description: "Returns the hypergeometric distribution",
    example: "=HYPGEOM.DIST(A1, 10, A1, 10)",
    parameters: [
      {
        name: "sampleS",
        description: "Is the number of successes in the sample",
        type: "value|range",
        optional: false
      },
      {
        name: "numberSample",
        description: "Is the size of the sample",
        type: "number|range",
        optional: false
      },
      {
        name: "populationS",
        description: "Is the number of successes in the population",
        type: "value|range",
        optional: false
      },
      {
        name: "numberPop",
        description: "Is the population size",
        type: "number|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value: for the cumulative distribution function, use TRUE; for the probability density function, use FALSE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "LOGNORM.DIST",
    category: "statistical",
    id: 385,
    description: "Returns the lognormal distribution of x, where ln(x) is normally distributed with parameters Mean and Standard_dev",
    example: "=LOGNORM.DIST(A1, A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value at which to evaluate the function, a positive number",
        type: "value|range",
        optional: false
      },
      {
        name: "mean",
        description: "Is the mean of ln(x)",
        type: "value|range",
        optional: false
      },
      {
        name: "standardDev",
        description: "Is the standard deviation of ln(x), a positive number",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value: for the cumulative distribution function, use TRUE; for the probability density function, use FALSE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "LOGNORM.INV",
    category: "statistical",
    id: 386,
    description: "Returns the inverse of the lognormal cumulative distribution function of x, where ln(x) is normally distributed with parameters Mean and Standard_dev",
    example: "=LOGNORM.INV(A1, A1, A1)",
    parameters: [
      {
        name: "probability",
        description: "Is a probability associated with the lognormal distribution, a number between 0 and 1, inclusive",
        type: "value|range",
        optional: false
      },
      {
        name: "mean",
        description: "Is the mean of ln(x)",
        type: "value|range",
        optional: false
      },
      {
        name: "standardDev",
        description: "Is the standard deviation of ln(x), a positive number",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "NEGBINOM.DIST",
    category: "statistical",
    id: 387,
    description: "Returns the negative binomial distribution, the probability that there will be Number_f failures before the Number_s-th success, with Probability_s probability of a success",
    example: "=NEGBINOM.DIST(10, 10, A1, A1)",
    parameters: [
      {
        name: "numberF",
        description: "Is the number of failures",
        type: "number|range",
        optional: false
      },
      {
        name: "numberS",
        description: "Is the threshold number of successes",
        type: "number|range",
        optional: false
      },
      {
        name: "probabilityS",
        description: "Is the probability of a success; a number between 0 and 1",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value: for the cumulative distribution function, use TRUE; for the probability mass function, use FALSE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "NORM.S.DIST",
    category: "statistical",
    id: 388,
    description: "Returns the standard normal distribution (has a mean of zero and a standard deviation of one)",
    example: "=NORM.S.DIST(A1, A1)",
    parameters: [
      {
        name: "z",
        description: "Is the value for which you want the distribution",
        type: "value|range",
        optional: false
      },
      {
        name: "cumulative",
        description: "Is a logical value for the function to return: the cumulative distribution function = TRUE; the probability density function = FALSE",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "NORM.S.INV",
    category: "statistical",
    id: 389,
    description: "Returns the inverse of the standard normal cumulative distribution (has a mean of zero and a standard deviation of one)",
    example: "=NORM.S.INV(A1)",
    parameters: [
      {
        name: "probability",
        description: "Is a probability corresponding to the normal distribution, a number between 0 and 1 inclusive",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "T.TEST",
    category: "statistical",
    id: 390,
    description: "Returns the probability associated with a Student's t-Test",
    example: "=T.TEST({1,2;3,4}, {1,2;3,4}, A1, A1)",
    parameters: [
      {
        name: "array1",
        description: "Is the first data set",
        type: "array",
        optional: false
      },
      {
        name: "array2",
        description: "Is the second data set",
        type: "array",
        optional: false
      },
      {
        name: "tails",
        description: "Specifies the number of distribution tails to return: one-tailed distribution = 1; two-tailed distribution = 2",
        type: "value|range",
        optional: false
      },
      {
        name: "typeParam",
        description: "Is the kind of t-test: paired = 1, two-sample equal variance (homoscedastic) = 2, two-sample unequal variance = 3",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "Z.TEST",
    category: "statistical",
    id: 391,
    description: "Returns the one-tailed P-value of a z-test",
    example: "=Z.TEST({1,2;3,4}, A1, A1)",
    parameters: [
      {
        name: "array",
        description: "Is the array or range of data against which to test X",
        type: "array",
        optional: false
      },
      {
        name: "x",
        description: "Is the value to test",
        type: "value|range",
        optional: false
      },
      {
        name: "sigma",
        description: "Is the population (known) standard deviation. If omitted, the sample standard deviation is used",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "GAMMALN.PRECISE",
    category: "statistical",
    id: 394,
    description: "Returns the natural logarithm of the gamma function",
    example: "=GAMMALN.PRECISE(A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value for which you want to calculate GAMMALN.PRECISE, a positive number",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "PERMUTATIONA",
    category: "statistical",
    id: 414,
    description: "Returns the number of permutations for a given number of objects (with repetitions) that can be selected from the total objects",
    example: "=PERMUTATIONA(10, 10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the total number of objects",
        type: "number|range",
        optional: false
      },
      {
        name: "numberChosen",
        description: "Is the number of objects in each permutation",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "BINOM.DIST.RANGE",
    category: "statistical",
    id: 421,
    description: "Returns the probability of a trial result using a binomial distribution",
    example: "=BINOM.DIST.RANGE(A1, A1, 10)",
    parameters: [
      {
        name: "trials",
        description: "Is the number of independent trials",
        type: "value|range",
        optional: false
      },
      {
        name: "probabilityS",
        description: "Is the probability of success on each trial",
        type: "value|range",
        optional: false
      },
      {
        name: "numberS",
        description: "Is the number of successes in trials",
        type: "number|range",
        optional: false
      },
      {
        name: "numberS2",
        description: "If provided this function returns the probability that the number of successful trials shall lie between number_s and number_s2",
        type: "number|range",
        optional: true
      }
    ]
  },
  {
    name: "GAMMA",
    category: "statistical",
    id: 422,
    description: "Returns the Gamma function value",
    example: "=GAMMA(A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value for which you want to calculate Gamma",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "SKEW.P",
    category: "statistical",
    id: 423,
    description: "Returns the skewness of a distribution based on a population: a characterization of the degree of asymmetry of a distribution around its mean",
    example: "=SKEW.P(10, C1:C5, 20, C1:C5)",
    parameters: [
      {
        name: "number1",
        description: "Are 1 to 254 numbers or names, arrays, or references that contain numbers for which you want the population skewness",
        type: "number|range",
        optional: false
      },
      {
        name: "number2",
        description: "Additional number, range, or reference to include.",
        type: "number|range",
        optional: true
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "GAUSS",
    category: "statistical",
    id: 424,
    description: "Returns 0.5 less than the standard normal cumulative distribution",
    example: "=GAUSS(A1)",
    parameters: [
      {
        name: "x",
        description: "Is the value for which you want the distribution",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "PHI",
    category: "statistical",
    id: 425,
    description: "Returns the value of the density function for a standard normal distribution",
    example: "=PHI(A1)",
    parameters: [
      {
        name: "x",
        description: "Is the number for which you want the density of the standard normal distribution",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "FORECAST.LINEAR",
    category: "statistical",
    id: 442,
    description: "Calculates, or predicts, a future value along a linear trend by using existing values",
    example: "=FORECAST.LINEAR(A1, A1, A1)",
    parameters: [
      {
        name: "x",
        description: "Is the data point for which you want to predict a value and must be a numeric value",
        type: "value|range",
        optional: false
      },
      {
        name: "knownYs",
        description: "Is the dependent array or range of numeric data",
        type: "value|range",
        optional: false
      },
      {
        name: "knownXs",
        description: "Is the independent array or range of numeric data. The variance of Known_x's must not be zero",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "MAXIFS",
    category: "statistical",
    id: 443,
    description: "Returns the maximum value from maxRange after applying one or more criteria ranges.",
    example: '=MAXIFS(B2:B20, A2:A20, "North", C2:C20, ">1000")',
    parameters: [
      {
        name: "maxRange",
        description: "Cells that contain the values to compare.",
        type: "range",
        optional: false
      },
      {
        name: "criteriaRange1",
        description: "First range to test against the paired criteria.",
        type: "range",
        optional: false
      },
      {
        name: "criteria1",
        description: 'First condition, such as "=East" or ">0".',
        type: "criteria",
        optional: false
      },
      {
        name: "rest",
        description: "Optional additional pairs supplied as criteria_range2, criteria2, criteria_range3, criteria3, and so on.",
        type: "range|criteria",
        optional: false
      }
    ]
  },
  {
    name: "MINIFS",
    category: "statistical",
    id: 444,
    description: "Returns the minimum value from minRange after applying one or more criteria ranges.",
    example: '=MINIFS(B2:B20, A2:A20, "North", C2:C20, ">0")',
    parameters: [
      {
        name: "minRange",
        description: "Cells that contain the values to compare.",
        type: "range",
        optional: false
      },
      {
        name: "criteriaRange1",
        description: "First range to test against the paired criteria.",
        type: "range",
        optional: false
      },
      {
        name: "criteria1",
        description: 'First condition, such as "=East" or ">0".',
        type: "criteria",
        optional: false
      },
      {
        name: "rest",
        description: "Optional additional pairs supplied as criteria_range2, criteria2, criteria_range3, criteria3, and so on.",
        type: "range|criteria",
        optional: false
      }
    ]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/engine/metadata/text.json
var text_default = [
  {
    name: "DOLLAR",
    category: "text",
    id: 14,
    description: "Converts a number to text, using currency format",
    example: "=DOLLAR(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is a number, a reference to a cell containing a number, or a formula that evaluates to a number",
        type: "number|range",
        optional: false
      },
      {
        name: "decimals",
        description: "Is the number of digits to the right of the decimal point. The number is rounded as necessary; if omitted, Decimals = 2",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "FIXED",
    category: "text",
    id: 15,
    description: "Rounds a number to the specified number of decimals and returns the result as text with or without commas",
    example: "=FIXED(10, A1)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the number you want to round and convert to text",
        type: "number|range",
        optional: false
      },
      {
        name: "decimals",
        description: "Is the number of digits to the right of the decimal point. If omitted, Decimals = 2",
        type: "value|range",
        optional: true
      },
      {
        name: "noCommas",
        description: "Is a logical value: do not display commas in the returned text = TRUE; do display commas in the returned text = FALSE or omitted",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "REPT",
    category: "text",
    id: 31,
    description: "Repeats text a given number of times. Use REPT to fill a cell with a number of instances of a text string",
    example: '=REPT("text", TIME(9, 0, 0))',
    parameters: [
      {
        name: "text",
        description: "Is the text you want to repeat",
        type: "string",
        optional: false
      },
      {
        name: "numberTimes",
        description: "Is a positive number specifying the number of times to repeat text",
        type: "time",
        optional: false
      }
    ]
  },
  {
    name: "MID",
    category: "text",
    id: 32,
    description: "Returns the characters from the middle of a text string, given a starting position and length",
    example: '=MID("text", A1, A1)',
    parameters: [
      {
        name: "text",
        description: "Is the text string from which you want to extract the characters",
        type: "string",
        optional: false
      },
      {
        name: "startNum",
        description: "Is the position of the first character you want to extract. The first character in Text is 1",
        type: "value|range",
        optional: false
      },
      {
        name: "numChars",
        description: "Specifies how many characters to return from Text",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "LEN",
    category: "text",
    id: 33,
    description: "Returns the number of characters in a text string",
    example: '=LEN("text")',
    parameters: [
      {
        name: "text",
        description: "Is the text whose length you want to find. Spaces count as characters",
        type: "string",
        optional: false
      }
    ]
  },
  {
    name: "VALUE",
    category: "text",
    id: 34,
    description: "Converts a text string that represents a number to a number",
    example: '=VALUE("text")',
    parameters: [
      {
        name: "text",
        description: "Is the text enclosed in quotation marks or a reference to a cell containing the text you want to convert",
        type: "string",
        optional: false
      }
    ]
  },
  {
    name: "TEXT",
    category: "text",
    id: 49,
    description: "Converts a value to text in a specific number format",
    example: '=TEXT(A1:A5, "#,##0.00")',
    parameters: [
      {
        name: "value",
        description: "Is a number, a formula that evaluates to a numeric value, or a reference to a cell containing a numeric value",
        type: "value|range",
        optional: false
      },
      {
        name: "formatText",
        description: "Is a number format in text form from the Category box on the Number tab in the Format Cells dialog box",
        type: "string",
        optional: false
      }
    ]
  },
  {
    name: "SEARCH",
    category: "text",
    id: 77,
    description: "Returns the number of the character at which a specific character or text string is first found, reading left to right (not case-sensitive)",
    example: '=SEARCH("text", "text", A1)',
    parameters: [
      {
        name: "findText",
        description: "Is the text you want to find. You can use the ? and * wildcard characters; use ~? and ~* to find the ? and * characters",
        type: "string",
        optional: false
      },
      {
        name: "withinText",
        description: "Is the text in which you want to search for Find_text",
        type: "string",
        optional: false
      },
      {
        name: "startNum",
        description: "Is the character number in Within_text, counting from the left, at which you want to start searching. If omitted, 1 is used",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "CHAR",
    category: "text",
    id: 88,
    description: "Returns the character specified by the code number from the character set for your computer",
    example: "=CHAR(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is a number between 1 and 255 specifying which character you want",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "LOWER",
    category: "text",
    id: 89,
    description: "Converts all letters in a text string to lowercase",
    example: '=LOWER("text")',
    parameters: [
      {
        name: "text",
        description: "Is the text you want to convert to lowercase. Characters in Text that are not letters are not changed",
        type: "string",
        optional: false
      }
    ]
  },
  {
    name: "UPPER",
    category: "text",
    id: 90,
    description: "Converts a text string to all uppercase letters",
    example: '=UPPER("text")',
    parameters: [
      {
        name: "text",
        description: "Is the text you want converted to uppercase, a reference or a text string",
        type: "string",
        optional: false
      }
    ]
  },
  {
    name: "PROPER",
    category: "text",
    id: 91,
    description: "Converts a text string to proper case; the first letter in each word to uppercase, and all other letters to lowercase",
    example: '=PROPER("text")',
    parameters: [
      {
        name: "text",
        description: "Is text enclosed in quotation marks, a formula that returns text, or a reference to a cell containing text to partially capitalize",
        type: "string",
        optional: false
      }
    ]
  },
  {
    name: "LEFT",
    category: "text",
    id: 92,
    description: "Returns the specified number of characters from the start of a text string",
    example: '=LEFT("text", A1)',
    parameters: [
      {
        name: "text",
        description: "Is the text string containing the characters you want to extract",
        type: "string",
        optional: false
      },
      {
        name: "numChars",
        description: "Specifies how many characters you want LEFT to extract; 1 if omitted",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "RIGHT",
    category: "text",
    id: 93,
    description: "Returns the specified number of characters from the end of a text string",
    example: '=RIGHT("text", A1)',
    parameters: [
      {
        name: "text",
        description: "Is the text string that contains the characters you want to extract",
        type: "string",
        optional: false
      },
      {
        name: "numChars",
        description: "Specifies how many characters you want to extract, 1 if omitted",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "EXACT",
    category: "text",
    id: 94,
    description: "Checks whether two text strings are exactly the same, and returns TRUE or FALSE. EXACT is case-sensitive",
    example: '=EXACT("text1", "text2")',
    parameters: [
      {
        name: "text1",
        description: "Is the first text string",
        type: "string",
        optional: false
      },
      {
        name: "text2",
        description: "Is the second text string",
        type: "string",
        optional: false
      }
    ]
  },
  {
    name: "TRIM",
    category: "text",
    id: 95,
    description: "Removes all spaces from a text string except for single spaces between words",
    example: '=TRIM("text")',
    parameters: [
      {
        name: "text",
        description: "Is the text from which you want spaces removed",
        type: "string",
        optional: false
      }
    ]
  },
  {
    name: "REPLACE",
    category: "text",
    id: 96,
    description: "Replaces part of a text string with a different text string",
    example: '=REPLACE("text", A1, A1, "text")',
    parameters: [
      {
        name: "oldText",
        description: "Is text in which you want to replace some characters",
        type: "string",
        optional: false
      },
      {
        name: "startNum",
        description: "Is the position of the character in Old_text that you want to replace with New_text",
        type: "value|range",
        optional: false
      },
      {
        name: "numChars",
        description: "Is the number of characters in Old_text that you want to replace",
        type: "value|range",
        optional: false
      },
      {
        name: "newText",
        description: "Is the text that will replace characters in Old_text",
        type: "string",
        optional: false
      }
    ]
  },
  {
    name: "SUBSTITUTE",
    category: "text",
    id: 97,
    description: "Replaces existing text with new text in a text string",
    example: '=SUBSTITUTE("text", "text", "text")',
    parameters: [
      {
        name: "text",
        description: "Is the text or the reference to a cell containing text in which you want to substitute characters",
        type: "string",
        optional: false
      },
      {
        name: "oldText",
        description: "Is the existing text you want to replace. If the case of Old_text does not match the case of text, SUBSTITUTE will not replace the text",
        type: "string",
        optional: false
      },
      {
        name: "newText",
        description: "Is the text you want to replace Old_text with",
        type: "string",
        optional: false
      },
      {
        name: "instanceNum",
        description: "Specifies which occurrence of Old_text you want to replace. If omitted, every instance of Old_text is replaced",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "CODE",
    category: "text",
    id: 98,
    description: "Returns a numeric code for the first character in a text string, in the character set used by your computer",
    example: '=CODE("text")',
    parameters: [
      {
        name: "text",
        description: "Is the text for which you want the code of the first character",
        type: "string",
        optional: false
      }
    ]
  },
  {
    name: "FIND",
    category: "text",
    id: 99,
    description: "Returns the starting position of one text string within another text string. FIND is case-sensitive",
    example: '=FIND("text", "text", A1)',
    parameters: [
      {
        name: "findText",
        description: "Is the text you want to find. Use double quotes (empty text) to match the first character in Within_text; wildcard characters not allowed",
        type: "string",
        optional: false
      },
      {
        name: "withinText",
        description: "Is the text containing the text you want to find",
        type: "string",
        optional: false
      },
      {
        name: "startNum",
        description: "Specifies the character at which to start the search. The first character in Within_text is character number 1. If omitted, Start_num = 1",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "T",
    category: "text",
    id: 104,
    description: "Checks whether a value is text, and returns the text if it is, or returns double quotes (empty text) if it is not",
    example: "=T(A1:A5)",
    parameters: [
      {
        name: "value",
        description: "Is the value to test",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CLEAN",
    category: "text",
    id: 112,
    description: "Removes all nonprintable characters from text",
    example: '=CLEAN("text")',
    parameters: [
      {
        name: "text",
        description: "Is any worksheet information from which you want to remove nonprintable characters",
        type: "string",
        optional: false
      }
    ]
  },
  {
    name: "BAHTTEXT",
    category: "text",
    id: 232,
    description: "Converts a number to text (baht)",
    example: "=BAHTTEXT(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is a number that you want to convert",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "UNICHAR",
    category: "text",
    id: 427,
    description: "Returns the Unicode character referenced by the given numeric value",
    example: "=UNICHAR(10)",
    parameters: [
      {
        name: "numberParam",
        description: "Is the Unicode number representing a character",
        type: "number|range",
        optional: false
      }
    ]
  },
  {
    name: "UNICODE",
    category: "text",
    id: 428,
    description: "Returns the number (code point) corresponding to the first character of the text",
    example: '=UNICODE("text")',
    parameters: [
      {
        name: "text",
        description: "Is the character that you want the Unicode value of",
        type: "string",
        optional: false
      }
    ]
  },
  {
    name: "NUMBERVALUE",
    category: "text",
    id: 432,
    description: "Converts text to number in a locale-independent manner",
    example: '=NUMBERVALUE("text", A1)',
    parameters: [
      {
        name: "text",
        description: "Is the string representing the number you want to convert",
        type: "string",
        optional: false
      },
      {
        name: "decimalSeparator",
        description: "Is the character used as the decimal separator in the string",
        type: "value|range",
        optional: true
      },
      {
        name: "groupSeparator",
        description: "Is the character used as the group separator in the string",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "TEXTJOIN",
    category: "text",
    id: 445,
    description: "Concatenates a list or range of text strings using a delimiter",
    example: '=TEXTJOIN(",", A1, "text1", C1:C5)',
    parameters: [
      {
        name: "delimiter",
        description: "Character or string to insert between each text item",
        type: "string",
        optional: false
      },
      {
        name: "ignoreEmpty",
        description: "If TRUE(default), ignores empty cells",
        type: "value|range",
        optional: false
      },
      {
        name: "text1",
        description: "Are 1 to 252 text strings or ranges to be joined",
        type: "string",
        optional: false
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "CONCAT",
    category: "text",
    id: 446,
    description: "Concatenates a list or range of text strings",
    example: '=CONCAT("text1", C1:C5, C1:C5)',
    parameters: [
      {
        name: "text1",
        description: "Are 1 to 254 text strings or ranges to be joined to a single text string",
        type: "string",
        optional: false
      },
      {
        name: "rest",
        description: "Value, reference, or range.",
        type: "value|range",
        optional: false
      }
    ]
  },
  {
    name: "TEXTBEFORE",
    category: "text",
    id: 453,
    description: "Returns text that's before delimiting characters.",
    example: '=TEXTBEFORE("text", ",", A1)',
    parameters: [
      {
        name: "text",
        description: "The text you want to search for the delimiter.",
        type: "string",
        optional: false
      },
      {
        name: "delimiter",
        description: "The character or string to use as a delimiter.",
        type: "string",
        optional: false
      },
      {
        name: "instanceNum",
        description: "The desired occurrence of delimiter. The default is 1. A negative number searches from the end.",
        type: "value|range",
        optional: true
      },
      {
        name: "matchMode",
        description: "Searches the text for a delimiter match. By default, a case-sensitive match is done.",
        type: "value|range",
        optional: true
      },
      {
        name: "matchEnd",
        description: "Whether to match the delimiter against the end of text. By default, they're not matched.",
        type: "value|range",
        optional: true
      },
      {
        name: "ifNotFound",
        description: "Returned if no match is found. By default, #N/A is returned.",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "TEXTAFTER",
    category: "text",
    id: 454,
    description: "Returns text that's after delimiting characters.",
    example: '=TEXTAFTER("text", ",", A1)',
    parameters: [
      {
        name: "text",
        description: "The text you want to search for the delimiter.",
        type: "string",
        optional: false
      },
      {
        name: "delimiter",
        description: "The character or string to use as a delimiter.",
        type: "string",
        optional: false
      },
      {
        name: "instanceNum",
        description: "The desired occurrence of delimiter. The default is 1. A negative number searches from the end.",
        type: "value|range",
        optional: true
      },
      {
        name: "matchMode",
        description: "Searches the text for a delimiter match. By default, a case-sensitive match is done.",
        type: "value|range",
        optional: true
      },
      {
        name: "matchEnd",
        description: "Whether to match the delimiter against the end of text. By default, they're not matched.",
        type: "value|range",
        optional: true
      },
      {
        name: "ifNotFound",
        description: "Returned if no match is found. By default, #N/A is returned.",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "TEXTSPLIT",
    category: "text",
    id: 455,
    description: "Splits text into rows or columns using delimiters.",
    example: '=TEXTSPLIT("text", ",", ",")',
    parameters: [
      {
        name: "text",
        description: "The text to split",
        type: "string",
        optional: false
      },
      {
        name: "colDelimiter",
        description: "Character or string to split columns by.",
        type: "string",
        optional: false
      },
      {
        name: "rowDelimiter",
        description: "Character or string to split rows by.",
        type: "string",
        optional: true
      },
      {
        name: "ignoreEmpty",
        description: "Whether to ignore empty cells. Defaults to TRUE.",
        type: "value|range",
        optional: true
      },
      {
        name: "matchMode",
        description: "Searches the text for a delimiter match. By default, a case-sensitive match is done.",
        type: "value|range",
        optional: true
      },
      {
        name: "padWith",
        description: "The value to use for padding. Defaults to an empty string.",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "VALUETOTEXT",
    category: "text",
    id: 471,
    description: "Returns a text representation of a value",
    example: '=VALUETOTEXT(A1:A5, "#,##0.00")',
    parameters: [
      {
        name: "value",
        description: "The value to represent as text",
        type: "value|range",
        optional: false
      },
      {
        name: "format",
        description: "The format of the text",
        type: "string",
        optional: true
      }
    ]
  },
  {
    name: "ARRAYTOTEXT",
    category: "text",
    id: 472,
    description: "Returns a text representation of an array",
    example: '=ARRAYTOTEXT({1,2;3,4}, "#,##0.00")',
    parameters: [
      {
        name: "array",
        description: "The array to represent as text",
        type: "array",
        optional: false
      },
      {
        name: "format",
        description: "The format of the text",
        type: "string",
        optional: true
      }
    ]
  },
  {
    name: "TRANSLATE",
    category: "text",
    id: 489,
    description: "Translates a text string from one language into another language using the Microsoft Translation service",
    example: '=TRANSLATE("text", A1)',
    parameters: [
      {
        name: "text",
        description: "Is the text you want to translate",
        type: "string",
        optional: false
      },
      {
        name: "sourceLanguage",
        description: "Specifies the source language your text is currently in. Expressed as a two-letter language code",
        type: "value|range",
        optional: true
      },
      {
        name: "targetLanguage",
        description: "Specifies the language you want your text to be translated into. Expressed as a two-letter language code",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "DETECTLANGUAGE",
    category: "text",
    id: 490,
    description: "Detects the language of a text string using the Microsoft Translation service",
    example: '=DETECTLANGUAGE("text")',
    parameters: [
      {
        name: "text",
        description: "Is the text you would like to detect the language for",
        type: "string",
        optional: false
      }
    ]
  },
  {
    name: "REGEXTEST",
    category: "text",
    id: 491,
    description: "Checks whether the input matches the pattern, and returns TRUE or FALSE",
    example: '=REGEXTEST("text", A1, A1)',
    parameters: [
      {
        name: "text",
        description: "Is the text you are searching within",
        type: "string",
        optional: false
      },
      {
        name: "pattern",
        description: "The regular expression to be applied",
        type: "value|range",
        optional: false
      },
      {
        name: "caseSensitivity",
        description: "Whether the match is case sensitive",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "REGEXREPLACE",
    category: "text",
    id: 492,
    description: "Returns 'text', with 'replacement' in place of matches with 'pattern'",
    example: '=REGEXREPLACE("text", A1, A1)',
    parameters: [
      {
        name: "text",
        description: "The text you are searching within",
        type: "string",
        optional: false
      },
      {
        name: "pattern",
        description: "The regular expression to be applied",
        type: "value|range",
        optional: false
      },
      {
        name: "replacement",
        description: "The string that replaces the matching substring in text. Where $n appears in the string, where $n is a whole number, $n is replaced with the nth capture group",
        type: "value|range",
        optional: false
      },
      {
        name: "occurrence",
        description: "Which occurrence to be replaced. If 0, all occurrences are replaced. A negative value means that number of occurrences from the end of the text.",
        type: "value|range",
        optional: true
      },
      {
        name: "caseSensitivity",
        description: "Whether the match is case sensitive",
        type: "value|range",
        optional: true
      }
    ]
  },
  {
    name: "REGEXEXTRACT",
    category: "text",
    id: 493,
    description: "Extracts substrings of 'text' based on the provided REGEX 'pattern'",
    example: '=REGEXEXTRACT("text", A1, A1)',
    parameters: [
      {
        name: "text",
        description: "Is the text you are searching within",
        type: "string",
        optional: false
      },
      {
        name: "pattern",
        description: "The regular expression to be applied",
        type: "value|range",
        optional: false
      },
      {
        name: "returnMode",
        description: "Specify which matches to return",
        type: "value|range",
        optional: true
      },
      {
        name: "caseSensitivity",
        description: "Whether the match is case sensitive",
        type: "value|range",
        optional: true
      }
    ]
  }
];

// node_modules/@oai/granola/dist/formula-metadata.js
var formulaMetadata = [
  ...compatibility_default,
  ...cube_default,
  ...database_default,
  ...date_time_default,
  ...engineering_default,
  ...financial_default,
  ...information_default,
  ...logical_default,
  ...lookup_reference_default,
  ...math_trig_default,
  ...statistical_default,
  ...text_default
];

// node_modules/@oai/granola/dist/models/spreadsheet/apply/ops-docs.js
var OP_DOCS = {
  "theme.colorScheme.set": {
    summary: "Replace the workbook theme color scheme snapshot.",
    examples: [
      {
        op: "theme.colorScheme.set",
        scheme: {
          name: "Ocean",
          themeColors: {
            accent1: "#0F4C81",
            accent2: "#00A6A6",
            bg1: "#FFFFFF",
            tx1: "#0F172A"
          }
        }
      }
    ]
  },
  "sheet.add": {
    summary: "Add a worksheet to the workbook.",
    examples: [
      {
        op: "sheet.add",
        name: "Inventory"
      }
    ]
  },
  "sheet.set": {
    summary: "Rename or reorder a worksheet.",
    examples: [
      {
        op: "sheet.set",
        target: "Sheet1",
        props: {
          name: "Dashboard",
          index: 0
        }
      }
    ]
  },
  "sheet.remove": {
    summary: "Delete a worksheet by name.",
    examples: [
      {
        op: "sheet.remove",
        target: "Scratch"
      }
    ]
  },
  "range.values.set": {
    summary: "Set cell values for a range.",
    examples: [
      {
        op: "range.values.set",
        target: { sheet: "Inventory", range: "A1:C2" },
        values: [
          ["SKU", "Color", "Stock"],
          ["100-001", "Black", 15]
        ]
      }
    ]
  },
  "range.formulas.set": {
    summary: "Set formulas for a range.",
    examples: [
      {
        op: "range.formulas.set",
        target: { sheet: "Inventory", range: "E2" },
        formulas: [["=AVERAGE(C2:C4)"]]
      }
    ]
  },
  "range.merge": {
    summary: "Merge cells in a range.",
    examples: [
      {
        op: "range.merge",
        target: { sheet: "Report", range: "A1:D1" }
      }
    ]
  },
  "range.unmerge": {
    summary: "Unmerge any merged blocks intersecting the range.",
    examples: [
      {
        op: "range.unmerge",
        target: { sheet: "Report", range: "A1:D4" }
      }
    ]
  },
  "range.format.set": {
    summary: "Apply formatting to a range.",
    examples: [
      {
        op: "range.format.set",
        target: { sheet: "Scorecard", range: "A1:C1" },
        props: {
          fill: "accent1",
          font: { bold: true, size: 14 },
          horizontalAlignment: "center",
          numberFormat: "$#,##0.00",
          wrapText: true,
          borders: { preset: "outside", style: "solid", color: "accent3" }
        }
      }
    ]
  },
  "range.format.clear": {
    summary: "Clear cell formatting for a range.",
    examples: [
      {
        op: "range.format.clear",
        target: { sheet: "Scorecard", range: "A2:C8" }
      }
    ]
  },
  "table.add": {
    summary: "Create a table from a range.",
    examples: [
      {
        op: "table.add",
        props: {
          range: { sheet: "Inventory", range: "A1:C3" },
          hasHeaders: true,
          name: "InventoryTable"
        }
      }
    ]
  },
  "table.rows.add": {
    summary: "Append or insert rows into a table.",
    examples: [
      {
        op: "table.rows.add",
        target: { name: "InventoryTable", sheet: "Inventory" },
        props: {
          index: null,
          values: [["100-003", "Denim", 12]]
        }
      }
    ]
  },
  "table.set": {
    summary: "Update table metadata.",
    examples: [
      {
        op: "table.set",
        target: { name: "InventoryTable", sheet: "Inventory" },
        props: {
          name: "InventoryArchive"
        }
      }
    ]
  },
  "table.remove": {
    summary: "Delete a table from a worksheet.",
    examples: [
      {
        op: "table.remove",
        target: { name: "InventoryTable", sheet: "Inventory" }
      }
    ]
  },
  "conditionalformat.add": {
    summary: "Add a conditional formatting rule to a range.",
    notes: [
      "Supported rule types include cellIs, expression, text rules, blank/error rules, duplicate/unique, timePeriod, top10, aboveAverage, colorScale, dataBar, and iconSet.",
      "iconSet accepts built-in Excel icon names and supports showValue/reverse/custom/percent/thresholds."
    ],
    examples: [
      {
        op: "conditionalformat.add",
        target: { sheet: "CF", range: "A1:A3" },
        props: {
          rule: {
            type: "cellIs",
            operator: "greaterThan",
            formula: 3,
            format: {
              fill: "accent2",
              font: { bold: true, color: "accent3" }
            }
          }
        }
      },
      {
        op: "conditionalformat.add",
        target: { sheet: "KPIs", range: "F2:F20" },
        props: {
          rule: {
            type: "top10",
            rank: 10,
            percent: true,
            format: {
              fill: "#DCFCE7",
              font: { color: "#166534" }
            }
          }
        }
      },
      {
        op: "conditionalformat.add",
        target: { sheet: "KPIs", range: "G2:G20" },
        props: {
          rule: {
            type: "iconSet",
            iconSet: "5Rating",
            showValue: false,
            reverse: false,
            percent: true
          }
        }
      }
    ]
  },
  "conditionalformat.clear": {
    summary: "Remove conditional formatting rules from a range.",
    examples: [
      {
        op: "conditionalformat.clear",
        target: { sheet: "CF", range: "A1:A3" }
      }
    ]
  },
  "datavalidation.set": {
    summary: "Set data validation rules for a range.",
    examples: [
      {
        op: "datavalidation.set",
        target: { sheet: "Validation", range: "B2:B10" },
        props: {
          rule: { type: "list", values: ["Dog", "Cat", "Bat"] },
          prompt: { title: "Pick an animal", show: true },
          errorAlert: { title: "Invalid choice", show: true },
          ignoreBlanks: true,
          inCellDropDown: true
        }
      }
    ]
  },
  "datavalidation.clear": {
    summary: "Remove data validation rules from a range.",
    examples: [
      {
        op: "datavalidation.clear",
        target: { sheet: "Validation", range: "B2:B10" }
      }
    ]
  },
  "sparkline.add": {
    summary: "Create a sparkline group backed by source data.",
    examples: [
      {
        op: "sparkline.add",
        props: {
          uid: "{8FA89B8F-27A7-4E3D-A756-4CD08F8D7B2B}",
          type: "line",
          targetRange: { sheet: "KPIs", range: "H2:H3" },
          sourceData: { sheet: "KPIs", range: "B2:G3" },
          dateAxisRange: { sheet: "KPIs", range: "B1:G1" },
          seriesColor: "accent1",
          markers: { show: true, high: true, low: true }
        }
      }
    ]
  },
  "sparkline.set": {
    summary: "Replace a sparkline group's recorded settings.",
    examples: [
      {
        op: "sparkline.set",
        target: { sheet: "KPIs", uid: "{8FA89B8F-27A7-4E3D-A756-4CD08F8D7B2B}" },
        props: {
          type: "line",
          targetRange: { sheet: "KPIs", range: "I2:I5" },
          sourceData: { sheet: "KPIs", range: "C2:H5" },
          displayHidden: true,
          axis: { showAxis: true, rightToLeft: true }
        }
      }
    ]
  },
  "sparkline.remove": {
    summary: "Delete a sparkline group by uid.",
    examples: [
      {
        op: "sparkline.remove",
        target: { sheet: "KPIs", uid: "{8FA89B8F-27A7-4E3D-A756-4CD08F8D7B2B}" }
      }
    ]
  },
  "chart.add": {
    summary: "Add a chart anchored to worksheet cells.",
    examples: [
      {
        op: "chart.add",
        sheet: "Charts",
        props: {
          chartType: "line",
          anchor: {
            from: { row: 1, col: 1, rowOffsetPx: 4, colOffsetPx: 8 },
            extent: { widthPx: 520, heightPx: 280 }
          },
          title: "Milky Way Star Birth Rate",
          categories: ["2020", "2021", "2022", "2023"],
          series: [{ name: "Milky Way", values: [1.8, 1.9, 2, 2.2] }],
          hasLegend: true,
          legend: { position: "bottom" },
          dataLabels: { showValue: true }
        }
      }
    ]
  },
  "chart.set": {
    summary: "Replace an existing chart's workbook-facing snapshot.",
    examples: [
      {
        op: "chart.set",
        target: {
          sheet: "Charts",
          selector: {
            chartType: "line",
            title: "Updated chart"
          }
        },
        props: {
          chartType: "line",
          anchor: {
            from: { row: 1, col: 5 },
            extent: { widthPx: 520, heightPx: 280 }
          },
          title: "Updated chart",
          categories: ["Q1", "Q2", "Q3"],
          series: [{ name: "Revenue", values: [10, 12, 15] }]
        }
      }
    ]
  },
  "chart.remove": {
    summary: "Delete a worksheet chart by selector or id.",
    examples: [
      {
        op: "chart.remove",
        target: {
          sheet: "Charts",
          selector: {
            chartType: "line",
            title: "Updated chart"
          }
        }
      }
    ]
  },
  "shape.add": {
    summary: "Add a shape anchored to worksheet cells.",
    examples: [
      {
        op: "shape.add",
        sheet: "Shapes",
        props: {
          geometry: "rect",
          anchor: {
            from: { row: 2, col: 3 },
            extent: { widthPx: 260, heightPx: 140 }
          },
          fill: "accent1",
          line: {
            style: "dashed",
            fill: "accent4",
            width: 1
          }
        }
      }
    ]
  },
  "shape.set": {
    summary: "Update a worksheet shape's recorded properties.",
    examples: [
      {
        op: "shape.set",
        target: {
          sheet: "Shapes",
          selector: {
            geometry: "rect"
          }
        },
        props: {
          fill: "accent2",
          line: {
            style: "solid",
            fill: "accent3",
            width: 2
          }
        }
      }
    ]
  },
  "shape.remove": {
    summary: "Delete a worksheet shape by selector or id.",
    examples: [
      {
        op: "shape.remove",
        target: {
          sheet: "Shapes",
          selector: {
            geometry: "rect"
          }
        }
      }
    ]
  },
  "image.add": {
    summary: "Add an image anchored to worksheet cells.",
    examples: [
      {
        op: "image.add",
        sheet: "Images",
        props: {
          dataUrl: "data:image/png;base64,...",
          anchor: {
            from: { row: 1, col: 2 },
            extent: { widthPx: 160, heightPx: 120 }
          }
        }
      }
    ]
  },
  "image.set": {
    summary: "Update an existing worksheet image reference or anchor.",
    examples: [
      {
        op: "image.set",
        target: {
          sheet: "Images",
          imageId: "img-1",
          anchor: {
            from: { row: 1, col: 2 },
            extent: { widthPx: 160, heightPx: 120 }
          }
        },
        props: {
          anchor: {
            from: { row: 3, col: 4 },
            extent: { widthPx: 180, heightPx: 140 }
          }
        }
      }
    ]
  },
  "image.remove": {
    summary: "Delete a worksheet image by asset id and anchor.",
    examples: [
      {
        op: "image.remove",
        target: {
          sheet: "Images",
          imageId: "img-1",
          anchor: {
            from: { row: 1, col: 2 },
            extent: { widthPx: 160, heightPx: 120 }
          }
        }
      }
    ]
  },
  "names.range.add": {
    summary: "Define a workbook or worksheet named range.",
    examples: [
      {
        op: "names.range.add",
        name: "SalesRange",
        formula: "Data!$A$1:$A$3",
        description: "Input sales data"
      }
    ]
  },
  "names.function.add": {
    summary: "Define a workbook or worksheet named function (LAMBDA).",
    examples: [
      {
        op: "names.function.add",
        name: "AddTax",
        lambda: "LAMBDA(price, tax, price*(1+tax))",
        description: "Adds tax to a price",
        parameters: [
          { name: "price", description: "Base price" },
          { name: "tax", description: "Tax rate (e.g. 0.1)" }
        ],
        returns: "Taxed price"
      }
    ]
  },
  "names.remove": {
    summary: "Delete a workbook or worksheet scoped defined name.",
    examples: [
      {
        op: "names.remove",
        name: "SalesRange"
      },
      {
        op: "names.remove",
        name: "LocalRange",
        sheet: "Sheet1"
      }
    ]
  },
  "comments.self.set": {
    summary: "Set the current comment author identity.",
    examples: [
      {
        op: "comments.self.set",
        person: {
          displayName: "Artifact Bot",
          initials: "AB"
        }
      }
    ]
  },
  "thread.add": {
    summary: "Create a threaded comment on a cell or range.",
    examples: [
      {
        op: "thread.add",
        target: {
          cell: { sheet: "Sheet1", address: "F5" }
        },
        body: "Cell comment"
      }
    ]
  },
  "thread.reply": {
    summary: "Reply to a comment thread.",
    examples: [
      {
        op: "thread.reply",
        target: "threadId",
        body: "Reply on cell"
      }
    ]
  },
  "thread.resolve": {
    summary: "Resolve a comment thread.",
    examples: [
      {
        op: "thread.resolve",
        target: "threadId"
      }
    ]
  },
  "thread.reopen": {
    summary: "Reopen a resolved comment thread.",
    examples: [
      {
        op: "thread.reopen",
        target: "threadId"
      }
    ]
  },
  "thread.remove": {
    summary: "Delete a threaded comment.",
    examples: [
      {
        op: "thread.remove",
        target: "th/threadId"
      }
    ]
  }
};

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/ops-help.js
var WORKBOOK_OP_HELP = Object.entries(OP_DOCS).map(([op, doc2]) => ({
  kind: "op",
  op,
  summary: doc2.summary,
  examples: doc2.examples,
  notes: doc2.notes
}));

// node_modules/@oai/granola/dist/models/spreadsheet/help/project/project-entry.js
var mergeArrayFields = (shared, languageSpecific) => {
  if (!shared && !languageSpecific)
    return;
  return [...shared ?? [], ...languageSpecific ?? []];
};
var projectApiEntry = (entry, include, language) => {
  const projected = { kind: "api", name: entry.name };
  const languageFields = entry.languages?.[language];
  const languageFunctionName = languageFields?.functionName;
  const indexName = languageFunctionName ?? entry.name;
  const mergedTags = Array.from(new Set([
    ...entry.tags ?? [],
    ...languageFields?.tags ?? [],
    indexName
  ]));
  if (include.has("index")) {
    projected.name = indexName;
    projected.summary = entry.summary;
    projected.tags = mergedTags.length > 0 ? mergedTags : undefined;
  }
  if (include.has("examples")) {
    projected.examples = mergeArrayFields(entry.examples, languageFields?.examples);
  }
  if (include.has("notes")) {
    projected.notes = mergeArrayFields(entry.notes, languageFields?.notes);
  }
  return projected;
};
var projectOpEntry = (entry, include) => {
  const projected = { kind: "op", op: entry.op };
  if (include.has("index")) {
    projected.summary = entry.summary;
  }
  if (include.has("examples")) {
    projected.examples = entry.examples;
  }
  if (include.has("notes")) {
    projected.notes = entry.notes;
  }
  return projected;
};
var projectEnumEntry = (entry, include) => {
  const projected = { kind: "enum", name: entry.name };
  if (include.has("index")) {
    projected.summary = entry.summary;
    projected.values = entry.values ? [...entry.values] : undefined;
  }
  if (include.has("notes")) {
    projected.notes = entry.notes ? [...entry.notes] : undefined;
  }
  return projected;
};
var buildFormulaName = (name) => `fx.${name}`;
var projectFormulaEntry = (entry, include) => {
  const projected = {
    kind: "formula",
    name: buildFormulaName(entry.name)
  };
  if (include.has("index")) {
    projected.summary = entry.description;
    projected.category = entry.category;
  }
  if (include.has("examples")) {
    projected.examples = entry.example ? [entry.example] : undefined;
  }
  if (include.has("notes")) {
    projected.notes = entry.parameters.map((param) => {
      const optional2 = param.optional ? "optional" : "required";
      return `${param.name} (${param.type}, ${optional2}): ${param.description}`;
    });
  }
  return projected;
};

// node_modules/@oai/granola/dist/models/spreadsheet/help/search/text.js
var getHelpRecordKey = (record2) => {
  switch (record2.kind) {
    case "api":
    case "enum":
    case "formula":
      return record2.name;
    case "op":
      return record2.op;
    case "notice":
      return "notice";
  }
};
var stringifyExamples = (examples) => {
  if (!examples || examples.length === 0)
    return "";
  try {
    return JSON.stringify(examples);
  } catch {
    return "";
  }
};
var helpRecordToSearchText = (record2) => {
  switch (record2.kind) {
    case "api":
      return [
        record2.name,
        record2.summary ?? "",
        (record2.tags ?? []).join(" "),
        (record2.notes ?? []).join(`
`),
        stringifyExamples(record2.examples)
      ].join(`
`).toLowerCase();
    case "op":
      return [
        record2.op,
        record2.summary ?? "",
        (record2.notes ?? []).join(`
`),
        stringifyExamples(record2.examples)
      ].join(`
`).toLowerCase();
    case "enum":
      return [
        record2.name,
        record2.summary ?? "",
        (record2.values ?? []).join(" "),
        (record2.notes ?? []).join(`
`)
      ].join(`
`).toLowerCase();
    case "formula":
      return [
        record2.name,
        record2.category ?? "",
        record2.summary ?? "",
        (record2.notes ?? []).join(`
`),
        stringifyExamples(record2.examples)
      ].join(`
`).toLowerCase();
    case "notice":
      return record2.message.toLowerCase();
  }
};

// node_modules/@oai/granola/dist/models/spreadsheet/help/search/query.js
var globToRegex = (pattern) => {
  const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
  const withWildcards = escaped.replace(/\*/g, ".*").replace(/\?/g, ".");
  return new RegExp(`^${withWildcards}$`, "i");
};
var buildQueryMatcher = (query) => {
  const trimmed = query.trim();
  if (!trimmed || trimmed === "*") {
    return () => true;
  }
  if (/[?*]/.test(trimmed)) {
    const regex = globToRegex(trimmed);
    return (value) => regex.test(value);
  }
  const lowered = trimmed.toLowerCase();
  if (/\s/.test(trimmed)) {
    const tokens = trimmed.split(/[^A-Za-z0-9-]+/).map((token) => token.trim().toLowerCase()).filter((token) => token.length >= 3);
    if (tokens.length === 0) {
      return () => true;
    }
    return (value) => {
      const candidate = value.toLowerCase();
      return tokens.some((token) => candidate.includes(token));
    };
  }
  if (!trimmed.includes(".") && !trimmed.includes("/")) {
    return (value) => value.toLowerCase().includes(lowered);
  }
  return (value) => value.toLowerCase() === lowered;
};

// node_modules/@oai/granola/dist/models/spreadsheet/help/search/score.js
var tokenizeQuery = (query) => query.toLowerCase().split(/[^a-z0-9]+/g).map((t) => t.trim()).filter((t) => t.length >= 2);
var scoreHelpRecord = (record2, query) => {
  const q = query.trim().toLowerCase();
  if (!q)
    return 0;
  const tokens = tokenizeQuery(q);
  if (tokens.length === 0)
    return 0;
  const key = record2.kind === "op" ? record2.op.toLowerCase() : record2.kind === "notice" ? "" : record2.name.toLowerCase();
  const summary = record2.kind === "api" || record2.kind === "op" || record2.kind === "enum" || record2.kind === "formula" ? (record2.summary ?? "").toLowerCase() : "";
  const notes = record2.kind === "api" || record2.kind === "op" || record2.kind === "enum" || record2.kind === "formula" ? (record2.notes ?? []).join(`
`).toLowerCase() : "";
  const examples = record2.kind === "api" || record2.kind === "op" || record2.kind === "formula" ? stringifyExamples(record2.examples).toLowerCase() : "";
  const full = helpRecordToSearchText(record2);
  let score = 0;
  for (const token of tokens) {
    if (key.includes(token))
      score += 20;
    if (summary.includes(token))
      score += 10;
    if (examples.includes(token))
      score += 6;
    if (notes.includes(token))
      score += 4;
  }
  if (q.length >= 4 && full.includes(q))
    score += 15;
  if (record2.kind === "api")
    score += 2;
  if (record2.kind === "op")
    score += 1;
  return score;
};

// node_modules/@oai/granola/dist/models/spreadsheet/help/utils/regex.js
var safeRegex = (source) => {
  try {
    return new RegExp(source, "i");
  } catch {
    return null;
  }
};

// node_modules/@oai/granola/dist/models/spreadsheet/help/utils/truncation.js
var buildTruncationNoticeLine2 = (omittedLines) => JSON.stringify({
  kind: "notice",
  message: `Truncated: omitted ${omittedLines} lines. Increase maxChars or narrow query.`
});
var applyHelpTruncation = (lines, maxChars) => {
  const baseNdjson = lines.join(`
`);
  if (maxChars <= 0 || baseNdjson.length <= maxChars) {
    return { ndjson: baseNdjson, truncated: false };
  }
  let omittedLines = lines.length;
  let noticeLine = buildTruncationNoticeLine2(omittedLines);
  let truncatedLines = [];
  for (let pass = 0;pass < 3; pass += 1) {
    truncatedLines = [];
    let length2 = 0;
    for (const line of lines) {
      const lineLength = line.length + (truncatedLines.length > 0 ? 1 : 0);
      const noticeLength = noticeLine.length + (truncatedLines.length > 0 ? 1 : 0);
      if (length2 + lineLength + noticeLength > maxChars) {
        break;
      }
      truncatedLines.push(line);
      length2 += lineLength;
    }
    const nextOmitted = lines.length - truncatedLines.length;
    if (nextOmitted === omittedLines) {
      break;
    }
    omittedLines = nextOmitted;
    noticeLine = buildTruncationNoticeLine2(omittedLines);
  }
  const ndjson = truncatedLines.length > 0 ? `${truncatedLines.join(`
`)}
${noticeLine}` : noticeLine;
  return { ndjson, truncated: true };
};

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/api/validation-help.js
var VALIDATION_API_HELP = [
  {
    kind: "api",
    name: "range.dataValidation",
    tags: [
      "range.dataValidation",
      "range data validation",
      "data_validation",
      "categories"
    ],
    summary: "Configure data validation rules for a range.",
    languages: {
      javascript: {
        notes: [
          "You can use either compat shorthand fields (like list: { source }) or Granola's rule/prompt/errorAlert fields.",
          "Use range.dataValidation = null to clear validation for a range."
        ],
        examples: [
          {
            code: [
              "const range = sheet.getRange('B2:B6');",
              "range.dataValidation = {",
              "  allowBlank: true,",
              "  list: { inCellDropDown: true, source: ['Run', 'Bike', 'Rest'] },",
              "};"
            ].join(`
`),
            summary: "Create a list validation rule"
          },
          {
            code: [
              "const range = sheet.getRange('C2:C100');",
              "range.dataValidation = {",
              "  rule: { type: 'whole', operator: 'between', formula1: 1, formula2: 100 },",
              "  errorAlert: {",
              "    style: 'stop',",
              "    title: 'Invalid value',",
              "    message: 'Enter a whole number between 1 and 100.',",
              "  },",
              "};"
            ].join(`
`),
            summary: "Require whole numbers between 1 and 100"
          },
          {
            code: [
              "const range = sheet.getRange('D2:D200');",
              "range.dataValidation = {",
              "  rule: {",
              "    type: 'date',",
              "    operator: 'between',",
              "    formula1: '=DATE(2026,1,1)',",
              "    formula2: '=DATE(2026,12,31)',",
              "  },",
              "};"
            ].join(`
`),
            summary: "Constrain dates to a specific year"
          }
        ]
      },
      python: {
        functionName: "range.data_validation",
        notes: [
          "You can use either compat shorthand fields (like list: { source }) or rule/prompt/errorAlert fields.",
          "Use range.data_validation = null to clear validation for a range."
        ],
        examples: [
          {
            code: [
              "range = sheet.get_range('B2:B6')",
              "range.data_validation = {",
              "  'allowBlank': True,",
              "  'list': {'inCellDropDown': True, 'source': ['Run', 'Bike', 'Rest']},",
              "}"
            ].join(`
`),
            summary: "Create a list validation rule"
          },
          {
            code: [
              "range = sheet.get_range('C2:C100')",
              "range.data_validation = {",
              "  'rule': {'type': 'whole', 'operator': 'between', 'formula1': 1, 'formula2': 100},",
              "  'ignoreBlanks': True,",
              "  'inCellDropDown': True,",
              "  'errorAlert': {",
              "    'style': 'warning',",
              "    'title': 'Invalid value',",
              "    'message': 'Enter a whole number between 1 and 100.',",
              "  },",
              "}"
            ].join(`
`),
            summary: "Require whole numbers between 1 and 100"
          },
          {
            code: [
              "range = sheet.get_range('D2:D200')",
              "range.data_validation = {",
              "  'rule': {",
              "    'type': 'date',",
              "    'operator': 'between',",
              "    'formula1': '=DATE(2026,1,1)',",
              "    'formula2': '=DATE(2026,12,31)',",
              "  },",
              "}"
            ].join(`
`),
            summary: "Constrain dates to a specific year"
          }
        ]
      }
    }
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/api/styles-help.js
var COMMON_TAGS = ["styles", "range.format", "formatting"];
var STYLES_API_HELP = [
  {
    kind: "api",
    name: "styles",
    tags: COMMON_TAGS.concat([
      "number format",
      "number_format",
      "autofit",
      "fill",
      "font",
      "borders"
    ]),
    summary: "Formatting ranges (fills, fonts, borders, number formats).",
    notes: [
      "Use range.format.fill, range.format.font, and range.format.borders.",
      "Set range.format.numberFormat or range.format.wrapText.",
      "Use range.format.autofitColumns/Rows for sizing."
    ]
  },
  {
    kind: "api",
    name: "formatting-quick-reference",
    summary: "Copy/paste snippets for common range formatting tasks.",
    tags: COMMON_TAGS.concat([
      "formatting-quick-reference",
      "borders",
      "alignment",
      "number format",
      "horizontal alignment",
      "vertical alignment",
      "wrap text",
      "borders"
    ]),
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const range = sheet.getRange('A1:D10');",
              "",
              "// Fill + font",
              "range.format.fill = 'lt2';",
              "range.format.font = { name: 'Calibri', size: 11, color: 'tx1' };",
              "",
              "// Bulk format (single object assignment)",
              "range.format = {",
              "  fill: 'lt2',",
              "  font: { name: 'Calibri', size: 11, color: 'tx1' },",
              "  borders: { preset: 'outside', style: 'thin', color: '#D1D5DB' },",
              "  horizontalAlignment: 'center',",
              "  verticalAlignment: 'center',",
              "  wrapText: true,",
              "};",
              "",
              "// Theme token + transform (prefer this over manual hex shading)",
              "range.getRow(0).format.fill = {",
              "  type: 'solid',",
              "  color: { type: 'theme', value: 'accent1', transform: { darken: 10 } },",
              "};",
              "",
              "// Borders (edge + inside presets or per-edge)",
              "range.format.borders = { preset: 'outside', style: 'thin', color: '#D1D5DB' };",
              "range.format.borders.getItem('EdgeBottom').style = 'thin';",
              "range.format.borders.getItem('EdgeBottom').color = '#D1D5DB';",
              "",
              "// Alignment + wrapping",
              "range.format.horizontalAlignment = 'center';",
              "range.format.verticalAlignment = 'center';",
              "range.format.wrapText = true;",
              "",
              "// Autofit",
              "range.format.autofitColumns();",
              "range.format.autofitRows();",
              "",
              "// Number formats",
              "range.format.numberFormat = '0.00';",
              "sheet.getRange('E1:F2').format.numberFormat = [['0', '0.00'], ['0', '0.00']];"
            ].join(`
`),
            summary: "Formatting quick reference"
          }
        ]
      },
      python: {
        functionName: "range.format",
        examples: [
          {
            code: [
              "range = sheet.get_range('A1:D10')",
              "",
              "# Fill + font",
              "range.format.fill = 'lt2'",
              "range.format.font = {'name': 'Calibri', 'size': 11, 'color': 'tx1'}",
              "",
              "# Bulk format (single object assignment)",
              "range.format = {",
              "  'fill': 'lt2',",
              "  'font': {'name': 'Calibri', 'size': 11, 'color': 'tx1'},",
              "  'borders': {'preset': 'outside', 'style': 'thin', 'color': '#D1D5DB'},",
              "  'horizontalAlignment': 'center',",
              "  'verticalAlignment': 'center',",
              "  'wrapText': True,",
              "}",
              "",
              "# Theme token + transform (prefer this over manual hex shading)",
              "range.get_row(0).format.fill = {",
              "  'type': 'solid',",
              "  'color': {'type': 'theme', 'value': 'accent1', 'transform': {'darken': 10}},",
              "}",
              "",
              "# Borders (edge + inside presets or per-edge)",
              "range.format.borders = {'preset': 'outside', 'style': 'thin', 'color': '#D1D5DB'}",
              "range.format.borders.get_item('EdgeBottom').style = 'thin'",
              "range.format.borders.get_item('EdgeBottom').color = '#D1D5DB'",
              "",
              "# Alignment + wrapping",
              "range.format.horizontal_alignment = 'center'",
              "range.format.vertical_alignment = 'center'",
              "range.format.wrap_text = True",
              "",
              "# Autofit",
              "range.format.autofit_columns()",
              "range.format.autofit_rows()",
              "",
              "# Number formats",
              "range.format.number_format = '0.00'",
              "sheet.get_range('E1:F2').format.number_format = [['0', '0.00'], ['0', '0.00']]"
            ].join(`
`),
            summary: "Formatting quick reference"
          }
        ]
      }
    },
    notes: [
      "numberFormat accepts either a single string (broadcast) or a 2D string matrix matching the range size.",
      "Patch-style font updates are supported via range.format.font = { ... } or range.format.setFont({ ... }).",
      "Bulk updates are supported via range.format = { fill, font, borders, numberFormat, ... }."
    ]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/api/ranges-help.js
var RANGES_API_HELP = [
  {
    kind: "api",
    name: "worksheet.getRange",
    summary: "Get a Range using A1 notation.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const sheet = workbook.worksheets.getItem('Sheet1');",
              "const range = sheet.getRange('A1:C10');"
            ].join(`
`),
            summary: "Create a range from A1 notation"
          }
        ]
      },
      python: {
        functionName: "worksheet.get_range",
        examples: [
          {
            code: "range = sheet.get_range('A1:C10')",
            summary: "Create a range from A1 notation"
          }
        ]
      }
    },
    notes: [
      "A1 patterns: A1, A1:C10, A:A (entire column), 2:2 (entire row).",
      "Sheet names with spaces in formulas should be quoted: 'Cost Summary'!A1."
    ]
  },
  {
    kind: "api",
    name: "worksheet.getCell",
    summary: "Get a single cell by zero-based row and column.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const sheet = workbook.worksheets.getItem('Sheet1');",
              "const cell = sheet.getCell(1, 4);",
              "cell.values = [['Hello']];"
            ].join(`
`),
            summary: "Access a single cell by index"
          }
        ]
      },
      python: {
        functionName: "worksheet.get_cell",
        examples: [
          {
            code: [
              "cell = sheet.get_cell(1, 4)",
              "cell.values = [['Hello']]"
            ].join(`
`),
            summary: "Access a single cell by index"
          }
        ]
      }
    },
    notes: [
      "Row and column are 0-based indexes.",
      "Returns a Range representing a single cell."
    ]
  },
  {
    kind: "api",
    name: "range.getCell",
    summary: "Get a single cell inside a range by zero-based offsets.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const range = sheet.getRange('B2:D4');",
              "const cell = range.getCell(2, 2);"
            ].join(`
`),
            summary: "Access a cell relative to a range"
          }
        ]
      },
      python: {
        functionName: "range.get_cell",
        examples: [
          {
            code: [
              "range = sheet.get_range('B2:D4')",
              "cell = range.get_cell(2, 2)"
            ].join(`
`),
            summary: "Access a cell relative to a range"
          }
        ]
      }
    },
    notes: [
      "Row and column are 0-based offsets from the range's top-left cell."
    ]
  },
  {
    kind: "api",
    name: "range.rowIndex",
    summary: "Return the 0-based row index for the range's top-left cell.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const range = sheet.getRange('B2:D4');",
              "range.rowIndex; // 1"
            ].join(`
`),
            summary: "Read the range origin row"
          }
        ]
      },
      python: {
        functionName: "range.row_index",
        examples: [
          {
            code: [
              "range = sheet.get_range('B2:D4')",
              "start_row = range.row_index  # 1"
            ].join(`
`),
            summary: "Read the range origin row"
          }
        ]
      }
    },
    notes: ["Throws if the range is not attached to a worksheet."]
  },
  {
    kind: "api",
    name: "range.columnIndex",
    summary: "Return the 0-based column index for the range's top-left cell.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const range = sheet.getRange('B2:D4');",
              "range.columnIndex; // 1"
            ].join(`
`),
            summary: "Read the range origin column"
          }
        ]
      },
      python: {
        functionName: "range.column_index",
        examples: [
          {
            code: [
              "range = sheet.get_range('B2:D4')",
              "start_col = range.column_index  # 1"
            ].join(`
`),
            summary: "Read the range origin column"
          }
        ]
      }
    },
    notes: ["Throws if the range is not attached to a worksheet."]
  },
  {
    kind: "api",
    name: "range.getRow",
    summary: "Return a single row inside a range by 0-based offset.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const range = sheet.getRange('B2:D4');",
              "const row = range.getRow(1); // B3:D3"
            ].join(`
`),
            summary: "Select a row inside a block"
          }
        ]
      },
      python: {
        functionName: "range.get_row",
        examples: [
          {
            code: [
              "range = sheet.get_range('B2:D4')",
              "row = range.get_row(1)  # B3:D3"
            ].join(`
`),
            summary: "Select a row inside a block"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "range.getColumn",
    summary: "Return a single column inside a range by 0-based offset.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const range = sheet.getRange('B2:D4');",
              "const col = range.getColumn(0); // B2:B4"
            ].join(`
`),
            summary: "Select a column inside a block"
          }
        ]
      },
      python: {
        functionName: "range.get_column",
        examples: [
          {
            code: [
              "range = sheet.get_range('B2:D4')",
              "col = range.get_column(0)  # B2:B4"
            ].join(`
`),
            summary: "Select a column inside a block"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "range.getRangeByIndexes",
    summary: "Return a subrange inside a range using 0-based offsets and sizes.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const range = sheet.getRange('B2:D4');",
              "const sub = range.getRangeByIndexes(1, 1, 2, 2); // C3:D4"
            ].join(`
`),
            summary: "Select a sub-rectangle"
          }
        ]
      },
      python: {
        functionName: "range.get_range_by_indexes",
        examples: [
          {
            code: [
              "range = sheet.get_range('B2:D4')",
              "sub = range.get_range_by_indexes(1, 1, 2, 2)  # C3:D4"
            ].join(`
`),
            summary: "Select a sub-rectangle"
          }
        ]
      }
    },
    notes: [
      "Throws if the requested subrange exceeds the current range bounds."
    ]
  },
  {
    kind: "api",
    name: "range.getOffsetRange",
    summary: "Return a range shifted by offsets, optionally changing its size.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const range = sheet.getRange('B2:D4');",
              "const shifted = range.getOffsetRange(1, 0); // B3:D5"
            ].join(`
`),
            summary: "Shift a block down"
          },
          {
            code: [
              "const range = sheet.getRange('B2:D4');",
              "const window = range.getOffsetRange(-1, 0, 1, 3); // B1:D1"
            ].join(`
`),
            summary: "Build a small window relative to a block"
          }
        ]
      },
      python: {
        functionName: "range.get_offset_range",
        examples: [
          {
            code: [
              "range = sheet.get_range('B2:D4')",
              "shifted = range.get_offset_range(1, 0)  # B3:D5"
            ].join(`
`),
            summary: "Shift a block down"
          },
          {
            code: [
              "range = sheet.get_range('B2:D4')",
              "window = range.get_offset_range(-1, 0, 1, 3)  # B1:D1"
            ].join(`
`),
            summary: "Build a small window relative to a block"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "range.getResizedRange",
    summary: "Return a range resized by delta rows/columns, anchored at the current top-left cell.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const range = sheet.getRange('B2:D4');",
              "const wider = range.getResizedRange(0, 1); // B2:E4"
            ].join(`
`),
            summary: "Grow a range by one column"
          },
          {
            code: [
              "const range = sheet.getRange('B2:D4');",
              "const smaller = range.getResizedRange(-1, -1); // B2:C3"
            ].join(`
`),
            summary: "Shrink a range by one row and one column"
          }
        ]
      },
      python: {
        functionName: "range.get_resized_range",
        examples: [
          {
            code: [
              "range = sheet.get_range('B2:D4')",
              "wider = range.get_resized_range(0, 1)  # B2:E4"
            ].join(`
`),
            summary: "Grow a range by one column"
          },
          {
            code: [
              "range = sheet.get_range('B2:D4')",
              "smaller = range.get_resized_range(-1, -1)  # B2:C3"
            ].join(`
`),
            summary: "Shrink a range by one row and one column"
          }
        ]
      }
    },
    notes: [
      "Compatibility helper modeled after Office.js Range.getResizedRange(deltaRows, deltaColumns).",
      "If you have a matrix and just want to write it starting at a single cell, prefer a spill write: sheet.getRange('B2').values = matrix."
    ]
  },
  {
    kind: "api",
    name: "range.getResizeRange",
    summary: "Return a range resized to an explicit row/column count, anchored at the current top-left cell.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const range = sheet.getRange('B2:D4');",
              "const block = range.getResizeRange(5, 2); // B2:C6"
            ].join(`
`),
            summary: "Resize to a specific shape"
          }
        ]
      },
      python: {
        functionName: "range.get_resize_range",
        examples: [
          {
            code: [
              "range = sheet.get_range('B2:D4')",
              "block = range.get_resize_range(5, 2)  # B2:C6"
            ].join(`
`),
            summary: "Resize to a specific shape"
          }
        ]
      }
    },
    notes: [
      "Granola convenience helper (absolute size).",
      "Equivalent to range.getOffsetRange(0, 0, rowCount, columnCount)."
    ]
  },
  {
    kind: "api",
    name: "range.offset",
    summary: "Alias for range.getOffsetRange(...).",
    languages: {
      javascript: {},
      python: {
        functionName: "range.offset"
      }
    },
    notes: ["Use range.getOffsetRange for the full signature and examples."]
  },
  {
    kind: "api",
    name: "range.resize",
    summary: "Alias for range.getResizeRange(rowCount, columnCount).",
    languages: {
      javascript: {},
      python: {
        functionName: "range.resize"
      }
    },
    notes: [
      "This is an absolute resize helper.",
      "Use range.getResizedRange(deltaRows, deltaColumns) when you want Office.js-style delta resize."
    ]
  },
  {
    kind: "api",
    name: "range.write",
    summary: "Write a 2D matrix anchored at this range's top-left (auto-sizes the target).",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const anchor = sheet.getRange('B2');",
              "const block = anchor.write([['A','B'],[1,2],[3,4]]);",
              "// block is the resized range (B2:C4)",
              "block.format.autofitColumns();"
            ].join(`
`),
            summary: "Write a matrix without computing the end cell"
          }
        ]
      },
      python: {
        functionName: "range.write",
        examples: [
          {
            code: [
              "anchor = sheet.get_range('B2')",
              "block = anchor.write([['A', 'B'], [1, 2], [3, 4]])",
              "# block is the resized range (B2:C4)",
              "block.format.autofit_columns()"
            ].join(`
`),
            summary: "Write a matrix without computing the end cell"
          }
        ]
      }
    },
    notes: [
      "Prefer this over hand-building A1 end-cells like 'B2:F17'.",
      "You can pass overwrite: 'error' to prevent overwriting existing content.",
      "1D input is treated as a single row (wrap as [[...]] for 2D)."
    ]
  },
  {
    kind: "api",
    name: "range.values",
    summary: "Read or write cell values using a 2D array.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const range = sheet.getRange('A1:C2');",
              "range.values = [['Date', 'Dog', 'HR'], ['2025-01-02', 'Nova', 58]];"
            ].join(`
`),
            summary: "Write a values grid"
          }
        ]
      },
      python: {
        functionName: "range.values",
        examples: [
          {
            code: [
              "range = sheet.get_range('A1:C2')",
              "range.values = [['Date', 'Dog', 'HR'], ['2025-01-02', 'Nova', 58]]"
            ].join(`
`),
            summary: "Write a values grid"
          }
        ]
      }
    },
    notes: [
      "Values are string | number | boolean | Date | null.",
      "Single-cell ranges spill to fit larger matrices.",
      "Single-row ranges also accept 1D arrays (treated as a row).",
      "Single-column ranges also accept 1D arrays (treated as a column).",
      "Granola auto-fixes common transposed vectors for 1-row/1-col ranges (Nx1 vs 1xN).",
      "Use range.values = null to clear contents."
    ]
  },
  {
    kind: "api",
    name: "range.formulas",
    summary: "Read or write formulas using a 2D string array.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "sheet.getRange('A1:A3').values = [[5], [2], [3]];",
              "sheet.getRange('B1').formulas = [['=SUM(A:A)']];",
              "workbook.recalculate();",
              "const total = sheet.getRange('B1').values[0]?.[0];"
            ].join(`
`),
            summary: "Write a formula and recalculate"
          }
        ]
      },
      python: {
        functionName: "range.formulas",
        examples: [
          {
            code: [
              "sheet.get_range('A1:A3').values = [[5], [2], [3]]",
              "sheet.get_range('B1').formulas = [['=SUM(A:A)']]",
              "workbook.recalculate()",
              "total = sheet.get_range('B1').values[0][0]"
            ].join(`
`),
            summary: "Write a formula and recalculate"
          }
        ]
      }
    },
    notes: [
      "Formula strings may include or omit the leading '='.",
      "Single-cell ranges spill to fit larger matrices.",
      "Single-row and single-column ranges also accept 1D arrays.",
      "Granola auto-fixes common transposed vectors for 1-row/1-col ranges (Nx1 vs 1xN)."
    ]
  },
  {
    kind: "api",
    name: "range.clear",
    summary: "Clear contents and/or formatting for a range.",
    languages: {
      javascript: {
        examples: [
          {
            code: "sheet.getRange('A1:C10').clear();",
            summary: "Clear contents"
          },
          {
            code: "sheet.getRange('A1:C10').clear({ applyTo: 'all' });",
            summary: "Clear contents and formats"
          }
        ]
      },
      python: {
        functionName: "range.clear",
        examples: [
          {
            code: "sheet.get_range('A1:C10').clear()",
            summary: "Clear contents"
          },
          {
            code: "sheet.get_range('A1:C10').clear({'apply_to': 'all'})",
            summary: "Clear contents and formats"
          }
        ]
      }
    },
    notes: [
      "applyTo accepts 'contents', 'formats', or 'all'.",
      "Clearing formats does not change row/column sizing.",
      "Clearing ranges does not delete charts, shapes, or images."
    ]
  },
  {
    kind: "api",
    name: "ranges",
    summary: "Range addressing and cell reads/writes.",
    languages: {
      javascript: {},
      python: {
        functionName: "worksheet.get_range"
      }
    },
    notes: [
      "Create ranges with worksheet.getRange('A1:C10').",
      "Write with range.values or range.formulas.",
      "Use range.rowCount/range.columnCount (or range.getRowCount()/getColumnCount()) to inspect range dimensions.",
      "Use range.formulasR1C1 when it's easier to generate relative formulas (e.g. RC[-1]) and let the API translate them.",
      `range.values treats strings starting with '=' as formulas; use "'=..." to force literal text.`,
      "range.values and range.formulas require a rectangular matrix matching the range size; single-cell ranges spill to fit larger matrices.",
      "Clear with range.clear() or range.values = null."
    ]
  },
  {
    kind: "api",
    name: "range.fillDown",
    summary: "Copy the first row down, shifting formulas.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const r = sheet.getRange('B2:B10');",
              "r.getCell(0, 0).formulasR1C1 = [['=RC[-1]*2']];",
              "r.fillDown();"
            ].join(`
`),
            summary: "Fill down like Excel drag-fill"
          }
        ]
      },
      python: {
        functionName: "range.fill_down",
        examples: [
          {
            code: [
              "r = sheet.get_range('B2:B10')",
              "r.get_cell(0, 0).formulas_r1_c1 = [['=RC[-1]*2']]",
              "r.fill_down()"
            ].join(`
`),
            summary: "Fill down like Excel drag-fill"
          }
        ]
      }
    },
    notes: [
      "Copies formulas/values from the first row to the rest of the range.",
      "Relative references are shifted per row."
    ]
  },
  {
    kind: "api",
    name: "range.fillRight",
    summary: "Copy the first column right, shifting formulas.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const r = sheet.getRange('B2:F2');",
              "r.getCell(0, 0).formulasR1C1 = [['=RC[-1]*2']];",
              "r.fillRight();"
            ].join(`
`),
            summary: "Fill right like Excel drag-fill"
          }
        ]
      },
      python: {
        functionName: "range.fill_right",
        examples: [
          {
            code: [
              "r = sheet.get_range('B2:F2')",
              "r.get_cell(0, 0).formulas_r1_c1 = [['=RC[-1]*2']]",
              "r.fill_right()"
            ].join(`
`),
            summary: "Fill right like Excel drag-fill"
          }
        ]
      }
    },
    notes: [
      "Copies formulas/values from the first column to the rest of the range.",
      "Relative references are shifted per column."
    ]
  },
  {
    kind: "api",
    name: "range.fillFrom",
    summary: "Fill a larger one-axis range from a source block, repeating values and shifting formulas.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const seed = sheet.getRange('B2:C3');",
              "const target = sheet.getRange('B2:C8');",
              "target.fillFrom(seed);"
            ].join(`
`),
            summary: "Extend a block downward from a source selection"
          }
        ]
      },
      python: {
        functionName: "range.fill_from",
        examples: [
          {
            code: [
              "seed = sheet.get_range('B2:C3')",
              "target = sheet.get_range('B2:C8')",
              "target.fill_from(seed)"
            ].join(`
`),
            summary: "Extend a block downward from a source selection"
          }
        ]
      }
    },
    notes: [
      "Destination must extend source in exactly one direction while sharing the other axis.",
      "Repeated tails are allowed even when the destination size is not an even multiple of the source size.",
      "Copies literal values exactly and shifts relative formula references; it does not infer numeric/date series.",
      "Cell formatting and data validation are not propagated."
    ]
  },
  {
    kind: "api",
    name: "range.copyFrom",
    summary: "Copy values/formulas from another range (supports 1x1 broadcast).",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "// Excel-like drag-fill across a whole block (no manual 2D matrix)",
              "const grid = sheet.getRange('B3:AF17');",
              "const seed = sheet.getRange('B3');",
              "seed.formulasR1C1 = [['=RC[-1]*2']];",
              "grid.copyFrom(seed, 'formulas');"
            ].join(`
`),
            summary: "Fill a block of formulas using copyFrom"
          }
        ]
      },
      python: {
        functionName: "range.copy_from",
        examples: [
          {
            code: [
              "# Excel-like drag-fill across a whole block (no manual 2D matrix)",
              "grid = sheet.get_range('B3:AF17')",
              "seed = sheet.get_range('B3')",
              "seed.formulas_r1_c1 = [['=RC[-1]*2']]",
              "grid.copy_from(seed, 'formulas')"
            ].join(`
`),
            summary: "Fill a block of formulas using copyFrom"
          }
        ]
      }
    },
    notes: [
      "When source is 1x1, copyFrom broadcasts to the destination shape.",
      "When copying formulas, relative references shift across the destination cells."
    ]
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/api/tables-help.js
var COMMON_TAGS2 = ["tables", "table", "worksheet.tables", "tables.add"];
var TABLES_API_HELP = [
  {
    kind: "api",
    name: "tables",
    tags: COMMON_TAGS2.concat(["tables add", "table add"]),
    summary: "Excel table objects on a worksheet.",
    notes: [
      "Use worksheet.tables.add('A1:D10', true) (or worksheet.getRange('A1:D10')) to create a table.",
      "Use worksheet.tables.getItem(name) to access an existing table.",
      "Use worksheet.tables.getItemAt(index) to access tables by position.",
      "Use worksheet.tables.getItemOrNullObject(name) when the table may not exist; check table.isNullObject before using it.",
      "Use table.delete() to remove a single table, or worksheet.tables.deleteAll() to remove all tables."
    ],
    languages: {
      javascript: {},
      python: {
        functionName: "worksheet.tables.add"
      }
    }
  },
  {
    kind: "api",
    name: "data-tables",
    tags: COMMON_TAGS2.concat(["data tables add", "data_tables.add"]),
    summary: "What-if data tables for formulas.",
    notes: [
      "Use worksheet.dataTables.add('C2:E5', { rowInput, columnInput }) with the formula in the top-left cell of the range.",
      "Data tables require at least a rowInput or columnInput."
    ],
    languages: {
      javascript: {},
      python: {
        functionName: "worksheet.data_tables.add"
      }
    }
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/api/worksheets-help.js
var TAGS = ["sheets", "worksheets"];
var WORKSHEETS_API_HELP = [
  {
    kind: "api",
    name: "worksheets",
    tags: TAGS,
    summary: "Worksheet collection and selection.",
    languages: {
      javascript: {
        notes: [
          "Use workbook.worksheets.add(name) to create sheets.",
          "Use workbook.worksheets.getItem(name) to select by name.",
          "Use workbook.worksheets.getOrAdd(name, { renameFirstIfOnlyNewSpreadsheet: true }) to create-or-reuse.",
          "Use workbook.worksheets.getItemAt(index) to select by index.",
          "Use workbook.worksheets.getActiveWorksheet() for the active sheet."
        ]
      },
      python: {
        notes: [
          "Use workbook.worksheets.add(name) to create sheets.",
          "Use workbook.worksheets.get_item(name) to select by name.",
          "Use workbook.worksheets.get_or_add(name, { renameFirstIfOnlyNewSpreadsheet: True }) to create-or-reuse.",
          "Use workbook.worksheets.get_item_at(index) to select by index.",
          "Use workbook.worksheets.get_active_worksheet() for the active sheet."
        ]
      }
    }
  },
  {
    kind: "api",
    name: "worksheets get or add",
    tags: TAGS,
    summary: "Get an existing worksheet by name or create it if missing.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const sheet = workbook.worksheets.getOrAdd('Dashboard', {",
              "  renameFirstIfOnlyNewSpreadsheet: true,",
              "});"
            ].join(`
`),
            summary: "Create-or-reuse a worksheet"
          }
        ]
      },
      python: {
        functionName: "workbook.worksheets.get_or_add(name, options)",
        examples: [
          {
            code: [
              "sheet = workbook.worksheets.get_or_add(",
              "  'Dashboard',",
              "  {'renameFirstIfOnlyNewSpreadsheet': True},",
              ")"
            ].join(`
`),
            summary: "Create-or-reuse a worksheet"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "worksheet.freezePanes",
    tags: [
      "freeze panes",
      "freeze_panes",
      "freeze_rows",
      "freeze_columns",
      "unfreeze"
    ],
    summary: "Freeze or unfreeze worksheet panes.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const sheet = workbook.worksheets.getItem('Data');",
              "sheet.freezePanes.freezeRows(1);",
              "sheet.freezePanes.freezeColumns(2);"
            ].join(`
`),
            summary: "Freeze header row and first two columns"
          }
        ]
      },
      python: {
        functionName: "worksheet.freeze_panes",
        examples: [
          {
            code: [
              "sheet = workbook.worksheets.get_item('Data')",
              "sheet.freeze_panes.freeze_rows(1)",
              "sheet.freeze_panes.freeze_columns(2)"
            ].join(`
`),
            summary: "Freeze header row and first two columns"
          },
          {
            code: "sheet.freeze_panes.unfreeze()",
            summary: "Unfreeze panes"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "worksheet.showGridLines",
    tags: [
      "show_grid_lines",
      "showGridLines",
      "grid lines",
      "gridlines",
      "worksheet.show_grid_lines"
    ],
    summary: "Worksheet gridline visibility surface.",
    languages: {
      python: {
        functionName: "worksheet.show_grid_lines"
      }
    }
  },
  {
    kind: "api",
    name: "worksheet.getUsedRange",
    summary: "Return the used range for a worksheet.",
    languages: {
      javascript: {
        notes: [
          "Used range is the smallest rectangle covering cells that have been created (values, formulas, or formatting).",
          "Use sheet.getUsedRange(true) to approximate values-only used bounds."
        ],
        examples: [
          {
            code: [
              "const sheet = workbook.worksheets.getItem('Sheet1');",
              "const used = sheet.getUsedRange();",
              "used.clear({ applyTo: 'all' });"
            ].join(`
`),
            summary: "Clear the used range"
          }
        ]
      },
      python: {
        functionName: "worksheet.get_used_range",
        notes: [
          "Used range is the smallest rectangle covering cells that have been created (values, formulas, or formatting).",
          "Use worksheet.get_used_range(true) to approximate values-only used bounds."
        ],
        examples: [
          {
            code: [
              "used = sheet.get_used_range()",
              "used.clear({'apply_to': 'all'})"
            ].join(`
`),
            summary: "Clear the used range"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "worksheet.reset",
    summary: "Clear the sheet and delete common objects (tables, charts, drawings, sparklines).",
    notes: [
      "Defaults clear the used range (applyTo='all') and delete tables/charts/drawings/sparklines.",
      "Pass options to keep objects or to clear formats/contents selectively."
    ],
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const sheet = workbook.worksheets.getItem('Sheet1');",
              "sheet.reset();"
            ].join(`
`),
            summary: "Reset a worksheet for a clean rebuild"
          }
        ]
      },
      python: {
        functionName: "worksheet.reset",
        examples: [
          {
            code: "sheet.reset()",
            summary: "Reset a worksheet for a clean rebuild"
          }
        ]
      }
    }
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/api/conditional-formatting-help.js
var COMMON_TAGS3 = [
  "conditional-formatting",
  "conditional formatting",
  "conditional format"
];
var CONDITIONAL_FORMATTING_API_HELP = [
  {
    kind: "api",
    name: "conditional-formatting",
    tags: COMMON_TAGS3,
    summary: "Conditional formatting rules for ranges.",
    languages: {
      javascript: {
        notes: [
          "Use range.conditionalFormats.add(type, config) to add rules.",
          "Use range.conditionalFormats.clear() (or deleteAll()) to remove rules.",
          "Use range.conditionalFormats.add('Custom', { formula, format }) for expression rules.",
          "Convenience aliases: range.conditionalFormats.addExpression(...) and addCustom(...).",
          "Compat alias: use type='CellValue' for cellIs rules.",
          "Use range.conditionalFormats.addCellIs({ operator, formula, format }) for cellIs rules."
        ]
      },
      python: {
        functionName: "range.conditional_formats.add",
        notes: [
          "Use range.conditional_formats.add(type, config) to add rules.",
          "Use range.conditional_formats.clear() (or delete_all()) to remove rules.",
          "Use range.conditional_formats.add('Custom', {'formula': ..., 'format': ...}) for expression rules.",
          "Convenience aliases: range.conditional_formats.add_expression(...) and add_custom(...).",
          "Compat alias: use type='CellValue' for cellIs rules.",
          "Use range.conditional_formats.add_cell_is({'operator': ..., 'formula': ..., 'format': ...}) for cellIs rules."
        ]
      }
    },
    notes: [
      "Supported authored rule families include: cellIs, expression (Custom), containsText/notContainsText, beginsWith/endsWith, containsBlanks/notContainsBlanks, containsErrors/notContainsErrors, duplicateValues/uniqueValues, timePeriod, top10, aboveAverage, colorScale, dataBar, and iconSet.",
      "colorScale accepts { colors, thresholds } or criteria objects/arrays.",
      "iconSet accepts built-in Excel icon names such as 3Arrows, 3TrafficLights1, 4Rating, and 5Boxes, and it auto-generates 3/4/5 thresholds when omitted."
    ]
  },
  {
    kind: "api",
    name: "range.conditionalFormats",
    tags: COMMON_TAGS3,
    summary: "Conditional formatting rules scoped to a range.",
    languages: {
      javascript: {
        notes: [
          "Use range.conditionalFormats.add(type, config) to add rules.",
          "Use range.conditionalFormats.clear() (or deleteAll()) to remove rules.",
          "Use range.conditionalFormats.addCellIs({ operator, formula, format }) for cellIs rules.",
          "Use range.conditionalFormats.addExpression(...) and addCustom(...) as expression-rule convenience aliases."
        ],
        examples: [
          {
            code: [
              "const range = sheet.getRange('B2:B6');",
              "range.conditionalFormats.add('colorScale', {",
              "  colors: ['#FCA5A5', '#DC2626'],",
              "});"
            ].join(`
`),
            summary: "Add a color scale rule"
          },
          {
            code: [
              "const range = sheet.getRange('B2:B6');",
              "range.conditionalFormats.add('colorScale', {",
              "  criteria: [",
              "    { type: 'lowestValue', color: '#DC2626' },",
              "    { type: 'percentile', value: 50, color: '#FBBF24' },",
              "    { type: 'highestValue', color: '#16A34A' },",
              "  ],",
              "});"
            ].join(`
`),
            summary: "Add a 3-stop color scale (min/mid/max)"
          },
          {
            code: [
              "const range = sheet.getRange('B2:B6');",
              "range.conditionalFormats.add('Custom', {",
              "  formula: '=B2>10',",
              "  format: { fill: '#FDE68A', font: { bold: true } },",
              "});"
            ].join(`
`),
            summary: "Add a custom formula rule"
          },
          {
            code: [
              "const range = sheet.getRange('B2:B6');",
              "range.conditionalFormats.addCellIs({",
              "  operator: 'lessThan',",
              "  formula: 0,",
              "  format: { fill: '#F8CBAD' },",
              "});"
            ].join(`
`),
            summary: "Add a cell value rule"
          },
          {
            code: [
              "const range = sheet.getRange('C2:C10');",
              "range.conditionalFormats.add('dataBar', {",
              "  color: 'accent5',",
              "  gradient: true,",
              "});"
            ].join(`
`),
            summary: "Add data bars (color bars) for magnitude"
          },
          {
            code: [
              "const range = sheet.getRange('D2:D10');",
              "range.conditionalFormats.add('iconSet', {",
              "  iconSet: '3Arrows',",
              "  showValue: false,",
              "  reverse: false,",
              "  percent: true,",
              "});"
            ].join(`
`),
            summary: "Add an icon set for quick up/flat/down signals"
          },
          {
            code: [
              "const range = sheet.getRange('E2:E8');",
              "range.conditionalFormats.add('containsText', {",
              "  text: 'late',",
              "  format: { fill: '#FDE68A', font: { color: '#92400E', bold: true } },",
              "});"
            ].join(`
`),
            summary: "Highlight text cells that contain a substring"
          },
          {
            code: [
              "const range = sheet.getRange('F2:F12');",
              "range.conditionalFormats.add('timePeriod', {",
              "  timePeriod: 'last7Days',",
              "  format: { fill: '#DBEAFE', font: { color: '#1D4ED8' } },",
              "});"
            ].join(`
`),
            summary: "Highlight dates in a relative time window"
          },
          {
            code: [
              "const range = sheet.getRange('G2:G20');",
              "range.conditionalFormats.add('top10', {",
              "  rank: 10,",
              "  percent: true,",
              "  format: { fill: '#DCFCE7', font: { color: '#166534' } },",
              "});"
            ].join(`
`),
            summary: "Highlight top-ranked values by count or percent"
          },
          {
            code: [
              "const range = sheet.getRange('H2:H20');",
              "range.conditionalFormats.add('aboveAverage', {",
              "  aboveAverage: false,",
              "  equalAverage: true,",
              "  format: { fill: '#FECACA', font: { color: '#991B1B' } },",
              "});"
            ].join(`
`),
            summary: "Highlight values below or equal to the average"
          }
        ]
      },
      python: {
        functionName: "range.conditional_formats.add",
        notes: [
          "Use range.conditional_formats.add(type, config) to add rules.",
          "Use range.conditional_formats.clear() (or delete_all()) to remove rules.",
          "Use range.conditional_formats.add_cell_is({'operator': ..., 'formula': ..., 'format': ...}) for cellIs rules.",
          "Use range.conditional_formats.add_expression(...) and add_custom(...) as expression-rule convenience aliases."
        ],
        examples: [
          {
            code: [
              "range = sheet.get_range('B2:B6')",
              "range.conditional_formats.add('colorScale', {",
              "  'colors': ['#FCA5A5', '#DC2626'],",
              "})"
            ].join(`
`),
            summary: "Add a color scale rule"
          },
          {
            code: [
              "range = sheet.get_range('B2:B6')",
              "range.conditional_formats.add('colorScale', {",
              "  'criteria': [",
              "    {'type': 'lowestValue', 'color': '#DC2626'},",
              "    {'type': 'percentile', 'value': 50, 'color': '#FBBF24'},",
              "    {'type': 'highestValue', 'color': '#16A34A'},",
              "  ],",
              "})"
            ].join(`
`),
            summary: "Add a 3-stop color scale (min/mid/max)"
          },
          {
            code: [
              "range = sheet.get_range('B2:B6')",
              "range.conditional_formats.add('Custom', {",
              "  'formula': '=B2>10',",
              "  'format': {'fill': '#FDE68A', 'font': {'bold': True}},",
              "})"
            ].join(`
`),
            summary: "Add a custom formula rule"
          },
          {
            code: [
              "range = sheet.get_range('B2:B6')",
              "range.conditional_formats.add_cell_is({",
              "  'operator': 'lessThan',",
              "  'formula': 0,",
              "  'format': {'fill': '#F8CBAD'},",
              "})"
            ].join(`
`),
            summary: "Add a cell value rule"
          },
          {
            code: [
              "range = sheet.get_range('C2:C10')",
              "range.conditional_formats.add('dataBar', {",
              "  'color': 'accent5',",
              "  'gradient': True,",
              "})"
            ].join(`
`),
            summary: "Add data bars (color bars) for magnitude"
          },
          {
            code: [
              "range = sheet.get_range('D2:D10')",
              "range.conditional_formats.add('iconSet', {",
              "  'iconSet': '3Arrows',",
              "  'showValue': False,",
              "  'reverse': False,",
              "  'percent': True,",
              "})"
            ].join(`
`),
            summary: "Add an icon set for quick up/flat/down signals"
          },
          {
            code: [
              "range = sheet.get_range('E2:E8')",
              "range.conditional_formats.add('containsText', {",
              "  'text': 'late',",
              "  'format': {'fill': '#FDE68A', 'font': {'color': '#92400E', 'bold': True}},",
              "})"
            ].join(`
`),
            summary: "Highlight text cells that contain a substring"
          },
          {
            code: [
              "range = sheet.get_range('F2:F12')",
              "range.conditional_formats.add('timePeriod', {",
              "  'timePeriod': 'last7Days',",
              "  'format': {'fill': '#DBEAFE', 'font': {'color': '#1D4ED8'}},",
              "})"
            ].join(`
`),
            summary: "Highlight dates in a relative time window"
          },
          {
            code: [
              "range = sheet.get_range('G2:G20')",
              "range.conditional_formats.add('top10', {",
              "  'rank': 10,",
              "  'percent': True,",
              "  'format': {'fill': '#DCFCE7', 'font': {'color': '#166534'}},",
              "})"
            ].join(`
`),
            summary: "Highlight top-ranked values by count or percent"
          },
          {
            code: [
              "range = sheet.get_range('H2:H20')",
              "range.conditional_formats.add('aboveAverage', {",
              "  'aboveAverage': False,",
              "  'equalAverage': True,",
              "  'format': {'fill': '#FECACA', 'font': {'color': '#991B1B'}},",
              "})"
            ].join(`
`),
            summary: "Highlight values below or equal to the average"
          },
          {
            code: [
              "for rule in [",
              "  {",
              "    'range': 'E2:E1000',",
              "    'rule': {'type': 'dataBar', 'color': 'accent5', 'gradient': True},",
              "  },",
              "  {",
              "    'range': 'F2:F1000',",
              "    'rule': {'type': 'cellIs', 'operator': 'lessThanOrEqual', 'formula': 0, 'format': {'fill': '#F8CBAD'}},",
              "  },",
              "]:",
              "  sheet.conditional_formattings.add(rule)"
            ].join(`
`),
            summary: "Add multiple rules efficiently at worksheet scope"
          }
        ]
      }
    },
    notes: [
      "Compat alias: use type='CellValue' for cellIs rules.",
      "Use Custom as an alias for expression rules.",
      "Supported rule types include: cellIs, colorScale, dataBar, iconSet, expression (Custom), text rules, blank/error rules, duplicate/unique, timePeriod, top10, and aboveAverage.",
      "colorScale accepts { colors, thresholds } or criteria objects/arrays.",
      "iconSet preserves showValue/reverse/custom/percent/thresholds in inspect output."
    ]
  },
  {
    kind: "api",
    name: "range.conditionalFormats.addCustom",
    tags: COMMON_TAGS3,
    summary: "Add a custom (expression) conditional format to a range.",
    languages: {
      javascript: {
        notes: [
          "addCustom(formula, format) takes the differential format as the second argument (fill/font/border/numberFormat).",
          "If you already have a { formula, format } object, use range.conditionalFormats.add('Custom', { ... })."
        ],
        examples: [
          {
            code: [
              "const range = sheet.getRange('F2:F50');",
              "range.conditionalFormats.addCustom('=F2<E2', {",
              "  fill: '#FECACA',",
              "  font: { color: '#991B1B', bold: true },",
              "});"
            ].join(`
`),
            summary: "Highlight cells using a custom formula"
          },
          {
            code: [
              "const range = sheet.getRange('F2:F50');",
              "range.conditionalFormats.add('Custom', {",
              "  formula: '=F2<E2',",
              "  format: { fill: '#FECACA', font: { color: '#991B1B' } },",
              "});"
            ].join(`
`),
            summary: "Equivalent add('Custom', ...) form"
          }
        ]
      },
      python: {
        functionName: "range.conditional_formats.add_custom",
        notes: [
          "add_custom(formula, format) takes the differential format as the second argument (fill/font/border/numberFormat).",
          "If you already have a {'formula': ..., 'format': ...} object, use range.conditional_formats.add('Custom', { ... })."
        ],
        examples: [
          {
            code: [
              "range = sheet.get_range('F2:F50')",
              "range.conditional_formats.add_custom('=F2<E2', {",
              "  'fill': '#FECACA',",
              "  'font': {'color': '#991B1B', 'bold': True},",
              "})"
            ].join(`
`),
            summary: "Highlight cells using a custom formula"
          },
          {
            code: [
              "range = sheet.get_range('F2:F50')",
              "range.conditional_formats.add('Custom', {",
              "  'formula': '=F2<E2',",
              "  'format': {'fill': '#FECACA', 'font': {'color': '#991B1B'}},",
              "})"
            ].join(`
`),
            summary: "Equivalent add('Custom', ...) form"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "range.conditionalFormats.addExpression",
    tags: COMMON_TAGS3,
    summary: "Alias for addCustom; adds a custom (expression) conditional rule.",
    languages: {
      javascript: {
        notes: [
          "Use range.conditionalFormats.addCustom(...) for the same behavior."
        ]
      },
      python: {
        functionName: "range.conditional_formats.add_expression",
        notes: [
          "Use range.conditional_formats.add_custom(...) for the same behavior."
        ]
      }
    }
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/api/merge-help.js
var MERGE_API_HELP = [
  {
    kind: "api",
    name: "range.merge",
    summary: "Merge cells in a range into a single region.",
    languages: {
      javascript: {
        examples: [
          {
            code: "sheet.getRange('B1:H1').merge();",
            summary: "Merge a header row"
          },
          {
            code: "sheet.getRange('B2:H4').merge(true);",
            summary: "Merge across rows"
          }
        ]
      },
      python: {
        functionName: "range.merge",
        examples: [
          {
            code: "sheet.get_range('B1:H1').merge()",
            summary: "Merge a header row"
          },
          {
            code: "sheet.get_range('B2:H4').merge(True)",
            summary: "Merge across rows"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "range.unmerge",
    summary: "Unmerge any merged blocks intersecting the range.",
    languages: {
      javascript: {
        examples: [
          {
            code: "sheet.getRange('B1:H4').unmerge();",
            summary: "Remove merges touching a range"
          }
        ]
      },
      python: {
        functionName: "range.unmerge",
        examples: [
          {
            code: "sheet.get_range('B1:H4').unmerge()",
            summary: "Remove merges touching a range"
          }
        ]
      }
    }
  }
];

// node_modules/@oai/granola/dist/models/spreadsheet/help/data/api/range-formats-help.js
var RANGE_FORMATS_API_HELP = [
  {
    kind: "api",
    name: "range.format.fill",
    summary: "Set the fill (background) for a range.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const header = sheet.getRange('A1:C1');",
              "header.format.fill = 'accent1';",
              "header.format.font = { color: 'lt1', bold: true };"
            ].join(`
`),
            summary: "Apply a solid fill using a theme token"
          },
          {
            code: [
              "const header = sheet.getRange('A1:C1');",
              "header.format.fill = {",
              "  type: 'solid',",
              "  color: { type: 'theme', value: 'accent1', transform: { lighten: 15 } },",
              "};"
            ].join(`
`),
            summary: "Apply a theme color transform (LLM-friendly units)"
          },
          {
            code: "sheet.getRange('A2:C10').format.fill = null;",
            summary: "Clear a range's fill"
          }
        ]
      },
      python: {
        functionName: "range.format.fill",
        examples: [
          {
            code: [
              "header = sheet.get_range('A1:C1')",
              "header.format.fill = 'accent1'",
              "header.format.font = {'color': 'lt1', 'bold': True}"
            ].join(`
`),
            summary: "Apply a solid fill using a theme token"
          },
          {
            code: [
              "header = sheet.get_range('A1:C1')",
              "header.format.fill = {",
              "  'type': 'solid',",
              "  'color': {'type': 'theme', 'value': 'accent1', 'transform': {'lighten': 15}},",
              "}"
            ].join(`
`),
            summary: "Apply a theme color transform (LLM-friendly units)"
          },
          {
            code: "sheet.get_range('A2:C10').format.fill = None",
            summary: "Clear a range's fill"
          }
        ]
      }
    },
    notes: [
      "Fill supports theme tokens (accent1..6, lt1/lt2, etc) or hex colors.",
      "For shades/emphasis, prefer theme token + transform (lighten/darken/opacity) over manually picking multiple hex variants.",
      "Use the object form for gradients or patterned fills.",
      "Set fill to null to clear a range's fill."
    ]
  },
  {
    kind: "api",
    name: "range.format.fill.color",
    summary: "Set the fill foreground color via the Fill object.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const block = sheet.getRange('A1:B10');",
              "block.format.fill.color = '#0055A4';"
            ].join(`
`),
            summary: "Update fill via fill.color"
          }
        ]
      },
      python: {
        functionName: "range.format.fill.color",
        examples: [
          {
            code: [
              "block = sheet.get_range('A1:B10')",
              "block.format.fill.color = '#0055A4'"
            ].join(`
`),
            summary: "Update fill via fill.color"
          }
        ]
      }
    },
    notes: ["Use range.format.fill = ... for full fill configs."]
  },
  {
    kind: "api",
    name: "range.format.font",
    summary: "Control font styling on a range.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const header = sheet.getRange('A1:C1');",
              "header.format.font.bold = true;",
              "header.format.font.size = 14;",
              "// Patch-style assignment is supported too:",
              "header.format.font = { color: '#FFFFFF', bold: true };",
              "header.format.setFont({ name: 'Calibri', italic: true });"
            ].join(`
`),
            summary: "Bold header styling"
          }
        ]
      },
      python: {
        functionName: "range.format.font",
        examples: [
          {
            code: [
              "header = sheet.get_range('A1:C1')",
              "header.format.font.bold = True",
              "header.format.font.size = 14",
              "# Patch-style assignment is supported too:",
              "header.format.font = {'color': '#FFFFFF', 'bold': True}",
              "header.format.set_font({'name': 'Calibri', 'italic': True})"
            ].join(`
`),
            summary: "Bold header styling"
          }
        ]
      }
    },
    notes: [
      "Use header.format.font.<prop> = ... for incremental updates.",
      "Use header.format.font = { ... } or header.format.setFont({ ... }) for patch-style updates."
    ]
  },
  {
    kind: "api",
    name: "range.format.borders",
    summary: "Apply borders to a range using presets or per-edge config.",
    languages: {
      javascript: {
        examples: [
          {
            code: [
              "const body = sheet.getRange('A2:C10');",
              "body.format.borders = { preset: 'outside', style: 'thin', color: '#DDDDDD' };"
            ].join(`
`),
            summary: "Apply an outside border preset"
          }
        ]
      },
      python: {
        functionName: "range.format.borders",
        examples: [
          {
            code: [
              "body = sheet.get_range('A2:C10')",
              "body.format.borders = {'preset': 'outside', 'style': 'thin', 'color': '#DDDDDD'}"
            ].join(`
`),
            summary: "Apply an outside border preset"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "range.format.numberFormat",
    summary: "Assign Excel number format codes.",
    languages: {
      javascript: {
        examples: [
          {
            code: `sheet.getRange('B2:B5').format.numberFormat = '"$"#,##0.00';`,
            summary: "Format currency values"
          },
          {
            code: [
              "const r = sheet.getRange('A1:B2');",
              "r.format.numberFormat = [",
              "  ['0', '0.00'],",
              "  ['0', '0.00'],",
              "];"
            ].join(`
`),
            summary: "Assign a per-cell number format matrix"
          }
        ]
      },
      python: {
        functionName: "range.format.number_format",
        examples: [
          {
            code: `sheet.get_range('B2:B5').format.number_format = '"$"#,##0.00'`,
            summary: "Format currency values"
          },
          {
            code: [
              "r = sheet.get_range('A1:B2')",
              "r.format.number_format = [",
              "  ['0', '0.00'],",
              "  ['0', '0.00'],",
              "]"
            ].join(`
`),
            summary: "Assign a per-cell number format matrix"
          }
        ]
      }
    },
    notes: [
      "When passing a 2D array, it must match the range size exactly.",
      "If you want the same code everywhere, passing a single string is simplest."
    ]
  },
  {
    kind: "api",
    name: "range.format.wrapText",
    summary: "Toggle text wrapping for a range.",
    languages: {
      javascript: {
        examples: [
          {
            code: "sheet.getRange('A1:D1').format.wrapText = true;",
            summary: "Wrap header text"
          }
        ]
      },
      python: {
        functionName: "range.format.wrap_text",
        examples: [
          {
            code: "sheet.get_range('A1:D1').format.wrap_text = True",
            summary: "Wrap header text"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "range.format.horizontalAlignment",
    summary: "Set horizontal alignment for a range.",
    languages: {
      javascript: {
        examples: [
          {
            code: `sheet.getRange('A1:D1').format.horizontalAlignment = "center";`,
            summary: "Center align a header row"
          }
        ]
      },
      python: {
        functionName: "range.format.horizontal_alignment",
        examples: [
          {
            code: "sheet.get_range('A1:D1').format.horizontal_alignment = 'center'",
            summary: "Center align a header row"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "range.format.autofitColumns",
    summary: "Autofit column widths for a range.",
    languages: {
      javascript: {
        examples: [
          {
            code: "sheet.getRange('A1:D20').format.autofitColumns();",
            summary: "Autofit columns for the range"
          }
        ]
      },
      python: {
        functionName: "range.format.autofit_columns",
        examples: [
          {
            code: "sheet.get_range('A1:D20').format.autofit_columns()",
            summary: "Autofit columns for the range"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "range.format.autofitRows",
    summary: "Autofit row heights for a range.",
    languages: {
      javascript: {
        examples: [
          {
            code: "sheet.getRange('A1:D20').format.autofitRows();",
            summary: "Autofit rows for the range"
          }
        ]
      },
      python: {
        functionName: "range.format.autofit_rows",
        examples: [
          {
            code: "sheet.get_range('A1:D20').format.autofit_rows()",
            summary: "Autofit rows for the range"
          }
        ]
      }
    }
  },
  {
    kind: "api",
    name: "range.format.rowHeight",
    summary: "Set row height (points) for a range.",
    languages: {
      javascript: {
        examples: [
          {
            code: "sheet.getRange('A1:D10').format.rowHeight = 18;",
            summary: "Set row height to 18pt"
          }
        ]
      },
      python: {
        functionName: "range.format.row_height",
        examples: [
          {
            code: "sheet.get_range('A1:D10').format.row_height = 18",
            summary: "Set row height to 18pt"
          }
        ]
      }
    },
    notes: ["Use rowHeightPx for pixel-based layout sizing."]
  },
  {
    kind: "api",
    name: "range.format.rowHeightPx",
    summary: "Set row height (pixels) for a range.",
    languages: {
      javascript: {
        examples: [
          {
            code: "sheet.getRange('A1:D10').format.rowHeightPx = 24;",
            summary: "Set row height to 24px"
          }
        ]
      },
      python: {
        functionName: "range.format.row_height_px",
        examples: [
          {
            code: "sheet.get_range('A1:D10').format.row_height_px = 24",
            summary: "Set row height to 24px"
          }
        ]
      }
    },
    notes: ["Pixels are preferred for layout-sensitive dashboards."]
  },
  {
    kind: "api",
    name: "range.format.columnWidth",
    summary: "Set column width (Excel width units) for a range.",
    languages: {
      javascript: {
        examples: [
          {
            code: "sheet.getRange('A1:D10').format.columnWidth = 2.75;",
            summary: "Set column width to 2.75"
          }
        ]
      },
      python: {
        functionName: "range.format.column_width",
        examples: [
          {
            code: "sheet.get_range('A1:D10').format.column_width = 2.75",
            summary: "Set column width to 2.75"
          }
        ]
      }
    },
    notes: ["Use columnWidthPx for pixel-based layout sizing."]
  },
  {
    kind: "api",
    name: "range.format.columnWidthPx",
    summary: "Set column width (pixels) for a range.",
    languages: {
      javascript: {
        examples: [
          {
            code: "sheet.getRange('A1:D10').format.columnWidthPx = 120;",
            summary: "Set column width to 120px"
          }
        ]
      },
      python: {
        functionName: "range.format.column_width_px",
        examples: [
          {
            code: "sheet.get_range('A1:D10').format.column_width_px = 120",
            summary: "Set column width to 120px"
          }
        ]
      }
    },
    notes: ["Pixels are preferred for layout-sensitive dashboards."]
  }
];

// node_modules/@oai/granola/dist/models/help/normalize-include.js
var normalizeIncludeTokens = (args2) => {
  const tokens = [];
  const tokenSet = new Set;
  const notices = [];
  const supportedSet = new Set(args2.supported);
  const addToken = (token) => {
    if (!tokenSet.has(token)) {
      tokenSet.add(token);
      tokens.push(token);
    }
  };
  const applyDefaults = () => {
    args2.defaults.forEach((token) => addToken(token));
  };
  const requestedList = typeof args2.requested === "string" ? args2.requested.split(/[^A-Za-z0-9-]+/).map((token) => token.trim()).filter(Boolean) : args2.requested;
  if (!requestedList || requestedList.length === 0) {
    applyDefaults();
    return { tokens, tokenSet, notices };
  }
  for (const token of requestedList) {
    const normalized = args2.aliases?.[token] ?? token;
    if (supportedSet.has(normalized)) {
      addToken(normalized);
    } else {
      notices.push(`Unknown include token: ${token}`);
    }
  }
  if (tokens.length === 0) {
    applyDefaults();
  }
  return { tokens, tokenSet, notices };
};

// node_modules/@oai/granola/dist/models/workbook-help.js
var DEFAULT_INCLUDE = ["index", "examples"];
var HELP_INCLUDES = ["index", "examples", "notes"];
var DEFAULT_MAX_CHARS2 = 12000;
var WORKBOOK_API_HELP = [
  ...CHARTS_API_HELP,
  ...CONDITIONAL_FORMATTING_API_HELP,
  ...CORE_WORKBOOK_API_HELP,
  ...DRAWINGS_API_HELP,
  ...FORMULAS_API_HELP,
  ...IMAGES_API_HELP,
  ...INSPECT_API_HELP,
  ...MERGE_API_HELP,
  ...NAMES_API_HELP,
  ...RANGE_FORMATS_API_HELP,
  ...RANGES_API_HELP,
  ...SPARKLINES_API_HELP,
  ...STYLES_API_HELP,
  ...TABLES_API_HELP,
  ...VALIDATION_API_HELP,
  ...WORKSHEETS_API_HELP
];
var buildHelpIndex = (include, language) => [
  ...WORKBOOK_API_HELP.map((entry) => projectApiEntry(entry, include, language)),
  ...WORKBOOK_OP_HELP.map((entry) => projectOpEntry(entry, include)),
  ...WORKBOOK_ENUM_HELP.map((entry) => projectEnumEntry(entry, include)),
  ...formulaMetadata.map((entry) => projectFormulaEntry(entry, include))
];
function searchWorkbookHelp(query, options = {}, language) {
  const includeInfo = normalizeInclude(options.include);
  const revision = generateAidSuffix();
  const records = buildHelpIndex(includeInfo.tokenSet, language);
  const searchRegex = typeof options.search === "string" && options.search.trim().length > 0 ? safeRegex(options.search) : null;
  const scored = records.map((record2) => ({
    record: record2,
    score: scoreHelpRecord(record2, query),
    text: helpRecordToSearchText(record2)
  })).filter(({ score, text: text2 }) => score > 0 && (!searchRegex || searchRegex.test(text2)));
  scored.sort((a, b) => b.score - a.score);
  const limit = typeof options.limit === "number" && Number.isFinite(options.limit) ? Math.max(1, Math.floor(options.limit)) : 10;
  const results = scored.slice(0, limit).map(({ record: record2, score }) => ({
    kind: record2.kind,
    key: getHelpRecordKey(record2),
    score,
    summary: record2.kind === "api" || record2.kind === "op" || record2.kind === "enum" || record2.kind === "formula" ? record2.summary : undefined
  }));
  const notices = [...includeInfo.notices];
  if (searchRegex === null && typeof options.search === "string" && options.search.trim().length > 0) {
    notices.push("Invalid search regex.");
  }
  return {
    revision,
    query,
    results,
    ...notices.length ? { notices } : {}
  };
}
function getWorkbookHelpEntry(key, options = {}, language) {
  const includeInfo = normalizeInclude(options.include);
  const records = buildHelpIndex(includeInfo.tokenSet, language);
  const normalized = key.trim().toLowerCase();
  if (!normalized)
    return null;
  for (const record2 of records) {
    const recordKey = getHelpRecordKey(record2).trim().toLowerCase();
    if (recordKey === normalized)
      return record2;
  }
  return null;
}
function buildWorkbookHelp(query, options = {}, language) {
  const includeInfo = normalizeInclude(options.include);
  const metadata = {
    revision: generateAidSuffix(),
    query,
    include: {
      requested: options.include,
      tokens: includeInfo.tokens
    },
    search: options.search,
    notices: includeInfo.notices
  };
  const recordsIndex = buildHelpIndex(includeInfo.tokenSet, language);
  const trimmedQuery = query.trim();
  const matcher = buildQueryMatcher(trimmedQuery);
  const matchedByName = recordsIndex.filter((record2) => matcher(getHelpRecordKey(record2)));
  const matchedByTag = recordsIndex.filter((record2) => record2.kind === "api" && Array.isArray(record2.tags) && record2.tags.some((tag) => matcher(tag)));
  const matchedByDirect = [
    ...matchedByName,
    ...matchedByTag.filter((record2) => !matchedByName.includes(record2))
  ];
  const shouldRank = /\s/.test(trimmedQuery) || matchedByDirect.length === 0 && trimmedQuery.length > 0 && !trimmedQuery.includes(".") && !trimmedQuery.includes("/") && trimmedQuery !== "*";
  const searchRegex = typeof options.search === "string" && options.search.trim().length > 0 ? safeRegex(options.search) : null;
  if (searchRegex === null && typeof options.search === "string" && options.search.trim().length > 0) {
    metadata.notices ??= [];
    metadata.notices.push("Invalid search regex.");
  }
  let records;
  if (!shouldRank) {
    records = matchedByDirect;
    if (searchRegex) {
      records = records.filter((record2) => record2.kind === "notice" ? true : searchRegex.test(helpRecordToSearchText(record2)));
    }
  } else {
    metadata.notices ??= [];
    metadata.notices.push("Using ranked full-text help search.");
    const scored = recordsIndex.map((record2) => ({
      record: record2,
      score: scoreHelpRecord(record2, trimmedQuery),
      text: helpRecordToSearchText(record2)
    })).filter(({ score, text: text2 }) => score > 0 && (!searchRegex || searchRegex.test(text2)));
    scored.sort((a, b) => b.score - a.score);
    records = scored.map(({ record: record2 }) => record2);
  }
  if (records.length === 0) {
    metadata.notices ??= [];
    metadata.notices.push("Query matched 0 entries");
    records.push({
      kind: "notice",
      message: "Query matched 0 entries."
    });
  }
  const lines = records.map((record2) => JSON.stringify(record2));
  const maxChars = typeof options.maxChars === "number" && Number.isFinite(options.maxChars) ? Math.max(0, Math.floor(options.maxChars)) : DEFAULT_MAX_CHARS2;
  const { ndjson, truncated } = applyHelpTruncation(lines, maxChars);
  return { ndjson, truncated, metadata };
}
var normalizeInclude = (requested) => normalizeIncludeTokens({
  requested,
  supported: HELP_INCLUDES,
  defaults: DEFAULT_INCLUDE,
  aliases: {
    example: "examples"
  }
});

// node_modules/@oai/granola/dist/plugins/workbook-help.js
function installWorkbookHelp(options = {}) {
  const language = options.language ?? "javascript";
  registerWorkbookHelpProvider({
    buildWorkbookHelp: (query, buildOptions) => buildWorkbookHelp(query, buildOptions, language),
    searchWorkbookHelp: (query, searchOptions) => searchWorkbookHelp(query, searchOptions, language),
    getWorkbookHelpEntry: (key, entryOptions) => getWorkbookHelpEntry(key, entryOptions, language)
  });
}

// node_modules/@oai/granola/dist/shapes/preset-shape-definitions.part1.js
var presetShapeDefinitionsPart1 = {
  [114 /* SHAPE_GEOMETRY_ACCENT_BORDER_CALLOUT1 */]: {
    avLst: {
      adj1: "val 18750",
      adj2: "val -8333",
      adj3: "val 112500",
      adj4: "val -38333"
    },
    gdLst: {
      y1: "*/ h adj1 100000",
      x1: "*/ w adj2 100000",
      y2: "*/ h adj3 100000",
      x2: "*/ w adj4 100000"
    },
    ahLst: [
      {
        gdRefX: "adj2",
        gdRefY: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        gdRefX: "adj4",
        gdRefY: "adj3",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x2",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "close"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          }
        ]
      }
    ]
  },
  [115 /* SHAPE_GEOMETRY_ACCENT_BORDER_CALLOUT2 */]: {
    avLst: {
      adj1: "val 18750",
      adj2: "val -8333",
      adj3: "val 18750",
      adj4: "val -16667",
      adj5: "val 112500",
      adj6: "val -46667"
    },
    gdLst: {
      y1: "*/ h adj1 100000",
      x1: "*/ w adj2 100000",
      y2: "*/ h adj3 100000",
      x2: "*/ w adj4 100000",
      y3: "*/ h adj5 100000",
      x3: "*/ w adj6 100000"
    },
    ahLst: [
      {
        gdRefX: "adj2",
        gdRefY: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        gdRefX: "adj4",
        gdRefY: "adj3",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x2",
          y: "y2"
        }
      },
      {
        gdRefX: "adj6",
        gdRefY: "adj5",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x3",
          y: "y3"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "close"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          }
        ]
      }
    ]
  },
  [116 /* SHAPE_GEOMETRY_ACCENT_BORDER_CALLOUT3 */]: {
    avLst: {
      adj1: "val 18750",
      adj2: "val -8333",
      adj3: "val 18750",
      adj4: "val -16667",
      adj5: "val 100000",
      adj6: "val -16667",
      adj7: "val 112963",
      adj8: "val -8333"
    },
    gdLst: {
      y1: "*/ h adj1 100000",
      x1: "*/ w adj2 100000",
      y2: "*/ h adj3 100000",
      x2: "*/ w adj4 100000",
      y3: "*/ h adj5 100000",
      x3: "*/ w adj6 100000",
      y4: "*/ h adj7 100000",
      x4: "*/ w adj8 100000"
    },
    ahLst: [
      {
        gdRefX: "adj2",
        gdRefY: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        gdRefX: "adj4",
        gdRefY: "adj3",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x2",
          y: "y2"
        }
      },
      {
        gdRefX: "adj6",
        gdRefY: "adj5",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x3",
          y: "y3"
        }
      },
      {
        gdRefX: "adj8",
        gdRefY: "adj7",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x4",
          y: "y4"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "close"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y4"
          }
        ]
      }
    ]
  },
  [108 /* SHAPE_GEOMETRY_ACCENT_CALLOUT1 */]: {
    avLst: {
      adj1: "val 18750",
      adj2: "val -8333",
      adj3: "val 112500",
      adj4: "val -38333"
    },
    gdLst: {
      y1: "*/ h adj1 100000",
      x1: "*/ w adj2 100000",
      y2: "*/ h adj3 100000",
      x2: "*/ w adj4 100000"
    },
    ahLst: [
      {
        gdRefX: "adj2",
        gdRefY: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        gdRefX: "adj4",
        gdRefY: "adj3",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x2",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "close"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          }
        ]
      }
    ]
  },
  [109 /* SHAPE_GEOMETRY_ACCENT_CALLOUT2 */]: {
    avLst: {
      adj1: "val 18750",
      adj2: "val -8333",
      adj3: "val 18750",
      adj4: "val -16667",
      adj5: "val 112500",
      adj6: "val -46667"
    },
    gdLst: {
      y1: "*/ h adj1 100000",
      x1: "*/ w adj2 100000",
      y2: "*/ h adj3 100000",
      x2: "*/ w adj4 100000",
      y3: "*/ h adj5 100000",
      x3: "*/ w adj6 100000"
    },
    ahLst: [
      {
        gdRefX: "adj2",
        gdRefY: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        gdRefX: "adj4",
        gdRefY: "adj3",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x2",
          y: "y2"
        }
      },
      {
        gdRefX: "adj6",
        gdRefY: "adj5",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x3",
          y: "y3"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "close"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          }
        ]
      }
    ]
  },
  [110 /* SHAPE_GEOMETRY_ACCENT_CALLOUT3 */]: {
    avLst: {
      adj1: "val 18750",
      adj2: "val -8333",
      adj3: "val 18750",
      adj4: "val -16667",
      adj5: "val 100000",
      adj6: "val -16667",
      adj7: "val 112963",
      adj8: "val -8333"
    },
    gdLst: {
      y1: "*/ h adj1 100000",
      x1: "*/ w adj2 100000",
      y2: "*/ h adj3 100000",
      x2: "*/ w adj4 100000",
      y3: "*/ h adj5 100000",
      x3: "*/ w adj6 100000",
      y4: "*/ h adj7 100000",
      x4: "*/ w adj8 100000"
    },
    ahLst: [
      {
        gdRefX: "adj2",
        gdRefY: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        gdRefX: "adj4",
        gdRefY: "adj3",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x2",
          y: "y2"
        }
      },
      {
        gdRefX: "adj6",
        gdRefY: "adj5",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x3",
          y: "y3"
        }
      },
      {
        gdRefX: "adj8",
        gdRefY: "adj7",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x4",
          y: "y4"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "close"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y4"
          }
        ]
      }
    ]
  },
  [166 /* SHAPE_GEOMETRY_ACTION_BUTTON_BACK_PREVIOUS */]: {
    avLst: {},
    gdLst: {
      dx2: "*/ ss 3 8",
      g9: "+- vc 0 dx2",
      g10: "+- vc dx2 0",
      g11: "+- hc 0 dx2",
      g12: "+- hc dx2 0"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g11",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g10"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darken",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g11",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g10"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g11",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g10"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [168 /* SHAPE_GEOMETRY_ACTION_BUTTON_BEGINNING */]: {
    avLst: {},
    gdLst: {
      dx2: "*/ ss 3 8",
      g9: "+- vc 0 dx2",
      g10: "+- vc dx2 0",
      g11: "+- hc 0 dx2",
      g12: "+- hc dx2 0",
      g13: "*/ ss 3 4",
      g14: "*/ g13 1 8",
      g15: "*/ g13 1 4",
      g16: "+- g11 g14 0",
      g17: "+- g11 g15 0"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g17",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g10"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g16",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g16",
            y: "g10"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darken",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g17",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g10"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g16",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g16",
            y: "g10"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g17",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g10"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g16",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g16",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g9"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [161 /* SHAPE_GEOMETRY_ACTION_BUTTON_BLANK */]: {
    avLst: {},
    gdLst: {},
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [170 /* SHAPE_GEOMETRY_ACTION_BUTTON_DOCUMENT */]: {
    avLst: {},
    gdLst: {
      dx2: "*/ ss 3 8",
      g9: "+- vc 0 dx2",
      g10: "+- vc dx2 0",
      dx1: "*/ ss 9 32",
      g11: "+- hc 0 dx1",
      g12: "+- hc dx1 0",
      g13: "*/ ss 3 16",
      g14: "+- g12 0 g13",
      g15: "+- g9 g13 0"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g11",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g14",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g15"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g10"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darkenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g11",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g14",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g14",
            y: "g15"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g15"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g10"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darken",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g14",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g14",
            y: "g15"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g15"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g11",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g14",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g15"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g10"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g12",
            y: "g15"
          },
          {
            cmd: "lineTo",
            x: "g14",
            y: "g15"
          },
          {
            cmd: "lineTo",
            x: "g14",
            y: "g9"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [167 /* SHAPE_GEOMETRY_ACTION_BUTTON_END */]: {
    avLst: {},
    gdLst: {
      dx2: "*/ ss 3 8",
      g9: "+- vc 0 dx2",
      g10: "+- vc dx2 0",
      g11: "+- hc 0 dx2",
      g12: "+- hc dx2 0",
      g13: "*/ ss 3 4",
      g14: "*/ g13 3 4",
      g15: "*/ g13 7 8",
      g16: "+- g11 g14 0",
      g17: "+- g11 g15 0"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g16",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g10"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g17",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g17",
            y: "g10"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darken",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g16",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g10"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g17",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g17",
            y: "g10"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g16",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g9"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g17",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g17",
            y: "g10"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [165 /* SHAPE_GEOMETRY_ACTION_BUTTON_FORWARD_NEXT */]: {
    avLst: {},
    gdLst: {
      dx2: "*/ ss 3 8",
      g9: "+- vc 0 dx2",
      g10: "+- vc dx2 0",
      g11: "+- hc 0 dx2",
      g12: "+- hc dx2 0"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g12",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g10"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darken",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g12",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g10"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g12",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g9"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [163 /* SHAPE_GEOMETRY_ACTION_BUTTON_HELP */]: {
    avLst: {},
    gdLst: {
      dx2: "*/ ss 3 8",
      g9: "+- vc 0 dx2",
      g11: "+- hc 0 dx2",
      g13: "*/ ss 3 4",
      g14: "*/ g13 1 7",
      g15: "*/ g13 3 14",
      g16: "*/ g13 2 7",
      g19: "*/ g13 3 7",
      g20: "*/ g13 4 7",
      g21: "*/ g13 17 28",
      g23: "*/ g13 21 28",
      g24: "*/ g13 11 14",
      g27: "+- g9 g16 0",
      g29: "+- g9 g21 0",
      g30: "+- g9 g23 0",
      g31: "+- g9 g24 0",
      g33: "+- g11 g15 0",
      g36: "+- g11 g19 0",
      g37: "+- g11 g20 0",
      g41: "*/ g13 1 14",
      g42: "*/ g13 3 28"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g33",
            y: "g27"
          },
          {
            cmd: "arcTo",
            wR: "g16",
            hR: "g16",
            stAng: "cd2",
            swAng: "cd2"
          },
          {
            cmd: "arcTo",
            wR: "g14",
            hR: "g15",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "g41",
            hR: "g42",
            stAng: "3cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "g37",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g36",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g36",
            y: "g29"
          },
          {
            cmd: "arcTo",
            wR: "g14",
            hR: "g15",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "g41",
            hR: "g42",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "arcTo",
            wR: "g14",
            hR: "g14",
            stAng: "0",
            swAng: "-10800000"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "hc",
            y: "g31"
          },
          {
            cmd: "arcTo",
            wR: "g42",
            hR: "g42",
            stAng: "3cd4",
            swAng: "21600000"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darken",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g33",
            y: "g27"
          },
          {
            cmd: "arcTo",
            wR: "g16",
            hR: "g16",
            stAng: "cd2",
            swAng: "cd2"
          },
          {
            cmd: "arcTo",
            wR: "g14",
            hR: "g15",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "g41",
            hR: "g42",
            stAng: "3cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "g37",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g36",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g36",
            y: "g29"
          },
          {
            cmd: "arcTo",
            wR: "g14",
            hR: "g15",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "g41",
            hR: "g42",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "arcTo",
            wR: "g14",
            hR: "g14",
            stAng: "0",
            swAng: "-10800000"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "hc",
            y: "g31"
          },
          {
            cmd: "arcTo",
            wR: "g42",
            hR: "g42",
            stAng: "3cd4",
            swAng: "21600000"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g33",
            y: "g27"
          },
          {
            cmd: "arcTo",
            wR: "g16",
            hR: "g16",
            stAng: "cd2",
            swAng: "cd2"
          },
          {
            cmd: "arcTo",
            wR: "g14",
            hR: "g15",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "g41",
            hR: "g42",
            stAng: "3cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "g37",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g36",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g36",
            y: "g29"
          },
          {
            cmd: "arcTo",
            wR: "g14",
            hR: "g15",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "g41",
            hR: "g42",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "arcTo",
            wR: "g14",
            hR: "g14",
            stAng: "0",
            swAng: "-10800000"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "hc",
            y: "g31"
          },
          {
            cmd: "arcTo",
            wR: "g42",
            hR: "g42",
            stAng: "3cd4",
            swAng: "21600000"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [162 /* SHAPE_GEOMETRY_ACTION_BUTTON_HOME */]: {
    avLst: {},
    gdLst: {
      dx2: "*/ ss 3 8",
      g9: "+- vc 0 dx2",
      g10: "+- vc dx2 0",
      g11: "+- hc 0 dx2",
      g12: "+- hc dx2 0",
      g13: "*/ ss 3 4",
      g14: "*/ g13 1 16",
      g15: "*/ g13 1 8",
      g16: "*/ g13 3 16",
      g17: "*/ g13 5 16",
      g18: "*/ g13 7 16",
      g19: "*/ g13 9 16",
      g20: "*/ g13 11 16",
      g21: "*/ g13 3 4",
      g22: "*/ g13 13 16",
      g23: "*/ g13 7 8",
      g24: "+- g9 g14 0",
      g25: "+- g9 g16 0",
      g26: "+- g9 g17 0",
      g27: "+- g9 g21 0",
      g28: "+- g11 g15 0",
      g29: "+- g11 g18 0",
      g30: "+- g11 g19 0",
      g31: "+- g11 g20 0",
      g32: "+- g11 g22 0",
      g33: "+- g11 g23 0"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "hc",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g28",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g28",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g33",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g33",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g26"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g24"
          },
          {
            cmd: "lineTo",
            x: "g31",
            y: "g24"
          },
          {
            cmd: "lineTo",
            x: "g31",
            y: "g25"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darkenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g32",
            y: "g26"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g24"
          },
          {
            cmd: "lineTo",
            x: "g31",
            y: "g24"
          },
          {
            cmd: "lineTo",
            x: "g31",
            y: "g25"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g28",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g28",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g29",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g29",
            y: "g27"
          },
          {
            cmd: "lineTo",
            x: "g30",
            y: "g27"
          },
          {
            cmd: "lineTo",
            x: "g30",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g33",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g33",
            y: "vc"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darken",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "hc",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "vc"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g29",
            y: "g27"
          },
          {
            cmd: "lineTo",
            x: "g30",
            y: "g27"
          },
          {
            cmd: "lineTo",
            x: "g30",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g29",
            y: "g10"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "hc",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g31",
            y: "g25"
          },
          {
            cmd: "lineTo",
            x: "g31",
            y: "g24"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g24"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g26"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g33",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g33",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g28",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g28",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "vc"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g31",
            y: "g25"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g26"
          },
          {
            cmd: "moveTo",
            x: "g33",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g28",
            y: "vc"
          },
          {
            cmd: "moveTo",
            x: "g29",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g29",
            y: "g27"
          },
          {
            cmd: "lineTo",
            x: "g30",
            y: "g27"
          },
          {
            cmd: "lineTo",
            x: "g30",
            y: "g10"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [164 /* SHAPE_GEOMETRY_ACTION_BUTTON_INFORMATION */]: {
    avLst: {},
    gdLst: {
      dx2: "*/ ss 3 8",
      g9: "+- vc 0 dx2",
      g11: "+- hc 0 dx2",
      g13: "*/ ss 3 4",
      g14: "*/ g13 1 32",
      g17: "*/ g13 5 16",
      g18: "*/ g13 3 8",
      g19: "*/ g13 13 32",
      g20: "*/ g13 19 32",
      g22: "*/ g13 11 16",
      g23: "*/ g13 13 16",
      g24: "*/ g13 7 8",
      g25: "+- g9 g14 0",
      g28: "+- g9 g17 0",
      g29: "+- g9 g18 0",
      g30: "+- g9 g23 0",
      g31: "+- g9 g24 0",
      g32: "+- g11 g17 0",
      g34: "+- g11 g19 0",
      g35: "+- g11 g20 0",
      g37: "+- g11 g22 0",
      g38: "*/ g13 3 32"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "hc",
            y: "g9"
          },
          {
            cmd: "arcTo",
            wR: "dx2",
            hR: "dx2",
            stAng: "3cd4",
            swAng: "21600000"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darken",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "hc",
            y: "g9"
          },
          {
            cmd: "arcTo",
            wR: "dx2",
            hR: "dx2",
            stAng: "3cd4",
            swAng: "21600000"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "hc",
            y: "g25"
          },
          {
            cmd: "arcTo",
            wR: "g38",
            hR: "g38",
            stAng: "3cd4",
            swAng: "21600000"
          },
          {
            cmd: "moveTo",
            x: "g32",
            y: "g28"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g29"
          },
          {
            cmd: "lineTo",
            x: "g34",
            y: "g29"
          },
          {
            cmd: "lineTo",
            x: "g34",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g31"
          },
          {
            cmd: "lineTo",
            x: "g37",
            y: "g31"
          },
          {
            cmd: "lineTo",
            x: "g37",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g28"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "lighten",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "hc",
            y: "g25"
          },
          {
            cmd: "arcTo",
            wR: "g38",
            hR: "g38",
            stAng: "3cd4",
            swAng: "21600000"
          },
          {
            cmd: "moveTo",
            x: "g32",
            y: "g28"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g28"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g37",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g37",
            y: "g31"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g31"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g34",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g34",
            y: "g29"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g29"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "hc",
            y: "g9"
          },
          {
            cmd: "arcTo",
            wR: "dx2",
            hR: "dx2",
            stAng: "3cd4",
            swAng: "21600000"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "hc",
            y: "g25"
          },
          {
            cmd: "arcTo",
            wR: "g38",
            hR: "g38",
            stAng: "3cd4",
            swAng: "21600000"
          },
          {
            cmd: "moveTo",
            x: "g32",
            y: "g28"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g28"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g37",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g37",
            y: "g31"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g31"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g34",
            y: "g30"
          },
          {
            cmd: "lineTo",
            x: "g34",
            y: "g29"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g29"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [172 /* SHAPE_GEOMETRY_ACTION_BUTTON_MOVIE */]: {
    avLst: {},
    gdLst: {
      dx2: "*/ ss 3 8",
      g9: "+- vc 0 dx2",
      g10: "+- vc dx2 0",
      g11: "+- hc 0 dx2",
      g12: "+- hc dx2 0",
      g13: "*/ ss 3 4",
      g14: "*/ g13 1455 21600",
      g15: "*/ g13 1905 21600",
      g16: "*/ g13 2325 21600",
      g17: "*/ g13 16155 21600",
      g18: "*/ g13 17010 21600",
      g19: "*/ g13 19335 21600",
      g20: "*/ g13 19725 21600",
      g21: "*/ g13 20595 21600",
      g22: "*/ g13 5280 21600",
      g23: "*/ g13 5730 21600",
      g24: "*/ g13 6630 21600",
      g25: "*/ g13 7492 21600",
      g26: "*/ g13 9067 21600",
      g27: "*/ g13 9555 21600",
      g28: "*/ g13 13342 21600",
      g29: "*/ g13 14580 21600",
      g30: "*/ g13 15592 21600",
      g31: "+- g11 g14 0",
      g32: "+- g11 g15 0",
      g33: "+- g11 g16 0",
      g34: "+- g11 g17 0",
      g35: "+- g11 g18 0",
      g36: "+- g11 g19 0",
      g37: "+- g11 g20 0",
      g38: "+- g11 g21 0",
      g39: "+- g9 g22 0",
      g40: "+- g9 g23 0",
      g41: "+- g9 g24 0",
      g42: "+- g9 g25 0",
      g43: "+- g9 g26 0",
      g44: "+- g9 g27 0",
      g45: "+- g9 g28 0",
      g46: "+- g9 g29 0",
      g47: "+- g9 g30 0",
      g48: "+- g9 g31 0"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g11",
            y: "g39"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g44"
          },
          {
            cmd: "lineTo",
            x: "g31",
            y: "g44"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g43"
          },
          {
            cmd: "lineTo",
            x: "g33",
            y: "g43"
          },
          {
            cmd: "lineTo",
            x: "g33",
            y: "g47"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g47"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g45"
          },
          {
            cmd: "lineTo",
            x: "g36",
            y: "g45"
          },
          {
            cmd: "lineTo",
            x: "g38",
            y: "g46"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g46"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g41"
          },
          {
            cmd: "lineTo",
            x: "g38",
            y: "g41"
          },
          {
            cmd: "lineTo",
            x: "g37",
            y: "g42"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g42"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g41"
          },
          {
            cmd: "lineTo",
            x: "g34",
            y: "g40"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g40"
          },
          {
            cmd: "lineTo",
            x: "g31",
            y: "g39"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darken",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g11",
            y: "g39"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g44"
          },
          {
            cmd: "lineTo",
            x: "g31",
            y: "g44"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g43"
          },
          {
            cmd: "lineTo",
            x: "g33",
            y: "g43"
          },
          {
            cmd: "lineTo",
            x: "g33",
            y: "g47"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g47"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g45"
          },
          {
            cmd: "lineTo",
            x: "g36",
            y: "g45"
          },
          {
            cmd: "lineTo",
            x: "g38",
            y: "g46"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g46"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g41"
          },
          {
            cmd: "lineTo",
            x: "g38",
            y: "g41"
          },
          {
            cmd: "lineTo",
            x: "g37",
            y: "g42"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g42"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g41"
          },
          {
            cmd: "lineTo",
            x: "g34",
            y: "g40"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g40"
          },
          {
            cmd: "lineTo",
            x: "g31",
            y: "g39"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g11",
            y: "g39"
          },
          {
            cmd: "lineTo",
            x: "g31",
            y: "g39"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g40"
          },
          {
            cmd: "lineTo",
            x: "g34",
            y: "g40"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g41"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g42"
          },
          {
            cmd: "lineTo",
            x: "g37",
            y: "g42"
          },
          {
            cmd: "lineTo",
            x: "g38",
            y: "g41"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g41"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g46"
          },
          {
            cmd: "lineTo",
            x: "g38",
            y: "g46"
          },
          {
            cmd: "lineTo",
            x: "g36",
            y: "g45"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g45"
          },
          {
            cmd: "lineTo",
            x: "g35",
            y: "g47"
          },
          {
            cmd: "lineTo",
            x: "g33",
            y: "g47"
          },
          {
            cmd: "lineTo",
            x: "g33",
            y: "g43"
          },
          {
            cmd: "lineTo",
            x: "g32",
            y: "g43"
          },
          {
            cmd: "lineTo",
            x: "g31",
            y: "g44"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g44"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [169 /* SHAPE_GEOMETRY_ACTION_BUTTON_RETURN */]: {
    avLst: {},
    gdLst: {
      dx2: "*/ ss 3 8",
      g9: "+- vc 0 dx2",
      g10: "+- vc dx2 0",
      g11: "+- hc 0 dx2",
      g12: "+- hc dx2 0",
      g13: "*/ ss 3 4",
      g14: "*/ g13 7 8",
      g15: "*/ g13 3 4",
      g16: "*/ g13 5 8",
      g17: "*/ g13 3 8",
      g18: "*/ g13 1 4",
      g19: "+- g9 g15 0",
      g20: "+- g9 g16 0",
      g21: "+- g9 g18 0",
      g22: "+- g11 g14 0",
      g23: "+- g11 g15 0",
      g24: "+- g11 g16 0",
      g25: "+- g11 g17 0",
      g26: "+- g11 g18 0",
      g27: "*/ g13 1 8"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g12",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g23",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g24",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g24",
            y: "g20"
          },
          {
            cmd: "arcTo",
            wR: "g27",
            hR: "g27",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "g25",
            y: "g19"
          },
          {
            cmd: "arcTo",
            wR: "g27",
            hR: "g27",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "g26",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g20"
          },
          {
            cmd: "arcTo",
            wR: "g17",
            hR: "g17",
            stAng: "cd2",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "g10"
          },
          {
            cmd: "arcTo",
            wR: "g17",
            hR: "g17",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "g22",
            y: "g21"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darken",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g12",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g23",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g24",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g24",
            y: "g20"
          },
          {
            cmd: "arcTo",
            wR: "g27",
            hR: "g27",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "g25",
            y: "g19"
          },
          {
            cmd: "arcTo",
            wR: "g27",
            hR: "g27",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "g26",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g20"
          },
          {
            cmd: "arcTo",
            wR: "g17",
            hR: "g17",
            stAng: "cd2",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "g10"
          },
          {
            cmd: "arcTo",
            wR: "g17",
            hR: "g17",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "g22",
            y: "g21"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g12",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g22",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g22",
            y: "g20"
          },
          {
            cmd: "arcTo",
            wR: "g17",
            hR: "g17",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "g25",
            y: "g10"
          },
          {
            cmd: "arcTo",
            wR: "g17",
            hR: "g17",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g26",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g26",
            y: "g20"
          },
          {
            cmd: "arcTo",
            wR: "g27",
            hR: "g27",
            stAng: "cd2",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "g19"
          },
          {
            cmd: "arcTo",
            wR: "g27",
            hR: "g27",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "g24",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g23",
            y: "g9"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [171 /* SHAPE_GEOMETRY_ACTION_BUTTON_SOUND */]: {
    avLst: {},
    gdLst: {
      dx2: "*/ ss 3 8",
      g9: "+- vc 0 dx2",
      g10: "+- vc dx2 0",
      g11: "+- hc 0 dx2",
      g12: "+- hc dx2 0",
      g13: "*/ ss 3 4",
      g14: "*/ g13 1 8",
      g15: "*/ g13 5 16",
      g16: "*/ g13 5 8",
      g17: "*/ g13 11 16",
      g18: "*/ g13 3 4",
      g19: "*/ g13 7 8",
      g20: "+- g9 g14 0",
      g21: "+- g9 g15 0",
      g22: "+- g9 g17 0",
      g23: "+- g9 g19 0",
      g24: "+- g11 g15 0",
      g25: "+- g11 g16 0",
      g26: "+- g11 g18 0"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g11",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g22"
          },
          {
            cmd: "lineTo",
            x: "g24",
            y: "g22"
          },
          {
            cmd: "lineTo",
            x: "g25",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g25",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g24",
            y: "g21"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darken",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g11",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g22"
          },
          {
            cmd: "lineTo",
            x: "g24",
            y: "g22"
          },
          {
            cmd: "lineTo",
            x: "g25",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g25",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g24",
            y: "g21"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "g11",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g24",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g25",
            y: "g9"
          },
          {
            cmd: "lineTo",
            x: "g25",
            y: "g10"
          },
          {
            cmd: "lineTo",
            x: "g24",
            y: "g22"
          },
          {
            cmd: "lineTo",
            x: "g11",
            y: "g22"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "g26",
            y: "g21"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g20"
          },
          {
            cmd: "moveTo",
            x: "g26",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "vc"
          },
          {
            cmd: "moveTo",
            x: "g26",
            y: "g22"
          },
          {
            cmd: "lineTo",
            x: "g12",
            y: "g23"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [89 /* SHAPE_GEOMETRY_ARC */]: {
    avLst: {
      adj1: "val 16200000",
      adj2: "val 0"
    },
    gdLst: {
      stAng: "pin 0 adj1 21599999",
      enAng: "pin 0 adj2 21599999",
      sw11: "+- enAng 0 stAng",
      sw12: "+- sw11 21600000 0",
      swAng: "?: sw11 sw11 sw12",
      wt1: "sin wd2 stAng",
      ht1: "cos hd2 stAng",
      dx1: "cat2 wd2 ht1 wt1",
      dy1: "sat2 hd2 ht1 wt1",
      wt2: "sin wd2 enAng",
      ht2: "cos hd2 enAng",
      dx2: "cat2 wd2 ht2 wt2",
      dy2: "sat2 hd2 ht2 wt2",
      x1: "+- hc dx1 0",
      y1: "+- vc dy1 0",
      x2: "+- hc dx2 0",
      y2: "+- vc dy2 0",
      sw0: "+- 21600000 0 stAng",
      da1: "+- swAng 0 sw0",
      g1: "max x1 x2",
      ir: "?: da1 r g1",
      sw1: "+- cd4 0 stAng",
      sw2: "+- 27000000 0 stAng",
      sw3: "?: sw1 sw1 sw2",
      da2: "+- swAng 0 sw3",
      g5: "max y1 y2",
      ib: "?: da2 b g5",
      sw4: "+- cd2 0 stAng",
      sw5: "+- 32400000 0 stAng",
      sw6: "?: sw4 sw4 sw5",
      da3: "+- swAng 0 sw6",
      g9: "min x1 x2",
      il: "?: da3 l g9",
      sw7: "+- 3cd4 0 stAng",
      sw8: "+- 37800000 0 stAng",
      sw9: "?: sw7 sw7 sw8",
      da4: "+- swAng 0 sw9",
      g13: "min y1 y2",
      it: "?: da4 t g13",
      cang1: "+- stAng 0 cd4",
      cang2: "+- enAng cd4 0",
      cang3: "+/ cang1 cang2 2"
    },
    ahLst: [
      {
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        pos: {
          x: "x2",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "cang1",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        ang: "cang3",
        pos: {
          x: "hc",
          y: "vc"
        }
      },
      {
        ang: "cang2",
        pos: {
          x: "x2",
          y: "y2"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "stAng",
            swAng: "swAng"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "vc"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "stAng",
            swAng: "swAng"
          }
        ]
      }
    ]
  },
  [63 /* SHAPE_GEOMETRY_BENT_ARROW */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 25000",
      adj3: "val 25000",
      adj4: "val 43750"
    },
    gdLst: {
      a2: "pin 0 adj2 50000",
      maxAdj1: "*/ a2 2 1",
      a1: "pin 0 adj1 maxAdj1",
      a3: "pin 0 adj3 50000",
      th: "*/ ss a1 100000",
      aw2: "*/ ss a2 100000",
      th2: "*/ th 1 2",
      dh2: "+- aw2 0 th2",
      ah: "*/ ss a3 100000",
      bw: "+- r 0 ah",
      bh: "+- b 0 dh2",
      bs: "min bw bh",
      maxAdj4: "*/ 100000 bs ss",
      a4: "pin 0 adj4 maxAdj4",
      bd: "*/ ss a4 100000",
      bd3: "+- bd 0 th",
      bd2: "max bd3 0",
      x3: "+- th bd2 0",
      x4: "+- r 0 ah",
      y3: "+- dh2 th 0",
      y4: "+- y3 dh2 0",
      y5: "+- dh2 bd 0",
      y6: "+- y3 bd2 0"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "maxAdj1",
        pos: {
          x: "th",
          y: "b"
        }
      },
      {
        gdRefY: "adj2",
        minY: "0",
        maxY: "50000",
        pos: {
          x: "r",
          y: "y4"
        }
      },
      {
        gdRefX: "adj3",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x4",
          y: "t"
        }
      },
      {
        gdRefX: "adj4",
        minX: "0",
        maxX: "maxAdj4",
        pos: {
          x: "bd",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x4",
          y: "t"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x4",
          y: "y4"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "th2",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "aw2"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y5"
          },
          {
            cmd: "arcTo",
            wR: "bd",
            hR: "bd",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "dh2"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "aw2"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          },
          {
            cmd: "arcTo",
            wR: "bd2",
            hR: "bd2",
            stAng: "3cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "th",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [97 /* SHAPE_GEOMETRY_BENT_CONNECTOR2 */]: {
    avLst: {},
    gdLst: {},
    ahLst: [],
    cxnLst: [],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          }
        ]
      }
    ]
  },
  [98 /* SHAPE_GEOMETRY_BENT_CONNECTOR3 */]: {
    avLst: {
      adj1: "val 50000"
    },
    gdLst: {
      x1: "*/ w adj1 100000"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        pos: {
          x: "x1",
          y: "vc"
        }
      }
    ],
    cxnLst: [],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          }
        ]
      }
    ]
  },
  [99 /* SHAPE_GEOMETRY_BENT_CONNECTOR4 */]: {
    avLst: {
      adj1: "val 50000",
      adj2: "val 50000"
    },
    gdLst: {
      x1: "*/ w adj1 100000",
      x2: "+/ x1 r 2",
      y2: "*/ h adj2 100000",
      y1: "+/ t y2 2"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        gdRefY: "adj2",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x2",
          y: "y2"
        }
      }
    ],
    cxnLst: [],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          }
        ]
      }
    ]
  },
  [100 /* SHAPE_GEOMETRY_BENT_CONNECTOR5 */]: {
    avLst: {
      adj1: "val 50000",
      adj2: "val 50000",
      adj3: "val 50000"
    },
    gdLst: {
      x1: "*/ w adj1 100000",
      x3: "*/ w adj3 100000",
      x2: "+/ x1 x3 2",
      y2: "*/ h adj2 100000",
      y1: "+/ t y2 2",
      y3: "+/ b y2 2"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        gdRefY: "adj2",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x2",
          y: "y2"
        }
      },
      {
        gdRefX: "adj3",
        minX: "-2147483647",
        maxX: "2147483647",
        pos: {
          x: "x3",
          y: "y3"
        }
      }
    ],
    cxnLst: [],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          }
        ]
      }
    ]
  },
  [50 /* SHAPE_GEOMETRY_BENT_UP_ARROW */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 25000",
      adj3: "val 25000"
    },
    gdLst: {
      a1: "pin 0 adj1 50000",
      a2: "pin 0 adj2 50000",
      a3: "pin 0 adj3 50000",
      y1: "*/ ss a3 100000",
      dx1: "*/ ss a2 50000",
      x1: "+- r 0 dx1",
      dx3: "*/ ss a2 100000",
      x3: "+- r 0 dx3",
      dx2: "*/ ss a1 200000",
      x2: "+- x3 0 dx2",
      x4: "+- x3 dx2 0",
      dy2: "*/ ss a1 100000",
      y2: "+- b 0 dy2",
      x0: "*/ x4 1 2",
      y3: "+/ y2 b 2",
      y15: "+/ y1 b 2"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "50000",
        pos: {
          x: "l",
          y: "y2"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x1",
          y: "t"
        }
      },
      {
        gdRefY: "adj3",
        minY: "0",
        maxY: "50000",
        pos: {
          x: "x2",
          y: "y1"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x3",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y3"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x0",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x4",
          y: "y15"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "l",
      t: "y2",
      r: "x4",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [83 /* SHAPE_GEOMETRY_BEVEL */]: {
    avLst: {
      adj: "val 12500"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      x1: "*/ ss a 100000",
      x2: "+- r 0 x1",
      y2: "+- b 0 x1"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x1",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x2",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "y2"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "x1"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "x1",
      r: "x2",
      b: "y2"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "lightenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "x1"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darkenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "lighten",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darken",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "x1"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x1",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "x1"
          },
          {
            cmd: "moveTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "moveTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "x1"
          },
          {
            cmd: "moveTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          }
        ]
      }
    ]
  },
  [41 /* SHAPE_GEOMETRY_BLOCK_ARC */]: {
    avLst: {
      adj1: "val 10800000",
      adj2: "val 0",
      adj3: "val 25000"
    },
    gdLst: {
      stAng: "pin 0 adj1 21599999",
      istAng: "pin 0 adj2 21599999",
      a3: "pin 0 adj3 50000",
      sw11: "+- istAng 0 stAng",
      sw12: "+- sw11 21600000 0",
      swAng: "?: sw11 sw11 sw12",
      iswAng: "+- 0 0 swAng",
      wt1: "sin wd2 stAng",
      ht1: "cos hd2 stAng",
      wt3: "sin wd2 istAng",
      ht3: "cos hd2 istAng",
      dx1: "cat2 wd2 ht1 wt1",
      dy1: "sat2 hd2 ht1 wt1",
      dx3: "cat2 wd2 ht3 wt3",
      dy3: "sat2 hd2 ht3 wt3",
      x1: "+- hc dx1 0",
      y1: "+- vc dy1 0",
      x3: "+- hc dx3 0",
      y3: "+- vc dy3 0",
      dr: "*/ ss a3 100000",
      iwd2: "+- wd2 0 dr",
      ihd2: "+- hd2 0 dr",
      wt2: "sin iwd2 istAng",
      ht2: "cos ihd2 istAng",
      wt4: "sin iwd2 stAng",
      ht4: "cos ihd2 stAng",
      dx2: "cat2 iwd2 ht2 wt2",
      dy2: "sat2 ihd2 ht2 wt2",
      dx4: "cat2 iwd2 ht4 wt4",
      dy4: "sat2 ihd2 ht4 wt4",
      x2: "+- hc dx2 0",
      y2: "+- vc dy2 0",
      x4: "+- hc dx4 0",
      y4: "+- vc dy4 0",
      sw0: "+- 21600000 0 stAng",
      da1: "+- swAng 0 sw0",
      g1: "max x1 x2",
      g2: "max x3 x4",
      g3: "max g1 g2",
      ir: "?: da1 r g3",
      sw1: "+- cd4 0 stAng",
      sw2: "+- 27000000 0 stAng",
      sw3: "?: sw1 sw1 sw2",
      da2: "+- swAng 0 sw3",
      g5: "max y1 y2",
      g6: "max y3 y4",
      g7: "max g5 g6",
      ib: "?: da2 b g7",
      sw4: "+- cd2 0 stAng",
      sw5: "+- 32400000 0 stAng",
      sw6: "?: sw4 sw4 sw5",
      da3: "+- swAng 0 sw6",
      g9: "min x1 x2",
      g10: "min x3 x4",
      g11: "min g9 g10",
      il: "?: da3 l g11",
      sw7: "+- 3cd4 0 stAng",
      sw8: "+- 37800000 0 stAng",
      sw9: "?: sw7 sw7 sw8",
      da4: "+- swAng 0 sw9",
      g13: "min y1 y2",
      g14: "min y3 y4",
      g15: "min g13 g14",
      it: "?: da4 t g15",
      x5: "+/ x1 x4 2",
      y5: "+/ y1 y4 2",
      x6: "+/ x3 x2 2",
      y6: "+/ y3 y2 2",
      cang1: "+- stAng 0 cd4",
      cang2: "+- istAng cd4 0",
      cang3: "+/ cang1 cang2 2"
    },
    ahLst: [
      {
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        pos: {
          x: "x2",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "cang1",
        pos: {
          x: "x5",
          y: "y5"
        }
      },
      {
        ang: "cang2",
        pos: {
          x: "x6",
          y: "y6"
        }
      },
      {
        ang: "cang3",
        pos: {
          x: "hc",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "stAng",
            swAng: "swAng"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "iwd2",
            hR: "ihd2",
            stAng: "istAng",
            swAng: "iswAng"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [111 /* SHAPE_GEOMETRY_BORDER_CALLOUT1 */]: {
    avLst: {
      adj1: "val 18750",
      adj2: "val -8333",
      adj3: "val 112500",
      adj4: "val -38333"
    },
    gdLst: {
      y1: "*/ h adj1 100000",
      x1: "*/ w adj2 100000",
      y2: "*/ h adj3 100000",
      x2: "*/ w adj4 100000"
    },
    ahLst: [
      {
        gdRefX: "adj2",
        gdRefY: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        gdRefX: "adj4",
        gdRefY: "adj3",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x2",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          }
        ]
      }
    ]
  },
  [112 /* SHAPE_GEOMETRY_BORDER_CALLOUT2 */]: {
    avLst: {
      adj1: "val 18750",
      adj2: "val -8333",
      adj3: "val 18750",
      adj4: "val -16667",
      adj5: "val 112500",
      adj6: "val -46667"
    },
    gdLst: {
      y1: "*/ h adj1 100000",
      x1: "*/ w adj2 100000",
      y2: "*/ h adj3 100000",
      x2: "*/ w adj4 100000",
      y3: "*/ h adj5 100000",
      x3: "*/ w adj6 100000"
    },
    ahLst: [
      {
        gdRefX: "adj2",
        gdRefY: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        gdRefX: "adj4",
        gdRefY: "adj3",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x2",
          y: "y2"
        }
      },
      {
        gdRefX: "adj6",
        gdRefY: "adj5",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x3",
          y: "y3"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          }
        ]
      }
    ]
  },
  [113 /* SHAPE_GEOMETRY_BORDER_CALLOUT3 */]: {
    avLst: {
      adj1: "val 18750",
      adj2: "val -8333",
      adj3: "val 18750",
      adj4: "val -16667",
      adj5: "val 100000",
      adj6: "val -16667",
      adj7: "val 112963",
      adj8: "val -8333"
    },
    gdLst: {
      y1: "*/ h adj1 100000",
      x1: "*/ w adj2 100000",
      y2: "*/ h adj3 100000",
      x2: "*/ w adj4 100000",
      y3: "*/ h adj5 100000",
      x3: "*/ w adj6 100000",
      y4: "*/ h adj7 100000",
      x4: "*/ w adj8 100000"
    },
    ahLst: [
      {
        gdRefX: "adj2",
        gdRefY: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        gdRefX: "adj4",
        gdRefY: "adj3",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x2",
          y: "y2"
        }
      },
      {
        gdRefX: "adj6",
        gdRefY: "adj5",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x3",
          y: "y3"
        }
      },
      {
        gdRefX: "adj8",
        gdRefY: "adj7",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x4",
          y: "y4"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y4"
          }
        ]
      }
    ]
  },
  [95 /* SHAPE_GEOMETRY_BRACE_PAIR */]: {
    avLst: {
      adj: "val 8333"
    },
    gdLst: {
      a: "pin 0 adj 25000",
      x1: "*/ ss a 100000",
      x2: "*/ ss a 50000",
      x3: "+- r 0 x2",
      x4: "+- r 0 x1",
      y2: "+- vc 0 x1",
      y3: "+- vc x1 0",
      y4: "+- b 0 x1",
      it: "*/ x1 29289 100000",
      il: "+- x1 it 0",
      ir: "+- r 0 il",
      ib: "+- b 0 it"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "25000",
        pos: {
          x: "l",
          y: "x1"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "il",
      t: "il",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x2",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y3"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "0",
            swAng: "-5400000"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "x1"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd2",
            swAng: "-5400000"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "3cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y4"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x2",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y3"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "0",
            swAng: "-5400000"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "x1"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "moveTo",
            x: "x3",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd2",
            swAng: "-5400000"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "3cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y4"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "0",
            swAng: "cd4"
          }
        ]
      }
    ]
  },
  [94 /* SHAPE_GEOMETRY_BRACKET_PAIR */]: {
    avLst: {
      adj: "val 16667"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      x1: "*/ ss a 100000",
      x2: "+- r 0 x1",
      y2: "+- b 0 x1",
      il: "*/ x1 29289 100000",
      ir: "+- r 0 il",
      ib: "+- b 0 il"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "50000",
        pos: {
          x: "l",
          y: "x1"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "il",
      t: "il",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "x1"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "x1"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "moveTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "0",
            swAng: "cd4"
          }
        ]
      }
    ]
  },
  [105 /* SHAPE_GEOMETRY_CALLOUT1 */]: {
    avLst: {
      adj1: "val 18750",
      adj2: "val -8333",
      adj3: "val 112500",
      adj4: "val -38333"
    },
    gdLst: {
      y1: "*/ h adj1 100000",
      x1: "*/ w adj2 100000",
      y2: "*/ h adj3 100000",
      x2: "*/ w adj4 100000"
    },
    ahLst: [
      {
        gdRefX: "adj2",
        gdRefY: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        gdRefX: "adj4",
        gdRefY: "adj3",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x2",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          }
        ]
      }
    ]
  },
  [106 /* SHAPE_GEOMETRY_CALLOUT2 */]: {
    avLst: {
      adj1: "val 18750",
      adj2: "val -8333",
      adj3: "val 18750",
      adj4: "val -16667",
      adj5: "val 112500",
      adj6: "val -46667"
    },
    gdLst: {
      y1: "*/ h adj1 100000",
      x1: "*/ w adj2 100000",
      y2: "*/ h adj3 100000",
      x2: "*/ w adj4 100000",
      y3: "*/ h adj5 100000",
      x3: "*/ w adj6 100000"
    },
    ahLst: [
      {
        gdRefX: "adj2",
        gdRefY: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        gdRefX: "adj4",
        gdRefY: "adj3",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x2",
          y: "y2"
        }
      },
      {
        gdRefX: "adj6",
        gdRefY: "adj5",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x3",
          y: "y3"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          }
        ]
      }
    ]
  },
  [107 /* SHAPE_GEOMETRY_CALLOUT3 */]: {
    avLst: {
      adj1: "val 18750",
      adj2: "val -8333",
      adj3: "val 18750",
      adj4: "val -16667",
      adj5: "val 100000",
      adj6: "val -16667",
      adj7: "val 112963",
      adj8: "val -8333"
    },
    gdLst: {
      y1: "*/ h adj1 100000",
      x1: "*/ w adj2 100000",
      y2: "*/ h adj3 100000",
      x2: "*/ w adj4 100000",
      y3: "*/ h adj5 100000",
      x3: "*/ w adj6 100000",
      y4: "*/ h adj7 100000",
      x4: "*/ w adj8 100000"
    },
    ahLst: [
      {
        gdRefX: "adj2",
        gdRefY: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        gdRefX: "adj4",
        gdRefY: "adj3",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x2",
          y: "y2"
        }
      },
      {
        gdRefX: "adj6",
        gdRefY: "adj5",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x3",
          y: "y3"
        }
      },
      {
        gdRefX: "adj8",
        gdRefY: "adj7",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x4",
          y: "y4"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y4"
          }
        ]
      }
    ]
  },
  [74 /* SHAPE_GEOMETRY_CAN */]: {
    avLst: {
      adj: "val 25000"
    },
    gdLst: {
      maxAdj: "*/ 50000 h ss",
      a: "pin 0 adj maxAdj",
      y1: "*/ ss a 200000",
      y2: "+- y1 y1 0",
      y3: "+- b 0 y1"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "maxAdj",
        pos: {
          x: "hc",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "y2"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "y2",
      r: "r",
      b: "y3"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "cd2",
            swAng: "-10800000"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y3"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "0",
            swAng: "cd2"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "lighten",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "cd2",
            swAng: "cd2"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "0",
            swAng: "cd2"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "r",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "0",
            swAng: "cd2"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "cd2",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y3"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "0",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y1"
          }
        ]
      }
    ]
  },
  [187 /* SHAPE_GEOMETRY_CHART_PLUS */]: {
    avLst: {},
    gdLst: {},
    ahLst: [],
    cxnLst: [],
    paths: [
      {
        w: "10",
        h: "10",
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "5",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "5",
            y: "10"
          },
          {
            cmd: "moveTo",
            x: "0",
            y: "5"
          },
          {
            cmd: "lineTo",
            x: "10",
            y: "5"
          }
        ]
      },
      {
        w: "10",
        h: "10",
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "0",
            y: "10"
          },
          {
            cmd: "lineTo",
            x: "10",
            y: "10"
          },
          {
            cmd: "lineTo",
            x: "10",
            y: "0"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [186 /* SHAPE_GEOMETRY_CHART_STAR */]: {
    avLst: {},
    gdLst: {},
    ahLst: [],
    cxnLst: [],
    paths: [
      {
        w: "10",
        h: "10",
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "10",
            y: "10"
          },
          {
            cmd: "moveTo",
            x: "0",
            y: "10"
          },
          {
            cmd: "lineTo",
            x: "10",
            y: "0"
          },
          {
            cmd: "moveTo",
            x: "5",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "5",
            y: "10"
          }
        ]
      },
      {
        w: "10",
        h: "10",
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "0",
            y: "10"
          },
          {
            cmd: "lineTo",
            x: "10",
            y: "10"
          },
          {
            cmd: "lineTo",
            x: "10",
            y: "0"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  }
};

// node_modules/@oai/granola/dist/shapes/preset-shape-definitions.part2.js
var presetShapeDefinitionsPart2 = {
  [185 /* SHAPE_GEOMETRY_CHART_X */]: {
    avLst: {},
    gdLst: {},
    ahLst: [],
    cxnLst: [],
    paths: [
      {
        w: "10",
        h: "10",
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "10",
            y: "10"
          },
          {
            cmd: "moveTo",
            x: "0",
            y: "10"
          },
          {
            cmd: "lineTo",
            x: "10",
            y: "0"
          }
        ]
      },
      {
        w: "10",
        h: "10",
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "0",
            y: "10"
          },
          {
            cmd: "lineTo",
            x: "10",
            y: "10"
          },
          {
            cmd: "lineTo",
            x: "10",
            y: "0"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [38 /* SHAPE_GEOMETRY_CHEVRON */]: {
    avLst: {
      adj: "val 50000"
    },
    gdLst: {
      maxAdj: "*/ 100000 w ss",
      a: "pin 0 adj maxAdj",
      x1: "*/ ss a 100000",
      x2: "+- r 0 x1",
      x3: "*/ x2 1 2",
      dx: "+- x2 0 x1",
      il: "?: dx x1 l",
      ir: "?: dx x2 r"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "0",
        maxX: "maxAdj",
        pos: {
          x: "x2",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x3",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x3",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "il",
      t: "t",
      r: "ir",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "vc"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [88 /* SHAPE_GEOMETRY_CHORD */]: {
    avLst: {
      adj1: "val 2700000",
      adj2: "val 16200000"
    },
    gdLst: {
      stAng: "pin 0 adj1 21599999",
      enAng: "pin 0 adj2 21599999",
      sw1: "+- enAng 0 stAng",
      sw2: "+- sw1 21600000 0",
      swAng: "?: sw1 sw1 sw2",
      wt1: "sin wd2 stAng",
      ht1: "cos hd2 stAng",
      dx1: "cat2 wd2 ht1 wt1",
      dy1: "sat2 hd2 ht1 wt1",
      wt2: "sin wd2 enAng",
      ht2: "cos hd2 enAng",
      dx2: "cat2 wd2 ht2 wt2",
      dy2: "sat2 hd2 ht2 wt2",
      x1: "+- hc dx1 0",
      y1: "+- vc dy1 0",
      x2: "+- hc dx2 0",
      y2: "+- vc dy2 0",
      x3: "+/ x1 x2 2",
      y3: "+/ y1 y2 2",
      midAng0: "*/ swAng 1 2",
      midAng: "+- stAng midAng0 cd2",
      idx: "cos wd2 2700000",
      idy: "sin hd2 2700000",
      il: "+- hc 0 idx",
      ir: "+- hc idx 0",
      it: "+- vc 0 idy",
      ib: "+- vc idy 0"
    },
    ahLst: [
      {
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        pos: {
          x: "x2",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "stAng",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        ang: "enAng",
        pos: {
          x: "x2",
          y: "y2"
        }
      },
      {
        ang: "midAng",
        pos: {
          x: "x3",
          y: "y3"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        w: "43200",
        h: "43200",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "stAng",
            swAng: "swAng"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [65 /* SHAPE_GEOMETRY_CIRCULAR_ARROW */]: {
    avLst: {
      adj1: "val 12500",
      adj2: "val 1142319",
      adj3: "val 20457681",
      adj4: "val 10800000",
      adj5: "val 12500"
    },
    gdLst: {
      a5: "pin 0 adj5 25000",
      maxAdj1: "*/ a5 2 1",
      a1: "pin 0 adj1 maxAdj1",
      enAng: "pin 1 adj3 21599999",
      stAng: "pin 0 adj4 21599999",
      th: "*/ ss a1 100000",
      thh: "*/ ss a5 100000",
      th2: "*/ th 1 2",
      rw1: "+- wd2 th2 thh",
      rh1: "+- hd2 th2 thh",
      rw2: "+- rw1 0 th",
      rh2: "+- rh1 0 th",
      rw3: "+- rw2 th2 0",
      rh3: "+- rh2 th2 0",
      wtH: "sin rw3 enAng",
      htH: "cos rh3 enAng",
      dxH: "cat2 rw3 htH wtH",
      dyH: "sat2 rh3 htH wtH",
      xH: "+- hc dxH 0",
      yH: "+- vc dyH 0",
      rI: "min rw2 rh2",
      u1: "*/ dxH dxH 1",
      u2: "*/ dyH dyH 1",
      u3: "*/ rI rI 1",
      u4: "+- u1 0 u3",
      u5: "+- u2 0 u3",
      u6: "*/ u4 u5 u1",
      u7: "*/ u6 1 u2",
      u8: "+- 1 0 u7",
      u9: "sqrt u8",
      u10: "*/ u4 1 dxH",
      u11: "*/ u10 1 dyH",
      u12: "+/ 1 u9 u11",
      u13: "at2 1 u12",
      u14: "+- u13 21600000 0",
      u15: "?: u13 u13 u14",
      u16: "+- u15 0 enAng",
      u17: "+- u16 21600000 0",
      u18: "?: u16 u16 u17",
      u19: "+- u18 0 cd2",
      u20: "+- u18 0 21600000",
      u21: "?: u19 u20 u18",
      maxAng: "abs u21",
      aAng: "pin 0 adj2 maxAng",
      ptAng: "+- enAng aAng 0",
      wtA: "sin rw3 ptAng",
      htA: "cos rh3 ptAng",
      dxA: "cat2 rw3 htA wtA",
      dyA: "sat2 rh3 htA wtA",
      xA: "+- hc dxA 0",
      yA: "+- vc dyA 0",
      wtE: "sin rw1 stAng",
      htE: "cos rh1 stAng",
      dxE: "cat2 rw1 htE wtE",
      dyE: "sat2 rh1 htE wtE",
      xE: "+- hc dxE 0",
      yE: "+- vc dyE 0",
      dxG: "cos thh ptAng",
      dyG: "sin thh ptAng",
      xG: "+- xH dxG 0",
      yG: "+- yH dyG 0",
      dxB: "cos thh ptAng",
      dyB: "sin thh ptAng",
      xB: "+- xH 0 dxB 0",
      yB: "+- yH 0 dyB 0",
      sx1: "+- xB 0 hc",
      sy1: "+- yB 0 vc",
      sx2: "+- xG 0 hc",
      sy2: "+- yG 0 vc",
      rO: "min rw1 rh1",
      x1O: "*/ sx1 rO rw1",
      y1O: "*/ sy1 rO rh1",
      x2O: "*/ sx2 rO rw1",
      y2O: "*/ sy2 rO rh1",
      dxO: "+- x2O 0 x1O",
      dyO: "+- y2O 0 y1O",
      dO: "mod dxO dyO 0",
      q1: "*/ x1O y2O 1",
      q2: "*/ x2O y1O 1",
      DO: "+- q1 0 q2",
      q3: "*/ rO rO 1",
      q4: "*/ dO dO 1",
      q5: "*/ q3 q4 1",
      q6: "*/ DO DO 1",
      q7: "+- q5 0 q6",
      q8: "max q7 0",
      sdelO: "sqrt q8",
      ndyO: "*/ dyO -1 1",
      sdyO: "?: ndyO -1 1",
      q9: "*/ sdyO dxO 1",
      q10: "*/ q9 sdelO 1",
      q11: "*/ DO dyO 1",
      dxF1: "+/ q11 q10 q4",
      q12: "+- q11 0 q10",
      dxF2: "*/ q12 1 q4",
      adyO: "abs dyO",
      q13: "*/ adyO sdelO 1",
      q14: "*/ DO dxO -1",
      dyF1: "+/ q14 q13 q4",
      q15: "+- q14 0 q13",
      dyF2: "*/ q15 1 q4",
      q16: "+- x2O 0 dxF1",
      q17: "+- x2O 0 dxF2",
      q18: "+- y2O 0 dyF1",
      q19: "+- y2O 0 dyF2",
      q20: "mod q16 q18 0",
      q21: "mod q17 q19 0",
      q22: "+- q21 0 q20",
      dxF: "?: q22 dxF1 dxF2",
      dyF: "?: q22 dyF1 dyF2",
      sdxF: "*/ dxF rw1 rO",
      sdyF: "*/ dyF rh1 rO",
      xF: "+- hc sdxF 0",
      yF: "+- vc sdyF 0",
      x1I: "*/ sx1 rI rw2",
      y1I: "*/ sy1 rI rh2",
      x2I: "*/ sx2 rI rw2",
      y2I: "*/ sy2 rI rh2",
      dxI: "cat2 rw3 htI wtI",
      dyI: "sat2 rh3 htI wtI",
      dI: "mod dxI dyI 0",
      v1: "*/ x1I y2I 1",
      v2: "*/ x2I y1I 1",
      DI: "+- v1 0 v2",
      v3: "*/ rI rI 1",
      v4: "*/ dI dI 1",
      v5: "*/ v3 v4 1",
      v6: "*/ DI DI 1",
      v7: "+- v5 0 v6",
      v8: "max v7 0",
      sdelI: "sqrt v8",
      v9: "*/ sdyO dxI 1",
      v10: "*/ v9 sdelI 1",
      v11: "*/ DI dyI 1",
      dxC1: "+/ v11 v10 v4",
      v12: "+- v11 0 v10",
      dxC2: "*/ v12 1 v4",
      adyI: "abs dyI",
      v13: "*/ adyI sdelI 1",
      v14: "*/ DI dxI -1",
      dyC1: "+/ v14 v13 v4",
      v15: "+- v14 0 v13",
      dyC2: "*/ v15 1 v4",
      v16: "+- x1I 0 dxC1",
      v17: "+- x1I 0 dxC2",
      v18: "+- y1I 0 dyC1",
      v19: "+- y1I 0 dyC2",
      v20: "mod v16 v18 0",
      v21: "mod v17 v19 0",
      v22: "+- v21 0 v20",
      dxC: "?: v22 dxC1 dxC2",
      dyC: "?: v22 dyC1 dyC2",
      sdxC: "*/ dxC rw2 rI",
      sdyC: "*/ dyC rh2 rI",
      xC: "+- hc sdxC 0",
      yC: "+- vc sdyC 0",
      ist0: "at2 sdxC sdyC",
      ist1: "+- ist0 21600000 0",
      istAng: "?: ist0 ist0 ist1",
      isw1: "+- stAng 0 istAng",
      isw2: "+- isw1 0 21600000",
      iswAng: "?: isw1 isw2 isw1",
      p1: "+- xF 0 xC",
      p2: "+- yF 0 yC",
      p3: "mod p1 p2 0",
      p4: "*/ p3 1 2",
      p5: "+- p4 0 thh",
      xGp: "?: p5 xF xG",
      yGp: "?: p5 yF yG",
      xBp: "?: p5 xC xB",
      yBp: "?: p5 yC yB",
      en0: "at2 sdxF sdyF",
      en1: "+- en0 21600000 0",
      en2: "?: en0 en0 en1",
      sw0: "+- en2 0 stAng",
      sw1: "+- sw0 21600000 0",
      swAng: "?: sw0 sw0 sw1",
      wtI: "sin rw3 stAng",
      htI: "cos rh3 stAng",
      xI: "+- hc dxI 0",
      yI: "+- vc dyI 0",
      aI: "+- stAng 0 cd4",
      aA: "+- ptAng cd4 0",
      aB: "+- ptAng cd2 0",
      idx: "cos rw1 2700000",
      idy: "sin rh1 2700000",
      il: "+- hc 0 idx",
      ir: "+- hc idx 0",
      it: "+- vc 0 idy",
      ib: "+- vc idy 0"
    },
    ahLst: [
      {
        pos: {
          x: "xA",
          y: "yA"
        }
      },
      {
        pos: {
          x: "xE",
          y: "yE"
        }
      },
      {
        pos: {
          x: "xF",
          y: "yF"
        }
      },
      {
        pos: {
          x: "xB",
          y: "yB"
        }
      }
    ],
    cxnLst: [
      {
        ang: "aI",
        pos: {
          x: "xI",
          y: "yI"
        }
      },
      {
        ang: "ptAng",
        pos: {
          x: "xGp",
          y: "yGp"
        }
      },
      {
        ang: "aA",
        pos: {
          x: "xA",
          y: "yA"
        }
      },
      {
        ang: "aB",
        pos: {
          x: "xBp",
          y: "yBp"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        w: "43200",
        h: "43200",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "xE",
            y: "yE"
          },
          {
            cmd: "arcTo",
            wR: "rw1",
            hR: "rh1",
            stAng: "stAng",
            swAng: "swAng"
          },
          {
            cmd: "lineTo",
            x: "xGp",
            y: "yGp"
          },
          {
            cmd: "lineTo",
            x: "xA",
            y: "yA"
          },
          {
            cmd: "lineTo",
            x: "xBp",
            y: "yBp"
          },
          {
            cmd: "lineTo",
            x: "xC",
            y: "yC"
          },
          {
            cmd: "arcTo",
            wR: "rw2",
            hR: "rh2",
            stAng: "istAng",
            swAng: "iswAng"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [121 /* SHAPE_GEOMETRY_CLOUD */]: {
    avLst: {},
    gdLst: {
      il: "*/ w 2977 21600",
      it: "*/ h 3262 21600",
      ir: "*/ w 17087 21600",
      ib: "*/ h 17337 21600",
      g27: "*/ w 67 21600",
      g28: "*/ h 21577 21600",
      g29: "*/ w 21582 21600",
      g30: "*/ h 1235 21600"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "g29",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "g28"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "g27",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "g30"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        w: "43200",
        h: "43200",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "3900",
            y: "14370"
          },
          {
            cmd: "arcTo",
            wR: "6753",
            hR: "9190",
            stAng: "-11429249",
            swAng: "7426832"
          },
          {
            cmd: "arcTo",
            wR: "5333",
            hR: "7267",
            stAng: "-8646143",
            swAng: "5396714"
          },
          {
            cmd: "arcTo",
            wR: "4365",
            hR: "5945",
            stAng: "-8748475",
            swAng: "5983381"
          },
          {
            cmd: "arcTo",
            wR: "4857",
            hR: "6595",
            stAng: "-7859164",
            swAng: "7034504"
          },
          {
            cmd: "arcTo",
            wR: "5333",
            hR: "7273",
            stAng: "-4722533",
            swAng: "6541615"
          },
          {
            cmd: "arcTo",
            wR: "6775",
            hR: "9220",
            stAng: "-2776035",
            swAng: "7816140"
          },
          {
            cmd: "arcTo",
            wR: "5785",
            hR: "7867",
            stAng: "37501",
            swAng: "6842000"
          },
          {
            cmd: "arcTo",
            wR: "6752",
            hR: "9215",
            stAng: "1347096",
            swAng: "6910353"
          },
          {
            cmd: "arcTo",
            wR: "7720",
            hR: "10543",
            stAng: "3974558",
            swAng: "4542661"
          },
          {
            cmd: "arcTo",
            wR: "4360",
            hR: "5918",
            stAng: "-16496525",
            swAng: "8804134"
          },
          {
            cmd: "arcTo",
            wR: "4345",
            hR: "5945",
            stAng: "-14809710",
            swAng: "9151131"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        w: "43200",
        h: "43200",
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "4693",
            y: "26177"
          },
          {
            cmd: "arcTo",
            wR: "4345",
            hR: "5945",
            stAng: "5204520",
            swAng: "1585770"
          },
          {
            cmd: "moveTo",
            x: "6928",
            y: "34899"
          },
          {
            cmd: "arcTo",
            wR: "4360",
            hR: "5918",
            stAng: "4416628",
            swAng: "686848"
          },
          {
            cmd: "moveTo",
            x: "16478",
            y: "39090"
          },
          {
            cmd: "arcTo",
            wR: "6752",
            hR: "9215",
            stAng: "8257449",
            swAng: "844866"
          },
          {
            cmd: "moveTo",
            x: "28827",
            y: "34751"
          },
          {
            cmd: "arcTo",
            wR: "6752",
            hR: "9215",
            stAng: "387196",
            swAng: "959901"
          },
          {
            cmd: "moveTo",
            x: "34129",
            y: "22954"
          },
          {
            cmd: "arcTo",
            wR: "5785",
            hR: "7867",
            stAng: "-4217541",
            swAng: "4255042"
          },
          {
            cmd: "moveTo",
            x: "41798",
            y: "15354"
          },
          {
            cmd: "arcTo",
            wR: "5333",
            hR: "7273",
            stAng: "1819082",
            swAng: "1665090"
          },
          {
            cmd: "moveTo",
            x: "38324",
            y: "5426"
          },
          {
            cmd: "arcTo",
            wR: "4857",
            hR: "6595",
            stAng: "-824660",
            swAng: "891534"
          },
          {
            cmd: "moveTo",
            x: "29078",
            y: "3952"
          },
          {
            cmd: "arcTo",
            wR: "4857",
            hR: "6595",
            stAng: "-8950887",
            swAng: "1091722"
          },
          {
            cmd: "moveTo",
            x: "22141",
            y: "4720"
          },
          {
            cmd: "arcTo",
            wR: "4365",
            hR: "5945",
            stAng: "-9809656",
            swAng: "1061181"
          },
          {
            cmd: "moveTo",
            x: "14000",
            y: "5192"
          },
          {
            cmd: "arcTo",
            wR: "6753",
            hR: "9190",
            stAng: "-4002417",
            swAng: "739161"
          },
          {
            cmd: "moveTo",
            x: "4127",
            y: "15789"
          },
          {
            cmd: "arcTo",
            wR: "6753",
            hR: "9190",
            stAng: "9459261",
            swAng: "711490"
          }
        ]
      }
    ]
  },
  [120 /* SHAPE_GEOMETRY_CLOUD_CALLOUT */]: {
    avLst: {
      adj1: "val -20833",
      adj2: "val 62500"
    },
    gdLst: {
      dxPos: "*/ w adj1 100000",
      dyPos: "*/ h adj2 100000",
      xPos: "+- hc dxPos 0",
      yPos: "+- vc dyPos 0",
      ht: "cat2 hd2 dxPos dyPos",
      wt: "sat2 wd2 dxPos dyPos",
      g2: "cat2 wd2 ht wt",
      g3: "sat2 hd2 ht wt",
      g4: "+- hc g2 0",
      g5: "+- vc g3 0",
      g6: "+- g4 0 xPos",
      g7: "+- g5 0 yPos",
      g8: "mod g6 g7 0",
      g9: "*/ ss 6600 21600",
      g10: "+- g8 0 g9",
      g11: "*/ g10 1 3",
      g12: "*/ ss 1800 21600",
      g13: "+- g11 g12 0",
      g14: "*/ g13 g6 g8",
      g15: "*/ g13 g7 g8",
      g16: "+- g14 xPos 0",
      g17: "+- g15 yPos 0",
      g18: "*/ ss 4800 21600",
      g19: "*/ g11 2 1",
      g20: "+- g18 g19 0",
      g21: "*/ g20 g6 g8",
      g22: "*/ g20 g7 g8",
      g23: "+- g21 xPos 0",
      g24: "+- g22 yPos 0",
      g25: "*/ ss 1200 21600",
      g26: "*/ ss 600 21600",
      x23: "+- xPos g26 0",
      x24: "+- g16 g25 0",
      x25: "+- g23 g12 0",
      il: "*/ w 2977 21600",
      it: "*/ h 3262 21600",
      ir: "*/ w 17087 21600",
      ib: "*/ h 17337 21600",
      g27: "*/ w 67 21600",
      g28: "*/ h 21577 21600",
      g29: "*/ w 21582 21600",
      g30: "*/ h 1235 21600",
      pang: "at2 dxPos dyPos"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        gdRefY: "adj2",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "xPos",
          y: "yPos"
        }
      }
    ],
    cxnLst: [
      {
        ang: "cd2",
        pos: {
          x: "g27",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "g28"
        }
      },
      {
        ang: "0",
        pos: {
          x: "g29",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "g30"
        }
      },
      {
        ang: "pang",
        pos: {
          x: "xPos",
          y: "yPos"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        w: "43200",
        h: "43200",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "3900",
            y: "14370"
          },
          {
            cmd: "arcTo",
            wR: "6753",
            hR: "9190",
            stAng: "-11429249",
            swAng: "7426832"
          },
          {
            cmd: "arcTo",
            wR: "5333",
            hR: "7267",
            stAng: "-8646143",
            swAng: "5396714"
          },
          {
            cmd: "arcTo",
            wR: "4365",
            hR: "5945",
            stAng: "-8748475",
            swAng: "5983381"
          },
          {
            cmd: "arcTo",
            wR: "4857",
            hR: "6595",
            stAng: "-7859164",
            swAng: "7034504"
          },
          {
            cmd: "arcTo",
            wR: "5333",
            hR: "7273",
            stAng: "-4722533",
            swAng: "6541615"
          },
          {
            cmd: "arcTo",
            wR: "6775",
            hR: "9220",
            stAng: "-2776035",
            swAng: "7816140"
          },
          {
            cmd: "arcTo",
            wR: "5785",
            hR: "7867",
            stAng: "37501",
            swAng: "6842000"
          },
          {
            cmd: "arcTo",
            wR: "6752",
            hR: "9215",
            stAng: "1347096",
            swAng: "6910353"
          },
          {
            cmd: "arcTo",
            wR: "7720",
            hR: "10543",
            stAng: "3974558",
            swAng: "4542661"
          },
          {
            cmd: "arcTo",
            wR: "4360",
            hR: "5918",
            stAng: "-16496525",
            swAng: "8804134"
          },
          {
            cmd: "arcTo",
            wR: "4345",
            hR: "5945",
            stAng: "-14809710",
            swAng: "9151131"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x23",
            y: "yPos"
          },
          {
            cmd: "arcTo",
            wR: "g26",
            hR: "g26",
            stAng: "0",
            swAng: "21600000"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x24",
            y: "g17"
          },
          {
            cmd: "arcTo",
            wR: "g25",
            hR: "g25",
            stAng: "0",
            swAng: "21600000"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x25",
            y: "g24"
          },
          {
            cmd: "arcTo",
            wR: "g12",
            hR: "g12",
            stAng: "0",
            swAng: "21600000"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        w: "43200",
        h: "43200",
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "4693",
            y: "26177"
          },
          {
            cmd: "arcTo",
            wR: "4345",
            hR: "5945",
            stAng: "5204520",
            swAng: "1585770"
          },
          {
            cmd: "moveTo",
            x: "6928",
            y: "34899"
          },
          {
            cmd: "arcTo",
            wR: "4360",
            hR: "5918",
            stAng: "4416628",
            swAng: "686848"
          },
          {
            cmd: "moveTo",
            x: "16478",
            y: "39090"
          },
          {
            cmd: "arcTo",
            wR: "6752",
            hR: "9215",
            stAng: "8257449",
            swAng: "844866"
          },
          {
            cmd: "moveTo",
            x: "28827",
            y: "34751"
          },
          {
            cmd: "arcTo",
            wR: "6752",
            hR: "9215",
            stAng: "387196",
            swAng: "959901"
          },
          {
            cmd: "moveTo",
            x: "34129",
            y: "22954"
          },
          {
            cmd: "arcTo",
            wR: "5785",
            hR: "7867",
            stAng: "-4217541",
            swAng: "4255042"
          },
          {
            cmd: "moveTo",
            x: "41798",
            y: "15354"
          },
          {
            cmd: "arcTo",
            wR: "5333",
            hR: "7273",
            stAng: "1819082",
            swAng: "1665090"
          },
          {
            cmd: "moveTo",
            x: "38324",
            y: "5426"
          },
          {
            cmd: "arcTo",
            wR: "4857",
            hR: "6595",
            stAng: "-824660",
            swAng: "891534"
          },
          {
            cmd: "moveTo",
            x: "29078",
            y: "3952"
          },
          {
            cmd: "arcTo",
            wR: "4857",
            hR: "6595",
            stAng: "-8950887",
            swAng: "1091722"
          },
          {
            cmd: "moveTo",
            x: "22141",
            y: "4720"
          },
          {
            cmd: "arcTo",
            wR: "4365",
            hR: "5945",
            stAng: "-9809656",
            swAng: "1061181"
          },
          {
            cmd: "moveTo",
            x: "14000",
            y: "5192"
          },
          {
            cmd: "arcTo",
            wR: "6753",
            hR: "9190",
            stAng: "-4002417",
            swAng: "739161"
          },
          {
            cmd: "moveTo",
            x: "4127",
            y: "15789"
          },
          {
            cmd: "arcTo",
            wR: "6753",
            hR: "9190",
            stAng: "9459261",
            swAng: "711490"
          }
        ]
      }
    ]
  },
  [86 /* SHAPE_GEOMETRY_CORNER */]: {
    avLst: {
      adj1: "val 50000",
      adj2: "val 50000"
    },
    gdLst: {
      maxAdj1: "*/ 100000 h ss",
      maxAdj2: "*/ 100000 w ss",
      a1: "pin 0 adj1 maxAdj1",
      a2: "pin 0 adj2 maxAdj2",
      x1: "*/ ss a2 100000",
      dy1: "*/ ss a1 100000",
      y1: "+- b 0 dy1",
      cx1: "*/ x1 1 2",
      cy1: "+/ y1 b 2",
      d: "+- w 0 h",
      it: "?: d y1 t",
      ir: "?: d r x1"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "maxAdj1",
        pos: {
          x: "l",
          y: "y1"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "maxAdj2",
        pos: {
          x: "x1",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "cy1"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "cx1",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "it",
      r: "ir",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [182 /* SHAPE_GEOMETRY_CORNER_TABS */]: {
    avLst: {},
    gdLst: {
      md: "mod w h 0",
      dx: "*/ 1 md 20",
      y1: "+- 0 b dx",
      x1: "+- 0 r dx"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "dx"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y1"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "b"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "dx",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x1",
          y: "t"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "dx",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x1",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "t"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "dx"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y1"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "b"
        }
      }
    ],
    rect: {
      l: "dx",
      t: "dx",
      r: "x1",
      b: "y1"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "dx",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "dx"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "dx",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "dx"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "r",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [73 /* SHAPE_GEOMETRY_CUBE */]: {
    avLst: {
      adj: "val 25000"
    },
    gdLst: {
      a: "pin 0 adj 100000",
      y1: "*/ ss a 100000",
      y4: "+- b 0 y1",
      y2: "*/ y4 1 2",
      y3: "+/ y1 b 2",
      x4: "+- r 0 y1",
      x2: "*/ x4 1 2",
      x3: "+/ y1 r 2"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "100000",
        pos: {
          x: "l",
          y: "y1"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x3",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x2",
          y: "y1"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y3"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x2",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x4",
          y: "y3"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y2"
        }
      }
    ],
    rect: {
      l: "l",
      t: "y1",
      r: "x4",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darkenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "lightenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "y1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "y1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "l",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "moveTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "b"
          }
        ]
      }
    ]
  },
  [101 /* SHAPE_GEOMETRY_CURVED_CONNECTOR2 */]: {
    avLst: {},
    gdLst: {},
    ahLst: [],
    cxnLst: [],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "cubicBezTo",
            x: "r",
            y: "b",
            x1: "wd2",
            y1: "t",
            x2: "r",
            y2: "hd2"
          }
        ]
      }
    ]
  },
  [102 /* SHAPE_GEOMETRY_CURVED_CONNECTOR3 */]: {
    avLst: {
      adj1: "val 50000"
    },
    gdLst: {
      x2: "*/ w adj1 100000",
      x1: "+/ l x2 2",
      x3: "+/ r x2 2",
      y3: "*/ h 3 4"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        pos: {
          x: "x2",
          y: "vc"
        }
      }
    ],
    cxnLst: [],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "cubicBezTo",
            x: "x2",
            y: "vc",
            x1: "x1",
            y1: "t",
            x2: "x2",
            y2: "hd4"
          },
          {
            cmd: "cubicBezTo",
            x: "r",
            y: "b",
            x1: "x2",
            y1: "y3",
            x2: "x3",
            y2: "b"
          }
        ]
      }
    ]
  },
  [103 /* SHAPE_GEOMETRY_CURVED_CONNECTOR4 */]: {
    avLst: {
      adj1: "val 50000",
      adj2: "val 50000"
    },
    gdLst: {
      x2: "*/ w adj1 100000",
      x1: "+/ l x2 2",
      x3: "+/ r x2 2",
      x4: "+/ x2 x3 2",
      x5: "+/ x3 r 2",
      y4: "*/ h adj2 100000",
      y1: "+/ t y4 2",
      y2: "+/ t y1 2",
      y3: "+/ y1 y4 2",
      y5: "+/ b y4 2"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        pos: {
          x: "x2",
          y: "y1"
        }
      },
      {
        gdRefY: "adj2",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x3",
          y: "y4"
        }
      }
    ],
    cxnLst: [],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "cubicBezTo",
            x: "x2",
            y: "y1",
            x1: "x1",
            y1: "t",
            x2: "x2",
            y2: "y2"
          },
          {
            cmd: "cubicBezTo",
            x: "x3",
            y: "y4",
            x1: "x2",
            y1: "y3",
            x2: "x4",
            y2: "y4"
          },
          {
            cmd: "cubicBezTo",
            x: "r",
            y: "b",
            x1: "x5",
            y1: "y4",
            x2: "r",
            y2: "y5"
          }
        ]
      }
    ]
  },
  [104 /* SHAPE_GEOMETRY_CURVED_CONNECTOR5 */]: {
    avLst: {
      adj1: "val 50000",
      adj2: "val 50000",
      adj3: "val 50000"
    },
    gdLst: {
      x3: "*/ w adj1 100000",
      x6: "*/ w adj3 100000",
      x1: "+/ x3 x6 2",
      x2: "+/ l x3 2",
      x4: "+/ x3 x1 2",
      x5: "+/ x6 x1 2",
      x7: "+/ x6 r 2",
      y4: "*/ h adj2 100000",
      y1: "+/ t y4 2",
      y2: "+/ t y1 2",
      y3: "+/ y1 y4 2",
      y5: "+/ b y4 2",
      y6: "+/ y5 y4 2",
      y7: "+/ y5 b 2"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "-2147483647",
        maxX: "2147483647",
        pos: {
          x: "x3",
          y: "y1"
        }
      },
      {
        gdRefY: "adj2",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "x1",
          y: "y4"
        }
      },
      {
        gdRefX: "adj3",
        minX: "-2147483647",
        maxX: "2147483647",
        pos: {
          x: "x6",
          y: "y5"
        }
      }
    ],
    cxnLst: [],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "cubicBezTo",
            x: "x3",
            y: "y1",
            x1: "x2",
            y1: "t",
            x2: "x3",
            y2: "y2"
          },
          {
            cmd: "cubicBezTo",
            x: "x1",
            y: "y4",
            x1: "x3",
            y1: "y3",
            x2: "x4",
            y2: "y4"
          },
          {
            cmd: "cubicBezTo",
            x: "x6",
            y: "y5",
            x1: "x5",
            y1: "y4",
            x2: "x6",
            y2: "y6"
          },
          {
            cmd: "cubicBezTo",
            x: "r",
            y: "b",
            x1: "x6",
            y1: "y7",
            x2: "x7",
            y2: "b"
          }
        ]
      }
    ]
  },
  [71 /* SHAPE_GEOMETRY_CURVED_DOWN_ARROW */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 50000",
      adj3: "val 25000"
    },
    gdLst: {
      maxAdj2: "*/ 50000 w ss",
      a2: "pin 0 adj2 maxAdj2",
      a1: "pin 0 adj1 100000",
      th: "*/ ss a1 100000",
      aw: "*/ ss a2 100000",
      q1: "+/ th aw 4",
      wR: "+- wd2 0 q1",
      q7: "*/ wR 2 1",
      q8: "*/ q7 q7 1",
      q9: "*/ th th 1",
      q10: "+- q8 0 q9",
      q11: "sqrt q10",
      idy: "*/ q11 h q7",
      maxAdj3: "*/ 100000 idy ss",
      a3: "pin 0 adj3 maxAdj3",
      ah: "*/ ss adj3 100000",
      x3: "+- wR th 0",
      q2: "*/ h h 1",
      q3: "*/ ah ah 1",
      q4: "+- q2 0 q3",
      q5: "sqrt q4",
      dx: "*/ q5 wR h",
      x5: "+- wR dx 0",
      x7: "+- x3 dx 0",
      q6: "+- aw 0 th",
      dh: "*/ q6 1 2",
      x4: "+- x5 0 dh",
      x8: "+- x7 dh 0",
      aw2: "*/ aw 1 2",
      x6: "+- r 0 aw2",
      y1: "+- b 0 ah",
      swAng: "at2 ah dx",
      mswAng: "+- 0 0 swAng",
      iy: "+- b 0 idy",
      ix: "+/ wR x3 2",
      q12: "*/ th 1 2",
      dang2: "at2 idy q12",
      stAng: "+- 3cd4 swAng 0",
      stAng2: "+- 3cd4 0 dang2",
      swAng2: "+- dang2 0 cd4",
      swAng3: "+- cd4 dang2 0"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "adj2",
        pos: {
          x: "x7",
          y: "y1"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "maxAdj2",
        pos: {
          x: "x4",
          y: "b"
        }
      },
      {
        gdRefY: "adj3",
        minY: "0",
        maxY: "maxAdj3",
        pos: {
          x: "r",
          y: "y1"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "ix",
          y: "t"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "q12",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x4",
          y: "y1"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x6",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x8",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x6",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "h",
            stAng: "stAng",
            swAng: "mswAng"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "h",
            stAng: "3cd4",
            swAng: "swAng"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y1"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darkenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "ix",
            y: "iy"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "h",
            stAng: "stAng2",
            swAng: "swAng2"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "h",
            stAng: "cd2",
            swAng: "swAng3"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "ix",
            y: "iy"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "h",
            stAng: "stAng2",
            swAng: "swAng2"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "h",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "h",
            stAng: "3cd4",
            swAng: "swAng"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "h",
            stAng: "stAng",
            swAng: "mswAng"
          }
        ]
      }
    ]
  },
  [69 /* SHAPE_GEOMETRY_CURVED_LEFT_ARROW */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 50000",
      adj3: "val 25000"
    },
    gdLst: {
      maxAdj2: "*/ 50000 h ss",
      a2: "pin 0 adj2 maxAdj2",
      a1: "pin 0 adj1 a2",
      th: "*/ ss a1 100000",
      aw: "*/ ss a2 100000",
      q1: "+/ th aw 4",
      hR: "+- hd2 0 q1",
      q7: "*/ hR 2 1",
      q8: "*/ q7 q7 1",
      q9: "*/ th th 1",
      q10: "+- q8 0 q9",
      q11: "sqrt q10",
      idx: "*/ q11 w q7",
      maxAdj3: "*/ 100000 idx ss",
      a3: "pin 0 adj3 maxAdj3",
      ah: "*/ ss a3 100000",
      y3: "+- hR th 0",
      q2: "*/ w w 1",
      q3: "*/ ah ah 1",
      q4: "+- q2 0 q3",
      q5: "sqrt q4",
      dy: "*/ q5 hR w",
      y5: "+- hR dy 0",
      y7: "+- y3 dy 0",
      q6: "+- aw 0 th",
      dh: "*/ q6 1 2",
      y4: "+- y5 0 dh",
      y8: "+- y7 dh 0",
      aw2: "*/ aw 1 2",
      y6: "+- b 0 aw2",
      x1: "+- l ah 0",
      swAng: "at2 ah dy",
      mswAng: "+- 0 0 swAng",
      ix: "+- l idx 0",
      iy: "+/ hR y3 2",
      q12: "*/ th 1 2",
      dang2: "at2 idx q12",
      swAng2: "+- dang2 0 swAng",
      swAng3: "+- swAng dang2 0",
      stAng3: "+- 0 0 dang2"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "a2",
        pos: {
          x: "x1",
          y: "y5"
        }
      },
      {
        gdRefY: "adj2",
        minY: "0",
        maxY: "maxAdj2",
        pos: {
          x: "r",
          y: "y4"
        }
      },
      {
        gdRefX: "adj3",
        minX: "0",
        maxX: "maxAdj3",
        pos: {
          x: "x1",
          y: "b"
        }
      }
    ],
    cxnLst: [
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "q12"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y4"
        }
      },
      {
        ang: "cd3",
        pos: {
          x: "l",
          y: "y6"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x1",
          y: "y8"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "iy"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y5"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "hR",
            stAng: "swAng",
            swAng: "swAng2"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "hR",
            stAng: "stAng3",
            swAng: "swAng3"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y8"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darkenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "r",
            y: "y3"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "hR",
            stAng: "0",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "hR",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "r",
            y: "y3"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "hR",
            stAng: "0",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "hR",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y3"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "hR",
            stAng: "0",
            swAng: "swAng"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y8"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y5"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "hR",
            stAng: "swAng",
            swAng: "swAng2"
          }
        ]
      }
    ]
  },
  [68 /* SHAPE_GEOMETRY_CURVED_RIGHT_ARROW */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 50000",
      adj3: "val 25000"
    },
    gdLst: {
      maxAdj2: "*/ 50000 h ss",
      a2: "pin 0 adj2 maxAdj2",
      a1: "pin 0 adj1 a2",
      th: "*/ ss a1 100000",
      aw: "*/ ss a2 100000",
      q1: "+/ th aw 4",
      hR: "+- hd2 0 q1",
      q7: "*/ hR 2 1",
      q8: "*/ q7 q7 1",
      q9: "*/ th th 1",
      q10: "+- q8 0 q9",
      q11: "sqrt q10",
      idx: "*/ q11 w q7",
      maxAdj3: "*/ 100000 idx ss",
      a3: "pin 0 adj3 maxAdj3",
      ah: "*/ ss a3 100000",
      y3: "+- hR th 0",
      q2: "*/ w w 1",
      q3: "*/ ah ah 1",
      q4: "+- q2 0 q3",
      q5: "sqrt q4",
      dy: "*/ q5 hR w",
      y5: "+- hR dy 0",
      y7: "+- y3 dy 0",
      q6: "+- aw 0 th",
      dh: "*/ q6 1 2",
      y4: "+- y5 0 dh",
      y8: "+- y7 dh 0",
      aw2: "*/ aw 1 2",
      y6: "+- b 0 aw2",
      x1: "+- r 0 ah",
      swAng: "at2 ah dy",
      stAng: "+- cd2 0 swAng",
      mswAng: "+- 0 0 swAng",
      ix: "+- r 0 idx",
      iy: "+/ hR y3 2",
      q12: "*/ th 1 2",
      dang2: "at2 idx q12",
      swAng2: "+- dang2 0 cd4",
      swAng3: "+- cd4 dang2 0",
      stAng3: "+- cd2 0 dang2"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "a2",
        pos: {
          x: "x1",
          y: "y5"
        }
      },
      {
        gdRefY: "adj2",
        minY: "0",
        maxY: "maxAdj2",
        pos: {
          x: "r",
          y: "y4"
        }
      },
      {
        gdRefX: "adj3",
        minX: "0",
        maxX: "maxAdj3",
        pos: {
          x: "x1",
          y: "b"
        }
      }
    ],
    cxnLst: [
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "iy"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x1",
          y: "y8"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y6"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x1",
          y: "y4"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "q12"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "hR"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "hR",
            stAng: "cd2",
            swAng: "mswAng"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y8"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y7"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "hR",
            stAng: "stAng",
            swAng: "swAng"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darkenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "r",
            y: "th"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "hR",
            stAng: "3cd4",
            swAng: "swAng2"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "hR",
            stAng: "stAng3",
            swAng: "swAng3"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "hR"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "hR",
            stAng: "cd2",
            swAng: "mswAng"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y8"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y7"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "hR",
            stAng: "stAng",
            swAng: "swAng"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "hR"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "hR",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "th"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "hR",
            stAng: "3cd4",
            swAng: "swAng2"
          }
        ]
      }
    ]
  },
  [70 /* SHAPE_GEOMETRY_CURVED_UP_ARROW */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 50000",
      adj3: "val 25000"
    },
    gdLst: {
      maxAdj2: "*/ 50000 w ss",
      a2: "pin 0 adj2 maxAdj2",
      a1: "pin 0 adj1 100000",
      th: "*/ ss a1 100000",
      aw: "*/ ss a2 100000",
      q1: "+/ th aw 4",
      wR: "+- wd2 0 q1",
      q7: "*/ wR 2 1",
      q8: "*/ q7 q7 1",
      q9: "*/ th th 1",
      q10: "+- q8 0 q9",
      q11: "sqrt q10",
      idy: "*/ q11 h q7",
      maxAdj3: "*/ 100000 idy ss",
      a3: "pin 0 adj3 maxAdj3",
      ah: "*/ ss adj3 100000",
      x3: "+- wR th 0",
      q2: "*/ h h 1",
      q3: "*/ ah ah 1",
      q4: "+- q2 0 q3",
      q5: "sqrt q4",
      dx: "*/ q5 wR h",
      x5: "+- wR dx 0",
      x7: "+- x3 dx 0",
      q6: "+- aw 0 th",
      dh: "*/ q6 1 2",
      x4: "+- x5 0 dh",
      x8: "+- x7 dh 0",
      aw2: "*/ aw 1 2",
      x6: "+- r 0 aw2",
      y1: "+- t ah 0",
      swAng: "at2 ah dx",
      mswAng: "+- 0 0 swAng",
      iy: "+- t idy 0",
      ix: "+/ wR x3 2",
      q12: "*/ th 1 2",
      dang2: "at2 idy q12",
      swAng2: "+- dang2 0 swAng",
      mswAng2: "+- 0 0 swAng2",
      stAng3: "+- cd4 0 swAng",
      swAng3: "+- swAng dang2 0",
      stAng2: "+- cd4 0 dang2"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "a2",
        pos: {
          x: "x7",
          y: "y1"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "maxAdj2",
        pos: {
          x: "x4",
          y: "t"
        }
      },
      {
        gdRefY: "adj3",
        minY: "0",
        maxY: "maxAdj3",
        pos: {
          x: "r",
          y: "y1"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x6",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x4",
          y: "y1"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "q12",
          y: "t"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "ix",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x8",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x6",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "h",
            stAng: "stAng3",
            swAng: "swAng3"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "h",
            stAng: "stAng2",
            swAng: "swAng2"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darkenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "wR",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "h",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "th",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "h",
            stAng: "cd2",
            swAng: "-5400000"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "ix",
            y: "iy"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "h",
            stAng: "stAng2",
            swAng: "swAng2"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "h",
            stAng: "stAng3",
            swAng: "swAng"
          },
          {
            cmd: "lineTo",
            x: "wR",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "h",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "th",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "h",
            stAng: "cd2",
            swAng: "-5400000"
          }
        ]
      }
    ]
  },
  [14 /* SHAPE_GEOMETRY_DECAGON */]: {
    avLst: {
      vf: "val 105146"
    },
    gdLst: {
      shd2: "*/ hd2 vf 100000",
      dx1: "cos wd2 2160000",
      dx2: "cos wd2 4320000",
      x1: "+- hc 0 dx1",
      x2: "+- hc 0 dx2",
      x3: "+- hc dx2 0",
      x4: "+- hc dx1 0",
      dy1: "sin shd2 4320000",
      dy2: "sin shd2 2160000",
      y1: "+- vc 0 dy1",
      y2: "+- vc 0 dy2",
      y3: "+- vc dy2 0",
      y4: "+- vc dy1 0"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "x4",
          y: "y2"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x4",
          y: "y3"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x3",
          y: "y4"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x2",
          y: "y4"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y3"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y2"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x2",
          y: "y1"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x3",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "y2",
      r: "x4",
      b: "y3"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y3"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [87 /* SHAPE_GEOMETRY_DIAG_STRIPE */]: {
    avLst: {
      adj: "val 50000"
    },
    gdLst: {
      a: "pin 0 adj 100000",
      x2: "*/ w a 100000",
      x1: "*/ x2 1 2",
      x3: "+/ x2 r 2",
      y2: "*/ h a 100000",
      y1: "*/ y2 1 2",
      y3: "+/ y2 b 2"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "100000",
        pos: {
          x: "l",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "hc",
          y: "vc"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y3"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x3",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "x3",
      b: "y3"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [6 /* SHAPE_GEOMETRY_DIAMOND */]: {
    avLst: {},
    gdLst: {
      ir: "*/ w 3 4",
      ib: "*/ h 3 4"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "wd4",
      t: "hd4",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        w: "2",
        h: "2",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [15 /* SHAPE_GEOMETRY_DODECAGON */]: {
    avLst: {},
    gdLst: {
      x1: "*/ w 2894 21600",
      x2: "*/ w 7906 21600",
      x3: "*/ w 13694 21600",
      x4: "*/ w 18706 21600",
      y1: "*/ h 2894 21600",
      y2: "*/ h 7906 21600",
      y3: "*/ h 13694 21600",
      y4: "*/ h 18706 21600"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "x4",
          y: "y1"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y2"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y3"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x4",
          y: "y4"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x3",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x2",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y4"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y3"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y2"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x2",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x3",
          y: "t"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "y1",
      r: "x4",
      b: "y4"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y3"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [42 /* SHAPE_GEOMETRY_DONUT */]: {
    avLst: {
      adj: "val 25000"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      dr: "*/ ss a 100000",
      iwd2: "+- wd2 0 dr",
      ihd2: "+- hd2 0 dr",
      idx: "cos wd2 2700000",
      idy: "sin hd2 2700000",
      il: "+- hc 0 idx",
      ir: "+- hc idx 0",
      it: "+- vc 0 idy",
      ib: "+- vc idy 0"
    },
    ahLst: [
      {
        pos: {
          x: "dr",
          y: "vc"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "il",
          y: "it"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "il",
          y: "ib"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "ir",
          y: "ib"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "ir",
          y: "it"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "dr",
            y: "vc"
          },
          {
            cmd: "arcTo",
            wR: "iwd2",
            hR: "ihd2",
            stAng: "cd2",
            swAng: "-5400000"
          },
          {
            cmd: "arcTo",
            wR: "iwd2",
            hR: "ihd2",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "arcTo",
            wR: "iwd2",
            hR: "ihd2",
            stAng: "0",
            swAng: "-5400000"
          },
          {
            cmd: "arcTo",
            wR: "iwd2",
            hR: "ihd2",
            stAng: "3cd4",
            swAng: "-5400000"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [130 /* SHAPE_GEOMETRY_DOUBLE_WAVE */]: {
    avLst: {
      adj1: "val 6250",
      adj2: "val 0"
    },
    gdLst: {
      a1: "pin 0 adj1 12500",
      a2: "pin -10000 adj2 10000",
      y1: "*/ h a1 100000",
      dy2: "*/ y1 10 3",
      y2: "+- y1 0 dy2",
      y3: "+- y1 dy2 0",
      y4: "+- b 0 y1",
      y5: "+- y4 0 dy2",
      y6: "+- y4 dy2 0",
      dx1: "*/ w a2 100000",
      of2: "*/ w a2 50000",
      x1: "abs dx1",
      dx2: "?: of2 0 of2",
      x2: "+- l 0 dx2",
      dx8: "?: of2 of2 0",
      x8: "+- r 0 dx8",
      dx3: "+/ dx2 x8 6",
      x3: "+- x2 dx3 0",
      dx4: "+/ dx2 x8 3",
      x4: "+- x2 dx4 0",
      x5: "+/ x2 x8 2",
      x6: "+- x5 dx3 0",
      x7: "+/ x6 x8 2",
      x9: "+- l dx8 0",
      x15: "+- r dx2 0",
      x10: "+- x9 dx3 0",
      x11: "+- x9 dx4 0",
      x12: "+/ x9 x15 2",
      x13: "+- x12 dx3 0",
      x14: "+/ x13 x15 2",
      x16: "+- r 0 x1",
      xAdj: "+- hc dx1 0",
      il: "max x2 x9",
      ir: "min x8 x15",
      it: "*/ h a1 50000",
      ib: "+- b 0 it"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "12500",
        pos: {
          x: "l",
          y: "y1"
        }
      },
      {
        gdRefX: "adj2",
        minX: "-10000",
        maxX: "10000",
        pos: {
          x: "xAdj",
          y: "b"
        }
      }
    ],
    cxnLst: [
      {
        ang: "cd4",
        pos: {
          x: "x12",
          y: "y1"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x5",
          y: "y4"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x16",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "cubicBezTo",
            x: "x5",
            y: "y1",
            x1: "x3",
            y1: "y2",
            x2: "x4",
            y2: "y3"
          },
          {
            cmd: "cubicBezTo",
            x: "x8",
            y: "y1",
            x1: "x6",
            y1: "y2",
            x2: "x7",
            y2: "y3"
          },
          {
            cmd: "lineTo",
            x: "x15",
            y: "y4"
          },
          {
            cmd: "cubicBezTo",
            x: "x12",
            y: "y4",
            x1: "x14",
            y1: "y6",
            x2: "x13",
            y2: "y5"
          },
          {
            cmd: "cubicBezTo",
            x: "x9",
            y: "y4",
            x1: "x11",
            y1: "y6",
            x2: "x10",
            y2: "y5"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [47 /* SHAPE_GEOMETRY_DOWN_ARROW */]: {
    avLst: {
      adj1: "val 50000",
      adj2: "val 50000"
    },
    gdLst: {
      maxAdj2: "*/ 100000 h ss",
      a1: "pin 0 adj1 100000",
      a2: "pin 0 adj2 maxAdj2",
      dy1: "*/ ss a2 100000",
      y1: "+- b 0 dy1",
      dx1: "*/ w a1 200000",
      x1: "+- hc 0 dx1",
      x2: "+- hc dx1 0",
      dy2: "*/ x1 dy1 wd2",
      y2: "+- y1 dy2 0"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "100000",
        pos: {
          x: "x1",
          y: "t"
        }
      },
      {
        gdRefY: "adj2",
        minY: "0",
        maxY: "maxAdj2",
        pos: {
          x: "l",
          y: "y1"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y1"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "t",
      r: "x2",
      b: "y2"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [46 /* SHAPE_GEOMETRY_UP_ARROW */]: {
    avLst: {
      adj1: "val 50000",
      adj2: "val 50000"
    },
    gdLst: {
      maxAdj2: "*/ 100000 h ss",
      a1: "pin 0 adj1 100000",
      a2: "pin 0 adj2 maxAdj2",
      dy2: "*/ ss a2 100000",
      y2: "+- t dy2 0",
      dx1: "*/ w a1 200000",
      x1: "+- hc 0 dx1",
      x2: "+- hc dx1 0",
      dy1: "*/ x1 dy2 wd2",
      y1: "+- y2 0 dy1"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "100000",
        pos: {
          x: "x1",
          y: "b"
        }
      },
      {
        gdRefY: "adj2",
        minY: "0",
        maxY: "maxAdj2",
        pos: {
          x: "l",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y2"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y2"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "y1",
      r: "x2",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [59 /* SHAPE_GEOMETRY_DOWN_ARROW_CALLOUT */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 25000",
      adj3: "val 25000",
      adj4: "val 64977"
    },
    gdLst: {
      maxAdj2: "*/ 50000 w ss",
      a2: "pin 0 adj2 maxAdj2",
      maxAdj1: "*/ a2 2 1",
      a1: "pin 0 adj1 maxAdj1",
      maxAdj3: "*/ 100000 h ss",
      a3: "pin 0 adj3 maxAdj3",
      q2: "*/ a3 ss h",
      maxAdj4: "+- 100000 0 q2",
      a4: "pin 0 adj4 maxAdj4",
      dx1: "*/ ss a2 100000",
      dx2: "*/ ss a1 200000",
      x1: "+- hc 0 dx1",
      x2: "+- hc 0 dx2",
      x3: "+- hc dx2 0",
      x4: "+- hc dx1 0",
      dy3: "*/ ss a3 100000",
      y3: "+- b 0 dy3",
      y2: "*/ h a4 100000",
      y1: "*/ y2 1 2"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "maxAdj1",
        pos: {
          x: "x2",
          y: "y3"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "maxAdj2",
        pos: {
          x: "x1",
          y: "b"
        }
      },
      {
        gdRefY: "adj3",
        minY: "0",
        maxY: "maxAdj3",
        pos: {
          x: "r",
          y: "y3"
        }
      },
      {
        gdRefY: "adj4",
        minY: "0",
        maxY: "maxAdj4",
        pos: {
          x: "l",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y1"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "y2"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [35 /* SHAPE_GEOMETRY_ELLIPSE */]: {
    avLst: {},
    gdLst: {
      idx: "cos wd2 2700000",
      idy: "sin hd2 2700000",
      il: "+- hc 0 idx",
      ir: "+- hc idx 0",
      it: "+- vc 0 idy",
      ib: "+- vc idy 0"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "il",
          y: "it"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "il",
          y: "ib"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "ir",
          y: "ib"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "ir",
          y: "it"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          { cmd: "moveTo", x: "r", y: "vc" },
          { cmd: "arcTo", wR: "wd2", hR: "hd2", stAng: "0", swAng: "cd2" },
          { cmd: "arcTo", wR: "wd2", hR: "hd2", stAng: "cd2", swAng: "cd2" },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "sum cd2 cd2",
            swAng: "cd2"
          },
          { cmd: "arcTo", wR: "wd2", hR: "hd2", stAng: "3cd2", swAng: "cd2" },
          { cmd: "close" }
        ]
      }
    ]
  },
  [124 /* SHAPE_GEOMETRY_ELLIPSE_RIBBON */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 50000",
      adj3: "val 12500"
    },
    gdLst: {
      a1: "pin 0 adj1 100000",
      a2: "pin 25000 adj2 75000",
      q10: "+- 100000 0 a1",
      q11: "*/ q10 1 2",
      q12: "+- a1 0 q11",
      minAdj3: "max 0 q12",
      a3: "pin minAdj3 adj3 a1",
      dx2: "*/ w a2 200000",
      x2: "+- hc 0 dx2",
      x3: "+- x2 wd8 0",
      x4: "+- r 0 x3",
      x5: "+- r 0 x2",
      x6: "+- r 0 wd8",
      dy1: "*/ h a3 100000",
      f1: "*/ 4 dy1 w",
      q1: "*/ h a1 100000",
      q2: "+- x3 0 q1",
      y1: "*/ f1 q2 1",
      cx1: "*/ x3 1 2",
      cy1: "*/ f1 cx1 1",
      cx2: "+- r 0 cx1",
      dy3: "+- q1 0 dy1",
      q3: "*/ x2 x2 w",
      q4: "+- x2 0 q3",
      q5: "*/ f1 q4 1",
      y3: "+- q5 dy3 0",
      q6: "+- dy1 dy3 y3",
      q7: "+- q6 dy1 0",
      cy3: "+- q7 dy3 0",
      rh: "+- b 0 q1",
      q8: "*/ dy1 14 16",
      y2: "+/ q8 rh 2",
      y5: "+- q5 rh 0",
      y6: "+- y3 rh 0",
      cx4: "*/ x2 1 2",
      q9: "*/ f1 cx4 1",
      cy4: "+- q9 rh 0",
      cx5: "+- r 0 cx4",
      cy6: "+- cy3 rh 0",
      y7: "+- y1 dy3 0",
      cy7: "+- q1 q1 y7",
      y8: "+- b 0 dy1"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "100000",
        pos: {
          x: "hc",
          y: "q1"
        }
      },
      {
        gdRefX: "adj2",
        minX: "25000",
        maxX: "75000",
        pos: {
          x: "x2",
          y: "b"
        }
      },
      {
        gdRefY: "adj3",
        minY: "minAdj3",
        maxY: "a1",
        pos: {
          x: "l",
          y: "y8"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "q1"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "wd8",
          y: "y2"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x6",
          y: "y2"
        }
      }
    ],
    rect: {
      l: "x2",
      t: "q1",
      r: "x5",
      b: "y6"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "quadBezTo",
            x: "x3",
            y: "y1",
            x1: "cx1",
            y1: "cy1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y3"
          },
          {
            cmd: "quadBezTo",
            x: "x5",
            y: "y3",
            x1: "hc",
            y1: "cy3"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "quadBezTo",
            x: "r",
            y: "t",
            x1: "cx2",
            y1: "cy1"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "rh"
          },
          {
            cmd: "quadBezTo",
            x: "x5",
            y: "y5",
            x1: "cx5",
            y1: "cy4"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y6"
          },
          {
            cmd: "quadBezTo",
            x: "x2",
            y: "y6",
            x1: "hc",
            y1: "cy6"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y5"
          },
          {
            cmd: "quadBezTo",
            x: "l",
            y: "rh",
            x1: "cx4",
            y1: "cy4"
          },
          {
            cmd: "lineTo",
            x: "wd8",
            y: "y2"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darkenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x3",
            y: "y7"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y3"
          },
          {
            cmd: "quadBezTo",
            x: "x5",
            y: "y3",
            x1: "hc",
            y1: "cy3"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y7"
          },
          {
            cmd: "quadBezTo",
            x: "x3",
            y: "y7",
            x1: "hc",
            y1: "cy7"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "quadBezTo",
            x: "x3",
            y: "y1",
            x1: "cx1",
            y1: "cy1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y3"
          },
          {
            cmd: "quadBezTo",
            x: "x5",
            y: "y3",
            x1: "hc",
            y1: "cy3"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "quadBezTo",
            x: "r",
            y: "t",
            x1: "cx2",
            y1: "cy1"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "rh"
          },
          {
            cmd: "quadBezTo",
            x: "x5",
            y: "y5",
            x1: "cx5",
            y1: "cy4"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y6"
          },
          {
            cmd: "quadBezTo",
            x: "x2",
            y: "y6",
            x1: "hc",
            y1: "cy6"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y5"
          },
          {
            cmd: "quadBezTo",
            x: "l",
            y: "rh",
            x1: "cx4",
            y1: "cy4"
          },
          {
            cmd: "lineTo",
            x: "wd8",
            y: "y2"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x2",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y3"
          },
          {
            cmd: "moveTo",
            x: "x5",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y5"
          },
          {
            cmd: "moveTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y7"
          },
          {
            cmd: "moveTo",
            x: "x4",
            y: "y7"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          }
        ]
      }
    ]
  },
  [125 /* SHAPE_GEOMETRY_ELLIPSE_RIBBON2 */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 50000",
      adj3: "val 12500"
    },
    gdLst: {
      a1: "pin 0 adj1 100000",
      a2: "pin 25000 adj2 75000",
      q10: "+- 100000 0 a1",
      q11: "*/ q10 1 2",
      q12: "+- a1 0 q11",
      minAdj3: "max 0 q12",
      a3: "pin minAdj3 adj3 a1",
      dx2: "*/ w a2 200000",
      x2: "+- hc 0 dx2",
      x3: "+- x2 wd8 0",
      x4: "+- r 0 x3",
      x5: "+- r 0 x2",
      x6: "+- r 0 wd8",
      dy1: "*/ h a3 100000",
      f1: "*/ 4 dy1 w",
      q1: "*/ h a1 100000",
      q2: "+- x3 0 q1",
      u1: "*/ f1 q2 1",
      y1: "+- b 0 u1",
      cx1: "*/ x3 1 2",
      cu1: "*/ f1 cx1 1",
      cy1: "+- b 0 cu1",
      cx2: "+- r 0 cx1",
      dy3: "+- q1 0 dy1",
      q3: "*/ x2 x2 w",
      q4: "+- x2 0 q3",
      q5: "*/ f1 q4 1",
      u3: "+- q5 dy3 0",
      y3: "+- b 0 u3",
      q6: "+- dy1 dy3 u3",
      q7: "+- q6 dy1 0",
      cu3: "+- q7 dy3 0",
      cy3: "+- b 0 cu3",
      rh: "+- b 0 q1",
      q8: "*/ dy1 14 16",
      u2: "+/ q8 rh 2",
      y2: "+- b 0 u2",
      u5: "+- q5 rh 0",
      y5: "+- b 0 u5",
      u6: "+- u3 rh 0",
      y6: "+- b 0 u6",
      cx4: "*/ x2 1 2",
      q9: "*/ f1 cx4 1",
      cu4: "+- q9 rh 0",
      cy4: "+- b 0 cu4",
      cx5: "+- r 0 cx4",
      cu6: "+- cu3 rh 0",
      cy6: "+- b 0 cu6",
      u7: "+- u1 dy3 0",
      y7: "+- b 0 u7",
      cu7: "+- q1 q1 u7",
      cy7: "+- b 0 cu7"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "100000",
        pos: {
          x: "hc",
          y: "rh"
        }
      },
      {
        gdRefX: "adj2",
        minX: "25000",
        maxX: "100000",
        pos: {
          x: "x2",
          y: "t"
        }
      },
      {
        gdRefY: "adj3",
        minY: "minAdj3",
        maxY: "a1",
        pos: {
          x: "l",
          y: "dy1"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "wd8",
          y: "y2"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "rh"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x6",
          y: "y2"
        }
      }
    ],
    rect: {
      l: "x2",
      t: "y6",
      r: "x5",
      b: "rh"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "quadBezTo",
            x: "x3",
            y: "y1",
            x1: "cx1",
            y1: "cy1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y3"
          },
          {
            cmd: "quadBezTo",
            x: "x5",
            y: "y3",
            x1: "hc",
            y1: "cy3"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "quadBezTo",
            x: "r",
            y: "b",
            x1: "cx2",
            y1: "cy1"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "q1"
          },
          {
            cmd: "quadBezTo",
            x: "x5",
            y: "y5",
            x1: "cx5",
            y1: "cy4"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y6"
          },
          {
            cmd: "quadBezTo",
            x: "x2",
            y: "y6",
            x1: "hc",
            y1: "cy6"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y5"
          },
          {
            cmd: "quadBezTo",
            x: "l",
            y: "q1",
            x1: "cx4",
            y1: "cy4"
          },
          {
            cmd: "lineTo",
            x: "wd8",
            y: "y2"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darkenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x3",
            y: "y7"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y3"
          },
          {
            cmd: "quadBezTo",
            x: "x5",
            y: "y3",
            x1: "hc",
            y1: "cy3"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y7"
          },
          {
            cmd: "quadBezTo",
            x: "x3",
            y: "y7",
            x1: "hc",
            y1: "cy7"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "wd8",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "q1"
          },
          {
            cmd: "quadBezTo",
            x: "x2",
            y: "y5",
            x1: "cx4",
            y1: "cy4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y6"
          },
          {
            cmd: "quadBezTo",
            x: "x5",
            y: "y6",
            x1: "hc",
            y1: "cy6"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y5"
          },
          {
            cmd: "quadBezTo",
            x: "r",
            y: "q1",
            x1: "cx5",
            y1: "cy4"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "quadBezTo",
            x: "x4",
            y: "y1",
            x1: "cx2",
            y1: "cy1"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y3"
          },
          {
            cmd: "quadBezTo",
            x: "x2",
            y: "y3",
            x1: "hc",
            y1: "cy3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "quadBezTo",
            x: "l",
            y: "b",
            x1: "cx1",
            y1: "cy1"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x2",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y5"
          },
          {
            cmd: "moveTo",
            x: "x5",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y3"
          },
          {
            cmd: "moveTo",
            x: "x3",
            y: "y7"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "moveTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y7"
          }
        ]
      }
    ]
  },
  [159 /* SHAPE_GEOMETRY_FLOW_CHART_ALTERNATE_PROCESS */]: {
    avLst: {},
    gdLst: {
      x2: "+- r 0 ssd6",
      y2: "+- b 0 ssd6",
      il: "*/ ssd6 29289 100000",
      ir: "+- r 0 il",
      ib: "+- b 0 il"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "il",
      t: "il",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "ssd6"
          },
          {
            cmd: "arcTo",
            wR: "ssd6",
            hR: "ssd6",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "ssd6",
            hR: "ssd6",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "ssd6",
            hR: "ssd6",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "ssd6",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "ssd6",
            hR: "ssd6",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [148 /* SHAPE_GEOMETRY_FLOW_CHART_COLLATE */]: {
    avLst: {},
    gdLst: {
      ir: "*/ w 3 4",
      ib: "*/ h 3 4"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      }
    ],
    rect: {
      l: "wd4",
      t: "hd4",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        w: "2",
        h: "2",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "2",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "1"
          },
          {
            cmd: "lineTo",
            x: "2",
            y: "2"
          },
          {
            cmd: "lineTo",
            x: "0",
            y: "2"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "1"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [143 /* SHAPE_GEOMETRY_FLOW_CHART_CONNECTOR */]: {
    avLst: {},
    gdLst: {
      idx: "cos wd2 2700000",
      idy: "sin hd2 2700000",
      il: "+- hc 0 idx",
      ir: "+- hc idx 0",
      it: "+- vc 0 idy",
      ib: "+- vc idy 0"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "il",
          y: "it"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "il",
          y: "ib"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "ir",
          y: "ib"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "ir",
          y: "it"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [133 /* SHAPE_GEOMETRY_FLOW_CHART_DECISION */]: {
    avLst: {},
    gdLst: {
      ir: "*/ w 3 4",
      ib: "*/ h 3 4"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "wd4",
      t: "hd4",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        w: "2",
        h: "2",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "1"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "2",
            y: "1"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [158 /* SHAPE_GEOMETRY_FLOW_CHART_DELAY */]: {
    avLst: {},
    gdLst: {
      idx: "cos wd2 2700000",
      idy: "sin hd2 2700000",
      ir: "+- hc idx 0",
      it: "+- vc 0 idy",
      ib: "+- vc idy 0"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "3cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [157 /* SHAPE_GEOMETRY_FLOW_CHART_DISPLAY */]: {
    avLst: {},
    gdLst: {
      x2: "*/ w 5 6"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "wd6",
      t: "t",
      r: "x2",
      b: "b"
    },
    paths: [
      {
        w: "6",
        h: "6",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "3"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "5",
            y: "0"
          },
          {
            cmd: "arcTo",
            wR: "1",
            hR: "3",
            stAng: "3cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "6"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [137 /* SHAPE_GEOMETRY_FLOW_CHART_DOCUMENT */]: {
    avLst: {},
    gdLst: {
      y1: "*/ h 17322 21600",
      y2: "*/ h 20172 21600"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "y2"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "y1"
    },
    paths: [
      {
        w: "21600",
        h: "21600",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "21600",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "21600",
            y: "17322"
          },
          {
            cmd: "cubicBezTo",
            x: "0",
            y: "20172",
            x1: "10800",
            y1: "17322",
            x2: "10800",
            y2: "23922"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [150 /* SHAPE_GEOMETRY_FLOW_CHART_EXTRACT */]: {
    avLst: {},
    gdLst: {
      x2: "*/ w 3 4"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "wd4",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x2",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "wd4",
      t: "vc",
      r: "x2",
      b: "b"
    },
    paths: [
      {
        w: "2",
        h: "2",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "2"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "2",
            y: "2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [134 /* SHAPE_GEOMETRY_FLOW_CHART_INPUT_OUTPUT */]: {
    avLst: {},
    gdLst: {
      x3: "*/ w 2 5",
      x4: "*/ w 3 5",
      x5: "*/ w 4 5",
      x6: "*/ w 9 10"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x4",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "wd10",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x3",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x6",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "wd5",
      t: "t",
      r: "x5",
      b: "b"
    },
    paths: [
      {
        w: "5",
        h: "5",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "5"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "5",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "4",
            y: "5"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [136 /* SHAPE_GEOMETRY_FLOW_CHART_INTERNAL_STORAGE */]: {
    avLst: {},
    gdLst: {},
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "wd8",
      t: "hd8",
      r: "r",
      b: "b"
    },
    paths: [
      {
        w: "1",
        h: "1",
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "1"
          },
          {
            cmd: "lineTo",
            x: "0",
            y: "1"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        w: "8",
        h: "8",
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "1",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "8"
          },
          {
            cmd: "moveTo",
            x: "0",
            y: "1"
          },
          {
            cmd: "lineTo",
            x: "8",
            y: "1"
          }
        ]
      },
      {
        w: "1",
        h: "1",
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "1"
          },
          {
            cmd: "lineTo",
            x: "0",
            y: "1"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  }
};

// node_modules/@oai/granola/dist/shapes/preset-shape-definitions.part3.js
var presetShapeDefinitionsPart3 = {
  [155 /* SHAPE_GEOMETRY_FLOW_CHART_MAGNETIC_DISK */]: {
    avLst: {},
    gdLst: {
      y3: "*/ h 5 6"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "hd3"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "hd3",
      r: "r",
      b: "y3"
    },
    paths: [
      {
        w: "6",
        h: "6",
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "1"
          },
          {
            cmd: "arcTo",
            wR: "3",
            hR: "1",
            stAng: "cd2",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "6",
            y: "5"
          },
          {
            cmd: "arcTo",
            wR: "3",
            hR: "1",
            stAng: "0",
            swAng: "cd2"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        w: "6",
        h: "6",
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "6",
            y: "1"
          },
          {
            cmd: "arcTo",
            wR: "3",
            hR: "1",
            stAng: "0",
            swAng: "cd2"
          }
        ]
      },
      {
        w: "6",
        h: "6",
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "1"
          },
          {
            cmd: "arcTo",
            wR: "3",
            hR: "1",
            stAng: "cd2",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "6",
            y: "5"
          },
          {
            cmd: "arcTo",
            wR: "3",
            hR: "1",
            stAng: "0",
            swAng: "cd2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [156 /* SHAPE_GEOMETRY_FLOW_CHART_MAGNETIC_DRUM */]: {
    avLst: {},
    gdLst: {
      x2: "*/ w 2 3"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x2",
          y: "vc"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "wd6",
      t: "t",
      r: "x2",
      b: "b"
    },
    paths: [
      {
        w: "6",
        h: "6",
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "1",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "5",
            y: "0"
          },
          {
            cmd: "arcTo",
            wR: "1",
            hR: "3",
            stAng: "3cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "6"
          },
          {
            cmd: "arcTo",
            wR: "1",
            hR: "3",
            stAng: "cd4",
            swAng: "cd2"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        w: "6",
        h: "6",
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "5",
            y: "6"
          },
          {
            cmd: "arcTo",
            wR: "1",
            hR: "3",
            stAng: "cd4",
            swAng: "cd2"
          }
        ]
      },
      {
        w: "6",
        h: "6",
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "1",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "5",
            y: "0"
          },
          {
            cmd: "arcTo",
            wR: "1",
            hR: "3",
            stAng: "3cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "6"
          },
          {
            cmd: "arcTo",
            wR: "1",
            hR: "3",
            stAng: "cd4",
            swAng: "cd2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [154 /* SHAPE_GEOMETRY_FLOW_CHART_MAGNETIC_TAPE */]: {
    avLst: {},
    gdLst: {
      idx: "cos wd2 2700000",
      idy: "sin hd2 2700000",
      il: "+- hc 0 idx",
      ir: "+- hc idx 0",
      it: "+- vc 0 idy",
      ib: "+- vc idy 0",
      ang1: "at2 w h"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        w: "21600",
        h: "21600",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "0",
            swAng: "ang1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "ib"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [141 /* SHAPE_GEOMETRY_FLOW_CHART_MANUAL_INPUT */]: {
    avLst: {},
    gdLst: {},
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "hd10"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "hd5",
      r: "r",
      b: "b"
    },
    paths: [
      {
        w: "5",
        h: "5",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "1"
          },
          {
            cmd: "lineTo",
            x: "5",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "5",
            y: "5"
          },
          {
            cmd: "lineTo",
            x: "0",
            y: "5"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [142 /* SHAPE_GEOMETRY_FLOW_CHART_MANUAL_OPERATION */]: {
    avLst: {},
    gdLst: {
      x3: "*/ w 4 5",
      x4: "*/ w 9 10"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "wd10",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x4",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "wd5",
      t: "t",
      r: "x3",
      b: "b"
    },
    paths: [
      {
        w: "5",
        h: "5",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "5",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "4",
            y: "5"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "5"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [151 /* SHAPE_GEOMETRY_FLOW_CHART_MERGE */]: {
    avLst: {},
    gdLst: {
      x2: "*/ w 3 4"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "wd4",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x2",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "wd4",
      t: "t",
      r: "x2",
      b: "vc"
    },
    paths: [
      {
        w: "2",
        h: "2",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "2",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [138 /* SHAPE_GEOMETRY_FLOW_CHART_MULTIDOCUMENT */]: {
    avLst: {},
    gdLst: {
      y2: "*/ h 3675 21600",
      y8: "*/ h 20782 21600",
      x3: "*/ w 9298 21600",
      x4: "*/ w 12286 21600",
      x5: "*/ w 18595 21600"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x4",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x3",
          y: "y8"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "y2",
      r: "x5",
      b: "y8"
    },
    paths: [
      {
        w: "21600",
        h: "21600",
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "20782"
          },
          {
            cmd: "cubicBezTo",
            x: "18595",
            y: "18022",
            x1: "9298",
            y1: "23542",
            x2: "9298",
            y2: "18022"
          },
          {
            cmd: "lineTo",
            x: "18595",
            y: "3675"
          },
          {
            cmd: "lineTo",
            x: "0",
            y: "3675"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "1532",
            y: "3675"
          },
          {
            cmd: "lineTo",
            x: "1532",
            y: "1815"
          },
          {
            cmd: "lineTo",
            x: "20000",
            y: "1815"
          },
          {
            cmd: "lineTo",
            x: "20000",
            y: "16252"
          },
          {
            cmd: "cubicBezTo",
            x: "18595",
            y: "16352",
            x1: "19298",
            y1: "16252",
            x2: "18595",
            y2: "16352"
          },
          {
            cmd: "lineTo",
            x: "18595",
            y: "3675"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "2972",
            y: "1815"
          },
          {
            cmd: "lineTo",
            x: "2972",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "21600",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "21600",
            y: "14392"
          },
          {
            cmd: "cubicBezTo",
            x: "20000",
            y: "14467",
            x1: "20800",
            y1: "14392",
            x2: "20000",
            y2: "14467"
          },
          {
            cmd: "lineTo",
            x: "20000",
            y: "1815"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        w: "21600",
        h: "21600",
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "3675"
          },
          {
            cmd: "lineTo",
            x: "18595",
            y: "3675"
          },
          {
            cmd: "lineTo",
            x: "18595",
            y: "18022"
          },
          {
            cmd: "cubicBezTo",
            x: "0",
            y: "20782",
            x1: "9298",
            y1: "18022",
            x2: "9298",
            y2: "23542"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "1532",
            y: "3675"
          },
          {
            cmd: "lineTo",
            x: "1532",
            y: "1815"
          },
          {
            cmd: "lineTo",
            x: "20000",
            y: "1815"
          },
          {
            cmd: "lineTo",
            x: "20000",
            y: "16252"
          },
          {
            cmd: "cubicBezTo",
            x: "18595",
            y: "16352",
            x1: "19298",
            y1: "16252",
            x2: "18595",
            y2: "16352"
          },
          {
            cmd: "moveTo",
            x: "2972",
            y: "1815"
          },
          {
            cmd: "lineTo",
            x: "2972",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "21600",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "21600",
            y: "14392"
          },
          {
            cmd: "cubicBezTo",
            x: "20000",
            y: "14467",
            x1: "20800",
            y1: "14392",
            x2: "20000",
            y2: "14467"
          }
        ]
      },
      {
        w: "21600",
        h: "21600",
        fill: "none",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "20782"
          },
          {
            cmd: "cubicBezTo",
            x: "18595",
            y: "18022",
            x1: "9298",
            y1: "23542",
            x2: "9298",
            y2: "18022"
          },
          {
            cmd: "lineTo",
            x: "18595",
            y: "16352"
          },
          {
            cmd: "cubicBezTo",
            x: "20000",
            y: "16252",
            x1: "18595",
            y1: "16352",
            x2: "19298",
            y2: "16252"
          },
          {
            cmd: "lineTo",
            x: "20000",
            y: "14467"
          },
          {
            cmd: "cubicBezTo",
            x: "21600",
            y: "14392",
            x1: "20000",
            y1: "14467",
            x2: "20800",
            y2: "14392"
          },
          {
            cmd: "lineTo",
            x: "21600",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "2972",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "2972",
            y: "1815"
          },
          {
            cmd: "lineTo",
            x: "1532",
            y: "1815"
          },
          {
            cmd: "lineTo",
            x: "1532",
            y: "3675"
          },
          {
            cmd: "lineTo",
            x: "0",
            y: "3675"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [152 /* SHAPE_GEOMETRY_FLOW_CHART_OFFLINE_STORAGE */]: {
    avLst: {},
    gdLst: {
      x4: "*/ w 3 4"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "x4",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "wd4",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "wd4",
      t: "t",
      r: "x4",
      b: "vc"
    },
    paths: [
      {
        w: "2",
        h: "2",
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "2",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "2"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        w: "5",
        h: "5",
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "2",
            y: "4"
          },
          {
            cmd: "lineTo",
            x: "3",
            y: "4"
          }
        ]
      },
      {
        w: "2",
        h: "2",
        fill: "none",
        stroke: true,
        extrusionOk: true,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "2",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [160 /* SHAPE_GEOMETRY_FLOW_CHART_OFFPAGE_CONNECTOR */]: {
    avLst: {},
    gdLst: {
      y1: "*/ h 4 5"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "y1"
    },
    paths: [
      {
        w: "10",
        h: "10",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "10",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "10",
            y: "8"
          },
          {
            cmd: "lineTo",
            x: "5",
            y: "10"
          },
          {
            cmd: "lineTo",
            x: "0",
            y: "8"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [153 /* SHAPE_GEOMETRY_FLOW_CHART_ONLINE_STORAGE */]: {
    avLst: {},
    gdLst: {
      x2: "*/ w 5 6"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x2",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "wd6",
      t: "t",
      r: "x2",
      b: "b"
    },
    paths: [
      {
        w: "6",
        h: "6",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "1",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "6",
            y: "0"
          },
          {
            cmd: "arcTo",
            wR: "1",
            hR: "3",
            stAng: "3cd4",
            swAng: "-10800000"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "6"
          },
          {
            cmd: "arcTo",
            wR: "1",
            hR: "3",
            stAng: "cd4",
            swAng: "cd2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [147 /* SHAPE_GEOMETRY_FLOW_CHART_OR */]: {
    avLst: {},
    gdLst: {
      idx: "cos wd2 2700000",
      idy: "sin hd2 2700000",
      il: "+- hc 0 idx",
      ir: "+- hc idx 0",
      it: "+- vc 0 idy",
      ib: "+- vc idy 0"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "il",
          y: "it"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "il",
          y: "ib"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "ir",
          y: "ib"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "ir",
          y: "it"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [135 /* SHAPE_GEOMETRY_FLOW_CHART_PREDEFINED_PROCESS */]: {
    avLst: {},
    gdLst: {
      x2: "*/ w 7 8"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "wd8",
      t: "t",
      r: "x2",
      b: "b"
    },
    paths: [
      {
        w: "1",
        h: "1",
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "1"
          },
          {
            cmd: "lineTo",
            x: "0",
            y: "1"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        w: "8",
        h: "8",
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "1",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "8"
          },
          {
            cmd: "moveTo",
            x: "7",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "7",
            y: "8"
          }
        ]
      },
      {
        w: "1",
        h: "1",
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "1"
          },
          {
            cmd: "lineTo",
            x: "0",
            y: "1"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [140 /* SHAPE_GEOMETRY_FLOW_CHART_PREPARATION */]: {
    avLst: {},
    gdLst: {
      x2: "*/ w 4 5"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "wd5",
      t: "t",
      r: "x2",
      b: "b"
    },
    paths: [
      {
        w: "10",
        h: "10",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "5"
          },
          {
            cmd: "lineTo",
            x: "2",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "8",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "10",
            y: "5"
          },
          {
            cmd: "lineTo",
            x: "8",
            y: "10"
          },
          {
            cmd: "lineTo",
            x: "2",
            y: "10"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [132 /* SHAPE_GEOMETRY_FLOW_CHART_PROCESS */]: {
    avLst: {},
    gdLst: {},
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        w: "1",
        h: "1",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "1"
          },
          {
            cmd: "lineTo",
            x: "0",
            y: "1"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [144 /* SHAPE_GEOMETRY_FLOW_CHART_PUNCHED_CARD */]: {
    avLst: {},
    gdLst: {},
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "hd5",
      r: "r",
      b: "b"
    },
    paths: [
      {
        w: "5",
        h: "5",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "1"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "5",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "5",
            y: "5"
          },
          {
            cmd: "lineTo",
            x: "0",
            y: "5"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [145 /* SHAPE_GEOMETRY_FLOW_CHART_PUNCHED_TAPE */]: {
    avLst: {},
    gdLst: {
      y2: "*/ h 9 10",
      ib: "*/ h 4 5"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "hd10"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "y2"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "hd5",
      r: "r",
      b: "ib"
    },
    paths: [
      {
        w: "20",
        h: "20",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "2"
          },
          {
            cmd: "arcTo",
            wR: "5",
            hR: "2",
            stAng: "cd2",
            swAng: "-10800000"
          },
          {
            cmd: "arcTo",
            wR: "5",
            hR: "2",
            stAng: "cd2",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "20",
            y: "18"
          },
          {
            cmd: "arcTo",
            wR: "5",
            hR: "2",
            stAng: "0",
            swAng: "-10800000"
          },
          {
            cmd: "arcTo",
            wR: "5",
            hR: "2",
            stAng: "0",
            swAng: "cd2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [149 /* SHAPE_GEOMETRY_FLOW_CHART_SORT */]: {
    avLst: {},
    gdLst: {
      ir: "*/ w 3 4",
      ib: "*/ h 3 4"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "wd4",
      t: "hd4",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        w: "2",
        h: "2",
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "1"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "2",
            y: "1"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "2"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        w: "2",
        h: "2",
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "1"
          },
          {
            cmd: "lineTo",
            x: "2",
            y: "1"
          }
        ]
      },
      {
        w: "2",
        h: "2",
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "0",
            y: "1"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "2",
            y: "1"
          },
          {
            cmd: "lineTo",
            x: "1",
            y: "2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [146 /* SHAPE_GEOMETRY_FLOW_CHART_SUMMING_JUNCTION */]: {
    avLst: {},
    gdLst: {
      idx: "cos wd2 2700000",
      idy: "sin hd2 2700000",
      il: "+- hc 0 idx",
      ir: "+- hc idx 0",
      it: "+- vc 0 idy",
      ib: "+- vc idy 0"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "il",
          y: "it"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "il",
          y: "ib"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "ir",
          y: "ib"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "ir",
          y: "it"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "il",
            y: "it"
          },
          {
            cmd: "lineTo",
            x: "ir",
            y: "ib"
          },
          {
            cmd: "moveTo",
            x: "ir",
            y: "it"
          },
          {
            cmd: "lineTo",
            x: "il",
            y: "ib"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [139 /* SHAPE_GEOMETRY_FLOW_CHART_TERMINATOR */]: {
    avLst: {},
    gdLst: {
      il: "*/ w 1018 21600",
      ir: "*/ w 20582 21600",
      it: "*/ h 3163 21600",
      ib: "*/ h 18437 21600"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "3475",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "18125",
            y: "0"
          },
          {
            cmd: "arcTo",
            wR: "3475",
            hR: "10800",
            stAng: "3cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "3475",
            y: "21600"
          },
          {
            cmd: "arcTo",
            wR: "3475",
            hR: "10800",
            stAng: "cd4",
            swAng: "cd2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [82 /* SHAPE_GEOMETRY_FOLDED_CORNER */]: {
    avLst: {
      adj: "val 16667"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      dy2: "*/ ss a 100000",
      dy1: "*/ dy2 1 5",
      x1: "+- r 0 dy2",
      x2: "+- x1 dy1 0",
      y2: "+- b 0 dy2",
      y1: "+- y2 dy1 0"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x1",
          y: "b"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "y2"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darkenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          }
        ]
      }
    ]
  },
  [84 /* SHAPE_GEOMETRY_FRAME */]: {
    avLst: {
      adj1: "val 12500"
    },
    gdLst: {
      a1: "pin 0 adj1 50000",
      x1: "*/ ss a1 100000",
      x4: "+- r 0 x1",
      y4: "+- b 0 x1"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x1",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "x1",
      r: "x4",
      b: "y4"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x1",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "x1"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [175 /* SHAPE_GEOMETRY_FUNNEL */]: {
    avLst: {},
    gdLst: {
      d: "*/ ss 1 20",
      rw2: "+- wd2 0 d",
      rh2: "+- hd4 0 d",
      t1: "cos wd2 480000",
      t2: "sin hd4 480000",
      da: "at2 t1 t2",
      "2da": "*/ da 2 1",
      stAng1: "+- cd2 0 da",
      swAng1: "+- cd2 2da 0",
      swAng3: "+- cd2 0 2da",
      rw3: "*/ wd2 1 4",
      rh3: "*/ hd4 1 4",
      ct1: "cos hd4 stAng1",
      st1: "sin wd2 stAng1",
      m1: "mod ct1 st1 0",
      n1: "*/ wd2 hd4 m1",
      dx1: "cos n1 stAng1",
      dy1: "sin n1 stAng1",
      x1: "+- hc dx1 0",
      y1: "+- hd4 dy1 0",
      ct3: "cos rh3 da",
      st3: "sin rw3 da",
      m3: "mod ct3 st3 0",
      n3: "*/ rw3 rh3 m3",
      dx3: "cos n3 da",
      dy3: "sin n3 da",
      x3: "+- hc dx3 0",
      vc3: "+- b 0 rh3",
      y2: "+- vc3 dy3 0",
      x2: "+- wd2 0 rw2",
      cd: "*/ cd2 2 1"
    },
    ahLst: [],
    cxnLst: [],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd4",
            stAng: "stAng1",
            swAng: "swAng1"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "rw3",
            hR: "rh3",
            stAng: "da",
            swAng: "swAng3"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x2",
            y: "hd4"
          },
          {
            cmd: "arcTo",
            wR: "rw2",
            hR: "rh2",
            stAng: "cd2",
            swAng: "-21600000"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [173 /* SHAPE_GEOMETRY_GEAR6 */]: {
    avLst: {
      adj1: "val 15000",
      adj2: "val 3526"
    },
    gdLst: {
      a1: "at2 yAD1 xAD1",
      a2: "pin 0 adj2 5358",
      th: "*/ ss a1 100000",
      lFD: "*/ ss a2 100000",
      th2: "*/ th 1 2",
      l2: "*/ lFD 1 2",
      l3: "+- th2 l2 0",
      rh: "+- hd2 0 th",
      rw: "+- wd2 0 th",
      dr: "+- rw 0 rh",
      maxr: "?: dr rh rw",
      ha: "at2 maxr l3",
      aA1: "+- 19800000 0 ha",
      aD1: "+- 19800000 ha 0",
      ta11: "cos rw aA1",
      ta12: "sin rh aA1",
      bA1: "at2 ta11 ta12",
      cta1: "cos rh bA1",
      sta1: "sin rw bA1",
      ma1: "mod cta1 sta1 0",
      na1: "*/ rw rh ma1",
      dxa1: "cos na1 bA1",
      dya1: "sin na1 bA1",
      xA1: "+- hc dxa1 0",
      yA1: "+- vc dya1 0",
      td11: "cos rw aD1",
      td12: "sin rh aD1",
      bD1: "at2 td11 td12",
      ctd1: "cos rh bD1",
      std1: "sin rw bD1",
      md1: "mod ctd1 std1 0",
      nd1: "*/ rw rh md1",
      dxd1: "cos nd1 bD1",
      dyd1: "sin nd1 bD1",
      xD1: "+- hc dxd1 0",
      yD1: "+- vc dyd1 0",
      xAD1: "+- xA1 0 xD1",
      yAD1: "+- yA1 0 yD1",
      lAD1: "mod xAD1 yAD1 0",
      dxF1: "sin lFD a1",
      dyF1: "cos lFD a1",
      xF1: "+- xD1 dxF1 0",
      yF1: "+- yD1 dyF1 0",
      xE1: "+- xA1 0 dxF1",
      yE1: "+- yA1 0 dyF1",
      yC1t: "sin th a1",
      xC1t: "cos th a1",
      yC1: "+- yF1 yC1t 0",
      xC1: "+- xF1 0 xC1t",
      yB1: "+- yE1 yC1t 0",
      xB1: "+- xE1 0 xC1t",
      aD6: "+- 3cd4 ha 0",
      td61: "cos rw aD6",
      td62: "sin rh aD6",
      bD6: "at2 td61 td62",
      ctd6: "cos rh bD6",
      std6: "sin rw bD6",
      md6: "mod ctd6 std6 0",
      nd6: "*/ rw rh md6",
      dxd6: "cos nd6 bD6",
      dyd6: "sin nd6 bD6",
      xD6: "+- hc dxd6 0",
      yD6: "+- vc dyd6 0",
      xA6: "+- hc 0 dxd6",
      xF6: "+- xD6 0 lFD",
      xE6: "+- xA6 lFD 0",
      yC6: "+- yD6 0 th",
      swAng1: "+- bA1 0 bD6",
      aA2: "+- 1800000 0 ha",
      aD2: "+- 1800000 ha 0",
      ta21: "cos rw aA2",
      ta22: "sin rh aA2",
      bA2: "at2 ta21 ta22",
      yA2: "+- h 0 yD1",
      td21: "cos rw aD2",
      td22: "sin rh aD2",
      bD2: "at2 td21 td22",
      yD2: "+- h 0 yA1",
      yC2: "+- h 0 yB1",
      yB2: "+- h 0 yC1",
      xB2: "val xC1",
      swAng2: "+- bA2 0 bD1",
      aD3: "+- cd4 ha 0",
      td31: "cos rw aD3",
      td32: "sin rh aD3",
      bD3: "at2 td31 td32",
      yD3: "+- h 0 yD6",
      yB3: "+- h 0 yC6",
      aD4: "+- 9000000 ha 0",
      td41: "cos rw aD4",
      td42: "sin rh aD4",
      bD4: "at2 td41 td42",
      xD4: "+- w 0 xD1",
      xC4: "+- w 0 xC1",
      xB4: "+- w 0 xB1",
      aD5: "+- 12600000 ha 0",
      td51: "cos rw aD5",
      td52: "sin rh aD5",
      bD5: "at2 td51 td52",
      xD5: "+- w 0 xA1",
      xC5: "+- w 0 xB1",
      xB5: "+- w 0 xC1",
      xCxn1: "+/ xB1 xC1 2",
      yCxn1: "+/ yB1 yC1 2",
      yCxn2: "+- b 0 yCxn1",
      xCxn4: "+/ r 0 xCxn1"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "20000",
        pos: {
          x: "xD6",
          y: "yD6"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "5358",
        pos: {
          x: "xA6",
          y: "yD6"
        }
      }
    ],
    cxnLst: [
      {
        ang: "19800000",
        pos: {
          x: "xCxn1",
          y: "yCxn1"
        }
      },
      {
        ang: "1800000",
        pos: {
          x: "xCxn1",
          y: "yCxn2"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "yB3"
        }
      },
      {
        ang: "9000000",
        pos: {
          x: "xCxn4",
          y: "yCxn2"
        }
      },
      {
        ang: "12600000",
        pos: {
          x: "xCxn4",
          y: "yCxn1"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "yC6"
        }
      }
    ],
    rect: {
      l: "xD5",
      t: "yA1",
      r: "xA1",
      b: "yD2"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "xA1",
            y: "yA1"
          },
          {
            cmd: "lineTo",
            x: "xB1",
            y: "yB1"
          },
          {
            cmd: "lineTo",
            x: "xC1",
            y: "yC1"
          },
          {
            cmd: "lineTo",
            x: "xD1",
            y: "yD1"
          },
          {
            cmd: "arcTo",
            wR: "rw",
            hR: "rh",
            stAng: "bD1",
            swAng: "swAng2"
          },
          {
            cmd: "lineTo",
            x: "xC1",
            y: "yB2"
          },
          {
            cmd: "lineTo",
            x: "xB1",
            y: "yC2"
          },
          {
            cmd: "lineTo",
            x: "xA1",
            y: "yD2"
          },
          {
            cmd: "arcTo",
            wR: "rw",
            hR: "rh",
            stAng: "bD2",
            swAng: "swAng1"
          },
          {
            cmd: "lineTo",
            x: "xF6",
            y: "yB3"
          },
          {
            cmd: "lineTo",
            x: "xE6",
            y: "yB3"
          },
          {
            cmd: "lineTo",
            x: "xA6",
            y: "yD3"
          },
          {
            cmd: "arcTo",
            wR: "rw",
            hR: "rh",
            stAng: "bD3",
            swAng: "swAng1"
          },
          {
            cmd: "lineTo",
            x: "xB4",
            y: "yC2"
          },
          {
            cmd: "lineTo",
            x: "xC4",
            y: "yB2"
          },
          {
            cmd: "lineTo",
            x: "xD4",
            y: "yA2"
          },
          {
            cmd: "arcTo",
            wR: "rw",
            hR: "rh",
            stAng: "bD4",
            swAng: "swAng2"
          },
          {
            cmd: "lineTo",
            x: "xB5",
            y: "yC1"
          },
          {
            cmd: "lineTo",
            x: "xC5",
            y: "yB1"
          },
          {
            cmd: "lineTo",
            x: "xD5",
            y: "yA1"
          },
          {
            cmd: "arcTo",
            wR: "rw",
            hR: "rh",
            stAng: "bD5",
            swAng: "swAng1"
          },
          {
            cmd: "lineTo",
            x: "xE6",
            y: "yC6"
          },
          {
            cmd: "lineTo",
            x: "xF6",
            y: "yC6"
          },
          {
            cmd: "lineTo",
            x: "xD6",
            y: "yD6"
          },
          {
            cmd: "arcTo",
            wR: "rw",
            hR: "rh",
            stAng: "bD6",
            swAng: "swAng1"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [174 /* SHAPE_GEOMETRY_GEAR9 */]: {
    avLst: {
      adj1: "val 10000",
      adj2: "val 1763"
    },
    gdLst: {
      a1: "at2 yAD1 xAD1",
      a2: "at2 yAD2 xAD2",
      th: "*/ ss a1 100000",
      lFD: "*/ ss a2 100000",
      th2: "*/ th 1 2",
      l2: "*/ lFD 1 2",
      l3: "+- th2 l2 0",
      rh: "+- hd2 0 th",
      rw: "+- wd2 0 th",
      dr: "+- rw 0 rh",
      maxr: "?: dr rh rw",
      ha: "at2 maxr l3",
      aA1: "+- 18600000 0 ha",
      aD1: "+- 18600000 ha 0",
      ta11: "cos rw aA1",
      ta12: "sin rh aA1",
      bA1: "at2 ta11 ta12",
      cta1: "cos rh bA1",
      sta1: "sin rw bA1",
      ma1: "mod cta1 sta1 0",
      na1: "*/ rw rh ma1",
      dxa1: "cos na1 bA1",
      dya1: "sin na1 bA1",
      xA1: "+- hc dxa1 0",
      yA1: "+- vc dya1 0",
      td11: "cos rw aD1",
      td12: "sin rh aD1",
      bD1: "at2 td11 td12",
      ctd1: "cos rh bD1",
      std1: "sin rw bD1",
      md1: "mod ctd1 std1 0",
      nd1: "*/ rw rh md1",
      dxd1: "cos nd1 bD1",
      dyd1: "sin nd1 bD1",
      xD1: "+- hc dxd1 0",
      yD1: "+- vc dyd1 0",
      xAD1: "+- xA1 0 xD1",
      yAD1: "+- yA1 0 yD1",
      lAD1: "mod xAD1 yAD1 0",
      dxF1: "sin lFD a1",
      dyF1: "cos lFD a1",
      xF1: "+- xD1 dxF1 0",
      yF1: "+- yD1 dyF1 0",
      xE1: "+- xA1 0 dxF1",
      yE1: "+- yA1 0 dyF1",
      yC1t: "sin th a1",
      xC1t: "cos th a1",
      yC1: "+- yF1 yC1t 0",
      xC1: "+- xF1 0 xC1t",
      yB1: "+- yE1 yC1t 0",
      xB1: "+- xE1 0 xC1t",
      aA2: "+- 21000000 0 ha",
      aD2: "+- 21000000 ha 0",
      ta21: "cos rw aA2",
      ta22: "sin rh aA2",
      bA2: "at2 ta21 ta22",
      cta2: "cos rh bA2",
      sta2: "sin rw bA2",
      ma2: "mod cta2 sta2 0",
      na2: "*/ rw rh ma2",
      dxa2: "cos na2 bA2",
      dya2: "sin na2 bA2",
      xA2: "+- hc dxa2 0",
      yA2: "+- vc dya2 0",
      td21: "cos rw aD2",
      td22: "sin rh aD2",
      bD2: "at2 td21 td22",
      ctd2: "cos rh bD2",
      std2: "sin rw bD2",
      md2: "mod ctd2 std2 0",
      nd2: "*/ rw rh md2",
      dxd2: "cos nd2 bD2",
      dyd2: "sin nd2 bD2",
      xD2: "+- hc dxd2 0",
      yD2: "+- vc dyd2 0",
      xAD2: "+- xA2 0 xD2",
      yAD2: "+- yA2 0 yD2",
      lAD2: "mod xAD2 yAD2 0",
      dxF2: "sin lFD a2",
      dyF2: "cos lFD a2",
      xF2: "+- xD2 dxF2 0",
      yF2: "+- yD2 dyF2 0",
      xE2: "+- xA2 0 dxF2",
      yE2: "+- yA2 0 dyF2",
      yC2t: "sin th a2",
      xC2t: "cos th a2",
      yC2: "+- yF2 yC2t 0",
      xC2: "+- xF2 0 xC2t",
      yB2: "+- yE2 yC2t 0",
      xB2: "+- xE2 0 xC2t",
      swAng1: "+- bA2 0 bD1",
      aA3: "+- 1800000 0 ha",
      aD3: "+- 1800000 ha 0",
      ta31: "cos rw aA3",
      ta32: "sin rh aA3",
      bA3: "at2 ta31 ta32",
      cta3: "cos rh bA3",
      sta3: "sin rw bA3",
      ma3: "mod cta3 sta3 0",
      na3: "*/ rw rh ma3",
      dxa3: "cos na3 bA3",
      dya3: "sin na3 bA3",
      xA3: "+- hc dxa3 0",
      yA3: "+- vc dya3 0",
      td31: "cos rw aD3",
      td32: "sin rh aD3",
      bD3: "at2 td31 td32",
      ctd3: "cos rh bD3",
      std3: "sin rw bD3",
      md3: "mod ctd3 std3 0",
      nd3: "*/ rw rh md3",
      dxd3: "cos nd3 bD3",
      dyd3: "sin nd3 bD3",
      xD3: "+- hc dxd3 0",
      yD3: "+- vc dyd3 0",
      xAD3: "+- xA3 0 xD3",
      yAD3: "+- yA3 0 yD3",
      lAD3: "mod xAD3 yAD3 0",
      a3: "at2 yAD3 xAD3",
      dxF3: "sin lFD a3",
      dyF3: "cos lFD a3",
      xF3: "+- xD3 dxF3 0",
      yF3: "+- yD3 dyF3 0",
      xE3: "+- xA3 0 dxF3",
      yE3: "+- yA3 0 dyF3",
      yC3t: "sin th a3",
      xC3t: "cos th a3",
      yC3: "+- yF3 yC3t 0",
      xC3: "+- xF3 0 xC3t",
      yB3: "+- yE3 yC3t 0",
      xB3: "+- xE3 0 xC3t",
      swAng2: "+- bA3 0 bD2",
      aA4: "+- 4200000 0 ha",
      aD4: "+- 4200000 ha 0",
      ta41: "cos rw aA4",
      ta42: "sin rh aA4",
      bA4: "at2 ta41 ta42",
      cta4: "cos rh bA4",
      sta4: "sin rw bA4",
      ma4: "mod cta4 sta4 0",
      na4: "*/ rw rh ma4",
      dxa4: "cos na4 bA4",
      dya4: "sin na4 bA4",
      xA4: "+- hc dxa4 0",
      yA4: "+- vc dya4 0",
      td41: "cos rw aD4",
      td42: "sin rh aD4",
      bD4: "at2 td41 td42",
      ctd4: "cos rh bD4",
      std4: "sin rw bD4",
      md4: "mod ctd4 std4 0",
      nd4: "*/ rw rh md4",
      dxd4: "cos nd4 bD4",
      dyd4: "sin nd4 bD4",
      xD4: "+- hc dxd4 0",
      yD4: "+- vc dyd4 0",
      xAD4: "+- xA4 0 xD4",
      yAD4: "+- yA4 0 yD4",
      lAD4: "mod xAD4 yAD4 0",
      a4: "at2 yAD4 xAD4",
      dxF4: "sin lFD a4",
      dyF4: "cos lFD a4",
      xF4: "+- xD4 dxF4 0",
      yF4: "+- yD4 dyF4 0",
      xE4: "+- xA4 0 dxF4",
      yE4: "+- yA4 0 dyF4",
      yC4t: "sin th a4",
      xC4t: "cos th a4",
      yC4: "+- yF4 yC4t 0",
      xC4: "+- xF4 0 xC4t",
      yB4: "+- yE4 yC4t 0",
      xB4: "+- xE4 0 xC4t",
      swAng3: "+- bA4 0 bD3",
      aA5: "+- 6600000 0 ha",
      aD5: "+- 6600000 ha 0",
      ta51: "cos rw aA5",
      ta52: "sin rh aA5",
      bA5: "at2 ta51 ta52",
      td51: "cos rw aD5",
      td52: "sin rh aD5",
      bD5: "at2 td51 td52",
      xD5: "+- w 0 xA4",
      xC5: "+- w 0 xB4",
      xB5: "+- w 0 xC4",
      swAng4: "+- bA5 0 bD4",
      aD6: "+- 9000000 ha 0",
      td61: "cos rw aD6",
      td62: "sin rh aD6",
      bD6: "at2 td61 td62",
      xD6: "+- w 0 xA3",
      xC6: "+- w 0 xB3",
      xB6: "+- w 0 xC3",
      aD7: "+- 11400000 ha 0",
      td71: "cos rw aD7",
      td72: "sin rh aD7",
      bD7: "at2 td71 td72",
      xD7: "+- w 0 xA2",
      xC7: "+- w 0 xB2",
      xB7: "+- w 0 xC2",
      aD8: "+- 13800000 ha 0",
      td81: "cos rw aD8",
      td82: "sin rh aD8",
      bD8: "at2 td81 td82",
      xA8: "+- w 0 xD1",
      xD8: "+- w 0 xA1",
      xC8: "+- w 0 xB1",
      xB8: "+- w 0 xC1",
      aA9: "+- 3cd4 0 ha",
      aD9: "+- 3cd4 ha 0",
      td91: "cos rw aD9",
      td92: "sin rh aD9",
      bD9: "at2 td91 td92",
      ctd9: "cos rh bD9",
      std9: "sin rw bD9",
      md9: "mod ctd9 std9 0",
      nd9: "*/ rw rh md9",
      dxd9: "cos nd9 bD9",
      dyd9: "sin nd9 bD9",
      xD9: "+- hc dxd9 0",
      yD9: "+- vc dyd9 0",
      ta91: "cos rw aA9",
      ta92: "sin rh aA9",
      bA9: "at2 ta91 ta92",
      xA9: "+- hc 0 dxd9",
      xF9: "+- xD9 0 lFD",
      xE9: "+- xA9 lFD 0",
      yC9: "+- yD9 0 th",
      swAng5: "+- bA9 0 bD8",
      xCxn1: "+/ xB1 xC1 2",
      yCxn1: "+/ yB1 yC1 2",
      xCxn2: "+/ xB2 xC2 2",
      yCxn2: "+/ yB2 yC2 2",
      xCxn3: "+/ xB3 xC3 2",
      yCxn3: "+/ yB3 yC3 2",
      xCxn4: "+/ xB4 xC4 2",
      yCxn4: "+/ yB4 yC4 2",
      xCxn5: "+/ r 0 xCxn4",
      xCxn6: "+/ r 0 xCxn3",
      xCxn7: "+/ r 0 xCxn2",
      xCxn8: "+/ r 0 xCxn1"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "20000",
        pos: {
          x: "xD9",
          y: "yD9"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "2679",
        pos: {
          x: "xA9",
          y: "yD9"
        }
      }
    ],
    cxnLst: [
      {
        ang: "18600000",
        pos: {
          x: "xCxn1",
          y: "yCxn1"
        }
      },
      {
        ang: "21000000",
        pos: {
          x: "xCxn2",
          y: "yCxn2"
        }
      },
      {
        ang: "1800000",
        pos: {
          x: "xCxn3",
          y: "yCxn3"
        }
      },
      {
        ang: "4200000",
        pos: {
          x: "xCxn4",
          y: "yCxn4"
        }
      },
      {
        ang: "6600000",
        pos: {
          x: "xCxn5",
          y: "yCxn4"
        }
      },
      {
        ang: "9000000",
        pos: {
          x: "xCxn6",
          y: "yCxn3"
        }
      },
      {
        ang: "11400000",
        pos: {
          x: "xCxn7",
          y: "yCxn2"
        }
      },
      {
        ang: "13800000",
        pos: {
          x: "xCxn8",
          y: "yCxn1"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "yC9"
        }
      }
    ],
    rect: {
      l: "xA8",
      t: "yD1",
      r: "xD1",
      b: "yD3"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "xA1",
            y: "yA1"
          },
          {
            cmd: "lineTo",
            x: "xB1",
            y: "yB1"
          },
          {
            cmd: "lineTo",
            x: "xC1",
            y: "yC1"
          },
          {
            cmd: "lineTo",
            x: "xD1",
            y: "yD1"
          },
          {
            cmd: "arcTo",
            wR: "rw",
            hR: "rh",
            stAng: "bD1",
            swAng: "swAng1"
          },
          {
            cmd: "lineTo",
            x: "xB2",
            y: "yB2"
          },
          {
            cmd: "lineTo",
            x: "xC2",
            y: "yC2"
          },
          {
            cmd: "lineTo",
            x: "xD2",
            y: "yD2"
          },
          {
            cmd: "arcTo",
            wR: "rw",
            hR: "rh",
            stAng: "bD2",
            swAng: "swAng2"
          },
          {
            cmd: "lineTo",
            x: "xB3",
            y: "yB3"
          },
          {
            cmd: "lineTo",
            x: "xC3",
            y: "yC3"
          },
          {
            cmd: "lineTo",
            x: "xD3",
            y: "yD3"
          },
          {
            cmd: "arcTo",
            wR: "rw",
            hR: "rh",
            stAng: "bD3",
            swAng: "swAng3"
          },
          {
            cmd: "lineTo",
            x: "xB4",
            y: "yB4"
          },
          {
            cmd: "lineTo",
            x: "xC4",
            y: "yC4"
          },
          {
            cmd: "lineTo",
            x: "xD4",
            y: "yD4"
          },
          {
            cmd: "arcTo",
            wR: "rw",
            hR: "rh",
            stAng: "bD4",
            swAng: "swAng4"
          },
          {
            cmd: "lineTo",
            x: "xB5",
            y: "yC4"
          },
          {
            cmd: "lineTo",
            x: "xC5",
            y: "yB4"
          },
          {
            cmd: "lineTo",
            x: "xD5",
            y: "yA4"
          },
          {
            cmd: "arcTo",
            wR: "rw",
            hR: "rh",
            stAng: "bD5",
            swAng: "swAng3"
          },
          {
            cmd: "lineTo",
            x: "xB6",
            y: "yC3"
          },
          {
            cmd: "lineTo",
            x: "xC6",
            y: "yB3"
          },
          {
            cmd: "lineTo",
            x: "xD6",
            y: "yA3"
          },
          {
            cmd: "arcTo",
            wR: "rw",
            hR: "rh",
            stAng: "bD6",
            swAng: "swAng2"
          },
          {
            cmd: "lineTo",
            x: "xB7",
            y: "yC2"
          },
          {
            cmd: "lineTo",
            x: "xC7",
            y: "yB2"
          },
          {
            cmd: "lineTo",
            x: "xD7",
            y: "yA2"
          },
          {
            cmd: "arcTo",
            wR: "rw",
            hR: "rh",
            stAng: "bD7",
            swAng: "swAng1"
          },
          {
            cmd: "lineTo",
            x: "xB8",
            y: "yC1"
          },
          {
            cmd: "lineTo",
            x: "xC8",
            y: "yB1"
          },
          {
            cmd: "lineTo",
            x: "xD8",
            y: "yA1"
          },
          {
            cmd: "arcTo",
            wR: "rw",
            hR: "rh",
            stAng: "bD8",
            swAng: "swAng5"
          },
          {
            cmd: "lineTo",
            x: "xE9",
            y: "yC9"
          },
          {
            cmd: "lineTo",
            x: "xF9",
            y: "yC9"
          },
          {
            cmd: "lineTo",
            x: "xD9",
            y: "yD9"
          },
          {
            cmd: "arcTo",
            wR: "rw",
            hR: "rh",
            stAng: "bD9",
            swAng: "swAng5"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [85 /* SHAPE_GEOMETRY_HALF_FRAME */]: {
    avLst: {
      adj1: "val 33333",
      adj2: "val 33333"
    },
    gdLst: {
      maxAdj2: "*/ 100000 w ss",
      a2: "pin 0 adj2 maxAdj2",
      x1: "*/ ss a2 100000",
      g1: "*/ h x1 w",
      g2: "+- h 0 g1",
      maxAdj1: "*/ 100000 g2 ss",
      a1: "pin 0 adj1 maxAdj1",
      y1: "*/ ss a1 100000",
      dx2: "*/ y1 w h",
      x2: "+- r 0 dx2",
      dy2: "*/ x1 h w",
      y2: "+- b 0 dy2",
      cx1: "*/ x1 1 2",
      cy1: "+/ y2 b 2",
      cx2: "+/ x2 r 2",
      cy2: "*/ y1 1 2"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "maxAdj1",
        pos: {
          x: "l",
          y: "y1"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "maxAdj2",
        pos: {
          x: "x1",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "cx2",
          y: "cy2"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "cx1",
          y: "cy1"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [76 /* SHAPE_GEOMETRY_HEART */]: {
    avLst: {},
    gdLst: {
      dx1: "*/ w 49 48",
      dx2: "*/ w 10 48",
      x1: "+- hc 0 dx1",
      x2: "+- hc 0 dx2",
      x3: "+- hc dx2 0",
      x4: "+- hc dx1 0",
      y1: "+- t 0 hd3",
      il: "*/ w 1 6",
      ir: "*/ w 5 6",
      ib: "*/ h 2 3"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "hd4"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      }
    ],
    rect: {
      l: "il",
      t: "hd4",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "hc",
            y: "hd4"
          },
          {
            cmd: "cubicBezTo",
            x: "hc",
            y: "b",
            x1: "x3",
            y1: "y1",
            x2: "x4",
            y2: "hd4"
          },
          {
            cmd: "cubicBezTo",
            x: "hc",
            y: "hd4",
            x1: "x1",
            y1: "hd4",
            x2: "x2",
            y2: "y1"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [12 /* SHAPE_GEOMETRY_HEPTAGON */]: {
    avLst: {
      hf: "val 102572",
      vf: "val 105210"
    },
    gdLst: {
      swd2: "*/ wd2 hf 100000",
      shd2: "*/ hd2 vf 100000",
      svc: "*/ vc  vf 100000",
      dx1: "*/ swd2 97493 100000",
      dx2: "*/ swd2 78183 100000",
      dx3: "*/ swd2 43388 100000",
      dy1: "*/ shd2 62349 100000",
      dy2: "*/ shd2 22252 100000",
      dy3: "*/ shd2 90097 100000",
      x1: "+- hc 0 dx1",
      x2: "+- hc 0 dx2",
      x3: "+- hc 0 dx3",
      x4: "+- hc dx3 0",
      x5: "+- hc dx2 0",
      x6: "+- hc dx1 0",
      y1: "+- svc 0 dy1",
      y2: "+- svc dy2 0",
      y3: "+- svc dy3 0",
      ib: "+- b 0 y1"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "x5",
          y: "y1"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x6",
          y: "y2"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x4",
          y: "y3"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x3",
          y: "y3"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y2"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x2",
          y: "y1"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "x2",
      t: "y1",
      r: "x5",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [11 /* SHAPE_GEOMETRY_HEXAGON */]: {
    avLst: {
      adj: "val 25000",
      vf: "val 115470"
    },
    gdLst: {
      maxAdj: "*/ 50000 w ss",
      a: "pin 0 adj maxAdj",
      shd2: "*/ hd2 vf 100000",
      x1: "*/ ss a 100000",
      x2: "+- r 0 x1",
      dy1: "sin shd2 3600000",
      y1: "+- vc 0 dy1",
      y2: "+- vc dy1 0",
      q1: "*/ maxAdj -1 2",
      q2: "+- a q1 0",
      q3: "?: q2 4 2",
      q4: "?: q2 3 2",
      q5: "?: q2 q1 0",
      q6: "+/ a q5 q1",
      q7: "*/ q6 q4 -1",
      q8: "+- q3 q7 0",
      il: "*/ w q8 24",
      it: "*/ h q8 24",
      ir: "+- r 0 il",
      ib: "+- b 0 it"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "0",
        maxX: "maxAdj",
        pos: {
          x: "x1",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x2",
          y: "y2"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x1",
          y: "y2"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x2",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [37 /* SHAPE_GEOMETRY_HOME_PLATE */]: {
    avLst: {
      adj: "val 50000"
    },
    gdLst: {
      maxAdj: "*/ 100000 w ss",
      a: "pin 0 adj maxAdj",
      dx1: "*/ ss a 100000",
      x1: "+- r 0 dx1",
      ir: "+/ x1 r 2",
      x2: "*/ x1 1 2"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "0",
        maxX: "maxAdj",
        pos: {
          x: "x1",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x2",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x1",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "ir",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [128 /* SHAPE_GEOMETRY_HORIZONTAL_SCROLL */]: {
    avLst: {
      adj: "val 12500"
    },
    gdLst: {
      a: "pin 0 adj 25000",
      ch: "*/ ss a 100000",
      ch2: "*/ ch 1 2",
      ch4: "*/ ch 1 4",
      y3: "+- ch ch2 0",
      y4: "+- ch ch 0",
      y6: "+- b 0 ch",
      y7: "+- b 0 ch2",
      y5: "+- y6 0 ch2",
      x3: "+- r 0 ch",
      x4: "+- r 0 ch2"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "0",
        maxX: "25000",
        pos: {
          x: "ch",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "ch"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "y6"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "ch",
      t: "ch",
      r: "x4",
      b: "y6"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "r",
            y: "ch2"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "ch2"
          },
          {
            cmd: "arcTo",
            wR: "ch4",
            hR: "ch4",
            stAng: "0",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "ch"
          },
          {
            cmd: "lineTo",
            x: "ch2",
            y: "ch"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "3cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y7"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "cd2",
            swAng: "-10800000"
          },
          {
            cmd: "lineTo",
            x: "ch",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y6"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "ch2",
            y: "y4"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "arcTo",
            wR: "ch4",
            hR: "ch4",
            stAng: "0",
            swAng: "-10800000"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darkenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "ch2",
            y: "y4"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "arcTo",
            wR: "ch4",
            hR: "ch4",
            stAng: "0",
            swAng: "-10800000"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x4",
            y: "ch"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "cd4",
            swAng: "-16200000"
          },
          {
            cmd: "arcTo",
            wR: "ch4",
            hR: "ch4",
            stAng: "cd2",
            swAng: "-10800000"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y3"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "ch"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "ch2"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "cd2",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y5"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "ch",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "ch",
            y: "y7"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "0",
            swAng: "cd2"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x3",
            y: "ch"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "ch"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "moveTo",
            x: "x4",
            y: "ch"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "ch2"
          },
          {
            cmd: "arcTo",
            wR: "ch4",
            hR: "ch4",
            stAng: "0",
            swAng: "cd2"
          },
          {
            cmd: "moveTo",
            x: "ch2",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "ch2",
            y: "y3"
          },
          {
            cmd: "arcTo",
            wR: "ch4",
            hR: "ch4",
            stAng: "cd2",
            swAng: "cd2"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "0",
            swAng: "cd2"
          },
          {
            cmd: "moveTo",
            x: "ch",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "ch",
            y: "y6"
          }
        ]
      }
    ]
  },
  [80 /* SHAPE_GEOMETRY_IRREGULAR_SEAL1 */]: {
    avLst: {},
    gdLst: {
      x5: "*/ w 4627 21600",
      x12: "*/ w 8485 21600",
      x21: "*/ w 16702 21600",
      x24: "*/ w 14522 21600",
      y3: "*/ h 6320 21600",
      y6: "*/ h 8615 21600",
      y9: "*/ h 13937 21600",
      y18: "*/ h 13290 21600"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x24",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y6"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x12",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y18"
        }
      }
    ],
    rect: {
      l: "x5",
      t: "y3",
      r: "x21",
      b: "y9"
    },
    paths: [
      {
        w: "21600",
        h: "21600",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "10800",
            y: "5800"
          },
          {
            cmd: "lineTo",
            x: "14522",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "14155",
            y: "5325"
          },
          {
            cmd: "lineTo",
            x: "18380",
            y: "4457"
          },
          {
            cmd: "lineTo",
            x: "16702",
            y: "7315"
          },
          {
            cmd: "lineTo",
            x: "21097",
            y: "8137"
          },
          {
            cmd: "lineTo",
            x: "17607",
            y: "10475"
          },
          {
            cmd: "lineTo",
            x: "21600",
            y: "13290"
          },
          {
            cmd: "lineTo",
            x: "16837",
            y: "12942"
          },
          {
            cmd: "lineTo",
            x: "18145",
            y: "18095"
          },
          {
            cmd: "lineTo",
            x: "14020",
            y: "14457"
          },
          {
            cmd: "lineTo",
            x: "13247",
            y: "19737"
          },
          {
            cmd: "lineTo",
            x: "10532",
            y: "14935"
          },
          {
            cmd: "lineTo",
            x: "8485",
            y: "21600"
          },
          {
            cmd: "lineTo",
            x: "7715",
            y: "15627"
          },
          {
            cmd: "lineTo",
            x: "4762",
            y: "17617"
          },
          {
            cmd: "lineTo",
            x: "5667",
            y: "13937"
          },
          {
            cmd: "lineTo",
            x: "135",
            y: "14587"
          },
          {
            cmd: "lineTo",
            x: "3722",
            y: "11775"
          },
          {
            cmd: "lineTo",
            x: "0",
            y: "8615"
          },
          {
            cmd: "lineTo",
            x: "4627",
            y: "7617"
          },
          {
            cmd: "lineTo",
            x: "370",
            y: "2295"
          },
          {
            cmd: "lineTo",
            x: "7312",
            y: "6320"
          },
          {
            cmd: "lineTo",
            x: "8352",
            y: "2295"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [81 /* SHAPE_GEOMETRY_IRREGULAR_SEAL2 */]: {
    avLst: {},
    gdLst: {
      x2: "*/ w 9722 21600",
      x5: "*/ w 5372 21600",
      x16: "*/ w 11612 21600",
      x19: "*/ w 14640 21600",
      y2: "*/ h 1887 21600",
      y3: "*/ h 6382 21600",
      y8: "*/ h 12877 21600",
      y14: "*/ h 19712 21600",
      y16: "*/ h 18842 21600",
      y17: "*/ h 15935 21600",
      y24: "*/ h 6645 21600"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x2",
          y: "y2"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y8"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x16",
          y: "y16"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y24"
        }
      }
    ],
    rect: {
      l: "x5",
      t: "y3",
      r: "x19",
      b: "y17"
    },
    paths: [
      {
        w: "21600",
        h: "21600",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "11462",
            y: "4342"
          },
          {
            cmd: "lineTo",
            x: "14790",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "14525",
            y: "5777"
          },
          {
            cmd: "lineTo",
            x: "18007",
            y: "3172"
          },
          {
            cmd: "lineTo",
            x: "16380",
            y: "6532"
          },
          {
            cmd: "lineTo",
            x: "21600",
            y: "6645"
          },
          {
            cmd: "lineTo",
            x: "16985",
            y: "9402"
          },
          {
            cmd: "lineTo",
            x: "18270",
            y: "11290"
          },
          {
            cmd: "lineTo",
            x: "16380",
            y: "12310"
          },
          {
            cmd: "lineTo",
            x: "18877",
            y: "15632"
          },
          {
            cmd: "lineTo",
            x: "14640",
            y: "14350"
          },
          {
            cmd: "lineTo",
            x: "14942",
            y: "17370"
          },
          {
            cmd: "lineTo",
            x: "12180",
            y: "15935"
          },
          {
            cmd: "lineTo",
            x: "11612",
            y: "18842"
          },
          {
            cmd: "lineTo",
            x: "9872",
            y: "17370"
          },
          {
            cmd: "lineTo",
            x: "8700",
            y: "19712"
          },
          {
            cmd: "lineTo",
            x: "7527",
            y: "18125"
          },
          {
            cmd: "lineTo",
            x: "4917",
            y: "21600"
          },
          {
            cmd: "lineTo",
            x: "4805",
            y: "18240"
          },
          {
            cmd: "lineTo",
            x: "1285",
            y: "17825"
          },
          {
            cmd: "lineTo",
            x: "3330",
            y: "15370"
          },
          {
            cmd: "lineTo",
            x: "0",
            y: "12877"
          },
          {
            cmd: "lineTo",
            x: "3935",
            y: "11592"
          },
          {
            cmd: "lineTo",
            x: "1172",
            y: "8270"
          },
          {
            cmd: "lineTo",
            x: "5372",
            y: "7817"
          },
          {
            cmd: "lineTo",
            x: "4502",
            y: "3625"
          },
          {
            cmd: "lineTo",
            x: "8550",
            y: "6382"
          },
          {
            cmd: "lineTo",
            x: "9722",
            y: "1887"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [45 /* SHAPE_GEOMETRY_LEFT_ARROW */]: {
    avLst: {
      adj1: "val 50000",
      adj2: "val 50000"
    },
    gdLst: {
      maxAdj2: "*/ 100000 w ss",
      a1: "pin 0 adj1 100000",
      a2: "pin 0 adj2 maxAdj2",
      dx2: "*/ ss a2 100000",
      x2: "+- l dx2 0",
      dy1: "*/ h a1 200000",
      y1: "+- vc 0 dy1",
      y2: "+- vc dy1 0",
      dx1: "*/ y1 dx2 hd2",
      x1: "+- x2  0 dx1"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "100000",
        pos: {
          x: "r",
          y: "y1"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "maxAdj2",
        pos: {
          x: "x2",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x2",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x2",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "y1",
      r: "r",
      b: "y2"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [56 /* SHAPE_GEOMETRY_LEFT_ARROW_CALLOUT */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 25000",
      adj3: "val 25000",
      adj4: "val 64977"
    },
    gdLst: {
      maxAdj2: "*/ 50000 h ss",
      a2: "pin 0 adj2 maxAdj2",
      maxAdj1: "*/ a2 2 1",
      a1: "pin 0 adj1 maxAdj1",
      maxAdj3: "*/ 100000 w ss",
      a3: "pin 0 adj3 maxAdj3",
      q2: "*/ a3 ss w",
      maxAdj4: "+- 100000 0 q2",
      a4: "pin 0 adj4 maxAdj4",
      dy1: "*/ ss a2 100000",
      dy2: "*/ ss a1 200000",
      y1: "+- vc 0 dy1",
      y2: "+- vc 0 dy2",
      y3: "+- vc dy2 0",
      y4: "+- vc dy1 0",
      x1: "*/ ss a3 100000",
      dx2: "*/ w a4 100000",
      x2: "+- r 0 dx2",
      x3: "+/ x2 r 2"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "maxAdj1",
        pos: {
          x: "x1",
          y: "y2"
        }
      },
      {
        gdRefY: "adj2",
        minY: "0",
        maxY: "maxAdj2",
        pos: {
          x: "l",
          y: "y1"
        }
      },
      {
        gdRefX: "adj3",
        minX: "0",
        maxX: "maxAdj3",
        pos: {
          x: "x1",
          y: "t"
        }
      },
      {
        gdRefX: "adj4",
        minX: "0",
        maxX: "maxAdj4",
        pos: {
          x: "x2",
          y: "b"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x3",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x3",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "x2",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y4"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [92 /* SHAPE_GEOMETRY_LEFT_BRACE */]: {
    avLst: {
      adj1: "val 8333",
      adj2: "val 50000"
    },
    gdLst: {
      a2: "pin 0 adj2 100000",
      q1: "+- 100000 0 a2",
      q2: "min q1 a2",
      q3: "*/ q2 1 2",
      maxAdj1: "*/ q3 h ss",
      a1: "pin 0 adj1 maxAdj1",
      y1: "*/ ss a1 100000",
      y3: "*/ h a2 100000",
      y4: "+- y3 y1 0",
      dx1: "cos wd2 2700000",
      dy1: "sin y1 2700000",
      il: "+- r 0 dx1",
      it: "+- y1 0 dy1",
      ib: "+- b dy1 y1"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "maxAdj1",
        pos: {
          x: "hc",
          y: "y1"
        }
      },
      {
        gdRefY: "adj2",
        minY: "0",
        maxY: "100000",
        pos: {
          x: "l",
          y: "y3"
        }
      }
    ],
    cxnLst: [
      {
        ang: "cd4",
        pos: {
          x: "r",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y3"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "r",
          y: "b"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "r",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "y4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "0",
            swAng: "-5400000"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "y4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "0",
            swAng: "-5400000"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "cd2",
            swAng: "cd4"
          }
        ]
      }
    ]
  },
  [90 /* SHAPE_GEOMETRY_LEFT_BRACKET */]: {
    avLst: {
      adj: "val 8333"
    },
    gdLst: {
      maxAdj: "*/ 50000 h ss",
      a: "pin 0 adj maxAdj",
      y1: "*/ ss a 100000",
      y2: "+- b 0 y1",
      dx1: "cos w 2700000",
      dy1: "sin y1 2700000",
      il: "+- r 0 dx1",
      it: "+- y1 0 dy1",
      ib: "+- b dy1 y1"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "maxAdj",
        pos: {
          x: "l",
          y: "y1"
        }
      }
    ],
    cxnLst: [
      {
        ang: "cd4",
        pos: {
          x: "r",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "r",
          y: "b"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "r",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "y1",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "y1",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "y1",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "y1",
            stAng: "cd2",
            swAng: "cd4"
          }
        ]
      }
    ]
  },
  [66 /* SHAPE_GEOMETRY_LEFT_CIRCULAR_ARROW */]: {
    avLst: {
      adj1: "val 12500",
      adj2: "val -1142319",
      adj3: "val 1142319",
      adj4: "val 10800000",
      adj5: "val 12500"
    },
    gdLst: {
      a5: "pin 0 adj5 25000",
      maxAdj1: "*/ a5 2 1",
      a1: "pin 0 adj1 maxAdj1",
      enAng: "pin 1 adj3 21599999",
      stAng: "pin 0 adj4 21599999",
      th: "*/ ss a1 100000",
      thh: "*/ ss a5 100000",
      th2: "*/ th 1 2",
      rw1: "+- wd2 th2 thh",
      rh1: "+- hd2 th2 thh",
      rw2: "+- rw1 0 th",
      rh2: "+- rh1 0 th",
      rw3: "+- rw2 th2 0",
      rh3: "+- rh2 th2 0",
      wtH: "sin rw3 enAng",
      htH: "cos rh3 enAng",
      dxH: "cat2 rw3 htH wtH",
      dyH: "sat2 rh3 htH wtH",
      xH: "+- hc dxH 0",
      yH: "+- vc dyH 0",
      rI: "min rw2 rh2",
      u1: "*/ dxH dxH 1",
      u2: "*/ dyH dyH 1",
      u3: "*/ rI rI 1",
      u4: "+- u1 0 u3",
      u5: "+- u2 0 u3",
      u6: "*/ u4 u5 u1",
      u7: "*/ u6 1 u2",
      u8: "+- 1 0 u7",
      u9: "sqrt u8",
      u10: "*/ u4 1 dxH",
      u11: "*/ u10 1 dyH",
      u12: "+/ 1 u9 u11",
      u13: "at2 1 u12",
      u14: "+- u13 21600000 0",
      u15: "?: u13 u13 u14",
      u16: "+- u15 0 enAng",
      u17: "+- u16 21600000 0",
      u18: "?: u16 u16 u17",
      u19: "+- u18 0 cd2",
      u20: "+- u18 0 21600000",
      u21: "?: u19 u20 u18",
      u22: "abs u21",
      minAng: "*/ u22 -1 1",
      u23: "abs adj2",
      a2: "*/ u23 -1 1",
      aAng: "pin minAng a2 0",
      ptAng: "+- enAng aAng 0",
      wtA: "sin rw3 ptAng",
      htA: "cos rh3 ptAng",
      dxA: "cat2 rw3 htA wtA",
      dyA: "sat2 rh3 htA wtA",
      xA: "+- hc dxA 0",
      yA: "+- vc dyA 0",
      wtE: "sin rw1 stAng",
      htE: "cos rh1 stAng",
      dxE: "cat2 rw1 htE wtE",
      dyE: "sat2 rh1 htE wtE",
      xE: "+- hc dxE 0",
      yE: "+- vc dyE 0",
      wtD: "sin rw2 stAng",
      htD: "cos rh2 stAng",
      dxD: "cat2 rw2 htD wtD",
      dyD: "sat2 rh2 htD wtD",
      xD: "+- hc dxD 0",
      yD: "+- vc dyD 0",
      dxG: "cos thh ptAng",
      dyG: "sin thh ptAng",
      xG: "+- xH dxG 0",
      yG: "+- yH dyG 0",
      dxB: "cos thh ptAng",
      dyB: "sin thh ptAng",
      xB: "+- xH 0 dxB 0",
      yB: "+- yH 0 dyB 0",
      sx1: "+- xB 0 hc",
      sy1: "+- yB 0 vc",
      sx2: "+- xG 0 hc",
      sy2: "+- yG 0 vc",
      rO: "min rw1 rh1",
      x1O: "*/ sx1 rO rw1",
      y1O: "*/ sy1 rO rh1",
      x2O: "*/ sx2 rO rw1",
      y2O: "*/ sy2 rO rh1",
      dxO: "+- x2O 0 x1O",
      dyO: "+- y2O 0 y1O",
      dO: "mod dxO dyO 0",
      q1: "*/ x1O y2O 1",
      q2: "*/ x2O y1O 1",
      DO: "+- q1 0 q2",
      q3: "*/ rO rO 1",
      q4: "*/ dO dO 1",
      q5: "*/ q3 q4 1",
      q6: "*/ DO DO 1",
      q7: "+- q5 0 q6",
      q8: "max q7 0",
      sdelO: "sqrt q8",
      ndyO: "*/ dyO -1 1",
      sdyO: "?: ndyO -1 1",
      q9: "*/ sdyO dxO 1",
      q10: "*/ q9 sdelO 1",
      q11: "*/ DO dyO 1",
      dxF1: "+/ q11 q10 q4",
      q12: "+- q11 0 q10",
      dxF2: "*/ q12 1 q4",
      adyO: "abs dyO",
      q13: "*/ adyO sdelO 1",
      q14: "*/ DO dxO -1",
      dyF1: "+/ q14 q13 q4",
      q15: "+- q14 0 q13",
      dyF2: "*/ q15 1 q4",
      q16: "+- x2O 0 dxF1",
      q17: "+- x2O 0 dxF2",
      q18: "+- y2O 0 dyF1",
      q19: "+- y2O 0 dyF2",
      q20: "mod q16 q18 0",
      q21: "mod q17 q19 0",
      q22: "+- q21 0 q20",
      dxF: "?: q22 dxF1 dxF2",
      dyF: "?: q22 dyF1 dyF2",
      sdxF: "*/ dxF rw1 rO",
      sdyF: "*/ dyF rh1 rO",
      xF: "+- hc sdxF 0",
      yF: "+- vc sdyF 0",
      x1I: "*/ sx1 rI rw2",
      y1I: "*/ sy1 rI rh2",
      x2I: "*/ sx2 rI rw2",
      y2I: "*/ sy2 rI rh2",
      dxI: "cat2 rw3 htI wtI",
      dyI: "sat2 rh3 htI wtI",
      dI: "mod dxI dyI 0",
      v1: "*/ x1I y2I 1",
      v2: "*/ x2I y1I 1",
      DI: "+- v1 0 v2",
      v3: "*/ rI rI 1",
      v4: "*/ dI dI 1",
      v5: "*/ v3 v4 1",
      v6: "*/ DI DI 1",
      v7: "+- v5 0 v6",
      v8: "max v7 0",
      sdelI: "sqrt v8",
      v9: "*/ sdyO dxI 1",
      v10: "*/ v9 sdelI 1",
      v11: "*/ DI dyI 1",
      dxC1: "+/ v11 v10 v4",
      v12: "+- v11 0 v10",
      dxC2: "*/ v12 1 v4",
      adyI: "abs dyI",
      v13: "*/ adyI sdelI 1",
      v14: "*/ DI dxI -1",
      dyC1: "+/ v14 v13 v4",
      v15: "+- v14 0 v13",
      dyC2: "*/ v15 1 v4",
      v16: "+- x1I 0 dxC1",
      v17: "+- x1I 0 dxC2",
      v18: "+- y1I 0 dyC1",
      v19: "+- y1I 0 dyC2",
      v20: "mod v16 v18 0",
      v21: "mod v17 v19 0",
      v22: "+- v21 0 v20",
      dxC: "?: v22 dxC1 dxC2",
      dyC: "?: v22 dyC1 dyC2",
      sdxC: "*/ dxC rw2 rI",
      sdyC: "*/ dyC rh2 rI",
      xC: "+- hc sdxC 0",
      yC: "+- vc sdyC 0",
      ist0: "at2 sdxC sdyC",
      ist1: "+- ist0 21600000 0",
      istAng0: "?: ist0 ist0 ist1",
      isw1: "+- stAng 0 istAng0",
      isw2: "+- isw1 21600000 0",
      iswAng0: "?: isw1 isw1 isw2",
      istAng: "+- istAng0 iswAng0 0",
      iswAng: "+- 0 0 iswAng0",
      p1: "+- xF 0 xC",
      p2: "+- yF 0 yC",
      p3: "mod p1 p2 0",
      p4: "*/ p3 1 2",
      p5: "+- p4 0 thh",
      xGp: "?: p5 xF xG",
      yGp: "?: p5 yF yG",
      xBp: "?: p5 xC xB",
      yBp: "?: p5 yC yB",
      en0: "at2 sdxF sdyF",
      en1: "+- en0 21600000 0",
      en2: "?: en0 en0 en1",
      sw0: "+- en2 0 stAng",
      sw1: "+- sw0 0 21600000",
      swAng: "?: sw0 sw1 sw0",
      stAng0: "+- stAng swAng 0",
      swAng0: "+- 0 0 swAng",
      wtI: "sin rw3 stAng",
      htI: "cos rh3 stAng",
      xI: "+- hc dxI 0",
      yI: "+- vc dyI 0",
      aI: "+- stAng cd4 0",
      aA: "+- ptAng 0 cd4",
      aB: "+- ptAng cd2 0",
      idx: "cos rw1 2700000",
      idy: "sin rh1 2700000",
      il: "+- hc 0 idx",
      ir: "+- hc idx 0",
      it: "+- vc 0 idy",
      ib: "+- vc idy 0"
    },
    ahLst: [
      {
        pos: {
          x: "xA",
          y: "yA"
        }
      },
      {
        pos: {
          x: "xE",
          y: "yE"
        }
      },
      {
        pos: {
          x: "xF",
          y: "yF"
        }
      },
      {
        pos: {
          x: "xB",
          y: "yB"
        }
      }
    ],
    cxnLst: [
      {
        ang: "aI",
        pos: {
          x: "xI",
          y: "yI"
        }
      },
      {
        ang: "ptAng",
        pos: {
          x: "xGp",
          y: "yGp"
        }
      },
      {
        ang: "aA",
        pos: {
          x: "xA",
          y: "yA"
        }
      },
      {
        ang: "aB",
        pos: {
          x: "xBp",
          y: "yBp"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "xE",
            y: "yE"
          },
          {
            cmd: "lineTo",
            x: "xD",
            y: "yD"
          },
          {
            cmd: "arcTo",
            wR: "rw2",
            hR: "rh2",
            stAng: "istAng",
            swAng: "iswAng"
          },
          {
            cmd: "lineTo",
            x: "xBp",
            y: "yBp"
          },
          {
            cmd: "lineTo",
            x: "xA",
            y: "yA"
          },
          {
            cmd: "lineTo",
            x: "xGp",
            y: "yGp"
          },
          {
            cmd: "lineTo",
            x: "xF",
            y: "yF"
          },
          {
            cmd: "arcTo",
            wR: "rw1",
            hR: "rh1",
            stAng: "stAng0",
            swAng: "swAng0"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [51 /* SHAPE_GEOMETRY_LEFT_RIGHT_ARROW */]: {
    avLst: {
      adj1: "val 50000",
      adj2: "val 50000"
    },
    gdLst: {
      maxAdj2: "*/ 50000 w ss",
      a1: "pin 0 adj1 100000",
      a2: "pin 0 adj2 maxAdj2",
      x2: "*/ ss a2 100000",
      x3: "+- r 0 x2",
      dy: "*/ h a1 200000",
      y1: "+- vc 0 dy",
      y2: "+- vc dy 0",
      dx1: "*/ y1 x2 hd2",
      x1: "+- x2 0 dx1",
      x4: "+- x3 dx1 0"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "100000",
        pos: {
          x: "x3",
          y: "y1"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "maxAdj2",
        pos: {
          x: "x2",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x3",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x2",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x2",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x3",
          y: "t"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "y1",
      r: "x4",
      b: "y2"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  }
};

// node_modules/@oai/granola/dist/shapes/preset-shape-definitions.part4.js
var presetShapeDefinitionsPart4 = {
  [60 /* SHAPE_GEOMETRY_LEFT_RIGHT_ARROW_CALLOUT */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 25000",
      adj3: "val 25000",
      adj4: "val 48123"
    },
    gdLst: {
      maxAdj2: "*/ 50000 h ss",
      a2: "pin 0 adj2 maxAdj2",
      maxAdj1: "*/ a2 2 1",
      a1: "pin 0 adj1 maxAdj1",
      maxAdj3: "*/ 50000 w ss",
      a3: "pin 0 adj3 maxAdj3",
      q2: "*/ a3 ss wd2",
      maxAdj4: "+- 100000 0 q2",
      a4: "pin 0 adj4 maxAdj4",
      dy1: "*/ ss a2 100000",
      dy2: "*/ ss a1 200000",
      y1: "+- vc 0 dy1",
      y2: "+- vc 0 dy2",
      y3: "+- vc dy2 0",
      y4: "+- vc dy1 0",
      x1: "*/ ss a3 100000",
      x4: "+- r 0 x1",
      dx2: "*/ w a4 200000",
      x2: "+- hc 0 dx2",
      x3: "+- hc dx2 0"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "maxAdj1",
        pos: {
          x: "x1",
          y: "y2"
        }
      },
      {
        gdRefY: "adj2",
        minY: "0",
        maxY: "maxAdj2",
        pos: {
          x: "l",
          y: "y1"
        }
      },
      {
        gdRefX: "adj3",
        minX: "0",
        maxX: "maxAdj3",
        pos: {
          x: "x1",
          y: "t"
        }
      },
      {
        gdRefX: "adj4",
        minX: "0",
        maxX: "maxAdj4",
        pos: {
          x: "x2",
          y: "b"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "x2",
      t: "t",
      r: "x3",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y4"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [67 /* SHAPE_GEOMETRY_LEFT_RIGHT_CIRCULAR_ARROW */]: {
    avLst: {
      adj1: "val 12500",
      adj2: "val 1142319",
      adj3: "val 20457681",
      adj4: "val 11942319",
      adj5: "val 12500"
    },
    gdLst: {
      a5: "pin 0 adj5 25000",
      maxAdj1: "*/ a5 2 1",
      a1: "pin 0 adj1 maxAdj1",
      enAng: "pin 1 adj3 21599999",
      stAng: "pin 0 adj4 21599999",
      th: "*/ ss a1 100000",
      thh: "*/ ss a5 100000",
      th2: "*/ th 1 2",
      rw1: "+- wd2 th2 thh",
      rh1: "+- hd2 th2 thh",
      rw2: "+- rw1 0 th",
      rh2: "+- rh1 0 th",
      rw3: "+- rw2 th2 0",
      rh3: "+- rh2 th2 0",
      wtH: "sin rw3 enAng",
      htH: "cos rh3 enAng",
      dxH: "cat2 rw3 htH wtH",
      dyH: "sat2 rh3 htH wtH",
      xH: "+- hc dxH 0",
      yH: "+- vc dyH 0",
      rI: "min rw2 rh2",
      u1: "*/ dxH dxH 1",
      u2: "*/ dyH dyH 1",
      u3: "*/ rI rI 1",
      u4: "+- u1 0 u3",
      u5: "+- u2 0 u3",
      u6: "*/ u4 u5 u1",
      u7: "*/ u6 1 u2",
      u8: "+- 1 0 u7",
      u9: "sqrt u8",
      u10: "*/ u4 1 dxH",
      u11: "*/ u10 1 dyH",
      u12: "+/ 1 u9 u11",
      u13: "at2 1 u12",
      u14: "+- u13 21600000 0",
      u15: "?: u13 u13 u14",
      u16: "+- u15 0 enAng",
      u17: "+- u16 21600000 0",
      u18: "?: u16 u16 u17",
      u19: "+- u18 0 cd2",
      u20: "+- u18 0 21600000",
      u21: "?: u19 u20 u18",
      maxAng: "abs u21",
      aAng: "pin 0 adj2 maxAng",
      ptAng: "+- enAng aAng 0",
      wtA: "sin rw3 ptAng",
      htA: "cos rh3 ptAng",
      dxA: "cat2 rw3 htA wtA",
      dyA: "sat2 rh3 htA wtA",
      xA: "+- hc dxA 0",
      yA: "+- vc dyA 0",
      dxG: "cos thh ptAng",
      dyG: "sin thh ptAng",
      xG: "+- xH dxG 0",
      yG: "+- yH dyG 0",
      dxB: "cos thh ptAng",
      dyB: "sin thh ptAng",
      xB: "+- xH 0 dxB 0",
      yB: "+- yH 0 dyB 0",
      sx1: "+- xB 0 hc",
      sy1: "+- yB 0 vc",
      sx2: "+- xG 0 hc",
      sy2: "+- yG 0 vc",
      rO: "min rw1 rh1",
      x1O: "*/ sx1 rO rw1",
      y1O: "*/ sy1 rO rh1",
      x2O: "*/ sx2 rO rw1",
      y2O: "*/ sy2 rO rh1",
      dxO: "+- x2O 0 x1O",
      dyO: "+- y2O 0 y1O",
      dO: "mod dxO dyO 0",
      q1: "*/ x1O y2O 1",
      q2: "*/ x2O y1O 1",
      DO: "+- q1 0 q2",
      q3: "*/ rO rO 1",
      q4: "*/ dO dO 1",
      q5: "*/ q3 q4 1",
      q6: "*/ DO DO 1",
      q7: "+- q5 0 q6",
      q8: "max q7 0",
      sdelO: "sqrt q8",
      ndyO: "*/ dyO -1 1",
      sdyO: "?: ndyO -1 1",
      q9: "*/ sdyO dxO 1",
      q10: "*/ q9 sdelO 1",
      q11: "*/ DO dyO 1",
      dxF1: "+/ q11 q10 q4",
      q12: "+- q11 0 q10",
      dxF2: "*/ q12 1 q4",
      adyO: "abs dyO",
      q13: "*/ adyO sdelO 1",
      q14: "*/ DO dxO -1",
      dyF1: "+/ q14 q13 q4",
      q15: "+- q14 0 q13",
      dyF2: "*/ q15 1 q4",
      q16: "+- x2O 0 dxF1",
      q17: "+- x2O 0 dxF2",
      q18: "+- y2O 0 dyF1",
      q19: "+- y2O 0 dyF2",
      q20: "mod q16 q18 0",
      q21: "mod q17 q19 0",
      q22: "+- q21 0 q20",
      dxF: "?: q22 dxF1 dxF2",
      dyF: "?: q22 dyF1 dyF2",
      sdxF: "*/ dxF rw1 rO",
      sdyF: "*/ dyF rh1 rO",
      xF: "+- hc sdxF 0",
      yF: "+- vc sdyF 0",
      x1I: "*/ sx1 rI rw2",
      y1I: "*/ sy1 rI rh2",
      x2I: "*/ sx2 rI rw2",
      y2I: "*/ sy2 rI rh2",
      dxI: "cat2 rw3 htI wtI",
      dyI: "sat2 rh3 htI wtI",
      dI: "mod dxI dyI 0",
      v1: "*/ x1I y2I 1",
      v2: "*/ x2I y1I 1",
      DI: "+- v1 0 v2",
      v3: "*/ rI rI 1",
      v4: "*/ dI dI 1",
      v5: "*/ v3 v4 1",
      v6: "*/ DI DI 1",
      v7: "+- v5 0 v6",
      v8: "max v7 0",
      sdelI: "sqrt v8",
      v9: "*/ sdyO dxI 1",
      v10: "*/ v9 sdelI 1",
      v11: "*/ DI dyI 1",
      dxC1: "+/ v11 v10 v4",
      v12: "+- v11 0 v10",
      dxC2: "*/ v12 1 v4",
      adyI: "abs dyI",
      v13: "*/ adyI sdelI 1",
      v14: "*/ DI dxI -1",
      dyC1: "+/ v14 v13 v4",
      v15: "+- v14 0 v13",
      dyC2: "*/ v15 1 v4",
      v16: "+- x1I 0 dxC1",
      v17: "+- x1I 0 dxC2",
      v18: "+- y1I 0 dyC1",
      v19: "+- y1I 0 dyC2",
      v20: "mod v16 v18 0",
      v21: "mod v17 v19 0",
      v22: "+- v21 0 v20",
      dxC: "?: v22 dxC1 dxC2",
      dyC: "?: v22 dyC1 dyC2",
      sdxC: "*/ dxC rw2 rI",
      sdyC: "*/ dyC rh2 rI",
      xC: "+- hc sdxC 0",
      yC: "+- vc sdyC 0",
      wtI: "sin rw3 stAng",
      htI: "cos rh3 stAng",
      xI: "+- hc dxI 0",
      yI: "+- vc dyI 0",
      lptAng: "+- stAng 0 aAng",
      wtL: "sin rw3 lptAng",
      htL: "cos rh3 lptAng",
      dxL: "cat2 rw3 htL wtL",
      dyL: "sat2 rh3 htL wtL",
      xL: "+- hc dxL 0",
      yL: "+- vc dyL 0",
      dxK: "cos thh lptAng",
      dyK: "sin thh lptAng",
      xK: "+- xI dxK 0",
      yK: "+- yI dyK 0",
      dxJ: "cos thh lptAng",
      dyJ: "sin thh lptAng",
      xJ: "+- xI 0 dxJ 0",
      yJ: "+- yI 0 dyJ 0",
      p1: "+- xF 0 xC",
      p2: "+- yF 0 yC",
      p3: "mod p1 p2 0",
      p4: "*/ p3 1 2",
      p5: "+- p4 0 thh",
      xGp: "?: p5 xF xG",
      yGp: "?: p5 yF yG",
      xBp: "?: p5 xC xB",
      yBp: "?: p5 yC yB",
      en0: "at2 sdxF sdyF",
      en1: "+- en0 21600000 0",
      en2: "?: en0 en0 en1",
      od0: "+- en2 0 enAng",
      od1: "+- od0 21600000 0",
      od2: "?: od0 od0 od1",
      st0: "+- stAng 0 od2",
      st1: "+- st0 21600000 0",
      st2: "?: st0 st0 st1",
      sw0: "+- en2 0 st2",
      sw1: "+- sw0 21600000 0",
      swAng: "?: sw0 sw0 sw1",
      ist0: "at2 sdxC sdyC",
      ist1: "+- ist0 21600000 0",
      istAng: "?: ist0 ist0 ist1",
      id0: "+- istAng 0 enAng",
      id1: "+- id0 0 21600000",
      id2: "?: id0 id1 id0",
      ien0: "+- stAng 0 id2",
      ien1: "+- ien0 0 21600000",
      ien2: "?: ien1 ien1 ien0",
      isw1: "+- ien2 0 istAng",
      isw2: "+- isw1 0 21600000",
      iswAng: "?: isw1 isw2 isw1",
      wtE: "sin rw1 st2",
      htE: "cos rh1 st2",
      dxE: "cat2 rw1 htE wtE",
      dyE: "sat2 rh1 htE wtE",
      xE: "+- hc dxE 0",
      yE: "+- vc dyE 0",
      wtD: "sin rw2 ien2",
      htD: "cos rh2 ien2",
      dxD: "cat2 rw2 htD wtD",
      dyD: "sat2 rh2 htD wtD",
      xD: "+- hc dxD 0",
      yD: "+- vc dyD 0",
      xKp: "?: p5 xE xK",
      yKp: "?: p5 yE yK",
      xJp: "?: p5 xD xJ",
      yJp: "?: p5 yD yJ",
      aL: "+- lptAng 0 cd4",
      aA: "+- ptAng cd4 0",
      aB: "+- ptAng cd2 0",
      aJ: "+- lptAng cd2 0",
      idx: "cos rw1 2700000",
      idy: "sin rh1 2700000",
      il: "+- hc 0 idx",
      ir: "+- hc idx 0",
      it: "+- vc 0 idy",
      ib: "+- vc idy 0"
    },
    ahLst: [
      {
        pos: {
          x: "xA",
          y: "yA"
        }
      },
      {
        pos: {
          x: "xE",
          y: "yE"
        }
      },
      {
        pos: {
          x: "xF",
          y: "yF"
        }
      },
      {
        pos: {
          x: "xB",
          y: "yB"
        }
      }
    ],
    cxnLst: [
      {
        ang: "aL",
        pos: {
          x: "xL",
          y: "yL"
        }
      },
      {
        ang: "lptAng",
        pos: {
          x: "xKp",
          y: "yKp"
        }
      },
      {
        ang: "ptAng",
        pos: {
          x: "xGp",
          y: "yGp"
        }
      },
      {
        ang: "aA",
        pos: {
          x: "xA",
          y: "yA"
        }
      },
      {
        ang: "aB",
        pos: {
          x: "xBp",
          y: "yBp"
        }
      },
      {
        ang: "aJ",
        pos: {
          x: "xJp",
          y: "yJp"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "xL",
            y: "yL"
          },
          {
            cmd: "lineTo",
            x: "xKp",
            y: "yKp"
          },
          {
            cmd: "lineTo",
            x: "xE",
            y: "yE"
          },
          {
            cmd: "arcTo",
            wR: "rw1",
            hR: "rh1",
            stAng: "st2",
            swAng: "swAng"
          },
          {
            cmd: "lineTo",
            x: "xGp",
            y: "yGp"
          },
          {
            cmd: "lineTo",
            x: "xA",
            y: "yA"
          },
          {
            cmd: "lineTo",
            x: "xBp",
            y: "yBp"
          },
          {
            cmd: "lineTo",
            x: "xC",
            y: "yC"
          },
          {
            cmd: "arcTo",
            wR: "rw2",
            hR: "rh2",
            stAng: "istAng",
            swAng: "iswAng"
          },
          {
            cmd: "lineTo",
            x: "xJp",
            y: "yJp"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [126 /* SHAPE_GEOMETRY_LEFT_RIGHT_RIBBON */]: {
    avLst: {
      adj1: "val 50000",
      adj2: "val 50000",
      adj3: "val 16667"
    },
    gdLst: {
      a3: "pin 0 adj3 33333",
      maxAdj1: "+- 100000 0 a3",
      a1: "pin 0 adj1 maxAdj1",
      w1: "+- wd2 0 wd32",
      maxAdj2: "*/ 100000 w1 ss",
      a2: "pin 0 adj2 maxAdj2",
      x1: "*/ ss a2 100000",
      x4: "+- r 0 x1",
      dy1: "*/ h a1 200000",
      dy2: "*/ h a3 -200000",
      ly1: "+- vc dy2 dy1",
      ry4: "+- vc dy1 dy2",
      ly2: "+- ly1 dy1 0",
      ry3: "+- b 0 ly2",
      ly4: "*/ ly2 2 1",
      ry1: "+- b 0 ly4",
      ly3: "+- ly4 0 ly1",
      ry2: "+- b 0 ly3",
      hR: "*/ a3 ss 400000",
      x2: "+- hc 0 wd32",
      x3: "+- hc wd32 0",
      y1: "+- ly1 hR 0",
      y2: "+- ry2 0 hR"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "maxAdj1",
        pos: {
          x: "x4",
          y: "ry2"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "maxAdj2",
        pos: {
          x: "x1",
          y: "t"
        }
      },
      {
        gdRefY: "adj3",
        minY: "0",
        maxY: "33333",
        pos: {
          x: "x3",
          y: "ry2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "ry3"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x4",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x1",
          y: "ly4"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "ly2"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x1",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x4",
          y: "ry1"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "ly1",
      r: "x4",
      b: "ry4"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "ly2"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "ly1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "ly1"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "3cd4",
            swAng: "cd2"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "3cd4",
            swAng: "-10800000"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "ry2"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "ry1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "ry3"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "ry4"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "ry4"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "ly3"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "ly3"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "ly4"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darkenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "3cd4",
            swAng: "-10800000"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "ry2"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "ly2"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "ly1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "ly1"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "3cd4",
            swAng: "cd2"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "3cd4",
            swAng: "-10800000"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "ry2"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "ry1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "ry3"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "ry4"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "ry4"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "ly3"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "ly3"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "ly4"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "ry2"
          },
          {
            cmd: "moveTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "ly3"
          }
        ]
      }
    ]
  },
  [54 /* SHAPE_GEOMETRY_LEFT_RIGHT_UP_ARROW */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 25000",
      adj3: "val 25000"
    },
    gdLst: {
      a2: "pin 0 adj2 50000",
      maxAdj1: "*/ a2 2 1",
      a1: "pin 0 adj1 maxAdj1",
      q1: "+- 100000 0 maxAdj1",
      maxAdj3: "*/ q1 1 2",
      a3: "pin 0 adj3 maxAdj3",
      x1: "*/ ss a3 100000",
      dx2: "*/ ss a2 100000",
      x2: "+- hc 0 dx2",
      x5: "+- hc dx2 0",
      dx3: "*/ ss a1 200000",
      x3: "+- hc 0 dx3",
      x4: "+- hc dx3 0",
      x6: "+- r 0 x1",
      dy2: "*/ ss a2 50000",
      y2: "+- b 0 dy2",
      y4: "+- b 0 dx2",
      y3: "+- y4 0 dx3",
      y5: "+- y4 dx3 0",
      il: "*/ dx3 x1 dx2",
      ir: "+- r 0 il"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "maxAdj1",
        pos: {
          x: "x3",
          y: "x1"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x2",
          y: "t"
        }
      },
      {
        gdRefY: "adj3",
        minY: "0",
        maxY: "maxAdj3",
        pos: {
          x: "r",
          y: "x1"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y4"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "y5"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y4"
        }
      }
    ],
    rect: {
      l: "il",
      t: "y3",
      r: "ir",
      b: "y5"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [53 /* SHAPE_GEOMETRY_LEFT_UP_ARROW */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 25000",
      adj3: "val 25000"
    },
    gdLst: {
      a2: "pin 0 adj2 50000",
      maxAdj1: "*/ a2 2 1",
      a1: "pin 0 adj1 maxAdj1",
      maxAdj3: "+- 100000 0 maxAdj1",
      a3: "pin 0 adj3 maxAdj3",
      x1: "*/ ss a3 100000",
      dx2: "*/ ss a2 50000",
      x2: "+- r 0 dx2",
      y2: "+- b 0 dx2",
      dx4: "*/ ss a2 100000",
      x4: "+- r 0 dx4",
      y4: "+- b 0 dx4",
      dx3: "*/ ss a1 200000",
      x3: "+- x4 0 dx3",
      x5: "+- x4 dx3 0",
      y3: "+- y4 0 dx3",
      y5: "+- y4 dx3 0",
      il: "*/ dx3 x1 dx4",
      cx1: "+/ x1 x5 2",
      cy1: "+/ x1 y5 2"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "maxAdj1",
        pos: {
          x: "x3",
          y: "y3"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x2",
          y: "t"
        }
      },
      {
        gdRefY: "adj3",
        minY: "0",
        maxY: "maxAdj3",
        pos: {
          x: "x3",
          y: "x1"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x4",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x2",
          y: "x1"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x1",
          y: "y2"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y4"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x1",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "cx1",
          y: "y5"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x5",
          y: "cy1"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "x1"
        }
      }
    ],
    rect: {
      l: "il",
      t: "y3",
      r: "x4",
      b: "y5"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [75 /* SHAPE_GEOMETRY_LIGHTNING_BOLT */]: {
    avLst: {},
    gdLst: {
      x1: "*/ w 5022 21600",
      x3: "*/ w 8472 21600",
      x4: "*/ w 8757 21600",
      x5: "*/ w 10012 21600",
      x8: "*/ w 12860 21600",
      x9: "*/ w 13917 21600",
      x11: "*/ w 16577 21600",
      y1: "*/ h 3890 21600",
      y2: "*/ h 6080 21600",
      y4: "*/ h 7437 21600",
      y6: "*/ h 9705 21600",
      y7: "*/ h 12007 21600",
      y10: "*/ h 14277 21600",
      y11: "*/ h 14915 21600"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x3",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "l",
          y: "y1"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y6"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x5",
          y: "y11"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "r",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x11",
          y: "y7"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x8",
          y: "y2"
        }
      }
    ],
    rect: {
      l: "x4",
      t: "y4",
      r: "x9",
      b: "y10"
    },
    paths: [
      {
        w: "21600",
        h: "21600",
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "8472",
            y: "0"
          },
          {
            cmd: "lineTo",
            x: "12860",
            y: "6080"
          },
          {
            cmd: "lineTo",
            x: "11050",
            y: "6797"
          },
          {
            cmd: "lineTo",
            x: "16577",
            y: "12007"
          },
          {
            cmd: "lineTo",
            x: "14767",
            y: "12877"
          },
          {
            cmd: "lineTo",
            x: "21600",
            y: "21600"
          },
          {
            cmd: "lineTo",
            x: "10012",
            y: "14915"
          },
          {
            cmd: "lineTo",
            x: "12222",
            y: "13987"
          },
          {
            cmd: "lineTo",
            x: "5022",
            y: "9705"
          },
          {
            cmd: "lineTo",
            x: "7602",
            y: "8382"
          },
          {
            cmd: "lineTo",
            x: "0",
            y: "3890"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [1 /* SHAPE_GEOMETRY_LINE */]: {
    avLst: {},
    gdLst: {},
    ahLst: [],
    cxnLst: [
      {
        ang: "cd4",
        pos: {
          x: "l",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "r",
          y: "b"
        }
      }
    ],
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          }
        ]
      }
    ]
  },
  [2 /* SHAPE_GEOMETRY_LINE_INV */]: {
    avLst: {},
    gdLst: {},
    ahLst: [],
    cxnLst: [
      {
        ang: "cd4",
        pos: {
          x: "l",
          y: "b"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "r",
          y: "t"
        }
      }
    ],
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          }
        ]
      }
    ]
  },
  [179 /* SHAPE_GEOMETRY_MATH_DIVIDE */]: {
    avLst: {
      adj1: "val 23520",
      adj2: "val 5880",
      adj3: "val 11760"
    },
    gdLst: {
      a1: "pin 1000 adj1 36745",
      ma1: "+- 0 0 a1",
      ma3h: "+/ 73490 ma1 4",
      ma3w: "*/ 36745 w h",
      maxAdj3: "min ma3h ma3w",
      a3: "pin 1000 adj3 maxAdj3",
      m4a3: "*/ -4 a3 1",
      maxAdj2: "+- 73490 m4a3 a1",
      a2: "pin 0 adj2 maxAdj2",
      dy1: "*/ h a1 200000",
      yg: "*/ h a2 100000",
      rad: "*/ h a3 100000",
      dx1: "*/ w 73490 200000",
      y3: "+- vc 0 dy1",
      y4: "+- vc dy1 0",
      a: "+- yg rad 0",
      y2: "+- y3 0 a",
      y1: "+- y2 0 rad",
      y5: "+- b 0 y1",
      x1: "+- hc 0 dx1",
      x3: "+- hc dx1 0",
      x2: "+- hc 0 rad"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "1000",
        maxY: "36745",
        pos: {
          x: "l",
          y: "y3"
        }
      },
      {
        gdRefY: "adj2",
        minY: "0",
        maxY: "maxAdj2",
        pos: {
          x: "r",
          y: "y2"
        }
      },
      {
        gdRefX: "adj3",
        minX: "1000",
        maxX: "maxAdj3",
        pos: {
          x: "x2",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "x3",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "y5"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "y3",
      r: "x3",
      b: "y4"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "hc",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "rad",
            hR: "rad",
            stAng: "3cd4",
            swAng: "21600000"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "hc",
            y: "y5"
          },
          {
            cmd: "arcTo",
            wR: "rad",
            hR: "rad",
            stAng: "cd4",
            swAng: "21600000"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x1",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y4"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [180 /* SHAPE_GEOMETRY_MATH_EQUAL */]: {
    avLst: {
      adj1: "val 23520",
      adj2: "val 11760"
    },
    gdLst: {
      a1: "pin 0 adj1 36745",
      "2a1": "*/ a1 2 1",
      mAdj2: "+- 100000 0 2a1",
      a2: "pin 0 adj2 mAdj2",
      dy1: "*/ h a1 100000",
      dy2: "*/ h a2 200000",
      dx1: "*/ w 73490 200000",
      y2: "+- vc 0 dy2",
      y3: "+- vc dy2 0",
      y1: "+- y2 0 dy1",
      y4: "+- y3 dy1 0",
      x1: "+- hc 0 dx1",
      x2: "+- hc dx1 0",
      yC1: "+/ y1 y2 2",
      yC2: "+/ y3 y4 2"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "36745",
        pos: {
          x: "l",
          y: "y1"
        }
      },
      {
        gdRefY: "adj2",
        minY: "0",
        maxY: "mAdj2",
        pos: {
          x: "r",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "x2",
          y: "yC1"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x2",
          y: "yC2"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "y4"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "yC1"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "yC2"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "y1",
      r: "x2",
      b: "y4"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x1",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y4"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [177 /* SHAPE_GEOMETRY_MATH_MINUS */]: {
    avLst: {
      adj1: "val 23520"
    },
    gdLst: {
      a1: "pin 0 adj1 100000",
      dy1: "*/ h a1 200000",
      dx1: "*/ w 73490 200000",
      y1: "+- vc 0 dy1",
      y2: "+- vc dy1 0",
      x1: "+- hc 0 dx1",
      x2: "+- hc dx1 0"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "100000",
        pos: {
          x: "l",
          y: "y1"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "x2",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "y2"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "y1",
      r: "x2",
      b: "y2"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [178 /* SHAPE_GEOMETRY_MATH_MULTIPLY */]: {
    avLst: {
      adj1: "val 23520"
    },
    gdLst: {
      a1: "pin 0 adj1 51965",
      th: "*/ ss a1 100000",
      a: "at2 w h",
      sa: "sin 1 a",
      ca: "cos 1 a",
      ta: "tan 1 a",
      dl: "mod w h 0",
      rw: "*/ dl 51965 100000",
      lM: "+- dl 0 rw",
      xM: "*/ ca lM 2",
      yM: "*/ sa lM 2",
      dxAM: "*/ sa th 2",
      dyAM: "*/ ca th 2",
      xA: "+- xM 0 dxAM",
      yA: "+- yM dyAM 0",
      xB: "+- xM dxAM 0",
      yB: "+- yM 0 dyAM",
      xBC: "+- hc 0 xB",
      yBC: "*/ xBC ta 1",
      yC: "+- yBC yB 0",
      xD: "+- r 0 xB",
      xE: "+- r 0 xA",
      yFE: "+- vc 0 yA",
      xFE: "*/ yFE 1 ta",
      xF: "+- xE 0 xFE",
      xL: "+- xA xFE 0",
      yG: "+- b 0 yA",
      yH: "+- b 0 yB",
      yI: "+- b 0 yC",
      xC2: "+- r 0 xM",
      yC3: "+- b 0 yM"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "51965",
        pos: {
          x: "l",
          y: "th"
        }
      }
    ],
    cxnLst: [
      {
        ang: "cd2",
        pos: {
          x: "xM",
          y: "yM"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "xC2",
          y: "yM"
        }
      },
      {
        ang: "0",
        pos: {
          x: "xC2",
          y: "yC3"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "xM",
          y: "yC3"
        }
      }
    ],
    rect: {
      l: "xA",
      t: "yB",
      r: "xE",
      b: "yH"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "xA",
            y: "yA"
          },
          {
            cmd: "lineTo",
            x: "xB",
            y: "yB"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "yC"
          },
          {
            cmd: "lineTo",
            x: "xD",
            y: "yB"
          },
          {
            cmd: "lineTo",
            x: "xE",
            y: "yA"
          },
          {
            cmd: "lineTo",
            x: "xF",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "xE",
            y: "yG"
          },
          {
            cmd: "lineTo",
            x: "xD",
            y: "yH"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "yI"
          },
          {
            cmd: "lineTo",
            x: "xB",
            y: "yH"
          },
          {
            cmd: "lineTo",
            x: "xA",
            y: "yG"
          },
          {
            cmd: "lineTo",
            x: "xL",
            y: "vc"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [181 /* SHAPE_GEOMETRY_MATH_NOT_EQUAL */]: {
    avLst: {
      adj1: "val 23520",
      adj2: "val 6600000",
      adj3: "val 11760"
    },
    gdLst: {
      a1: "pin 0 adj1 50000",
      crAng: "pin 4200000 adj2 6600000",
      "2a1": "*/ a1 2 1",
      maxAdj3: "+- 100000 0 2a1",
      a3: "pin 0 adj3 maxAdj3",
      dy1: "*/ h a1 100000",
      dy2: "*/ h a3 200000",
      dx1: "*/ w 73490 200000",
      x1: "+- hc 0 dx1",
      x8: "+- hc dx1 0",
      y2: "+- vc 0 dy2",
      y3: "+- vc dy2 0",
      y1: "+- y2 0 dy1",
      y4: "+- y3 dy1 0",
      cadj2: "+- crAng 0 cd4",
      xadj2: "tan hd2 cadj2",
      len: "mod xadj2 hd2 0",
      bhw: "*/ len dy1 hd2",
      bhw2: "*/ bhw 1 2",
      x7: "+- hc xadj2 bhw2",
      dx67: "*/ xadj2 y1 hd2",
      x6: "+- x7 0 dx67",
      dx57: "*/ xadj2 y2 hd2",
      x5: "+- x7 0 dx57",
      dx47: "*/ xadj2 y3 hd2",
      x4: "+- x7 0 dx47",
      dx37: "*/ xadj2 y4 hd2",
      x3: "+- x7 0 dx37",
      dx27: "*/ xadj2 2 1",
      x2: "+- x7 0 dx27",
      rx7: "+- x7 bhw 0",
      rx6: "+- x6 bhw 0",
      rx5: "+- x5 bhw 0",
      rx4: "+- x4 bhw 0",
      rx3: "+- x3 bhw 0",
      rx2: "+- x2 bhw 0",
      dx7: "*/ dy1 hd2 len",
      rxt: "+- x7 dx7 0",
      lxt: "+- rx7 0 dx7",
      rx: "?: cadj2 rxt rx7",
      lx: "?: cadj2 x7 lxt",
      dy3: "*/ dy1 xadj2 len",
      dy4: "+- 0 0 dy3",
      ry: "?: cadj2 dy3 t",
      ly: "?: cadj2 t dy4",
      dlx: "+- w 0 rx",
      drx: "+- w 0 lx",
      dly: "+- h 0 ry",
      dry: "+- h 0 ly",
      xC1: "+/ rx lx 2",
      xC2: "+/ drx dlx 2",
      yC1: "+/ ry ly 2",
      yC2: "+/ y1 y2 2",
      yC3: "+/ y3 y4 2",
      yC4: "+/ dry dly 2"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "50000",
        pos: {
          x: "l",
          y: "y1"
        }
      },
      {
        pos: {
          x: "lx",
          y: "t"
        }
      },
      {
        gdRefY: "adj3",
        minY: "0",
        maxY: "maxAdj3",
        pos: {
          x: "r",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "x8",
          y: "yC2"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x8",
          y: "yC3"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "xC2",
          y: "yC4"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "yC2"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "yC3"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "xC1",
          y: "yC1"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "y1",
      r: "x8",
      b: "y4"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "lx",
            y: "ly"
          },
          {
            cmd: "lineTo",
            x: "rx",
            y: "ry"
          },
          {
            cmd: "lineTo",
            x: "rx6",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "rx5",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "rx4",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "rx3",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "drx",
            y: "dry"
          },
          {
            cmd: "lineTo",
            x: "dlx",
            y: "dly"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [176 /* SHAPE_GEOMETRY_MATH_PLUS */]: {
    avLst: {
      adj1: "val 23520"
    },
    gdLst: {
      a1: "pin 0 adj1 73490",
      dx1: "*/ w 73490 200000",
      dy1: "*/ h 73490 200000",
      dx2: "*/ ss a1 200000",
      x1: "+- hc 0 dx1",
      x2: "+- hc 0 dx2",
      x3: "+- hc dx2 0",
      x4: "+- hc dx1 0",
      y1: "+- vc 0 dy1",
      y2: "+- vc 0 dx2",
      y3: "+- vc dx2 0",
      y4: "+- vc dy1 0"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "73490",
        pos: {
          x: "l",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "x4",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "y4"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "y2",
      r: "x4",
      b: "y3"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y3"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [78 /* SHAPE_GEOMETRY_MOON */]: {
    avLst: {
      adj: "val 50000"
    },
    gdLst: {
      a: "pin 0 adj 87500",
      g0: "*/ ss a 100000",
      g0w: "*/ g0 w ss",
      g1: "+- ss 0 g0",
      g2: "*/ g0 g0 g1",
      g3: "*/ ss ss g1",
      g4: "*/ g3 2 1",
      g5: "+- g4 0 g2",
      g6: "+- g5 0 g0",
      g6w: "*/ g6 w ss",
      g7: "*/ g5 1 2",
      g8: "+- g7 0 g0",
      dy1: "*/ g8 hd2 ss",
      g10h: "+- vc 0 dy1",
      g11h: "+- vc dy1 0",
      g12: "*/ g0 9598 32768",
      g12w: "*/ g12 w ss",
      g13: "+- ss 0 g12",
      q1: "*/ ss ss 1",
      q2: "*/ g13 g13 1",
      q3: "+- q1 0 q2",
      q4: "sqrt q3",
      dy4: "*/ q4 hd2 ss",
      g15h: "+- vc 0 dy4",
      g16h: "+- vc dy4 0",
      g17w: "+- g6w 0 g0w",
      g18w: "*/ g17w 1 2",
      dx2p: "+- g0w g18w w",
      dx2: "*/ dx2p -1 1",
      dy2: "*/ hd2 -1 1",
      stAng1: "at2 dx2 dy2",
      enAngp1: "at2 dx2 hd2",
      enAng1: "+- enAngp1 0 21600000",
      swAng1: "+- enAng1 0 stAng1"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "0",
        maxX: "87500",
        pos: {
          x: "g0w",
          y: "vc"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "r",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "r",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "g0w",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "g12w",
      t: "g15h",
      r: "g0w",
      b: "g16h"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "hd2",
            stAng: "cd4",
            swAng: "cd2"
          },
          {
            cmd: "arcTo",
            wR: "g18w",
            hR: "dy1",
            stAng: "stAng1",
            swAng: "swAng1"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [9 /* SHAPE_GEOMETRY_NON_ISOSCELES_TRAPEZOID */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 25000"
    },
    gdLst: {
      maxAdj: "*/ 50000 w ss",
      a1: "pin 0 adj1 maxAdj",
      a2: "pin 0 adj2 maxAdj",
      x1: "*/ ss a1 200000",
      x2: "*/ ss a1 100000",
      dx3: "*/ ss a2 100000",
      x3: "+- r 0 dx3",
      x4: "+/ r x3 2",
      il: "*/ wd3 a1 maxAdj",
      adjm: "max a1 a2",
      it: "*/ hd3 adjm maxAdj",
      irt: "*/ wd3 a2 maxAdj",
      ir: "+- r 0 irt"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "maxAdj",
        pos: {
          x: "x2",
          y: "t"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "maxAdj",
        pos: {
          x: "x3",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "x4",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [43 /* SHAPE_GEOMETRY_NO_SMOKING */]: {
    avLst: {
      adj: "val 18750"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      dr: "*/ ss a 100000",
      iwd2: "+- wd2 0 dr",
      ihd2: "+- hd2 0 dr",
      ang: "at2 w h",
      ct: "cos ihd2 ang",
      st: "sin iwd2 ang",
      m: "mod ct st 0",
      n: "*/ iwd2 ihd2 m",
      drd2: "*/ dr 1 2",
      dang: "at2 n drd2",
      "2dang": "*/ dang 2 1",
      swAng: "+- -10800000 2dang 0",
      t3: "at2 w h",
      stAng1: "+- t3 0 dang",
      stAng2: "+- stAng1 0 cd2",
      ct1: "cos ihd2 stAng1",
      st1: "sin iwd2 stAng1",
      m1: "mod ct1 st1 0",
      n1: "*/ iwd2 ihd2 m1",
      dx1: "cos n1 stAng1",
      dy1: "sin n1 stAng1",
      x1: "+- hc dx1 0",
      y1: "+- vc dy1 0",
      x2: "+- hc 0 dx1",
      y2: "+- vc 0 dy1",
      idx: "cos wd2 2700000",
      idy: "sin hd2 2700000",
      il: "+- hc 0 idx",
      ir: "+- hc idx 0",
      it: "+- vc 0 idy",
      ib: "+- vc idy 0"
    },
    ahLst: [
      {
        pos: {
          x: "dr",
          y: "vc"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "il",
          y: "it"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "il",
          y: "ib"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "ir",
          y: "ib"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "ir",
          y: "it"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "iwd2",
            hR: "ihd2",
            stAng: "stAng1",
            swAng: "swAng"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "iwd2",
            hR: "ihd2",
            stAng: "stAng2",
            swAng: "swAng"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [49 /* SHAPE_GEOMETRY_NOTCHED_RIGHT_ARROW */]: {
    avLst: {
      adj1: "val 50000",
      adj2: "val 50000"
    },
    gdLst: {
      maxAdj2: "*/ 100000 w ss",
      a1: "pin 0 adj1 100000",
      a2: "pin 0 adj2 maxAdj2",
      dx2: "*/ ss a2 100000",
      x2: "+- r 0 dx2",
      dy1: "*/ h a1 200000",
      y1: "+- vc 0 dy1",
      y2: "+- vc dy1 0",
      x1: "*/ dy1 dx2 hd2",
      x3: "+- r 0 x1"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "100000",
        pos: {
          x: "r",
          y: "y1"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "maxAdj2",
        pos: {
          x: "x2",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x2",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x2",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "y1",
      r: "x3",
      b: "y2"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "vc"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [13 /* SHAPE_GEOMETRY_OCTAGON */]: {
    avLst: {
      adj: "val 29289"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      x1: "*/ ss a 100000",
      x2: "+- r 0 x1",
      y2: "+- b 0 x1",
      il: "*/ x1 1 2",
      ir: "+- r 0 il",
      ib: "+- b 0 il"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x1",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "x1"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y2"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x2",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x1",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y2"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "x1"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x1",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x2",
          y: "t"
        }
      }
    ],
    rect: {
      l: "il",
      t: "il",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [7 /* SHAPE_GEOMETRY_PARALLELOGRAM */]: {
    avLst: {
      adj: "val 25000"
    },
    gdLst: {
      maxAdj: "*/ 100000 w ss",
      a: "pin 0 adj maxAdj",
      x1: "*/ ss a 200000",
      x2: "*/ ss a 100000",
      x6: "+- r 0 x1",
      x5: "+- r 0 x2",
      x3: "*/ x5 1 2",
      x4: "+- r 0 x3",
      il: "*/ q2 w 1",
      q1: "*/ 5 a maxAdj",
      q2: "+/ 1 q1 12",
      it: "*/ q2 h 1",
      ir: "+- r 0 il",
      ib: "+- b 0 it",
      q3: "*/ h hc x2",
      y1: "pin 0 q3 h",
      y2: "+- b 0 y1"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "0",
        maxX: "maxAdj",
        pos: {
          x: "x2",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "y2"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x4",
          y: "t"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x6",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x3",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "y1"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [10 /* SHAPE_GEOMETRY_PENTAGON */]: {
    avLst: {
      hf: "val 105146",
      vf: "val 110557"
    },
    gdLst: {
      swd2: "*/ wd2 hf 100000",
      shd2: "*/ hd2 vf 100000",
      svc: "*/ vc  vf 100000",
      dx1: "cos swd2 1080000",
      dx2: "cos swd2 18360000",
      dy1: "sin shd2 1080000",
      dy2: "sin shd2 18360000",
      x1: "+- hc 0 dx1",
      x2: "+- hc 0 dx2",
      x3: "+- hc dx2 0",
      x4: "+- hc dx1 0",
      y1: "+- svc 0 dy1",
      y2: "+- svc 0 dy2",
      it: "*/ y1 dx2 dx1"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x2",
          y: "y2"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x3",
          y: "y2"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x4",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "x2",
      t: "it",
      r: "x3",
      b: "y2"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [40 /* SHAPE_GEOMETRY_PIE */]: {
    avLst: {
      adj1: "val 0",
      adj2: "val 16200000"
    },
    gdLst: {
      stAng: "pin 0 adj1 21599999",
      enAng: "pin 0 adj2 21599999",
      sw1: "+- enAng 0 stAng",
      sw2: "+- sw1 21600000 0",
      swAng: "?: sw1 sw1 sw2",
      wt1: "sin wd2 stAng",
      ht1: "cos hd2 stAng",
      dx1: "cat2 wd2 ht1 wt1",
      dy1: "sat2 hd2 ht1 wt1",
      x1: "+- hc dx1 0",
      y1: "+- vc dy1 0",
      wt2: "sin wd2 enAng",
      ht2: "cos hd2 enAng",
      dx2: "cat2 wd2 ht2 wt2",
      dy2: "sat2 hd2 ht2 wt2",
      x2: "+- hc dx2 0",
      y2: "+- vc dy2 0",
      idx: "cos wd2 2700000",
      idy: "sin hd2 2700000",
      il: "+- hc 0 idx",
      ir: "+- hc idx 0",
      it: "+- vc 0 idy",
      ib: "+- vc idy 0"
    },
    ahLst: [
      {
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        pos: {
          x: "x2",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "il",
      t: "ir",
      r: "it",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "stAng",
            swAng: "swAng"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "vc"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [39 /* SHAPE_GEOMETRY_PIE_WEDGE */]: {
    avLst: {},
    gdLst: {
      g1: "cos w 13500000",
      g2: "sin h 13500000",
      x1: "+- r g1 0",
      y1: "+- b g2 0"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "y1",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "h",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [34 /* SHAPE_GEOMETRY_PLAQUE */]: {
    avLst: {
      adj: "val 16667"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      x1: "*/ ss a 100000",
      x2: "+- r 0 x1",
      y2: "+- b 0 x1",
      il: "*/ x1 70711 100000",
      ir: "+- r 0 il",
      ib: "+- b 0 il"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x1",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "il",
      t: "il",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "x1"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd2",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "3cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "0",
            swAng: "-5400000"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [184 /* SHAPE_GEOMETRY_PLAQUE_TABS */]: {
    avLst: {},
    gdLst: {
      md: "mod w h 0",
      dx: "*/ 1 md 20",
      y1: "+- 0 b dx",
      x1: "+- 0 r dx"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "dx"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y1"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "b"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "dx",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x1",
          y: "t"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "dx",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x1",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "t"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "dx"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y1"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "b"
        }
      }
    ],
    rect: {
      l: "dx",
      t: "dx",
      r: "x1",
      b: "y1"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "dx",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "dx",
            hR: "dx",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "dx",
            hR: "dx",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "dx"
          },
          {
            cmd: "arcTo",
            wR: "dx",
            hR: "dx",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "dx",
            hR: "dx",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [131 /* SHAPE_GEOMETRY_PLUS */]: {
    avLst: {
      adj: "val 25000"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      x1: "*/ ss a 100000",
      x2: "+- r 0 x1",
      y2: "+- b 0 x1",
      d: "+- w 0 h",
      il: "?: d l x1",
      ir: "?: d r x2",
      it: "?: d x1 t",
      ib: "?: d y2 b"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x1",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [55 /* SHAPE_GEOMETRY_QUAD_ARROW */]: {
    avLst: {
      adj1: "val 22500",
      adj2: "val 22500",
      adj3: "val 22500"
    },
    gdLst: {
      a2: "pin 0 adj2 50000",
      maxAdj1: "*/ a2 2 1",
      a1: "pin 0 adj1 maxAdj1",
      q1: "+- 100000 0 maxAdj1",
      maxAdj3: "*/ q1 1 2",
      a3: "pin 0 adj3 maxAdj3",
      x1: "*/ ss a3 100000",
      dx2: "*/ ss a2 100000",
      x2: "+- hc 0 dx2",
      x5: "+- hc dx2 0",
      dx3: "*/ ss a1 200000",
      x3: "+- hc 0 dx3",
      x4: "+- hc dx3 0",
      x6: "+- r 0 x1",
      y2: "+- vc 0 dx2",
      y5: "+- vc dx2 0",
      y3: "+- vc 0 dx3",
      y4: "+- vc dx3 0",
      y6: "+- b 0 x1",
      il: "*/ dx3 x1 dx2",
      ir: "+- r 0 il"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "maxAdj1",
        pos: {
          x: "x3",
          y: "x1"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x2",
          y: "t"
        }
      },
      {
        gdRefY: "adj3",
        minY: "0",
        maxY: "maxAdj3",
        pos: {
          x: "r",
          y: "x1"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "il",
      t: "y3",
      r: "ir",
      b: "y4"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "x1"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y5"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [62 /* SHAPE_GEOMETRY_QUAD_ARROW_CALLOUT */]: {
    avLst: {
      adj1: "val 18515",
      adj2: "val 18515",
      adj3: "val 18515",
      adj4: "val 48123"
    },
    gdLst: {
      a2: "pin 0 adj2 50000",
      maxAdj1: "*/ a2 2 1",
      a1: "pin 0 adj1 maxAdj1",
      maxAdj3: "+- 50000 0 a2",
      a3: "pin 0 adj3 maxAdj3",
      q2: "*/ a3 2 1",
      maxAdj4: "+- 100000 0 q2",
      a4: "pin a1 adj4 maxAdj4",
      dx2: "*/ ss a2 100000",
      dx3: "*/ ss a1 200000",
      ah: "*/ ss a3 100000",
      dx1: "*/ w a4 200000",
      dy1: "*/ h a4 200000",
      x8: "+- r 0 ah",
      x2: "+- hc 0 dx1",
      x7: "+- hc dx1 0",
      x3: "+- hc 0 dx2",
      x6: "+- hc dx2 0",
      x4: "+- hc 0 dx3",
      x5: "+- hc dx3 0",
      y8: "+- b 0 ah",
      y2: "+- vc 0 dy1",
      y7: "+- vc dy1 0",
      y3: "+- vc 0 dx2",
      y6: "+- vc dx2 0",
      y4: "+- vc 0 dx3",
      y5: "+- vc dx3 0"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "maxAdj1",
        pos: {
          x: "x4",
          y: "ah"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x3",
          y: "t"
        }
      },
      {
        gdRefY: "adj3",
        minY: "0",
        maxY: "maxAdj3",
        pos: {
          x: "r",
          y: "ah"
        }
      },
      {
        gdRefY: "adj4",
        minY: "a1",
        maxY: "maxAdj4",
        pos: {
          x: "l",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "x2",
      t: "y2",
      r: "x7",
      b: "y7"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "ah",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "ah",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "ah"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "ah"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "ah"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "ah"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "y7"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y7"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y8"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y8"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y8"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y8"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y7"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y7"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "ah",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "ah",
            y: "y6"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [5 /* SHAPE_GEOMETRY_RECT */]: {
    avLst: {},
    gdLst: {},
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [122 /* SHAPE_GEOMETRY_RIBBON */]: {
    avLst: {
      adj1: "val 16667",
      adj2: "val 50000"
    },
    gdLst: {
      a1: "pin 0 adj1 33333",
      a2: "pin 25000 adj2 75000",
      x10: "+- r 0 wd8",
      dx2: "*/ w a2 200000",
      x2: "+- hc 0 dx2",
      x9: "+- hc dx2 0",
      x3: "+- x2 wd32 0",
      x8: "+- x9 0 wd32",
      x5: "+- x2 wd8 0",
      x6: "+- x9 0 wd8",
      x4: "+- x5 0 wd32",
      x7: "+- x6 wd32 0",
      y1: "*/ h a1 200000",
      y2: "*/ h a1 100000",
      y4: "+- b 0 y2",
      y3: "*/ y4 1 2",
      hR: "*/ h a1 400000",
      y5: "+- b 0 hR",
      y6: "+- y2 0 hR"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "33333",
        pos: {
          x: "hc",
          y: "y2"
        }
      },
      {
        gdRefX: "adj2",
        minX: "25000",
        maxX: "75000",
        pos: {
          x: "x2",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "y2"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "wd8",
          y: "y3"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x10",
          y: "y3"
        }
      }
    ],
    rect: {
      l: "x2",
      t: "y2",
      r: "x9",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "3cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "3cd4",
            swAng: "-10800000"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "cd4",
            swAng: "-10800000"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x10",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x9",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x9",
            y: "y5"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "wd8",
            y: "y3"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darkenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x5",
            y: "hR"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "3cd4",
            swAng: "-10800000"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y2"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x6",
            y: "hR"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "cd2",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "3cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y2"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "3cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "3cd4",
            swAng: "-10800000"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "cd4",
            swAng: "-10800000"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x10",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x9",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x9",
            y: "y5"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "wd8",
            y: "y3"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x5",
            y: "hR"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y2"
          },
          {
            cmd: "moveTo",
            x: "x6",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "hR"
          },
          {
            cmd: "moveTo",
            x: "x2",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y6"
          },
          {
            cmd: "moveTo",
            x: "x9",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "x9",
            y: "y4"
          }
        ]
      }
    ]
  },
  [123 /* SHAPE_GEOMETRY_RIBBON2 */]: {
    avLst: {
      adj1: "val 16667",
      adj2: "val 50000"
    },
    gdLst: {
      a1: "pin 0 adj1 33333",
      a2: "pin 25000 adj2 75000",
      x10: "+- r 0 wd8",
      dx2: "*/ w a2 200000",
      x2: "+- hc 0 dx2",
      x9: "+- hc dx2 0",
      x3: "+- x2 wd32 0",
      x8: "+- x9 0 wd32",
      x5: "+- x2 wd8 0",
      x6: "+- x9 0 wd8",
      x4: "+- x5 0 wd32",
      x7: "+- x6 wd32 0",
      dy1: "*/ h a1 200000",
      y1: "+- b 0 dy1",
      dy2: "*/ h a1 100000",
      y2: "+- b 0 dy2",
      y4: "+- t dy2 0",
      y3: "+/ y4 b 2",
      hR: "*/ h a1 400000",
      y6: "+- b 0 hR",
      y7: "+- y1 0 hR"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "33333",
        pos: {
          x: "hc",
          y: "y2"
        }
      },
      {
        gdRefX: "adj2",
        minX: "25000",
        maxX: "75000",
        pos: {
          x: "x2",
          y: "b"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "wd8",
          y: "y3"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "y2"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x10",
          y: "y3"
        }
      }
    ],
    rect: {
      l: "x2",
      t: "t",
      r: "x9",
      b: "y2"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "cd4",
            swAng: "-10800000"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "3cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "3cd4",
            swAng: "-10800000"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x10",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x9",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x9",
            y: "hR"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "0",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "3cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "wd8",
            y: "y3"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darkenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x5",
            y: "y6"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "0",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y2"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x6",
            y: "y6"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "cd4",
            swAng: "-10800000"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y2"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "wd8",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "hR"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x9",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x9",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x10",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "cd4",
            swAng: "-10800000"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "3cd4",
            swAng: "-10800000"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd32",
            hR: "hR",
            stAng: "3cd4",
            swAng: "cd2"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x5",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y6"
          },
          {
            cmd: "moveTo",
            x: "x6",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y2"
          },
          {
            cmd: "moveTo",
            x: "x2",
            y: "y7"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y4"
          },
          {
            cmd: "moveTo",
            x: "x9",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x9",
            y: "y7"
          }
        ]
      }
    ]
  },
  [44 /* SHAPE_GEOMETRY_RIGHT_ARROW */]: {
    avLst: {
      adj1: "val 50000",
      adj2: "val 50000"
    },
    gdLst: {
      maxAdj2: "*/ 100000 w ss",
      a1: "pin 0 adj1 100000",
      a2: "pin 0 adj2 maxAdj2",
      dx1: "*/ ss a2 100000",
      x1: "+- r 0 dx1",
      dy1: "*/ h a1 200000",
      y1: "+- vc 0 dy1",
      y2: "+- vc dy1 0",
      dx2: "*/ y1 dx1 hd2",
      x2: "+- x1 dx2 0"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "100000",
        pos: {
          x: "l",
          y: "y1"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "maxAdj2",
        pos: {
          x: "x1",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x1",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x1",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "y1",
      r: "x2",
      b: "y2"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [57 /* SHAPE_GEOMETRY_RIGHT_ARROW_CALLOUT */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 25000",
      adj3: "val 25000",
      adj4: "val 64977"
    },
    gdLst: {
      maxAdj2: "*/ 50000 h ss",
      a2: "pin 0 adj2 maxAdj2",
      maxAdj1: "*/ a2 2 1",
      a1: "pin 0 adj1 maxAdj1",
      maxAdj3: "*/ 100000 w ss",
      a3: "pin 0 adj3 maxAdj3",
      q2: "*/ a3 ss w",
      maxAdj4: "+- 100000 0 q2",
      a4: "pin 0 adj4 maxAdj4",
      dy1: "*/ ss a2 100000",
      dy2: "*/ ss a1 200000",
      y1: "+- vc 0 dy1",
      y2: "+- vc 0 dy2",
      y3: "+- vc dy2 0",
      y4: "+- vc dy1 0",
      dx3: "*/ ss a3 100000",
      x3: "+- r 0 dx3",
      x2: "*/ w a4 100000",
      x1: "*/ x2 1 2"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "maxAdj1",
        pos: {
          x: "x3",
          y: "y2"
        }
      },
      {
        gdRefY: "adj2",
        minY: "0",
        maxY: "maxAdj2",
        pos: {
          x: "r",
          y: "y1"
        }
      },
      {
        gdRefX: "adj3",
        minX: "0",
        maxX: "maxAdj3",
        pos: {
          x: "x3",
          y: "t"
        }
      },
      {
        gdRefX: "adj4",
        minX: "0",
        maxX: "maxAdj4",
        pos: {
          x: "x2",
          y: "b"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x1",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x1",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "x2",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [93 /* SHAPE_GEOMETRY_RIGHT_BRACE */]: {
    avLst: {
      adj1: "val 8333",
      adj2: "val 50000"
    },
    gdLst: {
      a2: "pin 0 adj2 100000",
      q1: "+- 100000 0 a2",
      q2: "min q1 a2",
      q3: "*/ q2 1 2",
      maxAdj1: "*/ q3 h ss",
      a1: "pin 0 adj1 maxAdj1",
      y1: "*/ ss a1 100000",
      y3: "*/ h a2 100000",
      y2: "+- y3 0 y1",
      y4: "+- b 0 y1",
      dx1: "cos wd2 2700000",
      dy1: "sin y1 2700000",
      ir: "+- l dx1 0",
      it: "+- y1 0 dy1",
      ib: "+- b dy1 y1"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "maxAdj1",
        pos: {
          x: "hc",
          y: "y1"
        }
      },
      {
        gdRefY: "adj2",
        minY: "0",
        maxY: "100000",
        pos: {
          x: "r",
          y: "y3"
        }
      }
    ],
    cxnLst: [
      {
        ang: "cd4",
        pos: {
          x: "l",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "r",
          y: "y3"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "l",
          y: "b"
        }
      }
    ],
    rect: {
      l: "l",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "cd2",
            swAng: "-5400000"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "3cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "y4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "cd2",
            swAng: "-5400000"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "3cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "y4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "y1",
            stAng: "0",
            swAng: "cd4"
          }
        ]
      }
    ]
  },
  [91 /* SHAPE_GEOMETRY_RIGHT_BRACKET */]: {
    avLst: {
      adj: "val 8333"
    },
    gdLst: {
      maxAdj: "*/ 50000 h ss",
      a: "pin 0 adj maxAdj",
      y1: "*/ ss a 100000",
      y2: "+- b 0 y1",
      dx1: "cos w 2700000",
      dy1: "sin y1 2700000",
      ir: "+- l dx1 0",
      it: "+- y1 0 dy1",
      ib: "+- b dy1 y1"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "maxAdj",
        pos: {
          x: "r",
          y: "y1"
        }
      }
    ],
    cxnLst: [
      {
        ang: "cd4",
        pos: {
          x: "l",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "l",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "y1",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "y1",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "y1",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "w",
            hR: "y1",
            stAng: "0",
            swAng: "cd4"
          }
        ]
      }
    ]
  },
  [27 /* SHAPE_GEOMETRY_ROUND1_RECT */]: {
    avLst: {
      adj: "val 16667"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      dx1: "*/ ss a 100000",
      x1: "+- r 0 dx1",
      idx: "*/ dx1 29289 100000",
      ir: "+- r 0 idx"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x1",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "ir",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "dx1",
            hR: "dx1",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [29 /* SHAPE_GEOMETRY_ROUND2_DIAG_RECT */]: {
    avLst: {
      adj1: "val 16667",
      adj2: "val 0"
    },
    gdLst: {
      a1: "pin 0 adj1 50000",
      a2: "pin 0 adj2 50000",
      x1: "*/ ss a1 100000",
      y1: "+- b 0 x1",
      a: "*/ ss a2 100000",
      x2: "+- r 0 a",
      y2: "+- b 0 a",
      dx1: "*/ x1 29289 100000",
      dx2: "*/ a 29289 100000",
      d: "+- dx1 0 dx2",
      dx: "?: d dx1 dx2",
      ir: "+- r 0 dx",
      ib: "+- b 0 dx"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x1",
          y: "t"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x2",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "dx",
      t: "dx",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "a",
            hR: "a",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "a",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "a",
            hR: "a",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "x1"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [28 /* SHAPE_GEOMETRY_ROUND2_SAME_RECT */]: {
    avLst: {
      adj1: "val 16667",
      adj2: "val 0"
    },
    gdLst: {
      a1: "pin 0 adj1 50000",
      a2: "pin 0 adj2 50000",
      tx1: "*/ ss a1 100000",
      tx2: "+- r 0 tx1",
      bx1: "*/ ss a2 100000",
      bx2: "+- r 0 bx1",
      by1: "+- b 0 bx1",
      d: "+- tx1 0 bx1",
      tdx: "*/ tx1 29289 100000",
      bdx: "*/ bx1 29289 100000",
      il: "?: d tdx bdx",
      ir: "+- r 0 il",
      ib: "+- b 0 bdx"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "tx2",
          y: "t"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "bx1",
          y: "b"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "il",
      t: "tdx",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "tx1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "tx2",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "tx1",
            hR: "tx1",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "by1"
          },
          {
            cmd: "arcTo",
            wR: "bx1",
            hR: "bx1",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "bx1",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "bx1",
            hR: "bx1",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "tx1"
          },
          {
            cmd: "arcTo",
            wR: "tx1",
            hR: "tx1",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  }
};

// node_modules/@oai/granola/dist/shapes/preset-shape-definitions.part5.js
var presetShapeDefinitionsPart5 = {
  [26 /* SHAPE_GEOMETRY_ROUND_RECT */]: {
    avLst: {
      adj: "val 16667"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      x1: "*/ ss a 100000",
      x2: "+- r 0 x1",
      y2: "+- b 0 x1",
      il: "*/ x1 29289 100000",
      ir: "+- r 0 il",
      ib: "+- b 0 il"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x1",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "il",
      t: "il",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "x1"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [4 /* SHAPE_GEOMETRY_RT_TRIANGLE */]: {
    avLst: {},
    gdLst: {
      it: "*/ h 7 12",
      ir: "*/ w 7 12",
      ib: "*/ h 11 12"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "l",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "l",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "r",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "hc",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "wd12",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [79 /* SHAPE_GEOMETRY_SMILEY_FACE */]: {
    avLst: {
      adj: "val 4653"
    },
    gdLst: {
      a: "pin -4653 adj 4653",
      x1: "*/ w 4969 21699",
      x2: "*/ w 6215 21600",
      x3: "*/ w 13135 21600",
      x4: "*/ w 16640 21600",
      y1: "*/ h 7570 21600",
      y3: "*/ h 16515 21600",
      dy2: "*/ h a 100000",
      y2: "+- y3 0 dy2",
      y4: "+- y3 dy2 0",
      dy3: "*/ h a 50000",
      y5: "+- y4 dy3 0",
      idx: "cos wd2 2700000",
      idy: "sin hd2 2700000",
      il: "+- hc 0 idx",
      ir: "+- hc idx 0",
      it: "+- vc 0 idy",
      ib: "+- vc idy 0",
      wR: "*/ w 1125 21600",
      hR: "*/ h 1125 21600"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "-4653",
        maxY: "4653",
        pos: {
          x: "hc",
          y: "y4"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "il",
          y: "it"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "il",
          y: "ib"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "ir",
          y: "ib"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "ir",
          y: "it"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd2",
            swAng: "21600000"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darkenLess",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "hR",
            stAng: "cd2",
            swAng: "21600000"
          },
          {
            cmd: "moveTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "hR",
            stAng: "cd2",
            swAng: "21600000"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "quadBezTo",
            x: "x4",
            y: "y2",
            x1: "hc",
            y1: "y5"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd2",
            swAng: "21600000"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [31 /* SHAPE_GEOMETRY_SNIP1_RECT */]: {
    avLst: {
      adj: "val 16667"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      dx1: "*/ ss a 100000",
      x1: "+- r 0 dx1",
      it: "*/ dx1 1 2",
      ir: "+/ x1 r 2"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x1",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "l",
      t: "it",
      r: "ir",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "dx1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [33 /* SHAPE_GEOMETRY_SNIP2_DIAG_RECT */]: {
    avLst: {
      adj1: "val 0",
      adj2: "val 16667"
    },
    gdLst: {
      a1: "pin 0 adj1 50000",
      a2: "pin 0 adj2 50000",
      lx1: "*/ ss a1 100000",
      lx2: "+- r 0 lx1",
      ly1: "+- b 0 lx1",
      rx1: "*/ ss a2 100000",
      rx2: "+- r 0 rx1",
      ry1: "+- b 0 rx1",
      d: "+- lx1 0 rx1",
      dx: "?: d lx1 rx1",
      il: "*/ dx 1 2",
      ir: "+- r 0 il",
      ib: "+- b 0 il"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "lx1",
          y: "t"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "rx2",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "il",
      t: "il",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "lx1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "rx2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "rx1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "ly1"
          },
          {
            cmd: "lineTo",
            x: "lx2",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "rx1",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "ry1"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "lx1"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [32 /* SHAPE_GEOMETRY_SNIP2_SAME_RECT */]: {
    avLst: {
      adj1: "val 16667",
      adj2: "val 0"
    },
    gdLst: {
      a1: "pin 0 adj1 50000",
      a2: "pin 0 adj2 50000",
      tx1: "*/ ss a1 100000",
      tx2: "+- r 0 tx1",
      bx1: "*/ ss a2 100000",
      bx2: "+- r 0 bx1",
      by1: "+- b 0 bx1",
      d: "+- tx1 0 bx1",
      dx: "?: d tx1 bx1",
      il: "*/ dx 1 2",
      ir: "+- r 0 il",
      it: "*/ tx1 1 2",
      ib: "+/ by1 b 2"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "tx2",
          y: "t"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "bx1",
          y: "b"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "tx1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "tx2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "tx1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "by1"
          },
          {
            cmd: "lineTo",
            x: "bx2",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "bx1",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "by1"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "tx1"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [30 /* SHAPE_GEOMETRY_SNIP_ROUND_RECT */]: {
    avLst: {
      adj1: "val 16667",
      adj2: "val 16667"
    },
    gdLst: {
      a1: "pin 0 adj1 50000",
      a2: "pin 0 adj2 50000",
      x1: "*/ ss a1 100000",
      dx2: "*/ ss a2 100000",
      x2: "+- r 0 dx2",
      il: "*/ x1 29289 100000",
      ir: "+/ x2 r 2"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x1",
          y: "t"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "50000",
        pos: {
          x: "x2",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "il",
      t: "il",
      r: "ir",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "dx2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "x1"
          },
          {
            cmd: "arcTo",
            wR: "x1",
            hR: "x1",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [183 /* SHAPE_GEOMETRY_SQUARE_TABS */]: {
    avLst: {},
    gdLst: {
      md: "mod w h 0",
      dx: "*/ 1 md 20",
      y1: "+- 0 b dx",
      x1: "+- 0 r dx"
    },
    ahLst: [],
    cxnLst: [
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "dx"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y1"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "dx",
          y: "dx"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "dx",
          y: "x1"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "dx",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x1",
          y: "t"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "dx",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x1",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "t"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "dx"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y1"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x1",
          y: "dx"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x1",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "dx",
      t: "dx",
      r: "x1",
      b: "y1"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "dx",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "dx",
            y: "dx"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "dx"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "dx",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "dx",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "dx"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "dx"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [21 /* SHAPE_GEOMETRY_STAR10 */]: {
    avLst: {
      adj: "val 42533",
      hf: "val 105146"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      swd2: "*/ wd2 hf 100000",
      dx1: "*/ swd2 95106 100000",
      dx2: "*/ swd2 58779 100000",
      x1: "+- hc 0 dx1",
      x2: "+- hc 0 dx2",
      x3: "+- hc dx2 0",
      x4: "+- hc dx1 0",
      dy1: "*/ hd2 80902 100000",
      dy2: "*/ hd2 30902 100000",
      y1: "+- vc 0 dy1",
      y2: "+- vc 0 dy2",
      y3: "+- vc dy2 0",
      y4: "+- vc dy1 0",
      iwd2: "*/ swd2 a 50000",
      ihd2: "*/ hd2 a 50000",
      sdx1: "*/ iwd2 80902 100000",
      sdx2: "*/ iwd2 30902 100000",
      sdy1: "*/ ihd2 95106 100000",
      sdy2: "*/ ihd2 58779 100000",
      sx1: "+- hc 0 iwd2",
      sx2: "+- hc 0 sdx1",
      sx3: "+- hc 0 sdx2",
      sx4: "+- hc sdx2 0",
      sx5: "+- hc sdx1 0",
      sx6: "+- hc iwd2 0",
      sy1: "+- vc 0 sdy1",
      sy2: "+- vc 0 sdy2",
      sy3: "+- vc sdy2 0",
      sy4: "+- vc sdy1 0",
      yAdj: "+- vc 0 ihd2"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "50000",
        pos: {
          x: "hc",
          y: "yAdj"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "x4",
          y: "y2"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x4",
          y: "y3"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x3",
          y: "y4"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x2",
          y: "y4"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y3"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y2"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x2",
          y: "y1"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x3",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "sx2",
      t: "sy2",
      r: "sx5",
      b: "sy3"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "sx3",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "sx4",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "sx5",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "sx6",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "sx5",
            y: "sy3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "sx4",
            y: "sy4"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "sx3",
            y: "sy4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy3"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "sx1",
            y: "vc"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [22 /* SHAPE_GEOMETRY_STAR12 */]: {
    avLst: {
      adj: "val 37500"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      dx1: "cos wd2 1800000",
      dy1: "sin hd2 3600000",
      x1: "+- hc 0 dx1",
      x3: "*/ w 3 4",
      x4: "+- hc dx1 0",
      y1: "+- vc 0 dy1",
      y3: "*/ h 3 4",
      y4: "+- vc dy1 0",
      iwd2: "*/ wd2 a 50000",
      ihd2: "*/ hd2 a 50000",
      sdx1: "cos iwd2 900000",
      sdx2: "cos iwd2 2700000",
      sdx3: "cos iwd2 4500000",
      sdy1: "sin ihd2 4500000",
      sdy2: "sin ihd2 2700000",
      sdy3: "sin ihd2 900000",
      sx1: "+- hc 0 sdx1",
      sx2: "+- hc 0 sdx2",
      sx3: "+- hc 0 sdx3",
      sx4: "+- hc sdx3 0",
      sx5: "+- hc sdx2 0",
      sx6: "+- hc sdx1 0",
      sy1: "+- vc 0 sdy1",
      sy2: "+- vc 0 sdy2",
      sy3: "+- vc 0 sdy3",
      sy4: "+- vc sdy3 0",
      sy5: "+- vc sdy2 0",
      sy6: "+- vc sdy1 0",
      yAdj: "+- vc 0 ihd2"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "50000",
        pos: {
          x: "hc",
          y: "yAdj"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "x4",
          y: "hd4"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x4",
          y: "y3"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x3",
          y: "y4"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "wd4",
          y: "y4"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y3"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "hd4"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "wd4",
          y: "y1"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x3",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "sx2",
      t: "sy2",
      r: "sx5",
      b: "sy5"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "sx1",
            y: "sy3"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "hd4"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "wd4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "sx3",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "sx4",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "sx5",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "hd4"
          },
          {
            cmd: "lineTo",
            x: "sx6",
            y: "sy3"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "sx6",
            y: "sy4"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "sx5",
            y: "sy5"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "sx4",
            y: "sy6"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "sx3",
            y: "sy6"
          },
          {
            cmd: "lineTo",
            x: "wd4",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy5"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "sx1",
            y: "sy4"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [23 /* SHAPE_GEOMETRY_STAR16 */]: {
    avLst: {
      adj: "val 37500"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      dx1: "*/ wd2 92388 100000",
      dx2: "*/ wd2 70711 100000",
      dx3: "*/ wd2 38268 100000",
      dy1: "*/ hd2 92388 100000",
      dy2: "*/ hd2 70711 100000",
      dy3: "*/ hd2 38268 100000",
      x1: "+- hc 0 dx1",
      x2: "+- hc 0 dx2",
      x3: "+- hc 0 dx3",
      x4: "+- hc dx3 0",
      x5: "+- hc dx2 0",
      x6: "+- hc dx1 0",
      y1: "+- vc 0 dy1",
      y2: "+- vc 0 dy2",
      y3: "+- vc 0 dy3",
      y4: "+- vc dy3 0",
      y5: "+- vc dy2 0",
      y6: "+- vc dy1 0",
      iwd2: "*/ wd2 a 50000",
      ihd2: "*/ hd2 a 50000",
      sdx1: "*/ iwd2 98079 100000",
      sdx2: "*/ iwd2 83147 100000",
      sdx3: "*/ iwd2 55557 100000",
      sdx4: "*/ iwd2 19509 100000",
      sdy1: "*/ ihd2 98079 100000",
      sdy2: "*/ ihd2 83147 100000",
      sdy3: "*/ ihd2 55557 100000",
      sdy4: "*/ ihd2 19509 100000",
      sx1: "+- hc 0 sdx1",
      sx2: "+- hc 0 sdx2",
      sx3: "+- hc 0 sdx3",
      sx4: "+- hc 0 sdx4",
      sx5: "+- hc sdx4 0",
      sx6: "+- hc sdx3 0",
      sx7: "+- hc sdx2 0",
      sx8: "+- hc sdx1 0",
      sy1: "+- vc 0 sdy1",
      sy2: "+- vc 0 sdy2",
      sy3: "+- vc 0 sdy3",
      sy4: "+- vc 0 sdy4",
      sy5: "+- vc sdy4 0",
      sy6: "+- vc sdy3 0",
      sy7: "+- vc sdy2 0",
      sy8: "+- vc sdy1 0",
      idx: "cos iwd2 2700000",
      idy: "sin ihd2 2700000",
      il: "+- hc 0 idx",
      it: "+- vc 0 idy",
      ir: "+- hc idx 0",
      ib: "+- vc idy 0",
      yAdj: "+- vc 0 ihd2"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "50000",
        pos: {
          x: "hc",
          y: "yAdj"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "x5",
          y: "y2"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x6",
          y: "y3"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x6",
          y: "y4"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x5",
          y: "y5"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x4",
          y: "y6"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x3",
          y: "y6"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x2",
          y: "y5"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y4"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y3"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x2",
          y: "y2"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x3",
          y: "y1"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x4",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "sx1",
            y: "sy4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy3"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "sx3",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "sx4",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "sx5",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "sx6",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "sx7",
            y: "sy3"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "sx8",
            y: "sy4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "sx8",
            y: "sy5"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "sx7",
            y: "sy6"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "sx6",
            y: "sy7"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "sx5",
            y: "sy8"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "sx4",
            y: "sy8"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "sx3",
            y: "sy7"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy6"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "sx1",
            y: "sy5"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [24 /* SHAPE_GEOMETRY_STAR24 */]: {
    avLst: {
      adj: "val 37500"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      dx1: "cos wd2 900000",
      dx2: "cos wd2 1800000",
      dx3: "cos wd2 2700000",
      dx4: "val wd4",
      dx5: "cos wd2 4500000",
      dy1: "sin hd2 4500000",
      dy2: "sin hd2 3600000",
      dy3: "sin hd2 2700000",
      dy4: "val hd4",
      dy5: "sin hd2 900000",
      x1: "+- hc 0 dx1",
      x2: "+- hc 0 dx2",
      x3: "+- hc 0 dx3",
      x4: "+- hc 0 dx4",
      x5: "+- hc 0 dx5",
      x6: "+- hc dx5 0",
      x7: "+- hc dx4 0",
      x8: "+- hc dx3 0",
      x9: "+- hc dx2 0",
      x10: "+- hc dx1 0",
      y1: "+- vc 0 dy1",
      y2: "+- vc 0 dy2",
      y3: "+- vc 0 dy3",
      y4: "+- vc 0 dy4",
      y5: "+- vc 0 dy5",
      y6: "+- vc dy5 0",
      y7: "+- vc dy4 0",
      y8: "+- vc dy3 0",
      y9: "+- vc dy2 0",
      y10: "+- vc dy1 0",
      iwd2: "*/ wd2 a 50000",
      ihd2: "*/ hd2 a 50000",
      sdx1: "*/ iwd2 99144 100000",
      sdx2: "*/ iwd2 92388 100000",
      sdx3: "*/ iwd2 79335 100000",
      sdx4: "*/ iwd2 60876 100000",
      sdx5: "*/ iwd2 38268 100000",
      sdx6: "*/ iwd2 13053 100000",
      sdy1: "*/ ihd2 99144 100000",
      sdy2: "*/ ihd2 92388 100000",
      sdy3: "*/ ihd2 79335 100000",
      sdy4: "*/ ihd2 60876 100000",
      sdy5: "*/ ihd2 38268 100000",
      sdy6: "*/ ihd2 13053 100000",
      sx1: "+- hc 0 sdx1",
      sx2: "+- hc 0 sdx2",
      sx3: "+- hc 0 sdx3",
      sx4: "+- hc 0 sdx4",
      sx5: "+- hc 0 sdx5",
      sx6: "+- hc 0 sdx6",
      sx7: "+- hc sdx6 0",
      sx8: "+- hc sdx5 0",
      sx9: "+- hc sdx4 0",
      sx10: "+- hc sdx3 0",
      sx11: "+- hc sdx2 0",
      sx12: "+- hc sdx1 0",
      sy1: "+- vc 0 sdy1",
      sy2: "+- vc 0 sdy2",
      sy3: "+- vc 0 sdy3",
      sy4: "+- vc 0 sdy4",
      sy5: "+- vc 0 sdy5",
      sy6: "+- vc 0 sdy6",
      sy7: "+- vc sdy6 0",
      sy8: "+- vc sdy5 0",
      sy9: "+- vc sdy4 0",
      sy10: "+- vc sdy3 0",
      sy11: "+- vc sdy2 0",
      sy12: "+- vc sdy1 0",
      idx: "cos iwd2 2700000",
      idy: "sin ihd2 2700000",
      il: "+- hc 0 idx",
      it: "+- vc 0 idy",
      ir: "+- hc idx 0",
      ib: "+- vc idy 0",
      yAdj: "+- vc 0 ihd2"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "ssd2",
        pos: {
          x: "hc",
          y: "yAdj"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "sx1",
            y: "sy6"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy5"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "sx3",
            y: "sy4"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "sx4",
            y: "sy3"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "sx5",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "sx6",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "sx7",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "sx8",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "sx9",
            y: "sy3"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "sx10",
            y: "sy4"
          },
          {
            cmd: "lineTo",
            x: "x9",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "sx11",
            y: "sy5"
          },
          {
            cmd: "lineTo",
            x: "x10",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "sx12",
            y: "sy6"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "sx12",
            y: "sy7"
          },
          {
            cmd: "lineTo",
            x: "x10",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "sx11",
            y: "sy8"
          },
          {
            cmd: "lineTo",
            x: "x9",
            y: "y7"
          },
          {
            cmd: "lineTo",
            x: "sx10",
            y: "sy9"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y8"
          },
          {
            cmd: "lineTo",
            x: "sx9",
            y: "sy10"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "y9"
          },
          {
            cmd: "lineTo",
            x: "sx8",
            y: "sy11"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y10"
          },
          {
            cmd: "lineTo",
            x: "sx7",
            y: "sy12"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "sx6",
            y: "sy12"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y10"
          },
          {
            cmd: "lineTo",
            x: "sx5",
            y: "sy11"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y9"
          },
          {
            cmd: "lineTo",
            x: "sx4",
            y: "sy10"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y8"
          },
          {
            cmd: "lineTo",
            x: "sx3",
            y: "sy9"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y7"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy8"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "sx1",
            y: "sy7"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [25 /* SHAPE_GEOMETRY_STAR32 */]: {
    avLst: {
      adj: "val 37500"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      dx1: "*/ wd2 98079 100000",
      dx2: "*/ wd2 92388 100000",
      dx3: "*/ wd2 83147 100000",
      dx4: "cos wd2 2700000",
      dx5: "*/ wd2 55557 100000",
      dx6: "*/ wd2 38268 100000",
      dx7: "*/ wd2 19509 100000",
      dy1: "*/ hd2 98079 100000",
      dy2: "*/ hd2 92388 100000",
      dy3: "*/ hd2 83147 100000",
      dy4: "sin hd2 2700000",
      dy5: "*/ hd2 55557 100000",
      dy6: "*/ hd2 38268 100000",
      dy7: "*/ hd2 19509 100000",
      x1: "+- hc 0 dx1",
      x2: "+- hc 0 dx2",
      x3: "+- hc 0 dx3",
      x4: "+- hc 0 dx4",
      x5: "+- hc 0 dx5",
      x6: "+- hc 0 dx6",
      x7: "+- hc 0 dx7",
      x8: "+- hc dx7 0",
      x9: "+- hc dx6 0",
      x10: "+- hc dx5 0",
      x11: "+- hc dx4 0",
      x12: "+- hc dx3 0",
      x13: "+- hc dx2 0",
      x14: "+- hc dx1 0",
      y1: "+- vc 0 dy1",
      y2: "+- vc 0 dy2",
      y3: "+- vc 0 dy3",
      y4: "+- vc 0 dy4",
      y5: "+- vc 0 dy5",
      y6: "+- vc 0 dy6",
      y7: "+- vc 0 dy7",
      y8: "+- vc dy7 0",
      y9: "+- vc dy6 0",
      y10: "+- vc dy5 0",
      y11: "+- vc dy4 0",
      y12: "+- vc dy3 0",
      y13: "+- vc dy2 0",
      y14: "+- vc dy1 0",
      iwd2: "*/ wd2 a 50000",
      ihd2: "*/ hd2 a 50000",
      sdx1: "*/ iwd2 99518 100000",
      sdx2: "*/ iwd2 95694 100000",
      sdx3: "*/ iwd2 88192 100000",
      sdx4: "*/ iwd2 77301 100000",
      sdx5: "*/ iwd2 63439 100000",
      sdx6: "*/ iwd2 47140 100000",
      sdx7: "*/ iwd2 29028 100000",
      sdx8: "*/ iwd2 9802 100000",
      sdy1: "*/ ihd2 99518 100000",
      sdy2: "*/ ihd2 95694 100000",
      sdy3: "*/ ihd2 88192 100000",
      sdy4: "*/ ihd2 77301 100000",
      sdy5: "*/ ihd2 63439 100000",
      sdy6: "*/ ihd2 47140 100000",
      sdy7: "*/ ihd2 29028 100000",
      sdy8: "*/ ihd2 9802 100000",
      sx1: "+- hc 0 sdx1",
      sx2: "+- hc 0 sdx2",
      sx3: "+- hc 0 sdx3",
      sx4: "+- hc 0 sdx4",
      sx5: "+- hc 0 sdx5",
      sx6: "+- hc 0 sdx6",
      sx7: "+- hc 0 sdx7",
      sx8: "+- hc 0 sdx8",
      sx9: "+- hc sdx8 0",
      sx10: "+- hc sdx7 0",
      sx11: "+- hc sdx6 0",
      sx12: "+- hc sdx5 0",
      sx13: "+- hc sdx4 0",
      sx14: "+- hc sdx3 0",
      sx15: "+- hc sdx2 0",
      sx16: "+- hc sdx1 0",
      sy1: "+- vc 0 sdy1",
      sy2: "+- vc 0 sdy2",
      sy3: "+- vc 0 sdy3",
      sy4: "+- vc 0 sdy4",
      sy5: "+- vc 0 sdy5",
      sy6: "+- vc 0 sdy6",
      sy7: "+- vc 0 sdy7",
      sy8: "+- vc 0 sdy8",
      sy9: "+- vc sdy8 0",
      sy10: "+- vc sdy7 0",
      sy11: "+- vc sdy6 0",
      sy12: "+- vc sdy5 0",
      sy13: "+- vc sdy4 0",
      sy14: "+- vc sdy3 0",
      sy15: "+- vc sdy2 0",
      sy16: "+- vc sdy1 0",
      idx: "cos iwd2 2700000",
      idy: "sin ihd2 2700000",
      il: "+- hc 0 idx",
      it: "+- vc 0 idy",
      ir: "+- hc idx 0",
      ib: "+- vc idy 0",
      yAdj: "+- vc 0 ihd2"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "ssd2",
        pos: {
          x: "hc",
          y: "yAdj"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "sx1",
            y: "sy8"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y7"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy7"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "sx3",
            y: "sy6"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "sx4",
            y: "sy5"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "sx5",
            y: "sy4"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "sx6",
            y: "sy3"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "sx7",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "sx8",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "sx9",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "sx10",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "x9",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "sx11",
            y: "sy3"
          },
          {
            cmd: "lineTo",
            x: "x10",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "sx12",
            y: "sy4"
          },
          {
            cmd: "lineTo",
            x: "x11",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "sx13",
            y: "sy5"
          },
          {
            cmd: "lineTo",
            x: "x12",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "sx14",
            y: "sy6"
          },
          {
            cmd: "lineTo",
            x: "x13",
            y: "y6"
          },
          {
            cmd: "lineTo",
            x: "sx15",
            y: "sy7"
          },
          {
            cmd: "lineTo",
            x: "x14",
            y: "y7"
          },
          {
            cmd: "lineTo",
            x: "sx16",
            y: "sy8"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "sx16",
            y: "sy9"
          },
          {
            cmd: "lineTo",
            x: "x14",
            y: "y8"
          },
          {
            cmd: "lineTo",
            x: "sx15",
            y: "sy10"
          },
          {
            cmd: "lineTo",
            x: "x13",
            y: "y9"
          },
          {
            cmd: "lineTo",
            x: "sx14",
            y: "sy11"
          },
          {
            cmd: "lineTo",
            x: "x12",
            y: "y10"
          },
          {
            cmd: "lineTo",
            x: "sx13",
            y: "sy12"
          },
          {
            cmd: "lineTo",
            x: "x11",
            y: "y11"
          },
          {
            cmd: "lineTo",
            x: "sx12",
            y: "sy13"
          },
          {
            cmd: "lineTo",
            x: "x10",
            y: "y12"
          },
          {
            cmd: "lineTo",
            x: "sx11",
            y: "sy14"
          },
          {
            cmd: "lineTo",
            x: "x9",
            y: "y13"
          },
          {
            cmd: "lineTo",
            x: "sx10",
            y: "sy15"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y14"
          },
          {
            cmd: "lineTo",
            x: "sx9",
            y: "sy16"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "sx8",
            y: "sy16"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "y14"
          },
          {
            cmd: "lineTo",
            x: "sx7",
            y: "sy15"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y13"
          },
          {
            cmd: "lineTo",
            x: "sx6",
            y: "sy14"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y12"
          },
          {
            cmd: "lineTo",
            x: "sx5",
            y: "sy13"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y11"
          },
          {
            cmd: "lineTo",
            x: "sx4",
            y: "sy12"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y10"
          },
          {
            cmd: "lineTo",
            x: "sx3",
            y: "sy11"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y9"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy10"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y8"
          },
          {
            cmd: "lineTo",
            x: "sx1",
            y: "sy9"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [16 /* SHAPE_GEOMETRY_STAR4 */]: {
    avLst: {
      adj: "val 12500"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      iwd2: "*/ wd2 a 50000",
      ihd2: "*/ hd2 a 50000",
      sdx: "cos iwd2 2700000",
      sdy: "sin ihd2 2700000",
      sx1: "+- hc 0 sdx",
      sx2: "+- hc sdx 0",
      sy1: "+- vc 0 sdy",
      sy2: "+- vc sdy 0",
      yAdj: "+- vc 0 ihd2"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "50000",
        pos: {
          x: "hc",
          y: "yAdj"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "sx1",
      t: "sy1",
      r: "sx2",
      b: "sy2"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "sx1",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "sx1",
            y: "sy2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [17 /* SHAPE_GEOMETRY_STAR5 */]: {
    avLst: {
      adj: "val 19098",
      hf: "val 105146",
      vf: "val 110557"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      swd2: "*/ wd2 hf 100000",
      shd2: "*/ hd2 vf 100000",
      svc: "*/ vc  vf 100000",
      dx1: "cos swd2 1080000",
      dx2: "cos swd2 18360000",
      dy1: "sin shd2 1080000",
      dy2: "sin shd2 18360000",
      x1: "+- hc 0 dx1",
      x2: "+- hc 0 dx2",
      x3: "+- hc dx2 0",
      x4: "+- hc dx1 0",
      y1: "+- svc 0 dy1",
      y2: "+- svc 0 dy2",
      iwd2: "*/ swd2 a 50000",
      ihd2: "*/ shd2 a 50000",
      sdx1: "cos iwd2 20520000",
      sdx2: "cos iwd2 3240000",
      sdy1: "sin ihd2 3240000",
      sdy2: "sin ihd2 20520000",
      sx1: "+- hc 0 sdx1",
      sx2: "+- hc 0 sdx2",
      sx3: "+- hc sdx2 0",
      sx4: "+- hc sdx1 0",
      sy1: "+- svc 0 sdy1",
      sy2: "+- svc 0 sdy2",
      sy3: "+- svc ihd2 0",
      yAdj: "+- svc 0 ihd2"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "50000",
        pos: {
          x: "hc",
          y: "yAdj"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x2",
          y: "y2"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x3",
          y: "y2"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x4",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "sx1",
      t: "sy1",
      r: "sx4",
      b: "sy3"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "sx3",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "sx4",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "sy3"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "sx1",
            y: "sy2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [18 /* SHAPE_GEOMETRY_STAR6 */]: {
    avLst: {
      adj: "val 28868",
      hf: "val 115470"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      swd2: "*/ wd2 hf 100000",
      dx1: "cos swd2 1800000",
      x1: "+- hc 0 dx1",
      x2: "+- hc dx1 0",
      y2: "+- vc hd4 0",
      iwd2: "*/ swd2 a 50000",
      ihd2: "*/ hd2 a 50000",
      sdx2: "*/ iwd2 1 2",
      sx1: "+- hc 0 iwd2",
      sx2: "+- hc 0 sdx2",
      sx3: "+- hc sdx2 0",
      sx4: "+- hc iwd2 0",
      sdy1: "sin ihd2 3600000",
      sy1: "+- vc 0 sdy1",
      sy2: "+- vc sdy1 0",
      yAdj: "+- vc 0 ihd2"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "50000",
        pos: {
          x: "hc",
          y: "yAdj"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "x2",
          y: "hd4"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x2",
          y: "y2"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y2"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "hd4"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "sx1",
      t: "sy1",
      r: "sx4",
      b: "sy2"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "hd4"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "sx3",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "hd4"
          },
          {
            cmd: "lineTo",
            x: "sx4",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "sx3",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "sx1",
            y: "vc"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [19 /* SHAPE_GEOMETRY_STAR7 */]: {
    avLst: {
      adj: "val 34601",
      hf: "val 102572",
      vf: "val 105210"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      swd2: "*/ wd2 hf 100000",
      shd2: "*/ hd2 vf 100000",
      svc: "*/ vc  vf 100000",
      dx1: "*/ swd2 97493 100000",
      dx2: "*/ swd2 78183 100000",
      dx3: "*/ swd2 43388 100000",
      dy1: "*/ shd2 62349 100000",
      dy2: "*/ shd2 22252 100000",
      dy3: "*/ shd2 90097 100000",
      x1: "+- hc 0 dx1",
      x2: "+- hc 0 dx2",
      x3: "+- hc 0 dx3",
      x4: "+- hc dx3 0",
      x5: "+- hc dx2 0",
      x6: "+- hc dx1 0",
      y1: "+- svc 0 dy1",
      y2: "+- svc dy2 0",
      y3: "+- svc dy3 0",
      iwd2: "*/ swd2 a 50000",
      ihd2: "*/ shd2 a 50000",
      sdx1: "*/ iwd2 97493 100000",
      sdx2: "*/ iwd2 78183 100000",
      sdx3: "*/ iwd2 43388 100000",
      sx1: "+- hc 0 sdx1",
      sx2: "+- hc 0 sdx2",
      sx3: "+- hc 0 sdx3",
      sx4: "+- hc sdx3 0",
      sx5: "+- hc sdx2 0",
      sx6: "+- hc sdx1 0",
      sdy1: "*/ ihd2 90097 100000",
      sdy2: "*/ ihd2 22252 100000",
      sdy3: "*/ ihd2 62349 100000",
      sy1: "+- svc 0 sdy1",
      sy2: "+- svc 0 sdy2",
      sy3: "+- svc sdy3 0",
      sy4: "+- svc ihd2 0",
      yAdj: "+- svc 0 ihd2"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "50000",
        pos: {
          x: "hc",
          y: "yAdj"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "x5",
          y: "y1"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x6",
          y: "y2"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x4",
          y: "y3"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x3",
          y: "y3"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "y2"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x2",
          y: "y1"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      }
    ],
    rect: {
      l: "sx2",
      t: "sy1",
      r: "sx5",
      b: "sy3"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "sx1",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "sx3",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "sx4",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "sx6",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "sx5",
            y: "sy3"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "sy4"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy3"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [20 /* SHAPE_GEOMETRY_STAR8 */]: {
    avLst: {
      adj: "val 37500"
    },
    gdLst: {
      a: "pin 0 adj 50000",
      dx1: "cos wd2 2700000",
      x1: "+- hc 0 dx1",
      x2: "+- hc dx1 0",
      dy1: "sin hd2 2700000",
      y1: "+- vc 0 dy1",
      y2: "+- vc dy1 0",
      iwd2: "*/ wd2 a 50000",
      ihd2: "*/ hd2 a 50000",
      sdx1: "*/ iwd2 92388 100000",
      sdx2: "*/ iwd2 38268 100000",
      sdy1: "*/ ihd2 92388 100000",
      sdy2: "*/ ihd2 38268 100000",
      sx1: "+- hc 0 sdx1",
      sx2: "+- hc 0 sdx2",
      sx3: "+- hc sdx2 0",
      sx4: "+- hc sdx1 0",
      sy1: "+- vc 0 sdy1",
      sy2: "+- vc 0 sdy2",
      sy3: "+- vc sdy2 0",
      sy4: "+- vc sdy1 0",
      yAdj: "+- vc 0 ihd2"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "50000",
        pos: {
          x: "hc",
          y: "yAdj"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x2",
          y: "y2"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x1",
          y: "y2"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x1",
          y: "y1"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x2",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "sx1",
      t: "sy1",
      r: "sx4",
      b: "sy4"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "sx1",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "sx3",
            y: "sy1"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "sx4",
            y: "sy2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "sx4",
            y: "sy3"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "sx3",
            y: "sy4"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "sx2",
            y: "sy4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "sx1",
            y: "sy3"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [96 /* SHAPE_GEOMETRY_STRAIGHT_CONNECTOR1 */]: {
    avLst: {},
    gdLst: {},
    ahLst: [],
    cxnLst: [],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          }
        ]
      }
    ]
  },
  [48 /* SHAPE_GEOMETRY_STRIPED_RIGHT_ARROW */]: {
    avLst: {
      adj1: "val 50000",
      adj2: "val 50000"
    },
    gdLst: {
      maxAdj2: "*/ 84375 w ss",
      a1: "pin 0 adj1 100000",
      a2: "pin 0 adj2 maxAdj2",
      x4: "*/ ss 5 32",
      dx5: "*/ ss a2 100000",
      x5: "+- r 0 dx5",
      dy1: "*/ h a1 200000",
      y1: "+- vc 0 dy1",
      y2: "+- vc dy1 0",
      dx6: "*/ dy1 dx5 hd2",
      x6: "+- r 0 dx6"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "100000",
        pos: {
          x: "l",
          y: "y1"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "maxAdj2",
        pos: {
          x: "x5",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x5",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x5",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "x4",
      t: "y1",
      r: "x6",
      b: "y2"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "ssd32",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "ssd32",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y2"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "ssd16",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "ssd8",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "ssd8",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "ssd16",
            y: "y2"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x5",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [77 /* SHAPE_GEOMETRY_SUN */]: {
    avLst: {
      adj: "val 25000"
    },
    gdLst: {
      a: "pin 12500 adj 46875",
      g0: "+- 50000 0 a",
      g1: "*/ g0 30274 32768",
      g2: "*/ g0 12540 32768",
      g3: "+- g1 50000 0",
      g4: "+- g2 50000 0",
      g5: "+- 50000 0 g1",
      g6: "+- 50000 0 g2",
      g7: "*/ g0 23170 32768",
      g8: "+- 50000 g7 0",
      g9: "+- 50000 0 g7",
      g10: "*/ g5 3 4",
      g11: "*/ g6 3 4",
      g12: "+- g10 3662 0",
      g13: "+- g11 3662 0",
      g14: "+- g11 12500 0",
      g15: "+- 100000 0 g10",
      g16: "+- 100000 0 g12",
      g17: "+- 100000 0 g13",
      g18: "+- 100000 0 g14",
      ox1: "*/ w 18436 21600",
      oy1: "*/ h 3163 21600",
      ox2: "*/ w 3163 21600",
      oy2: "*/ h 18436 21600",
      x8: "*/ w g8 100000",
      x9: "*/ w g9 100000",
      x10: "*/ w g10 100000",
      x12: "*/ w g12 100000",
      x13: "*/ w g13 100000",
      x14: "*/ w g14 100000",
      x15: "*/ w g15 100000",
      x16: "*/ w g16 100000",
      x17: "*/ w g17 100000",
      x18: "*/ w g18 100000",
      x19: "*/ w a 100000",
      wR: "*/ w g0 100000",
      hR: "*/ h g0 100000",
      y8: "*/ h g8 100000",
      y9: "*/ h g9 100000",
      y10: "*/ h g10 100000",
      y12: "*/ h g12 100000",
      y13: "*/ h g13 100000",
      y14: "*/ h g14 100000",
      y15: "*/ h g15 100000",
      y16: "*/ h g16 100000",
      y17: "*/ h g17 100000",
      y18: "*/ h g18 100000"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "12500",
        maxX: "46875",
        pos: {
          x: "x19",
          y: "vc"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "x9",
      t: "y9",
      r: "x8",
      b: "y8"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "r",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x15",
            y: "y18"
          },
          {
            cmd: "lineTo",
            x: "x15",
            y: "y14"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "ox1",
            y: "oy1"
          },
          {
            cmd: "lineTo",
            x: "x16",
            y: "y13"
          },
          {
            cmd: "lineTo",
            x: "x17",
            y: "y12"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x18",
            y: "y10"
          },
          {
            cmd: "lineTo",
            x: "x14",
            y: "y10"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "ox2",
            y: "oy1"
          },
          {
            cmd: "lineTo",
            x: "x13",
            y: "y12"
          },
          {
            cmd: "lineTo",
            x: "x12",
            y: "y13"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "lineTo",
            x: "x10",
            y: "y14"
          },
          {
            cmd: "lineTo",
            x: "x10",
            y: "y18"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "ox2",
            y: "oy2"
          },
          {
            cmd: "lineTo",
            x: "x12",
            y: "y17"
          },
          {
            cmd: "lineTo",
            x: "x13",
            y: "y16"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x14",
            y: "y15"
          },
          {
            cmd: "lineTo",
            x: "x18",
            y: "y15"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "ox1",
            y: "oy2"
          },
          {
            cmd: "lineTo",
            x: "x17",
            y: "y16"
          },
          {
            cmd: "lineTo",
            x: "x16",
            y: "y17"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x19",
            y: "vc"
          },
          {
            cmd: "arcTo",
            wR: "wR",
            hR: "hR",
            stAng: "cd2",
            swAng: "21600000"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [72 /* SHAPE_GEOMETRY_SWOOSH_ARROW */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 16667"
    },
    gdLst: {
      a1: "pin 1 adj1 75000",
      maxAdj2: "*/ 70000 w ss",
      a2: "pin 0 adj2 maxAdj2",
      ad1: "*/ h a1 100000",
      ad2: "*/ ss a2 100000",
      xB: "+- r 0 ad2",
      yB: "+- t ssd8 0",
      alfa: "*/ cd4 1 14",
      dx0: "tan ssd8 alfa",
      xC: "+- xB 0 dx0",
      dx1: "tan ad1 alfa",
      yF: "+- yB ad1 0",
      xF: "+- xB dx1 0",
      xE: "+- xF dx0 0",
      yE: "+- yF ssd8 0",
      dy2: "+- yE 0 t",
      dy22: "*/ dy2 1 2",
      dy3: "*/ h 1 20",
      yD: "+- t dy22 dy3",
      dy4: "*/ hd6 1 1",
      yP1: "+- hd6 dy4 0",
      xP1: "val wd6",
      dy5: "*/ hd6 1 2",
      yP2: "+- yF dy5 0",
      xP2: "val wd4"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "1",
        maxY: "75000",
        pos: {
          x: "xF",
          y: "yF"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "maxAdj2",
        pos: {
          x: "xB",
          y: "yB"
        }
      }
    ],
    cxnLst: [
      {
        ang: "cd4",
        pos: {
          x: "l",
          y: "b"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "xC",
          y: "t"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "yD"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "xE",
          y: "yE"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "quadBezTo",
            x: "xB",
            y: "yB",
            x1: "xP1",
            y1: "yP1"
          },
          {
            cmd: "lineTo",
            x: "xC",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "yD"
          },
          {
            cmd: "lineTo",
            x: "xE",
            y: "yE"
          },
          {
            cmd: "lineTo",
            x: "xF",
            y: "yF"
          },
          {
            cmd: "quadBezTo",
            x: "l",
            y: "b",
            x1: "xP2",
            y1: "yP2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [36 /* SHAPE_GEOMETRY_TEARDROP */]: {
    avLst: {
      adj: "val 100000"
    },
    gdLst: {
      a: "pin 0 adj 200000",
      r2: "sqrt 2",
      tw: "*/ wd2 r2 1",
      th: "*/ hd2 r2 1",
      sw: "*/ tw a 100000",
      sh: "*/ th a 100000",
      dx1: "cos sw 2700000",
      dy1: "sin sh 2700000",
      x1: "+- hc dx1 0",
      y1: "+- vc 0 dy1",
      x2: "+/ hc x1 2",
      y2: "+/ vc y1 2",
      idx: "cos wd2 2700000",
      idy: "sin hd2 2700000",
      il: "+- hc 0 idx",
      ir: "+- hc idx 0",
      it: "+- vc 0 idy",
      ib: "+- vc idy 0"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "0",
        maxX: "200000",
        pos: {
          x: "x1",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "ir",
          y: "ib"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "il",
          y: "ib"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "il",
          y: "it"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "x1",
          y: "y1"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "vc"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "quadBezTo",
            x: "x1",
            y: "y1",
            x1: "x2",
            y1: "t"
          },
          {
            cmd: "quadBezTo",
            x: "r",
            y: "vc",
            x1: "r",
            y1: "y2"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [8 /* SHAPE_GEOMETRY_TRAPEZOID */]: {
    avLst: {
      adj: "val 25000"
    },
    gdLst: {
      maxAdj: "*/ 50000 w ss",
      a: "pin 0 adj maxAdj",
      x1: "*/ ss a 200000",
      x2: "*/ ss a 100000",
      x3: "+- r 0 x2",
      x4: "+- r 0 x1",
      il: "*/ wd3 a maxAdj",
      it: "*/ hd3 a maxAdj",
      ir: "+- r 0 il"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "0",
        maxX: "maxAdj",
        pos: {
          x: "x2",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x4",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [3 /* SHAPE_GEOMETRY_TRIANGLE */]: {
    avLst: {
      adj: "val 50000"
    },
    gdLst: {
      a: "pin 0 adj 100000",
      x1: "*/ w a 200000",
      x2: "*/ w a 100000",
      x3: "+- x1 wd2 0"
    },
    ahLst: [
      {
        gdRefX: "adj",
        minX: "0",
        maxX: "100000",
        pos: {
          x: "x2",
          y: "t"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "x2",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "l",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x2",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "r",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x3",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "vc",
      r: "x3",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [58 /* SHAPE_GEOMETRY_UP_ARROW_CALLOUT */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 25000",
      adj3: "val 25000",
      adj4: "val 64977"
    },
    gdLst: {
      maxAdj2: "*/ 50000 w ss",
      a2: "pin 0 adj2 maxAdj2",
      maxAdj1: "*/ a2 2 1",
      a1: "pin 0 adj1 maxAdj1",
      maxAdj3: "*/ 100000 h ss",
      a3: "pin 0 adj3 maxAdj3",
      q2: "*/ a3 ss h",
      maxAdj4: "+- 100000 0 q2",
      a4: "pin 0 adj4 maxAdj4",
      dx1: "*/ ss a2 100000",
      dx2: "*/ ss a1 200000",
      x1: "+- hc 0 dx1",
      x2: "+- hc 0 dx2",
      x3: "+- hc dx2 0",
      x4: "+- hc dx1 0",
      y1: "*/ ss a3 100000",
      dy2: "*/ h a4 100000",
      y2: "+- b 0 dy2",
      y3: "+/ y2 b 2"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "maxAdj1",
        pos: {
          x: "x2",
          y: "y1"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "maxAdj2",
        pos: {
          x: "x1",
          y: "t"
        }
      },
      {
        gdRefY: "adj3",
        minY: "0",
        maxY: "maxAdj3",
        pos: {
          x: "r",
          y: "y1"
        }
      },
      {
        gdRefY: "adj4",
        minY: "0",
        maxY: "maxAdj4",
        pos: {
          x: "l",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y2"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y2"
        }
      }
    ],
    rect: {
      l: "l",
      t: "y2",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [52 /* SHAPE_GEOMETRY_UP_DOWN_ARROW */]: {
    avLst: {
      adj1: "val 50000",
      adj2: "val 50000"
    },
    gdLst: {
      maxAdj2: "*/ 50000 h ss",
      a1: "pin 0 adj1 100000",
      a2: "pin 0 adj2 maxAdj2",
      y2: "*/ ss a2 100000",
      y3: "+- b 0 y2",
      dx1: "*/ w a1 200000",
      x1: "+- hc 0 dx1",
      x2: "+- hc dx1 0",
      dy1: "*/ x1 y2 wd2",
      y1: "+- y2 0 dy1",
      y4: "+- y3 dy1 0"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "100000",
        pos: {
          x: "x1",
          y: "y3"
        }
      },
      {
        gdRefY: "adj2",
        minY: "0",
        maxY: "maxAdj2",
        pos: {
          x: "l",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y2"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "vc"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "y3"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y3"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x2",
          y: "vc"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y2"
        }
      }
    ],
    rect: {
      l: "x1",
      t: "y1",
      r: "x2",
      b: "y4"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y2"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [61 /* SHAPE_GEOMETRY_UP_DOWN_ARROW_CALLOUT */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 25000",
      adj3: "val 25000",
      adj4: "val 48123"
    },
    gdLst: {
      maxAdj2: "*/ 50000 w ss",
      a2: "pin 0 adj2 maxAdj2",
      maxAdj1: "*/ a2 2 1",
      a1: "pin 0 adj1 maxAdj1",
      maxAdj3: "*/ 50000 h ss",
      a3: "pin 0 adj3 maxAdj3",
      q2: "*/ a3 ss hd2",
      maxAdj4: "+- 100000 0 q2",
      a4: "pin 0 adj4 maxAdj4",
      dx1: "*/ ss a2 100000",
      dx2: "*/ ss a1 200000",
      x1: "+- hc 0 dx1",
      x2: "+- hc 0 dx2",
      x3: "+- hc dx2 0",
      x4: "+- hc dx1 0",
      y1: "*/ ss a3 100000",
      y4: "+- b 0 y1",
      dy2: "*/ h a4 200000",
      y2: "+- vc 0 dy2",
      y3: "+- vc dy2 0"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "maxAdj1",
        pos: {
          x: "x2",
          y: "y1"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "maxAdj2",
        pos: {
          x: "x1",
          y: "t"
        }
      },
      {
        gdRefY: "adj3",
        minY: "0",
        maxY: "maxAdj3",
        pos: {
          x: "r",
          y: "y1"
        }
      },
      {
        gdRefY: "adj4",
        minY: "0",
        maxY: "maxAdj4",
        pos: {
          x: "l",
          y: "y2"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "l",
      t: "y2",
      r: "r",
      b: "y3"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "hc",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y3"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [64 /* SHAPE_GEOMETRY_UTURN_ARROW */]: {
    avLst: {
      adj1: "val 25000",
      adj2: "val 25000",
      adj3: "val 25000",
      adj4: "val 43750",
      adj5: "val 75000"
    },
    gdLst: {
      a2: "pin 0 adj2 25000",
      maxAdj1: "*/ a2 2 1",
      a1: "pin 0 adj1 maxAdj1",
      q2: "*/ a1 ss h",
      q3: "+- 100000 0 q2",
      maxAdj3: "*/ q3 h ss",
      a3: "pin 0 adj3 maxAdj3",
      q1: "+- a3 a1 0",
      minAdj5: "*/ q1 ss h",
      a5: "pin minAdj5 adj5 100000",
      th: "*/ ss a1 100000",
      aw2: "*/ ss a2 100000",
      th2: "*/ th 1 2",
      dh2: "+- aw2 0 th2",
      y5: "*/ h a5 100000",
      ah: "*/ ss a3 100000",
      y4: "+- y5 0 ah",
      x9: "+- r 0 dh2",
      bw: "*/ x9 1 2",
      bs: "min bw y4",
      maxAdj4: "*/ bs 100000 ss",
      a4: "pin 0 adj4 maxAdj4",
      bd: "*/ ss a4 100000",
      bd3: "+- bd 0 th",
      bd2: "max bd3 0",
      x3: "+- th bd2 0",
      x8: "+- r 0 aw2",
      x6: "+- x8 0 aw2",
      x7: "+- x6 dh2 0",
      x4: "+- x9 0 bd",
      x5: "+- x7 0 bd2",
      cx: "+/ th x7 2"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        minX: "0",
        maxX: "maxAdj1",
        pos: {
          x: "th",
          y: "b"
        }
      },
      {
        gdRefX: "adj2",
        minX: "0",
        maxX: "25000",
        pos: {
          x: "x6",
          y: "b"
        }
      },
      {
        gdRefY: "adj3",
        minY: "0",
        maxY: "maxAdj3",
        pos: {
          x: "x6",
          y: "y4"
        }
      },
      {
        gdRefX: "adj4",
        minX: "0",
        maxX: "maxAdj4",
        pos: {
          x: "bd",
          y: "t"
        }
      },
      {
        gdRefY: "adj5",
        minY: "minAdj5",
        maxY: "100000",
        pos: {
          x: "r",
          y: "y5"
        }
      }
    ],
    cxnLst: [
      {
        ang: "cd4",
        pos: {
          x: "x6",
          y: "y4"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "x8",
          y: "y5"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "y4"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "cx",
          y: "t"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "th2",
          y: "b"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "bd"
          },
          {
            cmd: "arcTo",
            wR: "bd",
            hR: "bd",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "bd",
            hR: "bd",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x9",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x8",
            y: "y5"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "y4"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "x3"
          },
          {
            cmd: "arcTo",
            wR: "bd2",
            hR: "bd2",
            stAng: "0",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "th"
          },
          {
            cmd: "arcTo",
            wR: "bd2",
            hR: "bd2",
            stAng: "3cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "th",
            y: "b"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [127 /* SHAPE_GEOMETRY_VERTICAL_SCROLL */]: {
    avLst: {
      adj: "val 12500"
    },
    gdLst: {
      a: "pin 0 adj 25000",
      ch: "*/ ss a 100000",
      ch2: "*/ ch 1 2",
      ch4: "*/ ch 1 4",
      x3: "+- ch ch2 0",
      x4: "+- ch ch 0",
      x6: "+- r 0 ch",
      x7: "+- r 0 ch2",
      x5: "+- x6 0 ch2",
      y3: "+- b 0 ch",
      y4: "+- b 0 ch2"
    },
    ahLst: [
      {
        gdRefY: "adj",
        minY: "0",
        maxY: "25000",
        pos: {
          x: "l",
          y: "ch"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "0",
        pos: {
          x: "ch",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x6",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "ch",
      t: "ch",
      r: "x6",
      b: "y4"
    },
    paths: [
      {
        fill: "solid",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "ch2",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "ch2",
            y: "y4"
          },
          {
            cmd: "arcTo",
            wR: "ch4",
            hR: "ch4",
            stAng: "cd4",
            swAng: "-10800000"
          },
          {
            cmd: "lineTo",
            x: "ch",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "ch",
            y: "ch2"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "3cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "ch"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y4"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x4",
            y: "ch2"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "ch4",
            hR: "ch4",
            stAng: "cd4",
            swAng: "cd2"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "darkenLess",
        stroke: false,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x4",
            y: "ch2"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "arcTo",
            wR: "ch4",
            hR: "ch4",
            stAng: "cd4",
            swAng: "cd2"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "ch",
            y: "y4"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "0",
            swAng: "3cd4"
          },
          {
            cmd: "arcTo",
            wR: "ch4",
            hR: "ch4",
            stAng: "3cd4",
            swAng: "cd2"
          },
          {
            cmd: "close"
          }
        ]
      },
      {
        fill: "none",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "ch",
            y: "y3"
          },
          {
            cmd: "lineTo",
            x: "ch",
            y: "ch2"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x7",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "3cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "ch"
          },
          {
            cmd: "lineTo",
            x: "x6",
            y: "y4"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "ch2",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "cd4",
            swAng: "cd2"
          },
          {
            cmd: "close"
          },
          {
            cmd: "moveTo",
            x: "x3",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "3cd4",
            swAng: "cd2"
          },
          {
            cmd: "arcTo",
            wR: "ch4",
            hR: "ch4",
            stAng: "cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "x4",
            y: "ch2"
          },
          {
            cmd: "moveTo",
            x: "x6",
            y: "ch"
          },
          {
            cmd: "lineTo",
            x: "x3",
            y: "ch"
          },
          {
            cmd: "moveTo",
            x: "ch2",
            y: "y3"
          },
          {
            cmd: "arcTo",
            wR: "ch4",
            hR: "ch4",
            stAng: "3cd4",
            swAng: "cd2"
          },
          {
            cmd: "lineTo",
            x: "ch",
            y: "y4"
          },
          {
            cmd: "moveTo",
            x: "ch2",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "ch2",
            hR: "ch2",
            stAng: "cd4",
            swAng: "-5400000"
          },
          {
            cmd: "lineTo",
            x: "ch",
            y: "y3"
          }
        ]
      }
    ]
  },
  [129 /* SHAPE_GEOMETRY_WAVE */]: {
    avLst: {
      adj1: "val 12500",
      adj2: "val 0"
    },
    gdLst: {
      a1: "pin 0 adj1 20000",
      a2: "pin -10000 adj2 10000",
      y1: "*/ h a1 100000",
      dy2: "*/ y1 10 3",
      y2: "+- y1 0 dy2",
      y3: "+- y1 dy2 0",
      y4: "+- b 0 y1",
      y5: "+- y4 0 dy2",
      y6: "+- y4 dy2 0",
      dx1: "*/ w a2 100000",
      of2: "*/ w a2 50000",
      x1: "abs dx1",
      dx2: "?: of2 0 of2",
      x2: "+- l 0 dx2",
      dx5: "?: of2 of2 0",
      x5: "+- r 0 dx5",
      dx3: "+/ dx2 x5 3",
      x3: "+- x2 dx3 0",
      x4: "+/ x3 x5 2",
      x6: "+- l dx5 0",
      x10: "+- r dx2 0",
      x7: "+- x6 dx3 0",
      x8: "+/ x7 x10 2",
      x9: "+- r 0 x1",
      xAdj: "+- hc dx1 0",
      xAdj2: "+- hc 0 dx1",
      il: "max x2 x6",
      ir: "min x5 x10",
      it: "*/ h a1 50000",
      ib: "+- b 0 it"
    },
    ahLst: [
      {
        gdRefY: "adj1",
        minY: "0",
        maxY: "20000",
        pos: {
          x: "l",
          y: "y1"
        }
      },
      {
        gdRefX: "adj2",
        minX: "-10000",
        maxX: "10000",
        pos: {
          x: "xAdj",
          y: "b"
        }
      }
    ],
    cxnLst: [
      {
        ang: "cd4",
        pos: {
          x: "xAdj2",
          y: "y1"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "x1",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "xAdj",
          y: "y4"
        }
      },
      {
        ang: "0",
        pos: {
          x: "x9",
          y: "vc"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "x2",
            y: "y1"
          },
          {
            cmd: "cubicBezTo",
            x: "x5",
            y: "y1",
            x1: "x3",
            y1: "y2",
            x2: "x4",
            y2: "y3"
          },
          {
            cmd: "lineTo",
            x: "x10",
            y: "y4"
          },
          {
            cmd: "cubicBezTo",
            x: "x6",
            y: "y4",
            x1: "x8",
            y1: "y6",
            x2: "x7",
            y2: "y5"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [119 /* SHAPE_GEOMETRY_WEDGE_ELLIPSE_CALLOUT */]: {
    avLst: {
      adj1: "val -20833",
      adj2: "val 62500"
    },
    gdLst: {
      dxPos: "*/ w adj1 100000",
      dyPos: "*/ h adj2 100000",
      xPos: "+- hc dxPos 0",
      yPos: "+- vc dyPos 0",
      sdx: "*/ dxPos h 1",
      sdy: "*/ dyPos w 1",
      pang: "at2 sdx sdy",
      stAng: "+- pang 660000 0",
      enAng: "+- pang 0 660000",
      dx1: "cos wd2 stAng",
      dy1: "sin hd2 stAng",
      x1: "+- hc dx1 0",
      y1: "+- vc dy1 0",
      dx2: "cos wd2 enAng",
      dy2: "sin hd2 enAng",
      x2: "+- hc dx2 0",
      y2: "+- vc dy2 0",
      stAng1: "at2 dx1 dy1",
      enAng1: "at2 dx2 dy2",
      swAng1: "+- enAng1 0 stAng1",
      swAng2: "+- swAng1 21600000 0",
      swAng: "?: swAng1 swAng1 swAng2",
      idx: "cos wd2 2700000",
      idy: "sin hd2 2700000",
      il: "+- hc 0 idx",
      ir: "+- hc idx 0",
      it: "+- vc 0 idy",
      ib: "+- vc idy 0"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        gdRefY: "adj2",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "xPos",
          y: "yPos"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "il",
          y: "it"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "il",
          y: "ib"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "ir",
          y: "ib"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "3cd4",
        pos: {
          x: "ir",
          y: "it"
        }
      },
      {
        ang: "pang",
        pos: {
          x: "xPos",
          y: "yPos"
        }
      }
    ],
    rect: {
      l: "il",
      t: "it",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "xPos",
            y: "yPos"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "y1"
          },
          {
            cmd: "arcTo",
            wR: "wd2",
            hR: "hd2",
            stAng: "stAng1",
            swAng: "swAng"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [117 /* SHAPE_GEOMETRY_WEDGE_RECT_CALLOUT */]: {
    avLst: {
      adj1: "val -20833",
      adj2: "val 62500"
    },
    gdLst: {
      dxPos: "*/ w adj1 100000",
      dyPos: "*/ h adj2 100000",
      xPos: "+- hc dxPos 0",
      yPos: "+- vc dyPos 0",
      dx: "+- xPos 0 hc",
      dy: "+- yPos 0 vc",
      dq: "*/ dxPos h w",
      ady: "abs dyPos",
      adq: "abs dq",
      dz: "+- ady 0 adq",
      xg1: "?: dxPos 7 2",
      xg2: "?: dxPos 10 5",
      x1: "*/ w xg1 12",
      x2: "*/ w xg2 12",
      yg1: "?: dyPos 7 2",
      yg2: "?: dyPos 10 5",
      y1: "*/ h yg1 12",
      y2: "*/ h yg2 12",
      t1: "?: dxPos l xPos",
      xl: "?: dz l t1",
      t2: "?: dyPos x1 xPos",
      xt: "?: dz t2 x1",
      t3: "?: dxPos xPos r",
      xr: "?: dz r t3",
      t4: "?: dyPos xPos x1",
      xb: "?: dz t4 x1",
      t5: "?: dxPos y1 yPos",
      yl: "?: dz y1 t5",
      t6: "?: dyPos t yPos",
      yt: "?: dz t6 t",
      t7: "?: dxPos yPos y1",
      yr: "?: dz y1 t7",
      t8: "?: dyPos yPos b",
      yb: "?: dz t8 b"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        gdRefY: "adj2",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "xPos",
          y: "yPos"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "xPos",
          y: "yPos"
        }
      }
    ],
    rect: {
      l: "l",
      t: "t",
      r: "r",
      b: "b"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "xt",
            y: "yt"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "xr",
            y: "yr"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "xb",
            y: "yb"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "xl",
            y: "yl"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y1"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  },
  [118 /* SHAPE_GEOMETRY_WEDGE_ROUND_RECT_CALLOUT */]: {
    avLst: {
      adj1: "val -20833",
      adj2: "val 62500",
      adj3: "val 16667"
    },
    gdLst: {
      dxPos: "*/ w adj1 100000",
      dyPos: "*/ h adj2 100000",
      xPos: "+- hc dxPos 0",
      yPos: "+- vc dyPos 0",
      dq: "*/ dxPos h w",
      ady: "abs dyPos",
      adq: "abs dq",
      dz: "+- ady 0 adq",
      xg1: "?: dxPos 7 2",
      xg2: "?: dxPos 10 5",
      x1: "*/ w xg1 12",
      x2: "*/ w xg2 12",
      yg1: "?: dyPos 7 2",
      yg2: "?: dyPos 10 5",
      y1: "*/ h yg1 12",
      y2: "*/ h yg2 12",
      t1: "?: dxPos l xPos",
      xl: "?: dz l t1",
      t2: "?: dyPos x1 xPos",
      xt: "?: dz t2 x1",
      t3: "?: dxPos xPos r",
      xr: "?: dz r t3",
      t4: "?: dyPos xPos x1",
      xb: "?: dz t4 x1",
      t5: "?: dxPos y1 yPos",
      yl: "?: dz y1 t5",
      t6: "?: dyPos t yPos",
      yt: "?: dz t6 t",
      t7: "?: dxPos yPos y1",
      yr: "?: dz y1 t7",
      t8: "?: dyPos yPos b",
      yb: "?: dz t8 b",
      u1: "*/ ss adj3 100000",
      u2: "+- r 0 u1",
      v2: "+- b 0 u1",
      il: "*/ u1 29289 100000",
      ir: "+- r 0 il",
      ib: "+- b 0 il"
    },
    ahLst: [
      {
        gdRefX: "adj1",
        gdRefY: "adj2",
        minX: "-2147483647",
        maxX: "2147483647",
        minY: "-2147483647",
        maxY: "2147483647",
        pos: {
          x: "xPos",
          y: "yPos"
        }
      }
    ],
    cxnLst: [
      {
        ang: "3cd4",
        pos: {
          x: "hc",
          y: "t"
        }
      },
      {
        ang: "cd2",
        pos: {
          x: "l",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "hc",
          y: "b"
        }
      },
      {
        ang: "0",
        pos: {
          x: "r",
          y: "vc"
        }
      },
      {
        ang: "cd4",
        pos: {
          x: "xPos",
          y: "yPos"
        }
      }
    ],
    rect: {
      l: "il",
      t: "il",
      r: "ir",
      b: "ib"
    },
    paths: [
      {
        fill: "solid",
        stroke: true,
        extrusionOk: false,
        commands: [
          {
            cmd: "moveTo",
            x: "l",
            y: "u1"
          },
          {
            cmd: "arcTo",
            wR: "u1",
            hR: "u1",
            stAng: "cd2",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "xt",
            y: "yt"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "t"
          },
          {
            cmd: "lineTo",
            x: "u2",
            y: "t"
          },
          {
            cmd: "arcTo",
            wR: "u1",
            hR: "u1",
            stAng: "3cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y1"
          },
          {
            cmd: "lineTo",
            x: "xr",
            y: "yr"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "r",
            y: "v2"
          },
          {
            cmd: "arcTo",
            wR: "u1",
            hR: "u1",
            stAng: "0",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "x2",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "xb",
            y: "yb"
          },
          {
            cmd: "lineTo",
            x: "x1",
            y: "b"
          },
          {
            cmd: "lineTo",
            x: "u1",
            y: "b"
          },
          {
            cmd: "arcTo",
            wR: "u1",
            hR: "u1",
            stAng: "cd4",
            swAng: "cd4"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y2"
          },
          {
            cmd: "lineTo",
            x: "xl",
            y: "yl"
          },
          {
            cmd: "lineTo",
            x: "l",
            y: "y1"
          },
          {
            cmd: "close"
          }
        ]
      }
    ]
  }
};

// node_modules/@oai/granola/dist/shapes/preset-shape-definitions.js
var presetShapeDefinitions2 = {
  ...presetShapeDefinitionsPart1,
  ...presetShapeDefinitionsPart2,
  ...presetShapeDefinitionsPart3,
  ...presetShapeDefinitionsPart4,
  ...presetShapeDefinitionsPart5
};

// node_modules/@oai/granola/dist/plugins/preset-shape-definitions.js
function installPresetShapeDefinitions() {
  registerPresetShapeDefinitions(presetShapeDefinitions2);
}

// rpc_server/dispatcher.ts
import { Buffer as Buffer4 } from "node:buffer";

// node_modules/@oai/walnut/generated/oaiproto/coworker/docx/document.ts
var gt3 = (() => {
  if (typeof globalThis !== "undefined") {
    return globalThis;
  }
  if (typeof self !== "undefined") {
    return self;
  }
  if (typeof window !== "undefined") {
    return window;
  }
  if (typeof global !== "undefined") {
    return global;
  }
  throw "Unable to locate global object";
})();

// node_modules/@oai/granola/dist/models/defined-names.js
init_address_utils();

class DefinedNames2 {
  #owner;
  #workbookEntries;
  #entriesBySheet;
  constructor(owner) {
    this.#owner = owner;
    this.#workbookEntries = new Map;
    this.#entriesBySheet = new Map;
  }
  createApi(scopeSheet) {
    const scope = scopeSheet;
    const definedNames = this;
    return {
      addRange: (name, text2, options) => this.addRange(name, text2, {
        ...options,
        sheetName: options?.sheetName ?? scope
      }),
      addFunction: (name, options) => this.addFunction(name, {
        ...options,
        sheetName: options.sheetName ?? scope
      }),
      add: (name, refersTo, _comment) => {
        const formula = typeof refersTo === "string" ? refersTo : this.#rangeToFormula(refersTo, scope);
        this.addRange(name, formula, { sheetName: scope });
        return this.getItemApi(name, scope);
      },
      getItem: (name) => {
        const item = this.getItemApi(name, scope);
        if (item.isNullObject) {
          throw new Error(`Defined name ${name} not found`);
        }
        return item;
      },
      getItemOrNullObject: (name) => this.getItemApi(name, scope),
      get items() {
        const entries = scope ? definedNames.#listSheet(scope) : definedNames.#listWorkbook();
        return entries.map((entry) => new LiveNamedItem(definedNames, entry));
      }
    };
  }
  ingest(names) {
    if (!names) {
      return;
    }
    for (const proto of names) {
      this.#register(proto);
    }
  }
  replace(names) {
    this.#workbookEntries.clear();
    this.#entriesBySheet.clear();
    this.ingest(names);
    this.#owner.onChange?.();
  }
  addRange(name, text2, options) {
    this.#addRange(name, text2, options);
  }
  #addRange(name, text2, options = {}) {
    const shouldRecord = options.record ?? true;
    const normalizedName = this.normalizeName(name);
    if (!normalizedName) {
      throw new Error("Defined name requires a non-empty name");
    }
    const normalizedFormula = this.normalizeFormula(text2);
    const sheetName = options.sheetName;
    const localSheetId = sheetName !== undefined && sheetName !== null ? this.#owner.getLocalSheetIdByName(sheetName) : undefined;
    if (sheetName && localSheetId === undefined) {
      throw new Error(`Worksheet ${sheetName} was not found`);
    }
    const proto = {
      name,
      text: normalizedFormula.startsWith("=") ? normalizedFormula.slice(1) : normalizedFormula,
      localSheetId: localSheetId ?? undefined
    };
    this.#register(proto, normalizedFormula);
    this.#owner.onChange?.();
    if (shouldRecord) {
      this.#owner.recordOp?.({
        op: "names.range.add",
        name,
        formula: serializeDefinedNameFormula(normalizedFormula),
        description: options.description,
        sheet: sheetName
      });
    }
  }
  addFunction(name, options) {
    this.#addRange(name, options.lambda, {
      sheetName: options.sheetName,
      description: options.description,
      record: false
    });
    this.#owner.recordOp?.({
      op: "names.function.add",
      name,
      lambda: serializeDefinedNameFormula(this.normalizeFormula(options.lambda)),
      description: options.description,
      parameters: options.parameters,
      returns: options.returns,
      sheet: options.sheetName
    });
  }
  buildProto() {
    const result = [];
    const collect = (map4) => {
      for (const entry of map4.values()) {
        result.push({ ...entry.proto });
      }
    };
    collect(this.#workbookEntries);
    for (const map4 of this.#entriesBySheet.values()) {
      collect(map4);
    }
    return result;
  }
  lookup(normalizedName, contextSheet) {
    const sheetKey = contextSheet?.trim().toUpperCase();
    if (sheetKey && this.#entriesBySheet.has(sheetKey)) {
      const scoped = this.#entriesBySheet.get(sheetKey);
      const entry = scoped?.get(normalizedName);
      if (entry) {
        return entry;
      }
    }
    return this.#workbookEntries.get(normalizedName);
  }
  normalizeName(name) {
    return name?.trim().toUpperCase() ?? "";
  }
  normalizeFormula(text2) {
    if (!text2) {
      return "=";
    }
    const trimmed = text2.trim();
    if (!trimmed) {
      return "=";
    }
    return trimmed.startsWith("=") ? trimmed : `=${trimmed}`;
  }
  parseEntry(entry) {
    if (!entry.parsed) {
      const parsed = parseFormula(entry.normalizedFormula);
      entry.parsed = parsed;
      if (parsed.errors.length === 0) {
        entry.isLambda = this.#isLambdaExpression(parsed.expr);
      }
    }
    return entry.parsed ?? null;
  }
  makeGuardKey(entry) {
    return `${(entry.scopeSheet ?? "__WORKBOOK__").toUpperCase()}::${entry.normalizedName}`;
  }
  resolveRange(entry) {
    const parsed = this.parseEntry(entry);
    if (!parsed || parsed.errors.length > 0) {
      throw new Error(`Defined name "${entry.proto.name ?? entry.normalizedName}" has an invalid formula.`);
    }
    if (parsed.expr.kind !== "RangeRef") {
      throw new Error(`Defined name "${entry.proto.name ?? entry.normalizedName}" does not refer to a range.`);
    }
    const { sheetName, ref } = splitSheetAddress(entry.normalizedFormula);
    const resolvedSheetName = sheetName?.trim() || entry.scopeSheet?.trim();
    if (!resolvedSheetName) {
      throw new Error(`Defined name "${entry.proto.name ?? entry.normalizedName}" refers to "${entry.normalizedFormula}", which is missing a worksheet scope.`);
    }
    const worksheet = this.#owner.getWorksheetByName(resolvedSheetName);
    if (!worksheet) {
      throw new Error(`Worksheet "${resolvedSheetName}" was not found for defined name "${entry.proto.name ?? entry.normalizedName}".`);
    }
    return worksheet.getRange(ref);
  }
  #register(proto, normalizedFormula) {
    const normalizedName = this.normalizeName(proto.name);
    if (!normalizedName || normalizedName.startsWith("_XLNM.")) {
      return;
    }
    const scopeSheet = this.#owner.getSheetNameByLocalId(proto.localSheetId ?? null);
    const formula = normalizedFormula ?? this.normalizeFormula(proto.text);
    const entry = {
      proto: { ...proto },
      normalizedName,
      normalizedFormula: formula,
      scopeSheet,
      parsed: undefined,
      isLambda: false
    };
    this.#placeEntry(entry);
  }
  #placeEntry(entry) {
    if (entry.scopeSheet) {
      const map4 = this.#getSheetMap(entry.scopeSheet);
      map4.set(entry.normalizedName, entry);
      return;
    }
    this.#workbookEntries.set(entry.normalizedName, entry);
  }
  #getSheetMap(sheetName) {
    const key = sheetName.trim().toUpperCase();
    let map4 = this.#entriesBySheet.get(key);
    if (!map4) {
      map4 = new Map;
      this.#entriesBySheet.set(key, map4);
    }
    return map4;
  }
  #isLambdaExpression(expr) {
    return expr.kind === "FunctionCall" && (expr.name === "LAMBDA" || expr.name === "_XLFN.LAMBDA");
  }
  delete(name, scopeSheet) {
    const normalizedName = this.normalizeName(name);
    if (!normalizedName) {
      throw new Error("Defined name requires a non-empty name");
    }
    const entry = this.#lookupInScope(normalizedName, scopeSheet);
    if (!entry) {
      throw new Error(`Defined name ${name} not found`);
    }
    if (entry.scopeSheet) {
      const key = entry.scopeSheet.trim().toUpperCase();
      const map4 = this.#entriesBySheet.get(key);
      map4?.delete(entry.normalizedName);
    } else {
      this.#workbookEntries.delete(entry.normalizedName);
    }
    this.#owner.onChange?.();
    this.#owner.recordOp?.({
      op: "names.remove",
      name: entry.proto.name ?? name,
      sheet: entry.scopeSheet
    });
  }
  getItemApi(name, scopeSheet) {
    const normalizedName = this.normalizeName(name);
    if (!normalizedName) {
      return new NullNamedItem(name || "");
    }
    const entry = this.#lookupInScope(normalizedName, scopeSheet);
    if (!entry) {
      return new NullNamedItem(name);
    }
    return new LiveNamedItem(this, entry);
  }
  #lookupInScope(normalizedName, scopeSheet) {
    if (scopeSheet) {
      const key = scopeSheet.trim().toUpperCase();
      const scoped = this.#entriesBySheet.get(key);
      return scoped?.get(normalizedName);
    }
    return this.#workbookEntries.get(normalizedName);
  }
  #listWorkbook() {
    return [...this.#workbookEntries.values()].sort((a, b) => a.normalizedName.localeCompare(b.normalizedName));
  }
  #listSheet(scopeSheet) {
    const key = scopeSheet.trim().toUpperCase();
    const scoped = this.#entriesBySheet.get(key);
    return scoped ? [...scoped.values()].sort((a, b) => a.normalizedName.localeCompare(b.normalizedName)) : [];
  }
  #rangeToFormula(range2, fallbackScope) {
    const worksheet = getRangeWorksheet(range2);
    const sheetName = worksheet?.name ?? fallbackScope ?? "";
    if (!sheetName) {
      throw new Error("Defined names require a worksheet-scoped Range when passing a Range input.");
    }
    const escaped = escapeSheetName(sheetName);
    return `${escaped}!${range2.address}`;
  }
}

class LiveNamedItem {
  #definedNames;
  #entry;
  constructor(definedNames, entry) {
    this.#definedNames = definedNames;
    this.#entry = entry;
  }
  get isNullObject() {
    return false;
  }
  get name() {
    return this.#entry.proto.name ?? "";
  }
  get formula() {
    return this.#entry.normalizedFormula;
  }
  getRange() {
    return this.#definedNames.resolveRange(this.#entry);
  }
  delete() {
    this.#definedNames.delete(this.name, this.#entry.scopeSheet);
  }
}

class NullNamedItem {
  #name;
  constructor(name) {
    this.#name = name;
  }
  get isNullObject() {
    return true;
  }
  get name() {
    return this.#name;
  }
  get formula() {
    return "=";
  }
  getRange() {
    const label = this.#name || "Unknown";
    throw new Error(`Defined name "${label}" not found.`);
  }
  delete() {
    const label = this.#name || "Unknown";
    throw new Error(`Defined name "${label}" not found.`);
  }
}
function escapeSheetName(sheetName) {
  const escaped = sheetName.replace(/'/g, "''");
  return `'${escaped}'`;
}
function serializeDefinedNameFormula(formula) {
  return formula.startsWith("=") ? formula.slice(1) : formula;
}

// node_modules/@oai/granola/dist/models/document/defaults/default-document.js
function createDefaultParagraph() {
  const run = {
    id: "doc-run-1",
    text: "Start writing here...",
    textStyle: undefined,
    hyperlink: undefined,
    citations: [],
    reviewMarkIds: []
  };
  return {
    id: "doc-paragraph-1",
    runs: [run],
    textStyle: undefined,
    styleId: "Body"
  };
}
function createDefaultElement() {
  return {
    id: "doc-element-1",
    type: 1 /* ELEMENT_TYPE_TEXT */,
    paragraphs: [createDefaultParagraph()],
    bbox: undefined,
    zIndex: 0,
    innerXml: "",
    outerXml: "",
    shape: undefined,
    image: undefined,
    chartReference: undefined,
    video: undefined,
    table: undefined,
    name: "",
    placeholderIndex: 0,
    placeholderType: "",
    effects: [],
    children: [],
    levelsStyles: [],
    fill: undefined,
    lineReference: undefined,
    fillReference: undefined,
    effectReference: undefined,
    fontReference: undefined,
    hyperlink: undefined,
    textStyle: undefined,
    citations: []
  };
}
function createDefaultDocument() {
  const defaultElement = createDefaultElement();
  const defaultSectionElement = createDefaultElement();
  const widthEmu = 12240;
  const heightEmu = 15840;
  return {
    id: "walnut-document",
    name: "New document",
    widthEmu,
    heightEmu,
    charts: [],
    elements: [defaultElement],
    images: [],
    footnotes: [],
    comments: [],
    commentReferences: [],
    textStyles: [],
    reviewMarks: [],
    sections: [
      {
        id: "doc-section-1",
        breakType: 0 /* SECTION_BREAK_TYPE_UNSPECIFIED */,
        pageSetup: {
          widthEmu,
          heightEmu,
          pageMargin: undefined
        },
        columns: {
          count: 1,
          space: 0,
          widths: [],
          hasSeparatorLine: false
        },
        elements: [defaultSectionElement],
        header: undefined,
        footer: undefined
      }
    ],
    numberingDefinitions: [],
    paragraphNumberings: []
  };
}

// node_modules/@oai/granola/dist/models/document/comments/document-comments.js
class DocumentComments {
  #comments;
  #documentId;
  #textElementId;
  #resolveTextRange;
  constructor(config2) {
    this.#comments = new Comments({
      people: config2.people ?? [],
      threads: config2.threads ?? []
    });
    this.#documentId = config2.documentId ?? "";
    this.#textElementId = config2.textElementId ?? "";
    this.#resolveTextRange = config2.resolveTextRange;
  }
  get people() {
    return this.#comments.people;
  }
  get threads() {
    return this.#comments.threads;
  }
  setSelf(person) {
    return this.#comments.setSelf(person);
  }
  addThread(target, body, options = {}) {
    const protoTarget = this.#buildTextRangeTarget(target.textRange);
    return this.#comments.addThread({ proto: protoTarget }, body, options);
  }
  toProto() {
    return this.#comments.toProto();
  }
  #buildTextRangeTarget(range2) {
    const resolved = this.#resolveTextRange(range2);
    const startCp = resolved?.startCp ?? 0;
    const length2 = resolved?.length ?? 0;
    const target = {
      slideId: this.#documentId,
      elementId: this.#textElementId,
      startCp,
      length: length2
    };
    return { textRange: target };
  }
}

// node_modules/@oai/granola/dist/models/document/footnotes/footnotes.js
class DocumentFootnote {
  #data;
  constructor(proto) {
    this.#data = proto;
  }
  get id() {
    return this.#data.id ?? "";
  }
  toProto() {
    return {
      ...this.#data,
      referenceRunIds: this.#data.referenceRunIds ?? [],
      paragraphs: this.#data.paragraphs ? this.#data.paragraphs.map((paragraph) => ({
        ...paragraph,
        runs: paragraph.runs?.map((run) => ({ ...run })) ?? []
      })) : []
    };
  }
}

class DocumentFootnotes {
  #items = [];
  #documentId;
  #textElementId;
  #resolveTextRange;
  constructor(config2) {
    this.#documentId = config2.documentId ?? "";
    this.#textElementId = config2.textElementId ?? "";
    this.#resolveTextRange = config2.resolveTextRange;
    const protos = config2.footnotes ?? [];
    this.#items = protos.map((proto) => new DocumentFootnote(proto));
  }
  add(text2, options) {
    const paragraphs = this.#buildParagraphs(text2);
    const referenceTextRange = this.#buildReferenceTextRange(options.range);
    const footnote = {
      id: generateGuid(),
      paragraphs,
      referenceTextRange,
      referenceRunIds: []
    };
    const instance = new DocumentFootnote(footnote);
    this.#items.push(instance);
    return instance;
  }
  toProto() {
    return this.#items.map((footnote) => footnote.toProto());
  }
  #buildParagraphs(text2) {
    if (isStructuredTextInput(text2)) {
      return buildParagraphProtosFromInput(text2);
    }
    return buildParagraphProtosFromInput([String(text2)]);
  }
  #buildReferenceTextRange(range2) {
    const resolved = this.#resolveTextRange(range2);
    if (!resolved) {
      return;
    }
    return {
      slideId: this.#documentId,
      elementId: this.#textElementId,
      startCp: resolved.startCp,
      length: resolved.length
    };
  }
}

// node_modules/@oai/granola/dist/models/document/numbering/numbering.js
class DocumentNumbering {
  #definitionsByNumId;
  #paragraphBindings;
  constructor(definitions = [], paragraphBindings = []) {
    this.#definitionsByNumId = new Map;
    this.#paragraphBindings = new Map;
    for (const definition of definitions) {
      this.define(definition);
    }
    for (const binding of paragraphBindings) {
      this.assignParagraph(binding.paragraphId, binding.numId, binding.level);
    }
  }
  get definitions() {
    return Array.from(this.#definitionsByNumId.values());
  }
  get paragraphBindings() {
    return Array.from(this.#paragraphBindings.values());
  }
  define(definition) {
    if (!definition?.numId) {
      return;
    }
    this.#definitionsByNumId.set(definition.numId, {
      ...definition,
      levels: [...definition.levels ?? []]
    });
  }
  removeDefinition(numId) {
    this.#definitionsByNumId.delete(numId);
  }
  assignParagraph(paragraphId, numId, level = 0) {
    if (!paragraphId || !numId) {
      return;
    }
    this.#paragraphBindings.set(paragraphId, {
      paragraphId,
      numId,
      level
    });
  }
  clearParagraphBinding(paragraphId) {
    this.#paragraphBindings.delete(paragraphId);
  }
  toProto() {
    return {
      numberingDefinitions: this.definitions,
      paragraphNumberings: this.paragraphBindings
    };
  }
}

// node_modules/@oai/granola/dist/models/document/revisions/revisions.js
var REVIEW_MARK_TYPES = {
  insertion: 1 /* REVIEW_MARK_TYPE_INSERTION */,
  deletion: 2 /* REVIEW_MARK_TYPE_DELETION */
};

class DocumentReviewMark {
  #data;
  constructor(proto) {
    this.#data = { ...proto };
  }
  get id() {
    return this.#data.id;
  }
  toProto() {
    return { ...this.#data };
  }
}

class DocumentRevisions {
  #items = [];
  constructor(items = []) {
    this.#items = items.map((item) => new DocumentReviewMark(item));
  }
  add(options) {
    const proto = {
      id: generateGuid(),
      type: REVIEW_MARK_TYPES[options.type],
      author: options.author,
      initials: options.initials,
      createdAt: options.createdAt
    };
    const mark = new DocumentReviewMark(proto);
    this.#items.push(mark);
    return mark;
  }
  toProto() {
    return this.#items.map((item) => item.toProto());
  }
}

// node_modules/@oai/granola/dist/models/document/body/body-text.js
class BodyTextElement extends Element2 {
  type = "text";
  constructor(context, proto) {
    super(context, {
      ...proto ?? {},
      type: 1 /* ELEMENT_TYPE_TEXT */
    });
    this.data.type = 1 /* ELEMENT_TYPE_TEXT */;
  }
  get id() {
    return this.data.id;
  }
  toProto() {
    return super.toProto();
  }
}

// node_modules/@oai/granola/dist/models/document/body/paragraphs.js
class DocumentParagraphs {
  #paragraphs;
  constructor(paragraphs) {
    this.#paragraphs = paragraphs;
  }
  add(input = {}) {
    const { text: text2, style } = input;
    let paragraph;
    if (this.#shouldReplaceDefault()) {
      this.#paragraphs.clear();
    }
    if (text2 !== undefined && isStructuredTextInput(text2)) {
      const protos = buildParagraphProtosFromInput(text2);
      if (protos.length === 0) {
        paragraph = this.#paragraphs.add();
      } else {
        paragraph = this.#paragraphs.append(protos[0]);
        for (let index = 1;index < protos.length; index += 1) {
          this.#paragraphs.append(protos[index]);
        }
      }
    } else {
      paragraph = this.#paragraphs.add();
      if (text2 !== undefined) {
        paragraph.setPlainText(String(text2));
      }
    }
    if (style) {
      paragraph.style = style;
    }
    return paragraph;
  }
  #shouldReplaceDefault() {
    if (this.#paragraphs.length !== 1) {
      return false;
    }
    const paragraph = this.#paragraphs.getItem(0);
    if (!paragraph) {
      return false;
    }
    return paragraph.toPlainText().trim() === "Start writing here...";
  }
}

// node_modules/@oai/granola/dist/models/document/body/position-utils.js
function normalizeCoordinate(value) {
  if (value === undefined || !Number.isFinite(value)) {
    return;
  }
  return value;
}
function normalizeDimension2(value) {
  if (value === undefined || !Number.isFinite(value) || value <= 0) {
    return;
  }
  return value;
}
function normalizeDocumentBodyPosition(position, options = {}) {
  const normalized = {
    left: normalizeCoordinate(position.left),
    top: normalizeCoordinate(position.top),
    width: normalizeDimension2(position.width),
    height: normalizeDimension2(position.height)
  };
  if (options.inline) {
    normalized.left = undefined;
    normalized.top = undefined;
  }
  return normalized;
}

// node_modules/@oai/granola/dist/models/document/body/tables.js
function normalizePreset(value) {
  if (!value) {
    return;
  }
  const normalized = value.trim().toLowerCase();
  return normalized.length > 0 ? normalized : undefined;
}

class DocumentTables {
  #tables;
  constructor(tables) {
    this.#tables = tables;
  }
  add(input) {
    if (Array.isArray(input)) {
      return this.#tables.add(input);
    }
    const { position, style, ...rest } = input;
    const normalizedPosition = normalizeDocumentBodyPosition({
      left: position?.left,
      top: position?.top,
      width: position?.width,
      height: position?.height
    });
    const hasPosition = normalizedPosition.left !== undefined || normalizedPosition.top !== undefined || normalizedPosition.width !== undefined || normalizedPosition.height !== undefined;
    const normalized = {
      ...rest,
      left: hasPosition ? normalizedPosition.left : undefined,
      top: hasPosition ? normalizedPosition.top : undefined,
      width: hasPosition ? normalizedPosition.width : undefined,
      height: hasPosition ? normalizedPosition.height : undefined
    };
    const table2 = this.#tables.add(normalized);
    if (style) {
      if (style.preset) {
        table2.style = style.preset;
      }
      const { preset: _preset, ...styleOptions } = style;
      const merged = {
        ...table2.styleOptions,
        ...styleOptions
      };
      table2.styleOptions = merged;
    }
    if (normalizePreset(style?.preset) === "tablegrid" && table2.rowCount > 0 && table2.columnCount > 0) {
      table2.cells.block({
        row: 0,
        column: 0,
        rowCount: table2.rowCount,
        columnCount: table2.columnCount
      }).applyBorders({
        outside: { color: "#000000", width: 1, style: "solid" },
        inside: { color: "#000000", width: 1, style: "solid" }
      });
    }
    return table2;
  }
}

// node_modules/@oai/granola/dist/models/document/body/images.js
class DocumentImages {
  #images;
  constructor(images) {
    this.#images = images;
  }
  add(options) {
    const position = normalizePosition(options);
    const imageOptions = normalizeImageOptions(options, position);
    return this.#images.add(imageOptions);
  }
}
function normalizePosition(options) {
  const size2 = options.size;
  const position = options.position ?? {};
  return normalizeDocumentBodyPosition({
    left: position.left,
    top: position.top,
    width: position.width ?? size2?.width,
    height: position.height ?? size2?.height
  }, {
    inline: options.style?.wrap === "inline"
  });
}
function normalizeImageOptions(options, position) {
  const base = {
    alt: options.alt,
    position,
    contentType: options.contentType
  };
  if ("blob" in options) {
    return {
      ...base,
      blob: normalizeBlob(options.blob),
      contentType: options.contentType
    };
  }
  if ("dataUrl" in options) {
    return { ...base, dataUrl: options.dataUrl };
  }
  if ("uri" in options) {
    return { ...base, uri: options.uri };
  }
  return { ...base, prompt: options.prompt };
}
function normalizeBlob(input) {
  if (input instanceof ArrayBuffer) {
    return input;
  }
  const buffer = input.buffer;
  if (buffer instanceof ArrayBuffer && input.byteOffset === 0 && input.byteLength === buffer.byteLength) {
    return buffer;
  }
  const output = new Uint8Array(input.byteLength);
  output.set(input);
  return output.buffer;
}

// node_modules/@oai/granola/dist/models/document/body/shapes.js
class DocumentShapes {
  #shapes;
  constructor(shapes) {
    this.#shapes = shapes;
  }
  add(config2) {
    const position = normalizePosition2(config2);
    const shape2 = this.#shapes.add({
      geometry: config2.geometry,
      position,
      fill: config2.fill,
      line: config2.line
    });
    if (config2.text !== undefined) {
      shape2.text = config2.text;
    }
    return shape2;
  }
}
function normalizePosition2(config2) {
  const size2 = config2.size;
  const position = config2.position ?? {};
  const resolved = {
    left: position.left,
    top: position.top,
    width: position.width ?? size2?.width,
    height: position.height ?? size2?.height
  };
  if (config2.style?.wrap === "inline") {
    resolved.left = undefined;
    resolved.top = undefined;
  }
  return resolved;
}

// node_modules/@oai/granola/dist/models/document/text-style-resolution.js
function pickParagraphRunFallbackTextStyle(paragraphTextStyle, namedTextStyle) {
  const alignment = paragraphTextStyle?.alignment ?? namedTextStyle?.alignment;
  if (alignment === undefined) {
    return namedTextStyle;
  }
  return mergeDocumentTextStyle({ alignment }, namedTextStyle);
}
class DocumentTextStyleResolver {
  #styleResolver;
  constructor(textStyles = []) {
    this.#styleResolver = new ParagraphStyleDefinitionResolver(textStyles);
  }
  resolveTextStyleByName(name) {
    return this.#styleResolver.resolveByName(name)?.textStyle;
  }
  resolveParagraphTextStyle(paragraph, elementTextStyle) {
    const resolvedNamedStyle = this.resolveParagraphStyleDefinition(paragraph.styleId)?.textStyle;
    const paragraphTextStyle = mergeDocumentTextStyle(paragraph.textStyle, resolvedNamedStyle);
    return mergeDocumentTextStyle(paragraphTextStyle, elementTextStyle);
  }
  resolveParagraphStyle(paragraph) {
    const resolvedNamedStyle = this.resolveParagraphStyleDefinition(paragraph.styleId)?.paragraphStyle;
    return mergeStyleWithFallback(paragraph.paragraphStyle, resolvedNamedStyle);
  }
  resolveRunTextStyle(paragraph, run, elementTextStyle) {
    const resolvedNamedStyle = this.resolveParagraphStyleDefinition(paragraph.styleId)?.textStyle;
    const paragraphRunFallbackTextStyle = pickParagraphRunFallbackTextStyle(paragraph.textStyle, resolvedNamedStyle);
    const fallback = mergeDocumentTextStyle(paragraphRunFallbackTextStyle, elementTextStyle);
    return mergeDocumentTextStyle(run.textStyle, fallback);
  }
  resolveParagraphStyleDefinition(styleId) {
    return this.#styleResolver.resolve(styleId);
  }
}

// node_modules/@oai/granola/dist/models/document/body/body.js
class DocumentBody {
  #context;
  #slideStub;
  #order = [];
  #elementsById = new Map;
  #textElement;
  #paragraphs;
  #tables;
  #images;
  #shapes;
  #imageAssets;
  #textStyleResolver;
  constructor(options) {
    this.#imageAssets = options.images;
    this.#textStyleResolver = new DocumentTextStyleResolver(options.textStyles ?? []);
    this.#context = this.#buildContext();
    const { bodyElement, remainingElements } = this.#resolveBodyElement(options.elements ?? []);
    this.#textElement = new BodyTextElement(this.#context, bodyElement);
    this.#registerTextElement(this.#textElement);
    const shapes = new ShapeCollection(this.#context, []);
    const images = new ImageElementCollection(this.#context, []);
    const tables = new Tables(this.#context, []);
    this.#shapes = new DocumentShapes(shapes);
    this.#images = new DocumentImages(images);
    this.#tables = new DocumentTables(tables);
    this.#paragraphs = new DocumentParagraphs(this.#textElement.paragraphs);
    for (const element of remainingElements) {
      this.#hydrateElement(element, shapes, images, tables);
    }
  }
  get text() {
    return this.#textElement.text;
  }
  get textElements() {
    return this.#order.map((id2) => this.#elementsById.get(id2)).filter((element) => element instanceof BodyTextElement);
  }
  getElementById(id2) {
    if (!id2) {
      return;
    }
    return this.#elementsById.get(id2);
  }
  removeElementById(id2) {
    if (!id2 || id2 === this.#textElement.id) {
      return false;
    }
    const element = this.#elementsById.get(id2);
    if (!element) {
      return false;
    }
    this.#unregisterElement(id2);
    return true;
  }
  resolveTextBlock(id2) {
    const element = this.getElementById(id2);
    if (!element) {
      return null;
    }
    if (element instanceof BodyTextElement) {
      return element.text;
    }
    if ("text" in element) {
      return element.text;
    }
    return null;
  }
  set text(value) {
    this.#textElement.text.set(value);
  }
  get paragraphs() {
    return this.#paragraphs;
  }
  get tables() {
    return this.#tables;
  }
  get images() {
    return this.#images;
  }
  get shapes() {
    return this.#shapes;
  }
  get textElementId() {
    return this.#textElement.id;
  }
  toProto() {
    return this.#order.map((id2) => this.#elementsById.get(id2)).filter((element) => Boolean(element)).map((element) => {
      if (element instanceof BodyTextElement) {
        return element.toProto();
      }
      return element.toProto();
    });
  }
  #buildContext() {
    return {
      stub: () => {},
      getTextStyleByName: (name) => this.#resolveTextStyle(name),
      getResolvedParagraphTextStyle: (paragraph, elementTextStyle) => {
        const resolved = this.#textStyleResolver.resolveParagraphTextStyle(paragraph.toProto(), elementTextStyle?.toProto());
        return resolved ? new TextStyle2(resolved) : undefined;
      },
      getResolvedParagraphStyle: (paragraph) => this.#textStyleResolver.resolveParagraphStyle(paragraph.toProto()),
      getResolvedRunTextStyle: (paragraph, run, elementTextStyle) => {
        const resolved = this.#textStyleResolver.resolveRunTextStyle(paragraph.toProto(), run.toProto(), elementTextStyle?.toProto());
        return resolved ? new TextStyle2(resolved) : undefined;
      },
      getSlide: () => this.#getSlideStub(),
      getImageById: (id2) => this.#imageAssets.getById(id2),
      createImageAsset: (init) => this.#imageAssets.add(init),
      getChartById: () => {
        return;
      },
      createChartAsset: () => {
        throw new Error("Charts are not supported in documents yet.");
      },
      attachChartAsset: () => {
        throw new Error("Charts are not supported in documents yet.");
      },
      _register: (element, options) => this.#registerElement(element, options),
      _unregister: (id2) => this.#unregisterElement(id2)
    };
  }
  #getSlideStub() {
    if (this.#slideStub) {
      return this.#slideStub;
    }
    const getItems = () => [...this.#elementsById.values()];
    const stub = {
      id: undefined,
      elements: {
        get items() {
          return getItems();
        }
      }
    };
    this.#slideStub = stub;
    return stub;
  }
  #resolveTextStyle(name) {
    const resolved = this.#textStyleResolver.resolveTextStyleByName(name);
    if (!resolved) {
      return;
    }
    return new TextStyle2(resolved);
  }
  #registerTextElement(element) {
    this.#elementsById.set(element.id, element);
    this.#order = [element.id];
  }
  #registerElement(element, options) {
    const id2 = element.id;
    if (!id2) {
      return;
    }
    this.#elementsById.set(id2, element);
    const existingIndex = this.#order.indexOf(id2);
    if (existingIndex >= 0) {
      this.#order.splice(existingIndex, 1);
    }
    const textIndex = this.#order.indexOf(this.#textElement.id);
    const reservedIndex = textIndex >= 0 ? textIndex + 1 : 0;
    const requestedIndex = options?.index ?? this.#order.length;
    const insertIndex = Math.max(reservedIndex, requestedIndex);
    this.#order.splice(insertIndex, 0, id2);
  }
  #unregisterElement(id2) {
    this.#elementsById.delete(id2);
    const index = this.#order.indexOf(id2);
    if (index >= 0) {
      this.#order.splice(index, 1);
    }
  }
  #resolveBodyElement(elements) {
    const bodyIndex = elements.findIndex((element) => element.type === 1 /* ELEMENT_TYPE_TEXT */ || element.type === 2 /* ELEMENT_TYPE_TEXT_GROUP */);
    if (bodyIndex >= 0) {
      const bodyElement = elements[bodyIndex];
      const remaining = elements.filter((_, index) => index !== bodyIndex);
      return { bodyElement, remainingElements: remaining };
    }
    return { bodyElement: undefined, remainingElements: elements };
  }
  #hydrateElement(element, shapes, images, tables) {
    if (element.type === 1 /* ELEMENT_TYPE_TEXT */ || element.type === 2 /* ELEMENT_TYPE_TEXT_GROUP */) {
      const textElement = new BodyTextElement(this.#context, element);
      this.#registerElement(textElement);
      return;
    }
    if (element.type === 9 /* ELEMENT_TYPE_TABLE */ || element.table) {
      tables.add({ proto: element });
      return;
    }
    if (element.type === 3 /* ELEMENT_TYPE_IMAGE */ || element.type === 7 /* ELEMENT_TYPE_IMAGE_REFERENCE */ || element.imageReference) {
      images.add({ proto: element });
      return;
    }
    if (element.type === 5 /* ELEMENT_TYPE_SHAPE */ || element.shape !== undefined) {
      shapes.add({ proto: element });
    }
  }
}

// node_modules/@oai/granola/dist/models/document/sections/section-model.js
function clonePageSetup(pageSetup) {
  if (!pageSetup) {
    return;
  }
  const pageNumbers = pageSetup.pageNumbers ? { ...pageSetup.pageNumbers } : undefined;
  return {
    ...pageSetup,
    pageMargin: pageSetup.pageMargin ? { ...pageSetup.pageMargin } : undefined,
    pageNumbers
  };
}
function cloneColumns(columns) {
  if (!columns) {
    return;
  }
  return {
    ...columns,
    widths: [...columns.widths ?? []]
  };
}
function hasTextContent(element) {
  const paragraphs = element.paragraphs ?? [];
  for (const paragraph of paragraphs) {
    const runs = paragraph.runs ?? [];
    for (const run of runs) {
      if ((run.text ?? "").length > 0) {
        return true;
      }
    }
  }
  return false;
}
function hasBodyContent(elements) {
  for (const element of elements) {
    if (!element) {
      continue;
    }
    const isText = element.type === 1 /* ELEMENT_TYPE_TEXT */ || element.type === 2 /* ELEMENT_TYPE_TEXT_GROUP */;
    if (!isText) {
      return true;
    }
    if (hasTextContent(element)) {
      return true;
    }
  }
  return false;
}

class DocumentSectionModel {
  #id;
  #breakType;
  #pageSetup;
  #columns;
  #body;
  #headerBody;
  #footerBody;
  #hasHeader;
  #hasFooter;
  constructor(options) {
    const section = options.section;
    this.#id = section?.id || options.defaultId;
    this.#breakType = section?.breakType ?? 0 /* SECTION_BREAK_TYPE_UNSPECIFIED */;
    this.#pageSetup = clonePageSetup(section?.pageSetup);
    this.#columns = cloneColumns(section?.columns);
    this.#body = new DocumentBody({
      elements: section?.elements ?? options.fallbackElements ?? [],
      images: options.images,
      textStyles: options.textStyles
    });
    this.#headerBody = new DocumentBody({
      elements: section?.header?.elements ?? [],
      images: options.images,
      textStyles: options.textStyles
    });
    this.#footerBody = new DocumentBody({
      elements: section?.footer?.elements ?? [],
      images: options.images,
      textStyles: options.textStyles
    });
    this.#hasHeader = Boolean(section?.header);
    this.#hasFooter = Boolean(section?.footer);
  }
  get id() {
    return this.#id;
  }
  get breakType() {
    return this.#breakType;
  }
  set breakType(value) {
    this.#breakType = value;
  }
  get body() {
    return this.#body;
  }
  get pageSetup() {
    return this.#pageSetup ? clonePageSetup(this.#pageSetup) : undefined;
  }
  set pageSetup(value) {
    this.#pageSetup = clonePageSetup(value);
  }
  get columns() {
    return this.#columns ? cloneColumns(this.#columns) : undefined;
  }
  set columns(value) {
    this.#columns = cloneColumns(value);
  }
  get header() {
    this.#hasHeader = true;
    return this.#headerBody;
  }
  get footer() {
    this.#hasFooter = true;
    return this.#footerBody;
  }
  clearHeader() {
    this.#hasHeader = false;
  }
  clearFooter() {
    this.#hasFooter = false;
  }
  toProto() {
    const section = {
      id: this.#id,
      breakType: this.#breakType,
      pageSetup: clonePageSetup(this.#pageSetup),
      columns: cloneColumns(this.#columns),
      elements: this.#body.toProto(),
      header: undefined,
      footer: undefined
    };
    const headerElements = this.#headerBody.toProto();
    if (this.#hasHeader && hasBodyContent(headerElements)) {
      section.header = this.#buildHeaderFooterProto(headerElements);
    }
    const footerElements = this.#footerBody.toProto();
    if (this.#hasFooter && hasBodyContent(footerElements)) {
      section.footer = this.#buildHeaderFooterProto(footerElements);
    }
    return section;
  }
  #buildHeaderFooterProto(elements) {
    return {
      elements
    };
  }
}

// node_modules/@oai/granola/dist/models/document/sections/sections.js
class DocumentSections {
  #items = [];
  #nextSectionNumber;
  #images;
  #textStyles;
  constructor(options) {
    this.#images = options.images;
    this.#textStyles = options.textStyles;
    const inputSections = options.sections ?? [];
    if (inputSections.length > 0) {
      this.#items = inputSections.map((section, index) => new DocumentSectionModel({
        section,
        images: this.#images,
        textStyles: this.#textStyles,
        defaultId: `doc-section-${index + 1}`
      }));
    } else {
      this.#items = [
        new DocumentSectionModel({
          fallbackElements: options.fallbackElements ?? [],
          images: this.#images,
          textStyles: this.#textStyles,
          defaultId: "doc-section-1"
        })
      ];
    }
    this.#nextSectionNumber = this.#items.length + 1;
  }
  get items() {
    return this.#items;
  }
  get first() {
    return this.#items[0];
  }
  add(options = {}) {
    const section = {
      id: options.id || this.#createSectionId(),
      breakType: options.breakType ?? 0 /* SECTION_BREAK_TYPE_UNSPECIFIED */,
      pageSetup: options.pageSetup,
      columns: options.columns,
      elements: options.elements ?? [],
      header: options.header,
      footer: options.footer
    };
    const model = new DocumentSectionModel({
      section,
      images: this.#images,
      textStyles: this.#textStyles,
      defaultId: section.id
    });
    this.#items.push(model);
    return model;
  }
  toProto() {
    return this.#items.map((item) => item.toProto());
  }
  #createSectionId() {
    const id2 = `doc-section-${this.#nextSectionNumber}`;
    this.#nextSectionNumber += 1;
    return id2;
  }
}

// node_modules/@oai/granola/dist/models/document/document-model.js
class DocumentModel {
  #data;
  #charts;
  #textStyles;
  #commentReferences;
  #legacyComments;
  #images;
  #sections;
  #numbering;
  #comments;
  #footnotes;
  #revisions;
  constructor(document2) {
    this.#data = {
      id: document2.id ?? "",
      name: document2.name ?? "Untitled document",
      widthEmu: document2.widthEmu ?? 0,
      heightEmu: document2.heightEmu ?? 0
    };
    this.#charts = document2.charts ?? [];
    this.#textStyles = document2.textStyles ?? [];
    this.#commentReferences = document2.commentReferences ?? [];
    this.#legacyComments = document2.comments ?? [];
    this.#images = new ImageCollection({ stub: () => {} }, document2.images ?? []);
    this.#sections = new DocumentSections({
      sections: document2.sections ?? [],
      fallbackElements: document2.elements ?? [],
      images: this.#images,
      textStyles: this.#textStyles
    });
    this.#numbering = new DocumentNumbering(document2.numberingDefinitions ?? [], document2.paragraphNumberings ?? []);
    const rootBody = this.#sections.first.body;
    const firstSectionPageSetup = this.#sections.first.pageSetup;
    if (firstSectionPageSetup?.widthEmu) {
      this.#data.widthEmu = firstSectionPageSetup.widthEmu;
    }
    if (firstSectionPageSetup?.heightEmu) {
      this.#data.heightEmu = firstSectionPageSetup.heightEmu;
    }
    this.#comments = new DocumentComments({
      people: [],
      threads: [],
      documentId: this.#data.id,
      textElementId: rootBody.textElementId,
      resolveTextRange: (range2) => range2.getTextRange()
    });
    this.#footnotes = new DocumentFootnotes({
      footnotes: document2.footnotes ?? [],
      documentId: this.#data.id,
      textElementId: rootBody.textElementId,
      resolveTextRange: (range2) => range2.getTextRange()
    });
    this.#revisions = new DocumentRevisions(document2.reviewMarks ?? []);
  }
  static create() {
    return new DocumentModel(createDefaultDocument());
  }
  static load(document2) {
    return new DocumentModel(document2);
  }
  get id() {
    return this.#data.id;
  }
  get name() {
    return this.#data.name;
  }
  set name(value) {
    this.#data.name = value ?? "";
  }
  get body() {
    return this.#sections.first.body;
  }
  get sections() {
    return this.#sections;
  }
  get numbering() {
    return this.#numbering;
  }
  get comments() {
    return this.#comments;
  }
  get footnotes() {
    return this.#footnotes;
  }
  get revisions() {
    return this.#revisions;
  }
  toProto() {
    const commentProto = this.#comments.toProto();
    const sectionProto = this.#sections.toProto();
    const flatElements = sectionProto.flatMap((section) => section.elements ?? []);
    const numberingProto = this.#numbering.toProto();
    const firstSectionPageSetup = sectionProto[0]?.pageSetup;
    const proto = {
      id: this.#data.id,
      name: this.#data.name,
      widthEmu: firstSectionPageSetup?.widthEmu ?? this.#data.widthEmu,
      heightEmu: firstSectionPageSetup?.heightEmu ?? this.#data.heightEmu,
      charts: this.#charts,
      elements: flatElements,
      images: this.#images.toProto(),
      footnotes: this.#footnotes.toProto(),
      comments: this.#legacyComments,
      commentReferences: this.#commentReferences,
      textStyles: this.#textStyles,
      reviewMarks: this.#revisions.toProto(),
      sections: sectionProto,
      numberingDefinitions: numberingProto.numberingDefinitions,
      paragraphNumberings: numberingProto.paragraphNumberings
    };
    const extended = proto;
    extended.people = commentProto.people;
    extended.threads = commentProto.threads;
    return extended;
  }
  save() {}
}
// node_modules/@oai/granola/dist/models/notes-collection.js
class Note2 {
  #ctx;
  #proto;
  constructor(context, proto) {
    this.#ctx = context;
    this.#proto = proto;
  }
  delete() {
    this.#ctx.remove(this);
  }
  get proto() {
    return this.#proto;
  }
}

class NotesCollection {
  #noteCtx;
  #notes;
  #items = [];
  #onChange;
  constructor(notes, _context = {}, onChange) {
    this.#notes = notes;
    this.#onChange = onChange;
    this.#noteCtx = {
      remove: (note) => {
        this.#remove(note);
      }
    };
    this.#load();
  }
  add(note) {
    this.#notes.push(note);
    const wrapper = this.#createNote(note);
    this.#items.push(wrapper);
    this.#onChange?.();
    return wrapper;
  }
  get items() {
    return [...this.#items];
  }
  get proto() {
    return this.#items.map((note) => note.proto);
  }
  replace(notes) {
    this.#notes = [...notes];
    this.#load();
  }
  #load() {
    this.#items = this.#notes.map((note) => this.#createNote(note));
  }
  #remove(note) {
    const protoIndex = this.#notes.indexOf(note.proto);
    if (protoIndex !== -1) {
      this.#notes.splice(protoIndex, 1);
    }
    const cacheIndex = this.#items.indexOf(note);
    if (cacheIndex !== -1) {
      this.#items.splice(cacheIndex, 1);
    }
    this.#onChange?.();
  }
  #createNote(proto) {
    return new Note2(this.#noteCtx, proto);
  }
}

// node_modules/@oai/granola/dist/models/pivot-table-collection.js
init_address_utils();
class PivotTableCollection {
  #workbook;
  #worksheet;
  #items;
  #pivotCaches;
  constructor(options) {
    this.#workbook = options.workbook;
    this.#worksheet = options.worksheet;
    this.#pivotCaches = options.context.pivotCaches;
    this.#items = [];
    if (this.#worksheet) {
      if (!this.#workbook) {
        this.#loadFromWorksheet(this.#worksheet);
      }
    } else if (this.#workbook) {
      for (const worksheet of this.#workbook.worksheets) {
        this.#loadFromWorksheet(worksheet);
      }
    }
  }
  add(name, source, destination) {
    const workbook = this.#resolveWorkbook();
    this.#assertUniqueName(name);
    const sourceInfo = this.#resolveSource(workbook, source);
    const destinationInfo = this.#resolveDestination(workbook, destination, sourceInfo.worksheet);
    const cache = this.#createPivotCache(sourceInfo.headers, sourceInfo.rows, sourceInfo.numFmtIdByFieldIndex, name, sourceInfo.worksheet.name, sourceInfo.address);
    const pivotProto = this.#createPivotTableProto(name, cache.id, destinationInfo.address, sourceInfo.headers, sourceInfo.numFmtIdByFieldIndex);
    destinationInfo.worksheet.__getPivotTables().push(pivotProto);
    const pivotTable = this.#attachPivotTable({
      workbook,
      worksheet: destinationInfo.worksheet,
      cache,
      pivot: pivotProto,
      source: {
        headers: sourceInfo.headers,
        rows: sourceInfo.rows,
        address: sourceInfo.address,
        worksheet: sourceInfo.worksheet
      }
    });
    this.#items.push(pivotTable);
    recomputePivotTable(pivotTable);
    if (this.#worksheet == null || destinationInfo.worksheet !== this.#worksheet) {
      this.#registerWithWorksheetCollection(destinationInfo.worksheet, pivotTable);
    }
    destinationInfo.worksheet.__queueCollaborativePublish();
    return pivotTable;
  }
  getItem(name) {
    const pivot = this.#items.find((item) => item.name === name);
    if (!pivot) {
      throw new Error(`PivotTable ${name} not found`);
    }
    return pivot;
  }
  getItemOrNullObject(name) {
    return this.#items.find((item) => item.name === name) ?? null;
  }
  get items() {
    return [...this.#items];
  }
  reload() {
    this.#items = [];
    if (this.#worksheet) {
      this.#loadFromWorksheet(this.#worksheet);
      return;
    }
    if (this.#workbook) {
      for (const worksheet of this.#workbook.worksheets) {
        this.#loadFromWorksheet(worksheet);
      }
    }
  }
  _registerShared(pivotTable) {
    if (this.#items.includes(pivotTable))
      return;
    pivotTable.addDeleteListener((pivot) => this.#handleDelete(pivot));
    pivotTable.addNameChangeListener((pivot, previous, next) => this.#handleNameChange(pivot, previous, next));
    this.#items.push(pivotTable);
  }
  #resolveWorkbook() {
    if (this.#workbook)
      return this.#workbook;
    if (this.#worksheet?.workbook)
      return this.#worksheet.workbook;
    throw new Error("Workbook context not available");
  }
  #loadFromWorksheet(worksheet) {
    const source = worksheet.__getPivotTables() ?? [];
    for (const pivotProto of source) {
      const cache = this.#findPivotCache(pivotProto.cacheId);
      if (!cache)
        continue;
      const importedSource = this.#resolveImportedSource(worksheet, cache);
      const pivotTable = this.#attachPivotTable({
        workbook: this.#resolveWorkbook(),
        worksheet,
        cache,
        pivot: pivotProto,
        source: importedSource
      });
      this.#items.push(pivotTable);
      if (this.#worksheet == null) {
        this.#registerWithWorksheetCollection(worksheet, pivotTable);
      }
    }
  }
  #resolveImportedSource(pivotWorksheet, cache) {
    const fromCacheMetadata = this.#resolveSourceFromCacheMetadata(cache);
    if (fromCacheMetadata) {
      return fromCacheMetadata;
    }
    const fromTables = this.#resolveSourceFromTables(cache);
    if (fromTables) {
      return fromTables;
    }
    const fallbackHeaders = (cache.fields ?? []).map((field, idx) => field.name ?? `Column${idx + 1}`);
    return {
      headers: fallbackHeaders,
      rows: [],
      address: "",
      worksheet: pivotWorksheet
    };
  }
  #resolveSourceFromCacheMetadata(cache) {
    const reference = cache.worksheetSourceReference?.trim();
    if (!reference)
      return null;
    const workbook = this.#resolveWorkbook();
    const sheetName = cache.worksheetSourceSheet?.trim();
    let worksheet;
    if (sheetName && sheetName.length > 0) {
      try {
        worksheet = workbook.worksheets.getItem(sheetName);
      } catch {
        worksheet = undefined;
      }
    }
    if (!worksheet) {
      worksheet = this.#worksheet ?? workbook.worksheets.getActiveWorksheet() ?? Array.from(workbook.worksheets)[0];
    }
    if (!worksheet)
      return null;
    try {
      const range2 = worksheet.getRange(reference);
      const parsed = parseRangeAddress(range2.address);
      const address = parsed ? parsed.ref : range2.address;
      const extracted = this.#extractHeadersAndRows(range2, address);
      return {
        worksheet,
        address,
        headers: extracted.headers,
        rows: extracted.rows
      };
    } catch {
      return null;
    }
  }
  #resolveSourceFromTables(cache) {
    const expectedHeaders = (cache.fields ?? []).map((field, idx) => field.name ?? `Column${idx + 1}`);
    if (expectedHeaders.length === 0)
      return null;
    const worksheets = this.#getAllWorksheets();
    for (const worksheet of worksheets) {
      const tables = worksheet.__getTables() ?? [];
      for (const table2 of tables) {
        const tableRef = table2.ref?.trim();
        if (!tableRef)
          continue;
        let range2;
        try {
          range2 = worksheet.getRange(tableRef);
        } catch {
          continue;
        }
        const values = range2.values;
        const headerRow = values[0] ?? [];
        if (!this.#headersMatch(expectedHeaders, headerRow)) {
          continue;
        }
        const extracted = this.#extractHeadersAndRows(range2, tableRef);
        return {
          worksheet,
          address: tableRef,
          headers: extracted.headers,
          rows: extracted.rows
        };
      }
    }
    return null;
  }
  hydrateLayouts() {
    for (const pivotTable of this.#items) {
      const source = getPivotSource(pivotTable);
      const dataFields = getPivotTableProto(pivotTable).dataFields ?? [];
      if (source.rows.length === 0 || dataFields.length === 0) {
        this.#hydrateLayoutHintsFromExistingOutput(pivotTable);
        continue;
      }
      recomputePivotTable(pivotTable);
    }
  }
  #hydrateLayoutHintsFromExistingOutput(pivotTable) {
    pivotTable.__clearPivotCellRenderHints();
    const pivotProto = getPivotTableProto(pivotTable);
    const cacheProto = getPivotCacheProto(pivotTable);
    const reference = pivotProto.location?.reference?.trim();
    if (!reference)
      return;
    const parsed = parseRangeAddress(reference);
    if (!parsed)
      return;
    const bounds = parsed.bounds;
    const headerRows = typeof pivotProto.location?.firstDataRow === "number" && pivotProto.location.firstDataRow > 0 ? pivotProto.location.firstDataRow : 1;
    const headerCols = typeof pivotProto.location?.firstDataColumn === "number" && pivotProto.location.firstDataColumn > 0 ? pivotProto.location.firstDataColumn : 1;
    const headerRowEnd = Math.min(bounds.endRow, bounds.startRow + headerRows - 1);
    const labelColumnEnd = Math.min(bounds.endCol, bounds.startCol + headerCols - 1);
    for (let row2 = bounds.startRow;row2 <= headerRowEnd; row2++) {
      for (let col = bounds.startCol;col <= bounds.endCol; col++) {
        pivotTable.__setPivotCellRenderHint(row2, col, {
          type: "headerRow",
          indentLevel: 0
        });
      }
    }
    const worksheet = pivotTable.worksheet;
    const depthByLabel = this.#buildDepthByLabelFromSource(pivotTable);
    const bodyStartRow = headerRowEnd + 1;
    const usedParsed = parseRangeAddress(worksheet.getUsedRange(true).address);
    const scanEndRow = usedParsed ? Math.max(bounds.endRow, usedParsed.bounds.endRow) : bounds.endRow;
    const grandTotalRow = this.#findGrandTotalRow(worksheet, bounds.startCol, bodyStartRow, scanEndRow);
    const layoutEndRow = grandTotalRow != null ? Math.max(bounds.endRow, grandTotalRow) : bounds.endRow;
    const depthByStyleIndex = new Map;
    let nextDepth = 1;
    for (let row2 = bodyStartRow;row2 <= layoutEndRow; row2++) {
      if (grandTotalRow != null && row2 === grandTotalRow) {
        continue;
      }
      const styleIndex = this.#getLabelStyleIndex(worksheet, row2, bounds.startCol);
      if (styleIndex == null || depthByStyleIndex.has(styleIndex)) {
        continue;
      }
      depthByStyleIndex.set(styleIndex, Math.min(nextDepth, 3));
      nextDepth += 1;
    }
    for (let row2 = bodyStartRow;row2 <= layoutEndRow; row2++) {
      if (grandTotalRow != null && row2 === grandTotalRow) {
        for (let col = bounds.startCol;col <= bounds.endCol; col++) {
          pivotTable.__setPivotCellRenderHint(row2, col, {
            type: "totalRow",
            indentLevel: 0
          });
        }
        continue;
      }
      const styleIndex = this.#getLabelStyleIndex(worksheet, row2, bounds.startCol);
      const label = this.#normalizeLabel(worksheet.__getCell(row2, bounds.startCol)?.value);
      const depthFromLabel = label == null ? undefined : depthByLabel.get(label);
      const depth = depthFromLabel ?? (styleIndex != null ? depthByStyleIndex.get(styleIndex) : undefined) ?? 3;
      const rowType = depth <= 1 ? "firstSubtotalRow" : depth === 2 ? "secondRowSubheading" : "wholeTable";
      const indentLevel = Math.max(0, depth - 1);
      for (let col = bounds.startCol;col <= bounds.endCol; col++) {
        pivotTable.__setPivotCellRenderHint(row2, col, {
          type: rowType,
          indentLevel: col <= labelColumnEnd ? indentLevel : 0
        });
      }
    }
    const pageFields = Array.isArray(pivotProto.pageFields) ? pivotProto.pageFields : [];
    if (pageFields.length === 0)
      return;
    const sourceHeaders = getPivotSource(pivotTable).headers;
    const reservedRows = pageFields.length + 1;
    const pageStartRow = Math.max(0, bounds.startRow - reservedRows);
    for (let i = 0;i < pageFields.length; i++) {
      const pageField = pageFields[i];
      const row2 = pageStartRow + i;
      const labelCol = bounds.startCol;
      const valueCol = bounds.startCol + 1;
      const label = this.#resolvePageFieldLabel(pivotProto, cacheProto, pageField?.field, pageField?.name, sourceHeaders);
      const selectedValue = this.#resolvePageFieldSelectedValue(pivotProto, cacheProto, pageField?.field);
      const existingLabel = worksheet.__getCell(row2, labelCol)?.value;
      const existingValue = worksheet.__getCell(row2, valueCol)?.value;
      const labelText = label.length > 0 ? label : existingLabel == null ? "" : String(existingLabel);
      const valueText = selectedValue.length > 0 ? selectedValue : existingValue == null ? "" : String(existingValue);
      worksheet.getRange(makeCellAddress(row2, labelCol)).values = [[labelText]];
      worksheet.getRange(makeCellAddress(row2, valueCol)).values = [[valueText]];
      pivotTable.__setPivotCellRenderHint(row2, labelCol, {
        type: "pageFieldLabels",
        indentLevel: 0
      });
      if (valueCol <= bounds.endCol || valueCol === bounds.startCol + 1) {
        pivotTable.__setPivotCellRenderHint(row2, valueCol, {
          type: "pageFieldValues",
          indentLevel: 0
        });
      }
    }
  }
  #resolvePageFieldLabel(pivotProto, cacheProto, fieldIndex, explicitName, sourceHeaders) {
    const name = explicitName?.trim();
    if (name && name.length > 0)
      return name;
    const resolvedFieldIndex = this.#resolvePageFieldFieldIndex(pivotProto, fieldIndex);
    if (resolvedFieldIndex == null)
      return "";
    const pivotFields = Array.isArray(pivotProto.pivotFields) ? pivotProto.pivotFields : [];
    const pivotField = pivotFields[resolvedFieldIndex];
    const cacheField = cacheProto.fields?.[pivotField?.index ?? resolvedFieldIndex];
    const sourceHeader = sourceHeaders[typeof pivotField?.index === "number" ? pivotField.index : resolvedFieldIndex];
    return this.#pickFirstNonEmptyString(pivotField?.name, cacheField?.name, sourceHeader, `Field ${resolvedFieldIndex + 1}`);
  }
  #resolvePageFieldSelectedValue(pivotProto, cacheProto, fieldIndex) {
    const resolvedFieldIndex = this.#resolvePageFieldFieldIndex(pivotProto, fieldIndex);
    if (resolvedFieldIndex == null)
      return "";
    const filters = Array.isArray(pivotProto.filters) ? pivotProto.filters : [];
    for (const filter of filters) {
      if (filter?.field !== resolvedFieldIndex)
        continue;
      const descriptor = this.#parseFilterDescriptor(filter.description);
      if (!descriptor || descriptor.kind !== "manualFilter")
        continue;
      const selected = descriptor.payload.selectedItems;
      if (Array.isArray(selected) && selected.length > 0) {
        const first = selected[0];
        if (first != null)
          return String(first);
      }
    }
    const pivotFields = Array.isArray(pivotProto.pivotFields) ? pivotProto.pivotFields : [];
    const pivotField = pivotFields[resolvedFieldIndex];
    const pivotItems = Array.isArray(pivotField?.items) ? pivotField.items : [];
    const cacheField = cacheProto.fields?.[pivotField?.index ?? resolvedFieldIndex];
    const sharedValues = cacheField?.sharedItems?.values ?? [];
    for (const item of pivotItems) {
      if (item?.hidden === true)
        continue;
      const itemIndex = item?.index;
      if (typeof itemIndex !== "number" || itemIndex < 0)
        continue;
      const label = this.#sharedItemLabel(sharedValues[itemIndex]);
      if (label != null)
        return label;
    }
    return "";
  }
  #resolvePageFieldFieldIndex(pivotProto, fieldIndex) {
    if (typeof fieldIndex === "number" && fieldIndex >= 0) {
      return fieldIndex;
    }
    const filters = Array.isArray(pivotProto.filters) ? pivotProto.filters : [];
    const filterFieldIndices = new Set;
    for (const filter of filters) {
      if (typeof filter?.field === "number" && filter.field >= 0) {
        filterFieldIndices.add(filter.field);
      }
    }
    if (filterFieldIndices.size === 1) {
      return Array.from(filterFieldIndices)[0];
    }
    return;
  }
  #parseFilterDescriptor(description) {
    const raw = description?.trim();
    if (!raw)
      return null;
    try {
      const parsed = JSON.parse(raw);
      if (parsed.kind === "manualFilter" || parsed.kind === "labelFilter" || parsed.kind === "dateFilter" || parsed.kind === "valueFilter") {
        return parsed;
      }
      return null;
    } catch {
      return null;
    }
  }
  #sharedItemLabel(value) {
    if (value == null)
      return null;
    if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
      return String(value);
    }
    if (typeof value !== "object")
      return null;
    const record2 = value;
    const candidate = this.#pickFirstNonEmptyString(record2["text"], record2["string"], record2["number"] == null ? undefined : String(record2["number"]), record2["datetime"] == null ? undefined : String(record2["datetime"]), record2["dateTime"] == null ? undefined : String(record2["dateTime"]), record2["boolean"] == null ? undefined : String(record2["boolean"]));
    return candidate.length > 0 ? candidate : null;
  }
  #pickFirstNonEmptyString(...candidates) {
    for (const candidate of candidates) {
      const normalized = candidate?.trim();
      if (normalized && normalized.length > 0) {
        return normalized;
      }
    }
    return "";
  }
  #buildDepthByLabelFromSource(pivotTable) {
    const result = new Map;
    const source = getPivotSource(pivotTable);
    if (source.rows.length === 0)
      return result;
    const pivotProto = getPivotTableProto(pivotTable);
    const rowFieldIndices = Array.isArray(pivotProto.rowFields) ? pivotProto.rowFields : [];
    const pivotFields = Array.isArray(pivotProto.pivotFields) ? pivotProto.pivotFields : [];
    if (rowFieldIndices.length === 0)
      return result;
    for (let depth = 0;depth < rowFieldIndices.length; depth++) {
      const pivotFieldIndex = rowFieldIndices[depth];
      if (typeof pivotFieldIndex !== "number" || pivotFieldIndex < 0) {
        continue;
      }
      const pivotField = pivotFields[pivotFieldIndex];
      const headerIndex = pivotField?.index ?? pivotFieldIndex;
      for (const sourceRow of source.rows) {
        const label = this.#normalizeLabel(sourceRow[headerIndex]);
        if (label == null || result.has(label)) {
          continue;
        }
        result.set(label, depth + 1);
      }
    }
    return result;
  }
  #normalizeLabel(value) {
    if (value == null || value === "")
      return null;
    const normalized = String(value).trim().toLowerCase();
    if (normalized.length === 0)
      return null;
    return normalized;
  }
  #findGrandTotalRow(worksheet, labelCol, startRow, endRow) {
    for (let row2 = startRow;row2 <= endRow; row2++) {
      const value = worksheet.__getRawValue(row2, labelCol) ?? worksheet.__getCell(row2, labelCol)?.value;
      if (typeof value === "string" && value.trim().toLowerCase() === "grand total") {
        return row2;
      }
    }
    return null;
  }
  #getLabelStyleIndex(worksheet, row2, col) {
    const logical = worksheet.__getLogicalStyleIndex(row2, col);
    if (typeof logical === "number")
      return logical;
    const cellStyle = worksheet.__getCell(row2, col)?.styleIndex;
    if (typeof cellStyle === "number")
      return cellStyle;
    return;
  }
  #headersMatch(expected, actual) {
    if (expected.length === 0)
      return false;
    if (actual.length < expected.length)
      return false;
    for (let i = 0;i < expected.length; i++) {
      const expectedHeader = expected[i]?.trim().toLowerCase();
      const actualHeader = actual[i] != null && actual[i] !== "" ? String(actual[i]).trim().toLowerCase() : `column${i + 1}`;
      if (expectedHeader !== actualHeader) {
        return false;
      }
    }
    return true;
  }
  #attachPivotTable(options) {
    const pivotTable = getOrCreatePivotTable({
      ...options,
      onDelete: (pivot) => this.#handleDelete(pivot),
      onNameChange: (pivot, previous, next) => this.#handleNameChange(pivot, previous, next)
    });
    return pivotTable;
  }
  #registerWithWorksheetCollection(worksheet, pivotTable) {
    const collection = worksheet.pivotTables;
    if (collection === this)
      return;
    collection._registerShared(pivotTable);
  }
  #handleDelete(pivot) {
    const proto = getPivotTableProto(pivot);
    const pivotTables = pivot.worksheet.__getPivotTables();
    const idx = pivotTables.indexOf(proto);
    if (idx >= 0) {
      pivotTables.splice(idx, 1);
    }
    const cache = getPivotCacheProto(pivot);
    const stillUsed = this.#getAllWorksheets().some((worksheet) => worksheet.__getPivotTables().some((p) => p.cacheId === cache.id && p !== proto));
    if (!stillUsed) {
      const cacheIdx = this.#pivotCaches.indexOf(cache);
      if (cacheIdx >= 0) {
        this.#pivotCaches.splice(cacheIdx, 1);
      }
    }
    this.#items = this.#items.filter((item) => item !== pivot);
  }
  #handleNameChange(pivot, previous, next) {
    if (!previous || previous === next)
      return;
    const duplicates = this.#items.filter((item) => item !== pivot && item.name === next);
    if (duplicates.length > 0) {
      throw new Error(`PivotTable name ${next} already exists`);
    }
  }
  #resolveSource(workbook, source) {
    const resolved = source instanceof Range ? this.#resolveRangeFromInstance(source) : this.#resolveRangeFromString(workbook, source, this.#worksheet);
    const headersAndRows = this.#extractHeadersAndRows(resolved.range, resolved.address);
    return {
      ...resolved,
      headers: headersAndRows.headers,
      rows: headersAndRows.rows,
      numFmtIdByFieldIndex: this.#resolveSourceNumberFormatIds(resolved.worksheet, resolved.address, headersAndRows.headers.length)
    };
  }
  #resolveSourceNumberFormatIds(worksheet, address, fieldCount) {
    const parsed = parseRangeAddress(address);
    if (!parsed) {
      return new Map;
    }
    if (fieldCount <= 0) {
      return new Map;
    }
    const result = new Map;
    const styleRegistry = worksheet.workbook.getStyleRegistry();
    const dataStartRow = parsed.bounds.startRow + 1;
    const dataEndRow = parsed.bounds.endRow;
    for (let fieldIndex = 0;fieldIndex < fieldCount; fieldIndex++) {
      const col = parsed.bounds.startCol + fieldIndex;
      for (let row2 = dataStartRow;row2 <= dataEndRow; row2++) {
        const styleIndex = worksheet.__getLogicalStyleIndex(row2, col) ?? worksheet.__getCell(row2, col)?.styleIndex;
        if (typeof styleIndex !== "number") {
          continue;
        }
        const numberFormatId = styleRegistry.describe(styleIndex).numberFormatId;
        if (typeof numberFormatId === "number" && numberFormatId !== 0) {
          result.set(fieldIndex, numberFormatId);
          break;
        }
      }
    }
    return result;
  }
  #resolveRangeFromInstance(range2) {
    const worksheet = getRangeWorksheet(range2);
    if (!worksheet) {
      throw new Error("Range must belong to a worksheet");
    }
    const parsed = parseRangeAddress(range2.address);
    return {
      worksheet,
      range: range2,
      address: parsed ? parsed.ref : range2.address
    };
  }
  #resolveRangeFromString(workbook, input, fallbackWorksheet) {
    const trimmed = input.trim();
    if (!trimmed) {
      throw new Error("Source range cannot be empty");
    }
    let sheetName;
    let address = trimmed;
    const bang = trimmed.indexOf("!");
    if (bang !== -1) {
      sheetName = trimmed.slice(0, bang);
      address = trimmed.slice(bang + 1);
    }
    const worksheet = sheetName ? workbook.worksheets.getItem(sheetName) : fallbackWorksheet ?? this.#worksheet ?? workbook.worksheets.getActiveWorksheet();
    if (!worksheet) {
      throw new Error("Worksheet not found for source range");
    }
    const range2 = worksheet.getRange(address);
    const parsed = parseRangeAddress(range2.address);
    return {
      worksheet,
      range: range2,
      address: parsed ? parsed.ref : range2.address
    };
  }
  #extractHeadersAndRows(range2, address) {
    const values = range2.values;
    if (values.length === 0) {
      throw new Error(`Source range ${address} is empty`);
    }
    const headersRaw = values[0] ?? [];
    const colCount = headersRaw.length;
    const headers = headersRaw.map((value, idx) => value != null && value !== "" ? String(value) : `Column${idx + 1}`);
    const rows = [];
    for (let i = 1;i < values.length; i++) {
      const row2 = values[i] ?? [];
      const normalized = [];
      let hasValue = false;
      for (let c = 0;c < colCount; c++) {
        const cell = row2[c];
        normalized[c] = cell ?? null;
        if (cell != null && cell !== "") {
          hasValue = true;
        }
      }
      if (hasValue)
        rows.push(normalized);
    }
    return { headers, rows };
  }
  #resolveDestination(workbook, destination, fallbackWorksheet) {
    if (destination instanceof Range) {
      const worksheet2 = getRangeWorksheet(destination);
      if (!worksheet2) {
        throw new Error("Destination range must belong to a worksheet");
      }
      return { worksheet: worksheet2, address: destination.address };
    }
    const targetString = destination?.trim();
    let worksheet = fallbackWorksheet;
    let address = targetString;
    if (targetString) {
      const bang = targetString.indexOf("!");
      if (bang !== -1) {
        const sheetName = targetString.slice(0, bang);
        address = targetString.slice(bang + 1);
        worksheet = workbook.worksheets.getItem(sheetName);
      }
    }
    if (!worksheet) {
      worksheet = this.#worksheet ?? workbook.worksheets.getActiveWorksheet();
    }
    if (!worksheet) {
      throw new Error("Unable to determine destination worksheet");
    }
    const cellAddress = address && address.length > 0 ? address : "A1";
    const parsed = parseRangeAddress(cellAddress);
    if (!parsed) {
      throw new Error(`Invalid destination address: ${cellAddress}`);
    }
    return { worksheet, address: parsed.ref };
  }
  #createPivotCache(headers, rows, numFmtIdByFieldIndex, name, sourceSheet, sourceAddress) {
    const id2 = this.#nextPivotCacheId();
    const cache = PivotCacheDefinition.createFromSource({
      id: id2,
      name: `${name} Cache`,
      headers,
      rows
    }).toProto();
    const fields = cache.fields ?? [];
    for (let index = 0;index < fields.length; index++) {
      const field = fields[index];
      if (!field)
        continue;
      const numFmtId = numFmtIdByFieldIndex.get(index);
      if (typeof numFmtId === "number") {
        field.numFmtId = numFmtId;
      }
    }
    cache.worksheetSourceSheet = sourceSheet;
    cache.worksheetSourceReference = sourceAddress;
    cache.recordCount = rows.length;
    this.#pivotCaches.push(cache);
    return cache;
  }
  #createPivotTableProto(name, cacheId, destinationRef, headers, numFmtIdByFieldIndex) {
    const pivotFields = headers.map((header, index) => ({
      index,
      name: header,
      axis: undefined,
      dataField: false,
      showAll: true,
      subtotalTop: true,
      items: [],
      numberFormatId: numFmtIdByFieldIndex.get(index),
      sortType: undefined,
      axisEnum: undefined,
      sortTypeEnum: undefined
    }));
    return {
      name,
      cacheId,
      location: {
        reference: destinationRef,
        firstHeaderRow: 0,
        firstDataRow: 1,
        firstHeaderColumn: 0,
        firstDataColumn: 0
      },
      dataOnRows: false,
      rowGrandTotals: true,
      columnGrandTotals: true,
      pivotFields,
      rowFields: [],
      columnFields: [],
      pageFields: [],
      dataFields: [],
      filters: [],
      compact: true,
      outline: false,
      showDrill: true,
      styleName: undefined,
      rowItems: [],
      columnItems: [],
      showRowHeaders: true,
      showColHeaders: true,
      showRowStripes: false,
      showColStripes: false,
      showLastColumn: false
    };
  }
  #nextPivotCacheId() {
    let maxId = 0;
    for (const cache of this.#pivotCaches) {
      if (cache.id > maxId)
        maxId = cache.id;
    }
    return maxId + 1;
  }
  #findPivotCache(cacheId) {
    return this.#pivotCaches.find((cache) => cache.id === cacheId);
  }
  #assertUniqueName(name) {
    const exists = this.#getAllWorksheets().some((worksheet) => worksheet.__getPivotTables().some((pivot) => pivot.name === name));
    if (exists) {
      throw new Error(`PivotTable ${name} already exists`);
    }
  }
  #getAllWorksheets() {
    if (this.#worksheet) {
      return [this.#worksheet];
    }
    if (this.#workbook) {
      return Array.from(this.#workbook.worksheets);
    }
    return [];
  }
}
// node_modules/@oai/granola/dist/models/presentation/bounding-box.js
class BoundingBox2 {
  #data;
  constructor(_context, proto) {
    this.#data = {
      xEmu: proto?.xEmu ?? 0,
      yEmu: proto?.yEmu ?? 0,
      widthEmu: proto?.widthEmu ?? 0,
      heightEmu: proto?.heightEmu ?? 0,
      rotation: proto?.rotation ?? 0,
      horizontalFlip: proto?.horizontalFlip ?? false,
      verticalFlip: proto?.verticalFlip ?? false
    };
  }
  toProto() {
    return {
      xEmu: this.#data.xEmu,
      yEmu: this.#data.yEmu,
      widthEmu: this.#data.widthEmu,
      heightEmu: this.#data.heightEmu,
      rotation: this.#data.rotation,
      horizontalFlip: this.#data.horizontalFlip,
      verticalFlip: this.#data.verticalFlip
    };
  }
}
// node_modules/yaml/dist/index.js
var composer = require_composer();
var Document = require_Document();
var Schema = require_Schema();
var errors3 = require_errors();
var Alias = require_Alias();
var identity3 = require_identity();
var Pair2 = require_Pair();
var Scalar = require_Scalar();
var YAMLMap = require_YAMLMap();
var YAMLSeq = require_YAMLSeq();
var cst = require_cst();
var lexer = require_lexer();
var lineCounter = require_line_counter();
var parser = require_parser();
var publicApi = require_public_api();
var visit = require_visit();
var $Composer = composer.Composer;
var $Document = Document.Document;
var $Schema = Schema.Schema;
var $YAMLError = errors3.YAMLError;
var $YAMLParseError = errors3.YAMLParseError;
var $YAMLWarning = errors3.YAMLWarning;
var $Alias = Alias.Alias;
var $isAlias = identity3.isAlias;
var $isCollection = identity3.isCollection;
var $isDocument = identity3.isDocument;
var $isMap = identity3.isMap;
var $isNode = identity3.isNode;
var $isPair = identity3.isPair;
var $isScalar = identity3.isScalar;
var $isSeq = identity3.isSeq;
var $Pair = Pair2.Pair;
var $Scalar = Scalar.Scalar;
var $YAMLMap = YAMLMap.YAMLMap;
var $YAMLSeq = YAMLSeq.YAMLSeq;
var $Lexer = lexer.Lexer;
var $LineCounter = lineCounter.LineCounter;
var $Parser = parser.Parser;
var $parse = publicApi.parse;
var $parseAllDocuments = publicApi.parseAllDocuments;
var $parseDocument = publicApi.parseDocument;
var $stringify = publicApi.stringify;
var $visit = visit.visit;
var $visitAsync = visit.visitAsync;

// node_modules/@oai/granola/dist/models/presentation/c-star-mini.js
init_address_utils();

// node_modules/@oai/granola/dist/models/slicer.js
var SLICER_META_KEY = "__granolaSlicerMeta";
var SLICER_PROTO = new WeakMap;
var SLICER_WORKSHEET = new WeakMap;
var SLICER_PIVOT_TABLE = new WeakMap;
var SLICER_FIELD = new WeakMap;
var SLICER_DELETE_LISTENERS = new WeakMap;
var SLICER_NAME_CHANGE_LISTENERS = new WeakMap;

class Slicer2 {
  constructor(proto, options) {
    SLICER_PROTO.set(this, proto);
    SLICER_WORKSHEET.set(this, options.worksheet);
    SLICER_PIVOT_TABLE.set(this, options.pivotTable);
    SLICER_FIELD.set(this, options.field);
    SLICER_DELETE_LISTENERS.set(this, new Set);
    SLICER_NAME_CHANGE_LISTENERS.set(this, new Set);
    if (options.onDelete)
      this.addDeleteListener(options.onDelete);
    if (options.onNameChange)
      this.addNameChangeListener(options.onNameChange);
  }
  get name() {
    return this.#proto().name ?? "";
  }
  set name(value) {
    const proto = this.#proto();
    const previous = proto.name || undefined;
    proto.name = value;
    this.#worksheet().__queueCollaborativePublish();
    this.#notifyNameChange(previous, value);
  }
  get caption() {
    return this.#proto().caption ?? "";
  }
  set caption(value) {
    this.#proto().caption = value;
    this.#worksheet().__queueCollaborativePublish();
  }
  get left() {
    return 0;
  }
  set left(_value) {}
  get top() {
    return 0;
  }
  set top(_value) {}
  get height() {
    return this.#proto().height ?? 0;
  }
  set height(value) {
    this.#proto().height = value;
    this.#worksheet().__queueCollaborativePublish();
  }
  get width() {
    return this.#proto().width ?? 0;
  }
  set width(value) {
    this.#proto().width = value;
    this.#worksheet().__queueCollaborativePublish();
  }
  get style() {
    return this.#proto().style ?? "";
  }
  set style(value) {
    this.#proto().style = value;
    this.#worksheet().__queueCollaborativePublish();
  }
  selectItems(items) {
    const field = this.#field();
    field.applyFilter({ manualFilter: { selectedItems: items } });
    getSlicerMeta(this.#proto()).selectedItems = [...items];
    this.#worksheet().__queueCollaborativePublish();
    recomputePivotTable(this.#pivotTable());
  }
  clearFilters() {
    this.#field().clearAllFilters();
    getSlicerMeta(this.#proto()).selectedItems = [];
    this.#worksheet().__queueCollaborativePublish();
    recomputePivotTable(this.#pivotTable());
  }
  delete() {
    const proto = this.#proto();
    const worksheet = this.#worksheet();
    const slicers = worksheet.__getSlicers();
    const idx = slicers.indexOf(proto);
    if (idx >= 0) {
      slicers.splice(idx, 1);
    }
    worksheet.__queueCollaborativePublish();
    this.#notifyDelete();
  }
  addDeleteListener(listener) {
    SLICER_DELETE_LISTENERS.get(this)?.add(listener);
  }
  removeDeleteListener(listener) {
    SLICER_DELETE_LISTENERS.get(this)?.delete(listener);
  }
  addNameChangeListener(listener) {
    SLICER_NAME_CHANGE_LISTENERS.get(this)?.add(listener);
  }
  removeNameChangeListener(listener) {
    SLICER_NAME_CHANGE_LISTENERS.get(this)?.delete(listener);
  }
  #proto() {
    const proto = SLICER_PROTO.get(this);
    if (!proto) {
      throw new Error("Slicer proto not found");
    }
    return proto;
  }
  #worksheet() {
    const worksheet = SLICER_WORKSHEET.get(this);
    if (!worksheet) {
      throw new Error("Slicer worksheet not found");
    }
    return worksheet;
  }
  #pivotTable() {
    const pivotTable = SLICER_PIVOT_TABLE.get(this);
    if (!pivotTable) {
      throw new Error("Slicer pivot table not found");
    }
    return pivotTable;
  }
  #field() {
    const field = SLICER_FIELD.get(this);
    if (!field) {
      throw new Error("Slicer pivot field not found");
    }
    return field;
  }
  #notifyDelete() {
    const listeners = SLICER_DELETE_LISTENERS.get(this);
    if (!listeners)
      return;
    for (const listener of listeners)
      listener(this);
  }
  #notifyNameChange(previous, next) {
    const listeners = SLICER_NAME_CHANGE_LISTENERS.get(this);
    if (!listeners)
      return;
    for (const listener of listeners)
      listener(this, previous, next);
  }
}
function getSlicerMeta(proto) {
  if (!proto[SLICER_META_KEY]) {
    proto[SLICER_META_KEY] = {
      pivotTableName: "",
      fieldName: "",
      selectedItems: []
    };
  }
  return proto[SLICER_META_KEY];
}
function getSlicerProto(slicer) {
  const proto = SLICER_PROTO.get(slicer);
  if (!proto) {
    throw new Error("Slicer proto not found");
  }
  return proto;
}

// node_modules/@oai/granola/dist/models/slicer-collection.js
class SlicerCollection {
  #workbook;
  #worksheet;
  #items;
  #slicerCaches;
  constructor(options) {
    this.#workbook = options.workbook;
    this.#worksheet = options.worksheet;
    this.#slicerCaches = options.context.slicerCaches;
    this.#items = [];
    if (this.#worksheet) {
      this.#loadFromWorksheet(this.#worksheet);
    } else if (this.#workbook) {
      for (const worksheet of this.#workbook.worksheets) {
        this.#loadFromWorksheet(worksheet);
      }
    }
  }
  add(pivotTableName, fieldName) {
    const workbook = this.#resolveWorkbook();
    const pivotTable = workbook.pivotTables.getItem(pivotTableName);
    const hierarchy2 = pivotTable.hierarchies.getItem(fieldName);
    const field = hierarchy2.fields.getItem(fieldName);
    const worksheet = this.#worksheet ?? pivotTable.worksheet;
    const slicerProto = this.#createSlicerProto(pivotTableName, fieldName);
    worksheet.__getSlicers().push(slicerProto);
    const slicer = new Slicer2(slicerProto, {
      workbook,
      worksheet,
      pivotTable,
      field,
      onDelete: (target) => this.#handleDelete(target),
      onNameChange: (target, previous, next) => this.#handleNameChange(target, previous, next)
    });
    this.#items.push(slicer);
    const workbookCollection = workbook.slicers;
    if (this !== workbookCollection) {
      workbookCollection._registerShared(slicer);
    }
    const worksheetCollection = worksheet.slicers;
    if (this !== worksheetCollection) {
      worksheetCollection._registerShared(slicer);
    }
    worksheet.__queueCollaborativePublish();
    return slicer;
  }
  getItem(name) {
    const slicer = this.#items.find((candidate) => candidate.name === name);
    if (!slicer) {
      throw new Error(`Slicer ${name} not found`);
    }
    return slicer;
  }
  getItemAt(index) {
    const slicer = this.#items[index];
    if (!slicer) {
      throw new Error(`Slicer at index ${index} not found`);
    }
    return slicer;
  }
  get items() {
    return [...this.#items];
  }
  reload() {
    this.#items = [];
    if (this.#worksheet) {
      this.#loadFromWorksheet(this.#worksheet);
      return;
    }
    if (this.#workbook) {
      for (const worksheet of this.#workbook.worksheets) {
        this.#loadFromWorksheet(worksheet);
      }
    }
  }
  synthesizeCaches() {
    for (const slicer of this.#items) {
      const proto = getSlicerProto(slicer);
      const meta3 = getSlicerMeta(proto);
      const fieldName = meta3.fieldName || proto.caption || proto.name || "Field";
      const cacheName = proto.cache || `${meta3.pivotTableName}_${fieldName}_cache`;
      proto.cache = cacheName;
      let cache = this.#slicerCaches.find((candidate) => candidate.name === cacheName);
      if (!cache) {
        cache = {
          name: cacheName,
          caption: proto.caption ?? fieldName,
          type: "pivot",
          pivotCacheId: undefined,
          pivotTableIds: [],
          sourceName: fieldName,
          tableId: undefined,
          tableName: undefined,
          columnName: fieldName,
          crossFilter: undefined,
          sortOrder: undefined,
          items: []
        };
        this.#slicerCaches.push(cache);
      }
      proto.cacheId = this.#slicerCaches.findIndex((candidate) => candidate === cache) + 1;
      cache.caption = proto.caption ?? fieldName;
      cache.sourceName = fieldName;
      cache.columnName = fieldName;
      cache.items = cache.items ?? [];
    }
  }
  _registerShared(slicer) {
    if (this.#items.includes(slicer))
      return;
    slicer.addDeleteListener((target) => this.#handleDelete(target));
    slicer.addNameChangeListener((target, previous, next) => this.#handleNameChange(target, previous, next));
    this.#items.push(slicer);
  }
  #resolveWorkbook() {
    if (this.#workbook)
      return this.#workbook;
    if (this.#worksheet?.workbook)
      return this.#worksheet.workbook;
    throw new Error("Workbook context not available");
  }
  #loadFromWorksheet(worksheet) {
    const slicers = worksheet.__getSlicers() ?? [];
    for (const slicerProto of slicers) {
      const meta3 = getSlicerMeta(slicerProto);
      const workbook = this.#resolveWorkbook();
      let pivotTable;
      try {
        pivotTable = workbook.pivotTables.getItem(meta3.pivotTableName);
      } catch {
        continue;
      }
      const hierarchy2 = pivotTable.hierarchies.getItem(meta3.fieldName);
      const field = hierarchy2.fields.getItem(meta3.fieldName);
      const slicer = new Slicer2(slicerProto, {
        workbook,
        worksheet,
        pivotTable,
        field,
        onDelete: (target) => this.#handleDelete(target),
        onNameChange: (target, previous, next) => this.#handleNameChange(target, previous, next)
      });
      this.#items.push(slicer);
    }
  }
  #createSlicerProto(pivotTableName, fieldName) {
    const cacheName = `${pivotTableName}_${fieldName}_cache`;
    let cacheIndex = this.#slicerCaches.findIndex((cache) => cache.name === cacheName);
    if (cacheIndex === -1) {
      this.#slicerCaches.push({
        name: cacheName,
        caption: fieldName,
        type: "pivot",
        pivotCacheId: undefined,
        pivotTableIds: [],
        sourceName: fieldName,
        tableId: undefined,
        tableName: undefined,
        columnName: fieldName,
        crossFilter: undefined,
        sortOrder: undefined,
        items: []
      });
      cacheIndex = this.#slicerCaches.length - 1;
    }
    const cacheId = cacheIndex + 1;
    const uniqueName = this.#generateUniqueName(fieldName);
    const slicer = {
      name: uniqueName,
      caption: fieldName,
      cache: cacheName,
      lockedPosition: false,
      displayHeader: true,
      showNoDataItems: false,
      sortBy: undefined,
      style: undefined,
      fromAnchor: undefined,
      toAnchor: undefined,
      cacheId,
      width: undefined,
      height: undefined
    };
    const meta3 = getSlicerMeta(slicer);
    meta3.pivotTableName = pivotTableName;
    meta3.fieldName = fieldName;
    meta3.selectedItems = [];
    return slicer;
  }
  #generateUniqueName(base) {
    let counter = 1;
    let candidate = base;
    while (this.#items.some((item) => item.name === candidate)) {
      counter += 1;
      candidate = `${base}_${counter}`;
    }
    return candidate;
  }
  #handleDelete(slicer) {
    this.#items = this.#items.filter((candidate) => candidate !== slicer);
  }
  #handleNameChange(slicer, previous, next) {
    if (!previous || previous === next)
      return;
    const duplicate = this.#items.some((candidate) => candidate !== slicer && candidate.name === next);
    if (duplicate) {
      throw new Error(`Slicer name ${next} already exists`);
    }
  }
}

// node_modules/@oai/granola/dist/logger.js
var NAMESPACES = ["validation", "calculation", "creation"];
var DEFAULT_ENABLED = ["validation"];
var enabledNamespaces = new Set(DEFAULT_ENABLED);
var levelToConsole = {
  debug: "debug",
  info: "info",
  warn: "warn",
  error: "error"
};
function writeLog(level, namespace, message, ...rest) {
  if (!enabledNamespaces.has(namespace)) {
    return;
  }
  const method = levelToConsole[level];
  const candidate = console[method];
  const writer = typeof candidate === "function" ? candidate : console.log.bind(console);
  const prefix = `[granola:${namespace}]`;
  writer(prefix, message, ...rest);
}
var logger = {
  enable(namespace) {
    enabledNamespaces.add(namespace);
  },
  disable(namespace) {
    enabledNamespaces.delete(namespace);
  },
  isEnabled(namespace) {
    return enabledNamespaces.has(namespace);
  },
  debug(namespace, message, ...rest) {
    writeLog("debug", namespace, message, ...rest);
  },
  info(namespace, message, ...rest) {
    writeLog("info", namespace, message, ...rest);
  },
  warn(namespace, message, ...rest) {
    writeLog("warn", namespace, message, ...rest);
  },
  error(namespace, message, ...rest) {
    writeLog("error", namespace, message, ...rest);
  },
  namespaces: [...NAMESPACES]
};

// node_modules/@oai/granola/dist/models/table-collection.js
init_address_utils();

// node_modules/@oai/granola/dist/models/table.js
init_address_utils();

// node_modules/@oai/granola/dist/models/spreadsheet/table-metadata.js
function getEffectiveTableHeaderRowCount(table2) {
  if (table2.headerRowCount === 0) {
    return 0;
  }
  return 1;
}
function getEffectiveTableTotalsRowCount(table2) {
  if (table2.totalsRowCount === 0) {
    return 0;
  }
  if (typeof table2.totalsRowCount === "number") {
    return 1;
  }
  return table2.totalsRowShown ? 1 : 0;
}

// node_modules/@oai/granola/dist/models/table.js
var TABLE_PROTO = new WeakMap;
var DEFAULT_TABLE_STYLE_NAME = "TableStyleMedium2";
function createDefaultTableStyle(name = DEFAULT_TABLE_STYLE_NAME) {
  return {
    name,
    showFirstColumn: false,
    showLastColumn: false,
    showRowStripes: true,
    showColumnStripes: false
  };
}

class Table3 {
  #worksheet;
  #rows;
  #onNameChange;
  #onDelete;
  #hasHeaders;
  #headerRowCount;
  #startRow;
  #startCol;
  #colCount;
  #rowCount;
  constructor(worksheet, table2, options = {}) {
    this.#worksheet = worksheet;
    TABLE_PROTO.set(this, table2);
    this.#onNameChange = options.onNameChange;
    this.#onDelete = options.onDelete;
    this.#hasHeaders = options.hasHeaders ?? getEffectiveTableHeaderRowCount(table2) > 0;
    this.#headerRowCount = this.#hasHeaders ? 1 : 0;
    this.#rows = new TableRowCollection(this);
    const parsed = parseRangeAddress(table2.ref);
    if (parsed) {
      this.#startRow = parsed.bounds.startRow;
      this.#startCol = parsed.bounds.startCol;
      const size2 = boundsDimensions(parsed.bounds);
      this.#colCount = size2.cols;
      this.#rowCount = size2.rows - this.#headerRowCount;
    } else {
      this.#startRow = 0;
      this.#startCol = 0;
      this.#colCount = 0;
      this.#rowCount = 0;
    }
  }
  get isNullObject() {
    return false;
  }
  get worksheet() {
    return this.#worksheet;
  }
  get hasHeaders() {
    return this.#hasHeaders;
  }
  get showHeaders() {
    return this.#hasHeaders;
  }
  set showHeaders(value) {
    this.writeShowHeaders(value);
  }
  writeShowHeaders(value, options = {}) {
    if (this.#hasHeaders === value) {
      return;
    }
    const proto = this.#proto();
    this.#hasHeaders = value;
    this.#headerRowCount = value ? 1 : 0;
    proto.headerRowCount = this.#headerRowCount;
    if (!value) {
      proto.autoFilter = undefined;
    } else {
      this.syncColumnsFromSheet();
    }
    this.refreshBounds();
    if (options.record ?? true) {
      this.#recordSet({ showHeaders: value });
    }
  }
  get name() {
    const proto = this.#proto();
    return proto.name ?? "";
  }
  set name(value) {
    this.writeName(value);
  }
  writeName(value, options = {}) {
    const shouldRecord = options.record ?? true;
    const proto = this.#proto();
    const previous = proto.name || undefined;
    if (previous === value) {
      return;
    }
    proto.name = value;
    proto.displayName = value;
    this.#onNameChange?.(this, previous, value);
    if (!shouldRecord) {
      return;
    }
    this.#recordSet({ name: value }, previous ?? value);
  }
  get address() {
    return this.#proto().ref;
  }
  get style() {
    return this.#proto().style?.name ?? DEFAULT_TABLE_STYLE_NAME;
  }
  set style(value) {
    this.writeStyle(value);
  }
  writeStyle(value, options = {}) {
    const nextName = normalizeTableStyleName(value) ?? value.trim();
    if (!nextName) {
      return;
    }
    const style = this.#ensureStyle();
    if (style.name === nextName) {
      return;
    }
    style.name = nextName;
    if (options.record ?? true) {
      this.#recordSet({ style: nextName });
    }
  }
  get showTotals() {
    return getEffectiveTableTotalsRowCount(this.#proto()) > 0;
  }
  set showTotals(value) {
    this.writeShowTotals(value);
  }
  writeShowTotals(value, options = {}) {
    if (this.showTotals === value) {
      return;
    }
    const proto = this.#proto();
    proto.totalsRowShown = value;
    proto.totalsRowCount = value ? 1 : 0;
    if (options.record ?? true) {
      this.#recordSet({ showTotals: value });
    }
  }
  get showBandedRows() {
    return this.#proto().style?.showRowStripes ?? true;
  }
  set showBandedRows(value) {
    this.writeShowBandedRows(value);
  }
  writeShowBandedRows(value, options = {}) {
    const style = this.#ensureStyle();
    if (style.showRowStripes === value) {
      return;
    }
    style.showRowStripes = value;
    if (options.record ?? true) {
      this.#recordSet({ showBandedRows: value });
    }
  }
  get highlightFirstColumn() {
    return this.#proto().style?.showFirstColumn ?? false;
  }
  set highlightFirstColumn(value) {
    this.writeHighlightFirstColumn(value);
  }
  writeHighlightFirstColumn(value, options = {}) {
    const style = this.#ensureStyle();
    if (style.showFirstColumn === value) {
      return;
    }
    style.showFirstColumn = value;
    if (options.record ?? true) {
      this.#recordSet({ highlightFirstColumn: value });
    }
  }
  get highlightLastColumn() {
    return this.#proto().style?.showLastColumn ?? false;
  }
  set highlightLastColumn(value) {
    this.writeHighlightLastColumn(value);
  }
  writeHighlightLastColumn(value, options = {}) {
    const style = this.#ensureStyle();
    if (style.showLastColumn === value) {
      return;
    }
    style.showLastColumn = value;
    if (options.record ?? true) {
      this.#recordSet({ highlightLastColumn: value });
    }
  }
  get showBandedColumns() {
    return this.#proto().style?.showColumnStripes ?? false;
  }
  set showBandedColumns(value) {
    this.writeShowBandedColumns(value);
  }
  writeShowBandedColumns(value, options = {}) {
    const style = this.#ensureStyle();
    if (style.showColumnStripes === value) {
      return;
    }
    style.showColumnStripes = value;
    if (options.record ?? true) {
      this.#recordSet({ showBandedColumns: value });
    }
  }
  get showFilterButton() {
    return this.#hasHeaders && this.#proto().autoFilter !== undefined;
  }
  set showFilterButton(value) {
    this.writeShowFilterButton(value);
  }
  writeShowFilterButton(value, options = {}) {
    if (value && !this.#hasHeaders) {
      throw new Error("Filter buttons require the table to have a header row.");
    }
    if (this.showFilterButton === value) {
      return;
    }
    const proto = this.#proto();
    proto.autoFilter = value ? {
      ref: proto.ref,
      columns: []
    } : undefined;
    if (options.record ?? true) {
      this.#recordSet({ showFilterButton: value });
    }
  }
  getRange() {
    this.refreshBounds();
    return this.#worksheet.getRange(this.address);
  }
  getHeaderRowRange() {
    const headerRow = this.#startRow;
    return this.#worksheet.getRange(this.#rangeAddress(headerRow, headerRow));
  }
  get rows() {
    return this.#rows;
  }
  delete() {
    const recorder = this.#worksheet.workbook.getRecorder();
    if (recorder) {
      const op = {
        op: "table.remove",
        target: {
          name: this.name,
          sheet: this.#worksheet.name
        }
      };
      recorder.record(op);
    }
    this.#onDelete?.(this);
  }
  appendRows(values) {
    if (!values.length)
      return;
    this.refreshBounds();
    if (this.#colCount === 0) {
      this.#colCount = values[0]?.length ?? 0;
    }
    const dataStart = this.#startRow + this.#headerRowCount + this.#rowCount;
    const dataEnd = dataStart + values.length - 1;
    const address = this.#rangeAddress(dataStart, dataEnd);
    const normalized = values.map((row2) => this.#normalizeRow(row2));
    const recorder = this.#worksheet.workbook.getRecorder();
    this.#worksheet.getRange(address).writeValues(normalized, { record: false });
    this.#rowCount += values.length;
    this.#updateRef();
    this.syncColumnsFromSheet();
    if (recorder) {
      const recordedValues = normalized.map((row2) => row2.map((cell) => serializeTableCellValue(cell)));
      const op = {
        op: "table.rows.add",
        target: {
          name: this.name,
          sheet: this.#worksheet.name
        },
        props: {
          index: null,
          values: recordedValues
        }
      };
      recorder.record(op);
    }
  }
  getDataRows() {
    this.refreshBounds();
    if (this.#rowCount <= 0)
      return [];
    const dataStart = this.#startRow + this.#headerRowCount;
    const dataEnd = dataStart + this.#rowCount - 1;
    const range2 = this.#worksheet.getRange(this.#rangeAddress(dataStart, dataEnd));
    return range2.values;
  }
  #proto() {
    const proto = TABLE_PROTO.get(this);
    if (!proto) {
      throw new Error("Table proto not found");
    }
    return proto;
  }
  refreshBounds() {
    const parsed = parseRangeAddress(this.#proto().ref);
    if (!parsed)
      return;
    const size2 = boundsDimensions(parsed.bounds);
    this.#startRow = parsed.bounds.startRow;
    this.#startCol = parsed.bounds.startCol;
    this.#colCount = size2.cols;
    this.#rowCount = size2.rows - this.#headerRowCount;
  }
  #rangeAddress(rowStart, rowEnd) {
    const startBounds = {
      startRow: rowStart,
      endRow: rowEnd,
      startCol: this.#startCol,
      endCol: this.#startCol + Math.max(0, this.#colCount - 1)
    };
    return buildRangeRef(startBounds);
  }
  #normalizeRow(row2) {
    const normalized = [];
    for (let c = 0;c < this.#colCount; c++) {
      normalized[c] = row2?.[c] ?? null;
    }
    return normalized;
  }
  #updateRef() {
    const proto = this.#proto();
    const endRow = this.#startRow + this.#headerRowCount + Math.max(0, this.#rowCount) - 1;
    const bounds = {
      startRow: this.#startRow,
      startCol: this.#startCol,
      endRow: Math.max(this.#startRow, endRow),
      endCol: this.#startCol + Math.max(0, this.#colCount - 1)
    };
    proto.ref = buildRangeRef(bounds);
    proto.headerRowCount = this.#headerRowCount;
    proto.totalsRowCount = proto.totalsRowCount ?? 0;
    if (proto.autoFilter) {
      proto.autoFilter.ref = proto.ref;
    }
  }
  syncColumnsFromSheet() {
    const proto = this.#proto();
    const headerValues = this.#hasHeaders ? this.getHeaderRowRange().values?.[0] ?? [] : [];
    const columns = [];
    for (let i = 0;i < this.#colCount; i++) {
      const header = headerValues?.[i];
      columns.push({
        id: i + 1,
        name: header != null && header !== "" ? String(header) : `Column${i + 1}`,
        totalsRowLabel: undefined,
        totalsRowFunction: undefined,
        dataDxfId: undefined
      });
    }
    proto.columns = columns;
  }
  #ensureStyle() {
    const proto = this.#proto();
    if (!proto.style) {
      proto.style = createDefaultTableStyle();
    }
    return proto.style;
  }
  #recordSet(props, targetName = this.name) {
    const recorder = this.#worksheet.workbook.getRecorder();
    if (!recorder || Object.keys(props).length === 0) {
      return;
    }
    const op = {
      op: "table.set",
      target: {
        name: targetName,
        sheet: this.#worksheet.name
      },
      props
    };
    recorder.record(op);
  }
}
var buildNullTableProto = (name) => ({
  id: -1,
  name,
  displayName: name,
  ref: "A1",
  columns: [],
  headerRowCount: 0,
  totalsRowCount: 0,
  totalsRowShown: false
});

class NullTable extends Table3 {
  #missingName;
  constructor(worksheet, name) {
    super(worksheet, buildNullTableProto(name));
    this.#missingName = name;
  }
  get isNullObject() {
    return true;
  }
  get worksheet() {
    return this.#throwMissing();
  }
  get hasHeaders() {
    return this.#throwMissing();
  }
  get showHeaders() {
    return this.#throwMissing();
  }
  set showHeaders(_value) {
    this.#throwMissing();
  }
  get name() {
    return this.#missingName || "Unknown";
  }
  set name(_value) {
    this.#throwMissing();
  }
  get address() {
    return "";
  }
  get style() {
    return this.#throwMissing();
  }
  set style(_value) {
    this.#throwMissing();
  }
  get showTotals() {
    return this.#throwMissing();
  }
  set showTotals(_value) {
    this.#throwMissing();
  }
  get showBandedRows() {
    return this.#throwMissing();
  }
  set showBandedRows(_value) {
    this.#throwMissing();
  }
  get highlightFirstColumn() {
    return this.#throwMissing();
  }
  set highlightFirstColumn(_value) {
    this.#throwMissing();
  }
  get highlightLastColumn() {
    return this.#throwMissing();
  }
  set highlightLastColumn(_value) {
    this.#throwMissing();
  }
  get showBandedColumns() {
    return this.#throwMissing();
  }
  set showBandedColumns(_value) {
    this.#throwMissing();
  }
  get showFilterButton() {
    return this.#throwMissing();
  }
  set showFilterButton(_value) {
    this.#throwMissing();
  }
  getRange() {
    return this.#throwMissing();
  }
  getHeaderRowRange() {
    return this.#throwMissing();
  }
  get rows() {
    return this.#throwMissing();
  }
  delete() {
    this.#throwMissing();
  }
  appendRows(_values) {
    this.#throwMissing();
  }
  getDataRows() {
    return this.#throwMissing();
  }
  #throwMissing() {
    const label = this.#missingName || "Unknown";
    throw new Error(`Table "${label}" not found.`);
  }
}

class TableRowCollection {
  #table;
  constructor(table2) {
    this.#table = table2;
  }
  add(index, values) {
    if (index != null) {
      throw new Error("Inserting table rows at a specific index is not supported yet");
    }
    this.#table.appendRows(values);
  }
  get items() {
    const rows = this.#table.getDataRows();
    return rows.map((row2) => [row2]);
  }
}
function getTableProto(table2) {
  const proto = TABLE_PROTO.get(table2);
  if (!proto) {
    throw new Error("Table proto not found");
  }
  return proto;
}
function serializeTableCellValue(value) {
  if (value instanceof Date) {
    return value.toISOString();
  }
  return value ?? null;
}

// node_modules/@oai/granola/dist/models/table-collection.js
var DEFAULT_TABLE_STYLE = {
  name: "TableStyleMedium2",
  showFirstColumn: false,
  showLastColumn: false,
  showRowStripes: true,
  showColumnStripes: false
};
function createDefaultTableStyle2() {
  return { ...DEFAULT_TABLE_STYLE };
}

class TableCollection {
  #worksheet;
  #tables;
  #tableMap;
  constructor(worksheet) {
    this.#worksheet = worksheet;
    this.#tableMap = new Map;
    const tableProtos = this.#worksheet.__getTables();
    this.#tables = tableProtos.map((tableProto) => this.#createTableWrapper(tableProto, {
      hasHeaders: getEffectiveTableHeaderRowCount(tableProto) > 0
    }));
    for (const table2 of this.#tables) {
      const name = table2.name;
      if (name) {
        this.#tableMap.set(name, table2);
      }
    }
  }
  add(addressOrRange, hasHeaders, name) {
    const tableProtos = this.#worksheet.__getTables();
    const address = resolveTableAddressInput(addressOrRange);
    const parsed = parseRangeAddress(address);
    if (!parsed) {
      throw new Error(`Invalid table address: ${address}`);
    }
    assertHeaderRowHasNoFormulas(this.#worksheet, parsed, hasHeaders);
    const protoTable = {
      id: this.#nextTableId(),
      name: "",
      displayName: "",
      ref: parsed.ref,
      columns: [],
      style: undefined,
      totalsRowShown: false,
      headerRowCount: hasHeaders ? 1 : 0,
      totalsRowCount: 0,
      autoFilter: undefined,
      dataDxfId: undefined,
      headerRowCellStyle: undefined
    };
    protoTable.style = createDefaultTableStyle2();
    tableProtos.push(protoTable);
    const table2 = this.#createTableWrapper(protoTable, { hasHeaders });
    if (name) {
      table2.writeName(name, { record: false });
    } else {
      table2.writeName(this.#generateTableName(), { record: false });
    }
    table2.refreshBounds();
    table2.syncColumnsFromSheet();
    this.#tables.push(table2);
    const recorder = this.#worksheet.workbook.getRecorder();
    if (recorder) {
      const alias = recorder.assignAlias(table2, `tb/${table2.name}`, "table");
      const op = {
        op: "table.add",
        as: alias,
        props: {
          range: {
            sheet: this.#worksheet.name,
            range: parsed.ref
          },
          hasHeaders,
          name: table2.name
        }
      };
      recorder.record(op);
    }
    this.#worksheet.__queueCollaborativePublish();
    return table2;
  }
  getItem(name) {
    const table2 = this.#tableMap.get(name);
    if (!table2) {
      throw new Error(`Table ${name} not found`);
    }
    return table2;
  }
  getItemOrNullObject(name) {
    const table2 = this.#tableMap.get(name);
    if (table2) {
      return table2;
    }
    return new NullTable(this.#worksheet, name);
  }
  getItemAt(index) {
    const table2 = this.#tables[index];
    if (!table2) {
      throw new Error(`Table at index ${index} not found`);
    }
    return table2;
  }
  get items() {
    return this.#tables;
  }
  replaceFromProto() {
    this.#tableMap = new Map;
    this.#tables = this.#worksheet.__getTables().map((tableProto) => this.#createTableWrapper(tableProto, {
      hasHeaders: getEffectiveTableHeaderRowCount(tableProto) > 0
    }));
  }
  deleteAll() {
    for (const table2 of [...this.#tables]) {
      table2.delete();
    }
  }
  #nextTableId() {
    let maxId = 0;
    for (const sheet of this.#worksheet.workbook.worksheets.items) {
      for (const table2 of sheet.__getTables()) {
        if (table2.id != null && table2.id > maxId) {
          maxId = table2.id;
        }
      }
    }
    return maxId + 1;
  }
  #generateTableName() {
    const used = new Set;
    for (const table2 of this.#tables) {
      if (table2.name) {
        used.add(table2.name.toUpperCase());
      }
    }
    let suffix = 1;
    while (used.has(`TABLE${suffix}`)) {
      suffix += 1;
    }
    return `Table${suffix}`;
  }
  #createTableWrapper(protoTable, options) {
    const table2 = new Table3(this.#worksheet, protoTable, {
      hasHeaders: options.hasHeaders,
      onDelete: (target) => this.#deleteTable(target),
      onNameChange: (target, oldName, newName) => {
        if (oldName) {
          this.#tableMap.delete(oldName);
        }
        if (newName) {
          this.#tableMap.set(newName, target);
        }
      }
    });
    const name = table2.name;
    if (name) {
      this.#tableMap.set(name, table2);
    }
    return table2;
  }
  #deleteTable(target) {
    const name = target.name;
    if (name) {
      this.#tableMap.delete(name);
    }
    this.#tables = this.#tables.filter((table2) => table2 !== target);
    const proto = getTableProto(target);
    const protos = this.#worksheet.__getTables();
    const index = protos.indexOf(proto);
    if (index >= 0) {
      protos.splice(index, 1);
    }
    this.#worksheet.__queueCollaborativePublish();
  }
}
function resolveTableAddressInput(value) {
  if (typeof value === "string") {
    return value;
  }
  if (value && typeof value === "object" && typeof value.address === "string") {
    return value.address;
  }
  const display = value === null ? "null" : value === undefined ? "undefined" : typeof value;
  throw new Error(`Worksheet.tables.add(address, hasHeaders) expects an A1 string or a Range; received ${display}. ` + "If you have a Range, pass it directly or use range.address.");
}
function assertHeaderRowHasNoFormulas(worksheet, parsed, hasHeaders) {
  if (!hasHeaders) {
    return;
  }
  const { startRow, startCol, endCol } = parsed.bounds;
  const headerRangeRef = buildRangeRef({
    startRow,
    endRow: startRow,
    startCol,
    endCol
  });
  const formulaInfos = worksheet.getRange(headerRangeRef).formulaInfos;
  for (let colOffset = 0;colOffset < formulaInfos[0].length; colOffset += 1) {
    if (!formulaInfos[0][colOffset]) {
      continue;
    }
    const formulaCellRef = buildRangeRef({
      startRow,
      endRow: startRow,
      startCol: startCol + colOffset,
      endCol: startCol + colOffset
    });
    throw new Error(`Worksheet.tables.add(..., true) requires literal header cells. ` + `Header row ${headerRangeRef} contains a formula at ${formulaCellRef}. ` + `Use a range with static header text or pass hasHeaders=false.`);
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/data-table-collection.js
init_address_utils();

class WorksheetDataTableCollection {
  #worksheet;
  #definitions;
  constructor(worksheet) {
    this.#worksheet = worksheet;
    this.#definitions = [];
  }
  add(address, inputs) {
    if (!inputs.rowInput && !inputs.columnInput) {
      throw new Error("Data tables require at least a rowInput or columnInput address");
    }
    const { sheetName: addressSheetName, ref: addressRef } = splitSheetAddress(address);
    if (addressSheetName && this.#worksheet.name) {
      if (addressSheetName !== this.#worksheet.name) {
        throw new Error(`Data table range must be on sheet "${this.#worksheet.name}", got "${addressSheetName}"`);
      }
    }
    const parsed = parseRangeAddress(addressRef);
    if (!parsed) {
      throw new Error(`Invalid data table range: ${address}`);
    }
    const fullBounds = parsed.bounds;
    const dimensions = boundsDimensions(fullBounds);
    if (dimensions.rows < 2 || dimensions.cols < 2) {
      throw new Error(`Data table range must include the formula cell plus at least one row and one column of results: ${address}`);
    }
    const formulaRow = fullBounds.startRow;
    const formulaCol = fullBounds.startCol;
    const formulaCell = this.#worksheet.__getCell(formulaRow, formulaCol);
    const formulaValue = this.#worksheet.__getRawValue(formulaRow, formulaCol);
    if (!formulaCell?.formula && (formulaValue === undefined || formulaValue === null || formulaValue === "")) {
      let suggestion = "";
      if (fullBounds.startRow > 0 && fullBounds.startCol > 0) {
        const priorRow = fullBounds.startRow - 1;
        const priorCol = fullBounds.startCol - 1;
        const priorCell = this.#worksheet.__getCell(priorRow, priorCol);
        const priorValue = this.#worksheet.__getRawValue(priorRow, priorCol);
        if (priorCell?.formula || priorValue !== undefined && priorValue !== null && priorValue !== "") {
          const expanded = buildRangeRef({
            startRow: priorRow,
            startCol: priorCol,
            endRow: fullBounds.endRow,
            endCol: fullBounds.endCol
          });
          suggestion = ` Did you mean "${expanded}"?`;
        }
      }
      throw new Error(`Data table range needs a top-left formula cell. "${makeCellAddress(formulaRow, formulaCol)}" is empty.${suggestion}`);
    }
    const normalizeInput = (input, label) => {
      if (!input) {
        return;
      }
      const { sheetName, ref } = splitSheetAddress(input);
      if (sheetName && this.#worksheet.name && sheetName !== this.#worksheet.name) {
        throw new Error(`Data table ${label} must be on sheet "${this.#worksheet.name}", got "${sheetName}"`);
      }
      const parsedInput = parseRangeAddress(ref);
      if (!parsedInput) {
        throw new Error(`Invalid data table ${label} address: ${input}`);
      }
      const inputBounds = parsedInput.bounds;
      if (inputBounds.startRow !== inputBounds.endRow || inputBounds.startCol !== inputBounds.endCol) {
        throw new Error(`Data table ${label} must be a single cell address, not a range: ${input}`);
      }
      return makeCellAddress(inputBounds.startRow, inputBounds.startCol);
    };
    const normalizedRowInput = normalizeInput(inputs.rowInput, "rowInput");
    const normalizedColumnInput = normalizeInput(inputs.columnInput, "columnInput");
    const bounds = {
      startRow: fullBounds.startRow + 1,
      startCol: fullBounds.startCol + 1,
      endRow: fullBounds.endRow,
      endCol: fullBounds.endCol
    };
    const bodyRef = buildRangeRef(bounds);
    const anchor = {
      row: bounds.startRow,
      col: bounds.startCol,
      address: makeCellAddress(bounds.startRow, bounds.startCol)
    };
    const cell = this.#worksheet.__getOrCreateCell(anchor.row, anchor.col);
    cell.formula = undefined;
    cell.formulaType = 3 /* CELL_FORMULA_TYPE_DATA_TABLE */;
    cell.formulaRef = bodyRef;
    const definition = this.#registerDefinition({
      bounds,
      formulaRef: bodyRef,
      anchor,
      rowInput: normalizedRowInput,
      columnInput: normalizedColumnInput,
      rowOriented: undefined,
      twoVariable: undefined
    });
    cell.dataTableRowInput = definition.rowInput;
    cell.dataTableColumnInput = definition.columnInput;
    cell.dataTableRowOriented = definition.rowOriented;
    cell.dataTableTwoVariable = definition.twoVariable;
  }
  __getDefinitions() {
    return this.#definitions;
  }
  __hydrateFromProto(def) {
    if (!def.formulaRef) {
      return;
    }
    const parsed = parseRangeAddress(def.formulaRef);
    if (!parsed) {
      return;
    }
    this.#registerDefinition({
      bounds: parsed.bounds,
      formulaRef: parsed.ref,
      anchor: {
        row: def.anchor.row,
        col: def.anchor.col,
        address: makeCellAddress(def.anchor.row, def.anchor.col)
      },
      rowInput: def.rowInput,
      columnInput: def.columnInput,
      rowOriented: def.rowOriented,
      twoVariable: def.twoVariable
    });
  }
  #registerDefinition({ bounds, formulaRef, anchor, rowInput, columnInput, rowOriented, twoVariable }) {
    const normalizedRowInput = rowInput?.toUpperCase();
    const normalizedColumnInput = columnInput?.toUpperCase();
    const resolvedTwoVariable = twoVariable ?? Boolean(normalizedRowInput && normalizedColumnInput);
    const resolvedRowOriented = rowOriented ?? (resolvedTwoVariable || normalizedRowInput ? normalizedColumnInput ? undefined : true : false);
    const displayArgs = [normalizedRowInput, normalizedColumnInput].filter((value) => Boolean(value));
    const definition = {
      range: bounds,
      formulaRef,
      anchor: {
        row: anchor.row,
        col: anchor.col,
        address: anchor.address ?? makeCellAddress(anchor.row, anchor.col)
      },
      rowInput: normalizedRowInput,
      columnInput: normalizedColumnInput,
      rowOriented: resolvedRowOriented,
      twoVariable: resolvedTwoVariable,
      displayFormula: `{=TABLE(${displayArgs.join(",")})}`
    };
    this.#definitions.push(definition);
    return definition;
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/drawings.js
init_address_utils();
var clampIndex = (value) => Math.max(0, Math.floor(Number.isFinite(value ?? 0) ? value : 0));
var parseIndex = (value) => {
  const numeric = Number.parseInt(value ?? "", 10);
  return Number.isFinite(numeric) && numeric >= 0 ? numeric : 0;
};
var parseEmu = (value) => {
  const numeric = Number.parseFloat(value ?? "");
  return Number.isFinite(numeric) && numeric >= 0 ? Math.round(numeric) : 0;
};
var normalizeEmu = (explicitEmu, px, fallback) => {
  if (Number.isFinite(explicitEmu)) {
    return Math.max(0, Math.round(explicitEmu));
  }
  if (Number.isFinite(px)) {
    return Math.max(0, Math.round(px * EMUS_PER_PIXEL));
  }
  return Math.max(0, fallback ?? 0);
};
var anchorStateFromProto = (anchor) => {
  if (!anchor) {
    return;
  }
  return {
    row: parseIndex(anchor.rowId),
    col: parseIndex(anchor.colId),
    rowOffsetEmu: parseEmu(anchor.rowOffset),
    colOffsetEmu: parseEmu(anchor.colOffset)
  };
};
var anchorStateFromInput = (input, fallback) => {
  const base = fallback ?? {
    row: 0,
    col: 0,
    rowOffsetEmu: 0,
    colOffsetEmu: 0
  };
  if (!input) {
    return base;
  }
  return {
    row: clampIndex(input.row ?? base.row),
    col: clampIndex(input.col ?? base.col),
    rowOffsetEmu: normalizeEmu(input.rowOffsetEmu, input.rowOffsetPx, base.rowOffsetEmu),
    colOffsetEmu: normalizeEmu(input.colOffsetEmu, input.colOffsetPx, base.colOffsetEmu)
  };
};
var anchorToProto = (state) => ({
  rowId: String(state.row),
  colId: String(state.col),
  rowOffset: String(state.rowOffsetEmu),
  colOffset: String(state.colOffsetEmu)
});
var anchorSnapshot = (state) => ({
  row: state.row,
  col: state.col,
  rowOffsetEmu: state.rowOffsetEmu,
  colOffsetEmu: state.colOffsetEmu,
  rowOffsetPx: Math.round(state.rowOffsetEmu * PIXELS_PER_EMU),
  colOffsetPx: Math.round(state.colOffsetEmu * PIXELS_PER_EMU)
});
var extentStateFromProto = (drawing) => {
  const widthEmu = drawing?.extentCx ? parseEmu(drawing.extentCx) : undefined;
  const heightEmu = drawing?.extentCy ? parseEmu(drawing.extentCy) : undefined;
  return widthEmu === undefined && heightEmu === undefined ? {} : { widthEmu, heightEmu };
};
var extentStateFromInput = (input, fallback) => {
  const widthEmu = input?.widthEmu !== undefined || input?.widthPx !== undefined ? normalizeEmu(input?.widthEmu, input?.widthPx, fallback?.widthEmu) : fallback?.widthEmu;
  const heightEmu = input?.heightEmu !== undefined || input?.heightPx !== undefined ? normalizeEmu(input?.heightEmu, input?.heightPx, fallback?.heightEmu) : fallback?.heightEmu;
  if (widthEmu === undefined && heightEmu === undefined) {
    return {};
  }
  return { widthEmu, heightEmu };
};
var extentSnapshot = (state) => {
  if (!state) {
    return;
  }
  const { widthEmu, heightEmu } = state;
  if (widthEmu === undefined && heightEmu === undefined) {
    return;
  }
  return {
    widthEmu,
    heightEmu,
    widthPx: widthEmu === undefined ? undefined : Math.round(widthEmu * PIXELS_PER_EMU),
    heightPx: heightEmu === undefined ? undefined : Math.round(heightEmu * PIXELS_PER_EMU)
  };
};
var buildDrawingOffsetsPx = (sizes) => {
  const offsets = [0];
  for (let index = 0;index < sizes.length; index += 1) {
    offsets[index + 1] = (offsets[index] ?? 0) + (sizes[index] ?? 0);
  }
  return offsets;
};
var resolveDrawingOffsetsPx = (args2) => {
  if (args2.offsets && args2.offsets.length > 0) {
    return [...args2.offsets];
  }
  return buildDrawingOffsetsPx(args2.sizes ?? []);
};
var indexForOffset = (offsets, value) => {
  if (offsets.length === 0) {
    return { index: 0, offset: 0 };
  }
  const target = Math.max(0, value);
  let index = 0;
  while (index + 1 < offsets.length) {
    const next = offsets[index + 1];
    if (next == null || next > target) {
      break;
    }
    index += 1;
  }
  return {
    index: Math.min(index, Math.max(0, offsets.length - 2)),
    offset: target - (offsets[index] ?? 0)
  };
};
var extentWidthPx = (state) => state?.widthEmu === undefined ? undefined : state.widthEmu * PIXELS_PER_EMU;
var extentHeightPx = (state) => state?.heightEmu === undefined ? undefined : state.heightEmu * PIXELS_PER_EMU;
var resolveBoundsPxFromStates = (args2) => {
  const colOffsets = resolveDrawingOffsetsPx({
    sizes: args2.layout.columnWidths,
    offsets: args2.layout.columnOffsets
  });
  const rowOffsets = resolveDrawingOffsetsPx({
    sizes: args2.layout.rowHeights,
    offsets: args2.layout.rowOffsets
  });
  const fromColOffset = colOffsets[args2.from.col];
  const fromRowOffset = rowOffsets[args2.from.row];
  if (fromColOffset == null || fromRowOffset == null) {
    return null;
  }
  const fromOffset = anchorSnapshot(args2.from);
  const x2 = fromColOffset + fromOffset.colOffsetPx;
  const y2 = fromRowOffset + fromOffset.rowOffsetPx;
  if (args2.to) {
    const toColOffset = colOffsets[args2.to.col];
    const toRowOffset = rowOffsets[args2.to.row];
    if (toColOffset == null || toRowOffset == null) {
      return null;
    }
    const toOffset = anchorSnapshot(args2.to);
    return {
      x: x2,
      y: y2,
      width: Math.max(1, toColOffset + toOffset.colOffsetPx - x2),
      height: Math.max(1, toRowOffset + toOffset.rowOffsetPx - y2)
    };
  }
  const width = extentWidthPx(args2.extent);
  const height = extentHeightPx(args2.extent);
  if (width == null || height == null) {
    return null;
  }
  return {
    x: x2,
    y: y2,
    width: Math.max(1, width),
    height: Math.max(1, height)
  };
};
var buildAnchorStatesFromBoundsPx = (args2) => {
  const left = Math.max(0, args2.bounds.x);
  const top = Math.max(0, args2.bounds.y);
  const right = Math.max(left, args2.bounds.x + args2.bounds.width);
  const bottom = Math.max(top, args2.bounds.y + args2.bounds.height);
  const colOffsets = resolveDrawingOffsetsPx({
    sizes: args2.layout.columnWidths,
    offsets: args2.layout.columnOffsets
  });
  const rowOffsets = resolveDrawingOffsetsPx({
    sizes: args2.layout.rowHeights,
    offsets: args2.layout.rowOffsets
  });
  const fromCol = indexForOffset(colOffsets, left);
  const fromRow = indexForOffset(rowOffsets, top);
  const from2 = anchorStateFromInput({
    row: fromRow.index,
    col: fromCol.index,
    rowOffsetPx: fromRow.offset,
    colOffsetPx: fromCol.offset
  });
  if (!args2.usesTwoCellAnchor) {
    return {
      from: from2,
      extent: extentStateFromInput({
        widthPx: Math.max(1, args2.bounds.width),
        heightPx: Math.max(1, args2.bounds.height)
      })
    };
  }
  const toCol = indexForOffset(colOffsets, right);
  const toRow = indexForOffset(rowOffsets, bottom);
  return {
    from: from2,
    to: anchorStateFromInput({
      row: toRow.index,
      col: toCol.index,
      rowOffsetPx: toRow.offset,
      colOffsetPx: toCol.offset
    }),
    extent: undefined
  };
};

class DrawingAnchor {
  #from;
  #to;
  #extent;
  #previewFrom;
  #previewTo;
  #previewExtent;
  #onChange;
  constructor(proto, init) {
    const protoFrom = anchorStateFromProto(proto?.fromAnchor);
    const protoTo = anchorStateFromProto(proto?.toAnchor);
    const protoExtent = extentStateFromProto(proto);
    this.#from = anchorStateFromInput(init?.from, protoFrom);
    this.#to = protoTo;
    this.#extent = protoExtent;
    if (init?.to) {
      this.to = init.to;
    }
    if (init?.extent) {
      this.extent = init.extent;
    }
  }
  get from() {
    return anchorSnapshot(this.#from);
  }
  set from(value) {
    const previous = this.toConfig();
    this.#from = anchorStateFromInput(value, this.#from);
    this.#onChange?.(previous, this.toConfig());
  }
  get to() {
    return this.#to ? anchorSnapshot(this.#to) : undefined;
  }
  set to(value) {
    const previous = this.toConfig();
    this.#to = value ? anchorStateFromInput(value, this.#to) : undefined;
    if (value) {
      this.#extent = undefined;
    }
    this.#onChange?.(previous, this.toConfig());
  }
  get extent() {
    return extentSnapshot(this.#extent);
  }
  set extent(value) {
    const previous = this.toConfig();
    this.#extent = extentStateFromInput(value, this.#extent);
    if (value) {
      this.#to = undefined;
    }
    this.#onChange?.(previous, this.toConfig());
  }
  setChangeHandler(handler) {
    this.#onChange = handler;
  }
  toConfig() {
    const from2 = this.from;
    const to = this.to;
    const extent2 = this.extent;
    const config2 = {
      from: {
        row: from2.row,
        col: from2.col,
        ...from2.rowOffsetPx !== 0 ? { rowOffsetPx: from2.rowOffsetPx } : {},
        ...from2.colOffsetPx !== 0 ? { colOffsetPx: from2.colOffsetPx } : {}
      }
    };
    if (to) {
      config2.to = {
        row: to.row,
        col: to.col,
        ...to.rowOffsetPx !== 0 ? { rowOffsetPx: to.rowOffsetPx } : {},
        ...to.colOffsetPx !== 0 ? { colOffsetPx: to.colOffsetPx } : {}
      };
    }
    if (extent2) {
      config2.extent = {
        ...extent2.widthPx !== undefined ? { widthPx: extent2.widthPx } : {},
        ...extent2.heightPx !== undefined ? { heightPx: extent2.heightPx } : {}
      };
    }
    return config2;
  }
  captureSnapshot() {
    const from2 = this.from;
    const to = this.to;
    const extent2 = this.extent;
    return {
      from: {
        row: from2.row,
        col: from2.col,
        ...from2.rowOffsetPx !== 0 ? { rowOffsetPx: from2.rowOffsetPx } : {},
        ...from2.colOffsetPx !== 0 ? { colOffsetPx: from2.colOffsetPx } : {}
      },
      ...to ? {
        to: {
          row: to.row,
          col: to.col,
          ...to.rowOffsetPx !== 0 ? { rowOffsetPx: to.rowOffsetPx } : {},
          ...to.colOffsetPx !== 0 ? { colOffsetPx: to.colOffsetPx } : {}
        }
      } : {},
      ...extent2 ? {
        extent: {
          ...extent2.widthPx !== undefined ? { widthPx: extent2.widthPx } : {},
          ...extent2.heightPx !== undefined ? { heightPx: extent2.heightPx } : {}
        }
      } : {}
    };
  }
  restoreSnapshot(snapshot) {
    const previous = this.toConfig();
    this.#from = anchorStateFromInput(snapshot.from);
    this.#to = snapshot.to ? anchorStateFromInput(snapshot.to) : undefined;
    this.#extent = snapshot.extent ? extentStateFromInput(snapshot.extent) : undefined;
    this.clearPreviewBounds();
    this.#onChange?.(previous, this.toConfig());
  }
  resolveBoundsPx(layout, options) {
    const usePreview = options?.preferPreview === true && this.#previewFrom !== undefined;
    return resolveBoundsPxFromStates({
      from: usePreview ? this.#previewFrom : this.#from,
      to: usePreview ? this.#previewTo : this.#to,
      extent: usePreview ? this.#previewExtent : this.#extent,
      layout
    });
  }
  setPreviewBoundsPx(bounds, layout, options) {
    const next = buildAnchorStatesFromBoundsPx({
      bounds,
      layout,
      usesTwoCellAnchor: options.usesTwoCellAnchor
    });
    this.#previewFrom = next.from;
    this.#previewTo = next.to;
    this.#previewExtent = next.extent;
  }
  clearPreviewBounds() {
    this.#previewFrom = undefined;
    this.#previewTo = undefined;
    this.#previewExtent = undefined;
  }
  applyBoundsPx(bounds, layout, options) {
    const previous = this.toConfig();
    const next = buildAnchorStatesFromBoundsPx({
      bounds,
      layout,
      usesTwoCellAnchor: options.usesTwoCellAnchor
    });
    this.#from = next.from;
    this.#to = next.to;
    this.#extent = next.extent;
    this.clearPreviewBounds();
    this.#onChange?.(previous, this.toConfig());
  }
  toProtoFields(options) {
    const usePreview = options?.preferPreview === true && this.#previewFrom !== undefined;
    const fromState = usePreview ? this.#previewFrom : this.#from;
    const toState = usePreview ? this.#previewTo : this.#to;
    const extentState = usePreview ? this.#previewExtent : this.#extent;
    const fromAnchor = anchorToProto(fromState);
    const toAnchor = toState ? anchorToProto(toState) : undefined;
    const extentCx = extentState?.widthEmu === undefined ? undefined : String(extentState.widthEmu);
    const extentCy = extentState?.heightEmu === undefined ? undefined : String(extentState.heightEmu);
    return {
      fromAnchor,
      toAnchor,
      extentCx,
      extentCy
    };
  }
}
var installAxisTitleTextCompat = (axis) => {
  if (Object.prototype.hasOwnProperty.call(axis, "title")) {
    return;
  }
  const proto = Object.getPrototypeOf(axis);
  const desc = Object.getOwnPropertyDescriptor(proto, "title");
  if (!desc?.get || !desc?.set) {
    return;
  }
  const getRawTitle = () => desc.get.call(axis);
  const getTitle = () => {
    const raw = getRawTitle();
    if (typeof raw === "string") {
      return raw;
    }
    if (raw && typeof raw === "object") {
      return raw.text;
    }
    return;
  };
  const getTitleTextStyle = () => {
    const raw = getRawTitle();
    if (raw && typeof raw === "object") {
      return raw.textStyle;
    }
    return;
  };
  const setTitle = (value) => {
    desc.set.call(axis, value);
  };
  const titleProxy = {};
  Object.defineProperty(titleProxy, "text", {
    get: () => getTitle(),
    set: (value) => {
      setTitle(typeof value === "string" ? value : undefined);
    }
  });
  Object.defineProperty(titleProxy, "textStyle", {
    get: () => getTitleTextStyle()
  });
  Object.defineProperty(titleProxy, "toString", {
    value: () => getTitle() ?? ""
  });
  Object.defineProperty(titleProxy, "valueOf", {
    value: () => getTitle() ?? ""
  });
  Object.defineProperty(axis, "title", {
    get: () => titleProxy,
    set: (value) => {
      if (typeof value === "string") {
        setTitle(value);
        return;
      }
      if (value && typeof value === "object") {
        setTitle(value);
        return;
      }
      setTitle(undefined);
    }
  });
};

class ChartAreaFillFormat {
  #target;
  constructor(target) {
    this.#target = target;
  }
  clear() {
    this.#target.setFill({ type: "none" });
  }
  setSolidColor(value) {
    this.#target.setFill(value);
  }
  get color() {
    const fill2 = this.#target.getFill();
    const config2 = fill2?.toConfig();
    return typeof config2 === "string" ? config2 : undefined;
  }
  set color(value) {
    if (typeof value !== "string" || value.trim().length === 0) {
      return;
    }
    this.#target.setFill(value);
  }
}

class ChartAreaLineFormat {
  #target;
  constructor(target) {
    this.#target = target;
  }
  get visible() {
    return this.#target.line.visible;
  }
  set visible(value) {
    this.#target.line.visible = value;
    this.#target.onChange?.();
  }
  get color() {
    return this.#target.line.color;
  }
  set color(value) {
    this.#target.line.color = value;
    this.#target.onChange?.();
  }
  get style() {
    return this.#target.line.style;
  }
  set style(value) {
    this.#target.line.style = value;
    this.#target.onChange?.();
  }
  get weight() {
    return this.#target.line.width;
  }
  set weight(value) {
    this.#target.line.width = value;
    this.#target.onChange?.();
  }
}

class ChartAreaFormat {
  #target;
  #fill;
  #line;
  constructor(target) {
    this.#target = target;
    this.#fill = new ChartAreaFillFormat(target);
    this.#line = new ChartAreaLineFormat(target);
  }
  get fill() {
    return this.#fill;
  }
  set fill(value) {
    if (value === undefined) {
      return;
    }
    this.#target.setFill(value);
  }
  get line() {
    return this.#line;
  }
  set line(value) {
    const line = this.#target.line;
    const config2 = value;
    const fill2 = config2.fill ?? config2.color;
    if (fill2 !== undefined) {
      line.fill = fill2;
    }
    const width = config2.width ?? config2.weight;
    if (typeof width === "number" && Number.isFinite(width)) {
      line.width = width;
    }
    if (config2.style !== undefined) {
      line.style = config2.style;
    }
  }
}

class WorksheetChart extends Chart2 {
  anchor;
  #titleProxy;
  #titlePlacementBeforeHide;
  #axesProxy;
  #plotAreaProxy;
  #chartAreaProxy;
  #onDelete;
  #onChange;
  #context;
  #createdInRecorder;
  constructor(proto, init) {
    const chartProto = proto?.chart ?? (init?.type ? {
      id: init.id ?? generateAidSuffix(),
      type: CHART_TYPE_TO_PROTO[init.type]
    } : undefined);
    super(chartProto);
    this.anchor = new DrawingAnchor(proto, init?.anchor);
    this.#onDelete = init?.onDelete;
    this.#onChange = init?.onChange;
    this.#context = init?.context;
    this.#createdInRecorder = init?.createdInRecorder;
    this.anchor.setChangeHandler(() => this.#recordSet());
    const titleProxy = {};
    Object.defineProperty(titleProxy, "text", {
      get: () => this.titleText,
      set: (value) => {
        this.titleText = typeof value === "string" ? value : "";
      }
    });
    Object.defineProperty(titleProxy, "visible", {
      get: () => this.titlePlacement !== "none",
      set: (value) => {
        const wantsVisible = Boolean(value);
        if (!wantsVisible) {
          const current = this.titlePlacement;
          if (current !== "none") {
            this.#titlePlacementBeforeHide = current;
          }
          this.titlePlacement = "none";
          return;
        }
        if (this.titlePlacement === "none") {
          this.titlePlacement = this.#titlePlacementBeforeHide ?? undefined;
        }
      }
    });
    Object.preventExtensions(titleProxy);
    this.#titleProxy = titleProxy;
    installAxisTitleTextCompat(this.yAxis);
    installAxisTitleTextCompat(this.xAxis);
    const axesProxy = {};
    Object.defineProperty(axesProxy, "valueAxis", {
      get: () => this.yAxis
    });
    Object.defineProperty(axesProxy, "categoryAxis", {
      get: () => this.xAxis
    });
    this.#axesProxy = axesProxy;
    const plotAreaProxy = {};
    const plotAreaFormat = new ChartAreaFormat({
      getFill: () => this.plotAreaFill,
      setFill: (value) => {
        this.plotAreaFill = value;
        this.#recordSet();
      },
      line: this.plotAreaLine,
      onChange: () => this.#recordSet()
    });
    Object.defineProperty(plotAreaProxy, "format", {
      get: () => plotAreaFormat
    });
    this.#plotAreaProxy = plotAreaProxy;
    const chartAreaProxy = {};
    const chartAreaFormat = new ChartAreaFormat({
      getFill: () => this.chartFill,
      setFill: (value) => {
        this.chartFill = value;
        this.#recordSet();
      },
      line: this.chartLine,
      onChange: () => this.#recordSet()
    });
    Object.defineProperty(chartAreaProxy, "format", {
      get: () => chartAreaFormat
    });
    this.#chartAreaProxy = chartAreaProxy;
    this.series.setChangeHandler(() => this.#recordSet());
  }
  get titleText() {
    return super.title;
  }
  set titleText(value) {
    super.title = value ?? "";
    if (typeof value === "string" && value.trim().length > 0) {
      if (this.titlePlacement === "none") {
        this.titlePlacement = this.#titlePlacementBeforeHide ?? undefined;
      }
    }
    this.#recordSet();
  }
  get title() {
    return this.#titleProxy;
  }
  set title(value) {
    this.#applyTitleValue(value);
  }
  get categories() {
    return super.categories;
  }
  set categories(value) {
    super.categories = value;
    this.#recordSet();
  }
  get legend() {
    return super.legend;
  }
  set legend(value) {
    if (value instanceof ChartLegend) {
      super.legend = value;
      this.#recordSet();
      return;
    }
    if (!value || typeof value !== "object") {
      return;
    }
    const legend = super.legend;
    if (value.position !== undefined) {
      legend.position = value.position;
    }
    if (value.overlay !== undefined) {
      legend.overlay = value.overlay;
    }
    if (value.fill !== undefined) {
      legend.fill = value.fill;
    }
    if (value.line !== undefined) {
      legend.stroke = value.line;
    } else if (value.stroke !== undefined) {
      legend.stroke = value.stroke;
    }
    if (value.textStyle !== undefined) {
      applyTextStyleConfig(legend.textStyle, value.textStyle);
    }
    this.#recordSet();
  }
  get axes() {
    return this.#axesProxy;
  }
  get plotArea() {
    return this.#plotAreaProxy;
  }
  get chartArea() {
    return this.#chartAreaProxy;
  }
  get isNullObject() {
    return false;
  }
  get width() {
    return this.anchor.extent?.widthPx;
  }
  set width(value) {
    if (!Number.isFinite(value ?? undefined)) {
      return;
    }
    this.anchor.extent = {
      widthPx: Math.max(0, value)
    };
  }
  get height() {
    return this.anchor.extent?.heightPx;
  }
  set height(value) {
    if (!Number.isFinite(value ?? undefined)) {
      return;
    }
    this.anchor.extent = {
      heightPx: Math.max(0, value)
    };
  }
  setPosition(target, end) {
    const address = typeof target === "string" ? target : target?.address;
    if (!address) {
      return;
    }
    const parsed = parseRangeAddress(address);
    if (!parsed) {
      return;
    }
    this.anchor.from = {
      row: parsed.bounds.startRow,
      col: parsed.bounds.startCol
    };
    if (!end) {
      if (parsed.bounds.endRow !== parsed.bounds.startRow || parsed.bounds.endCol !== parsed.bounds.startCol) {
        this.anchor.to = {
          row: parsed.bounds.endRow + 1,
          col: parsed.bounds.endCol + 1
        };
      }
      return;
    }
    const endAddress = typeof end === "string" ? end : end?.address;
    if (!endAddress) {
      return;
    }
    const endParsed = parseRangeAddress(endAddress);
    if (!endParsed) {
      return;
    }
    this.anchor.to = {
      row: endParsed.bounds.endRow + 1,
      col: endParsed.bounds.endCol + 1
    };
  }
  setData(sourceData, _seriesBy) {
    applyChartDataFromRangeLike(this, sourceData);
    this.#recordSet();
  }
  delete() {
    this.#onDelete?.(this);
  }
  resolveBoundsPx(layout, options) {
    return this.anchor.resolveBoundsPx(layout, options);
  }
  captureAnchorSnapshot() {
    return this.anchor.captureSnapshot();
  }
  restoreAnchorSnapshot(snapshot) {
    this.anchor.restoreSnapshot(snapshot);
  }
  setPreviewBoundsPx(bounds, layout, options) {
    this.anchor.setPreviewBoundsPx(bounds, layout, options);
  }
  clearPreviewBounds() {
    this.anchor.clearPreviewBounds();
  }
  applyBoundsPx(bounds, layout, options) {
    this.anchor.applyBoundsPx(bounds, layout, options);
  }
  toDrawingProto(options) {
    const { fromAnchor, toAnchor, extentCx, extentCy } = this.anchor.toProtoFields(options);
    return {
      fromAnchor,
      toAnchor,
      extentCx,
      extentCy,
      chart: this.toProto()
    };
  }
  #applyTitleValue(value) {
    if (typeof value === "string") {
      this.titleText = value;
      return;
    }
    if (value && typeof value === "object") {
      const text2 = value.text;
      if (typeof text2 === "string") {
        this.titleText = text2;
        return;
      }
      if (text2 == null) {
        this.titleText = "";
      }
      return;
    }
    if (value == null) {
      this.titleText = "";
    }
  }
  #recordSet() {
    this.#onChange?.(this);
    const recorder = this.#context?.getRecorder();
    const sheet = this.#context?.getSheetName();
    if (!recorder || !sheet) {
      return;
    }
    if (this.#createdInRecorder === recorder) {
      return;
    }
    recorder.deferOnce(`chart.set:${this.id}`, () => buildChartSetOp({ sheet, chart: this }));
  }
}

class NullWorksheetChart extends WorksheetChart {
  #name;
  constructor(name) {
    super(undefined, { type: "line" });
    this.titleText = name;
    this.#name = name;
  }
  get isNullObject() {
    return true;
  }
  delete() {}
  get name() {
    return this.#name;
  }
}
var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
var isRangeLike = (value) => isRecord3(value) && ("values" in value) && Array.isArray(value.values);
var isChartPropsInput = (value) => isRecord3(value) && ("chartType" in value);
var isChartAnchorPropsInput = (value) => isRecord3(value) && ("from" in value);
var normalizeChartTypeToken = (value) => value.replace(/[^a-z0-9]/gi, "").toLowerCase();
var CHART_TYPE_ALIASES = Object.keys(CHART_TYPE_TO_PROTO).reduce((acc, key) => {
  acc[normalizeChartTypeToken(key)] = key;
  return acc;
}, {});
var SUPPORTED_CHART_TYPES = Object.keys(CHART_TYPE_TO_PROTO).sort();
var buildUnsupportedChartTypeError = (raw) => {
  const label = raw ?? "unknown";
  const supported = SUPPORTED_CHART_TYPES.join(", ");
  return new Error(`Unsupported chart type: ${label}. Supported types: ${supported}. ` + "Office.js aliases include ColumnClustered, ColumnStacked, BarClustered, " + "BarStacked, BoxAndWhisker, LineMarkers, and PieExploded.");
};
var resolveChartType2 = (raw) => {
  if (!raw) {
    return null;
  }
  const normalized = normalizeChartTypeToken(raw);
  switch (normalized) {
    case "column":
    case "columnclustered":
      return {
        chartType: "bar",
        barDirection: "column",
        barGrouping: "clustered"
      };
    case "columnstacked":
      return {
        chartType: "bar",
        barDirection: "column",
        barGrouping: "stacked"
      };
    case "barclustered":
      return {
        chartType: "bar",
        barDirection: "bar",
        barGrouping: "clustered"
      };
    case "barstacked":
      return {
        chartType: "bar",
        barDirection: "bar",
        barGrouping: "stacked"
      };
    case "linemarkers":
      return { chartType: "line" };
    case "pieexploded":
      return { chartType: "pie" };
    case "boxandwhisker":
      return { chartType: "boxWhisker" };
    default:
      return CHART_TYPE_ALIASES[normalized] ? { chartType: CHART_TYPE_ALIASES[normalized] } : null;
  }
};
var normalizeShapeGeometryToken = (value) => value.replace(/[^a-z0-9]/gi, "").toLowerCase();
var SHAPE_GEOMETRY_ALIASES = {
  rectangle: "rect",
  righttriangle: "rtTriangle"
};
var SHAPE_GEOMETRY_BY_TOKEN = Object.keys(SHAPE_GEOMETRY_NAME_TO_PROTO).reduce((acc, key) => {
  acc[normalizeShapeGeometryToken(key)] = key;
  return acc;
}, {});
var resolveShapeGeometryName = (raw) => {
  if (!raw) {
    return null;
  }
  const normalized = normalizeShapeGeometryToken(raw);
  if (normalized === "connector") {
    return "connector";
  }
  const direct = SHAPE_GEOMETRY_BY_TOKEN[normalized];
  if (direct) {
    return direct;
  }
  return SHAPE_GEOMETRY_ALIASES[normalized] ?? null;
};
var toFiniteNumber = (value) => {
  if (typeof value === "number" && Number.isFinite(value)) {
    return value;
  }
  if (typeof value === "string" && value.trim().length > 0) {
    const parsed = Number(value);
    return Number.isFinite(parsed) ? parsed : undefined;
  }
  return;
};
var normalizeAnchorMarker = (value) => {
  if (!isRecord3(value)) {
    return;
  }
  const row2 = toFiniteNumber(value["row"]);
  const col = toFiniteNumber(value["col"]);
  if (row2 === undefined || col === undefined) {
    return;
  }
  const rowOffsetPx = toFiniteNumber(value["rowOffsetPx"] ?? value["offsetY"] ?? value["offsety"]);
  const colOffsetPx = toFiniteNumber(value["colOffsetPx"] ?? value["offsetX"] ?? value["offsetx"]);
  const rowOffsetEmu = toFiniteNumber(value["rowOffsetEmu"]);
  const colOffsetEmu = toFiniteNumber(value["colOffsetEmu"]);
  return {
    row: row2,
    col,
    ...rowOffsetPx !== undefined ? { rowOffsetPx } : {},
    ...colOffsetPx !== undefined ? { colOffsetPx } : {},
    ...rowOffsetEmu !== undefined ? { rowOffsetEmu } : {},
    ...colOffsetEmu !== undefined ? { colOffsetEmu } : {}
  };
};
var normalizeExtentInput = (value) => {
  if (!isRecord3(value)) {
    return;
  }
  const widthPx = toFiniteNumber(value["widthPx"] ?? value["width"]);
  const heightPx = toFiniteNumber(value["heightPx"] ?? value["height"]);
  const widthEmu = toFiniteNumber(value["widthEmu"]);
  const heightEmu = toFiniteNumber(value["heightEmu"]);
  if (widthPx === undefined && heightPx === undefined && widthEmu === undefined && heightEmu === undefined) {
    return;
  }
  const extent2 = {};
  if (widthPx !== undefined) {
    extent2.widthPx = widthPx;
  }
  if (heightPx !== undefined) {
    extent2.heightPx = heightPx;
  }
  if (widthEmu !== undefined) {
    extent2.widthEmu = widthEmu;
  }
  if (heightEmu !== undefined) {
    extent2.heightEmu = heightEmu;
  }
  return extent2;
};
var buildAnchorFromRangeAddress = (address) => {
  const parsed = parseRangeAddress(address);
  if (!parsed) {
    throw new Error(`Shape anchor must be an A1 range; received "${address}". ` + "Use workbook.help('worksheet.shapes.add') for examples.");
  }
  const { startRow, startCol, endRow, endCol } = parsed.bounds;
  return {
    from: { row: startRow, col: startCol },
    to: { row: endRow, col: endCol }
  };
};
var resolveDrawingAnchor = (value) => {
  if (!value) {
    return;
  }
  if (value instanceof Range) {
    return buildAnchorFromRangeAddress(value.address);
  }
  if (typeof value === "string") {
    return buildAnchorFromRangeAddress(value);
  }
  if (!isRecord3(value)) {
    return;
  }
  if ("from" in value || "to" in value || "extent" in value) {
    const from2 = normalizeAnchorMarker(value["from"]);
    const to = normalizeAnchorMarker(value["to"]);
    const extent2 = normalizeExtentInput(value["extent"]);
    if (from2) {
      const anchor = { from: from2 };
      if (to) {
        anchor.to = to;
      }
      if (extent2) {
        anchor.extent = extent2;
      }
      return anchor;
    }
    return value;
  }
  const marker = normalizeAnchorMarker(value);
  return marker ? { from: marker } : undefined;
};
var applyExtentOverrides = (anchor, widthPx, heightPx) => {
  if (widthPx === undefined && heightPx === undefined) {
    return anchor;
  }
  if (!anchor) {
    return anchor;
  }
  const extent2 = { ...anchor.extent ?? {} };
  if (widthPx !== undefined) {
    extent2.widthPx = widthPx;
  }
  if (heightPx !== undefined) {
    extent2.heightPx = heightPx;
  }
  return { ...anchor, extent: extent2 };
};
var buildUnsupportedShapeGeometryError = (raw) => {
  const label = raw ?? "unknown";
  return new Error(`Unsupported shape geometry: ${label}. ` + "Use workbook.help('enum.ShapeGeometry') for valid values or " + "workbook.help('worksheet.shapes.add') for examples.");
};
var toChartNumber = (value) => {
  if (typeof value === "number" && Number.isFinite(value)) {
    return value;
  }
  const num = typeof value === "string" ? Number(value) : Number(value);
  return Number.isFinite(num) ? num : 0;
};
var isNumericCell = (value) => {
  if (typeof value === "number") {
    return Number.isFinite(value);
  }
  if (typeof value === "string") {
    const trimmed = value.trim();
    return trimmed.length > 0 && Number.isFinite(Number(trimmed));
  }
  return false;
};
var escapeSheetNameForFormula = (sheetName) => {
  const escaped = sheetName.replace(/'/g, "''");
  return `'${escaped}'`;
};
var absoluteCellRef = (rowIdx, colIdx) => `$${columnLabel(colIdx)}$${rowIdx + 1}`;
var absoluteRangeRef = (options) => {
  const sheet = escapeSheetNameForFormula(options.sheetName);
  const start = absoluteCellRef(options.startRow, options.startCol);
  const end = absoluteCellRef(options.endRow, options.endCol);
  return `${sheet}!${start === end ? start : `${start}:${end}`}`;
};
var buildChartDataFromValues = (values) => {
  const header = values[0];
  if (!header || header.length === 0) {
    return { categories: [], series: [] };
  }
  const rows = values.length;
  const cols = header.length;
  if (rows >= 2 && cols >= 2) {
    const headerHasNumber = header.some((cell) => isNumericCell(cell));
    const headerHasText = header.some((cell) => typeof cell === "string" && cell.trim().length > 0 && !isNumericCell(cell));
    const useHeader = headerHasText && !headerHasNumber;
    const dataRows = useHeader ? values.slice(1) : values;
    const categories = dataRows.map((row2) => String(row2?.[0] ?? ""));
    const series = [];
    for (let col = 1;col < cols; col += 1) {
      const name = useHeader ? String(header[col] ?? `Series ${col}`) : `Series ${col}`;
      const seriesValues = dataRows.map((row2) => toChartNumber(row2?.[col]));
      series.push({ name, values: seriesValues, categories });
    }
    return { categories, series };
  }
  const flatValues = header.map((value) => toChartNumber(value));
  return {
    categories: header.map((_value, index) => `Item ${index + 1}`),
    series: [{ name: "Series 1", values: flatValues }]
  };
};
var applyChartDataFromRangeLike = (chart2, sourceData) => {
  chart2.categories = [];
  chart2.series.clear();
  if (sourceData instanceof Range) {
    const worksheet = sourceData.__getWorksheet();
    const parsed = worksheet ? parseRangeAddress(sourceData.address) : null;
    if (worksheet && parsed) {
      const bounds = parsed.bounds;
      const rows = bounds.endRow - bounds.startRow + 1;
      const cols = bounds.endCol - bounds.startCol + 1;
      if (rows >= 1 && cols >= 2) {
        const values = sourceData.values ?? [];
        const header = values[0] ?? [];
        const headerHasNumber = header.some((cell) => isNumericCell(cell));
        const headerHasText = header.some((cell) => typeof cell === "string" && cell.trim().length > 0 && !isNumericCell(cell));
        const useHeader = rows >= 2 && headerHasText && !headerHasNumber;
        const dataStartRow = useHeader ? bounds.startRow + 1 : bounds.startRow;
        if (dataStartRow <= bounds.endRow) {
          const sheetName = worksheet.name?.trim() ?? "";
          if (sheetName) {
            const categoryFormula = absoluteRangeRef({
              sheetName,
              startRow: dataStartRow,
              startCol: bounds.startCol,
              endRow: bounds.endRow,
              endCol: bounds.startCol
            });
            for (let colOffset = 1;colOffset < cols; colOffset += 1) {
              const seriesCol = bounds.startCol + colOffset;
              const name = useHeader ? String(header[colOffset] ?? `Series ${colOffset}`) : `Series ${colOffset}`;
              const series = chart2.series.add(name);
              series.categoryFormula = categoryFormula;
              series.formula = absoluteRangeRef({
                sheetName,
                startRow: dataStartRow,
                startCol: seriesCol,
                endRow: bounds.endRow,
                endCol: seriesCol
              });
              const fmt = worksheet.getRangeByIndexes(dataStartRow, seriesCol, 1, 1).format.numberFormat;
              if (fmt) {
                series.valuesFormatCode = fmt;
              }
            }
            return;
          }
        }
      }
    }
  }
  const chartData = buildChartDataFromValues(sourceData.values ?? []);
  if (chartData.categories.length > 0) {
    chart2.categories = chartData.categories;
  }
  if (chartData.series.length > 0) {
    applyChartSeriesInputs(chart2, chartData.series);
  }
};
var applyChartSeriesInputs = (chart2, inputs) => {
  for (const seriesInput of inputs) {
    const series = chart2.series.add(seriesInput.name);
    if (seriesInput.values) {
      series.values = [...seriesInput.values];
    }
    if (seriesInput.xValues) {
      series.xValues = [...seriesInput.xValues];
    }
    if (seriesInput.categories) {
      series.categories = [...seriesInput.categories];
    }
    if (seriesInput.formula !== undefined) {
      series.formula = seriesInput.formula;
    }
    if (seriesInput.categoryFormula !== undefined) {
      series.categoryFormula = seriesInput.categoryFormula;
    }
    if (seriesInput.xFormula !== undefined) {
      series.xFormula = seriesInput.xFormula;
    }
    if (seriesInput.valuesFormatCode !== undefined) {
      series.valuesFormatCode = seriesInput.valuesFormatCode;
    }
    if (seriesInput.xValuesFormatCode !== undefined) {
      series.xValuesFormatCode = seriesInput.xValuesFormatCode;
    }
    if (seriesInput.fill !== undefined) {
      series.fill = seriesInput.fill;
    }
    if (seriesInput.stroke) {
      const stroke = seriesInput.stroke;
      if (stroke.fill !== undefined) {
        series.stroke.fill = stroke.fill;
      }
      if (stroke.style !== undefined) {
        series.stroke.style = stroke.style;
      }
      if (stroke.width !== undefined) {
        series.stroke.width = stroke.width;
      }
    }
    if (seriesInput.marker) {
      const marker = seriesInput.marker;
      if (marker.symbol !== undefined) {
        series.marker.symbol = marker.symbol;
      }
      if (marker.size !== undefined) {
        series.marker.size = marker.size;
      }
    }
  }
};
var applyChartSubtypeOptions = (chart2, props) => {
  if (props.barOptions) {
    if (props.barOptions.direction !== undefined) {
      chart2.barOptions.direction = props.barOptions.direction;
    }
    if (props.barOptions.grouping !== undefined) {
      chart2.barOptions.grouping = props.barOptions.grouping;
    }
    if (props.barOptions.varyColors !== undefined) {
      chart2.barOptions.varyColors = props.barOptions.varyColors;
    }
    if (props.barOptions.gapWidth !== undefined) {
      chart2.barOptions.gapWidth = props.barOptions.gapWidth;
    }
    if (props.barOptions.gapDepth !== undefined) {
      chart2.barOptions.gapDepth = props.barOptions.gapDepth;
    }
    if (props.barOptions.overlap !== undefined) {
      chart2.barOptions.overlap = props.barOptions.overlap;
    }
    if (props.barOptions.bar3dShape !== undefined) {
      chart2.barOptions.bar3dShape = props.barOptions.bar3dShape;
    }
  }
  if (props.pieOptions?.firstSliceAngle !== undefined) {
    chart2.pieOptions.firstSliceAngle = props.pieOptions.firstSliceAngle;
  }
  if (props.doughnutOptions) {
    if (props.doughnutOptions.holeSize !== undefined) {
      chart2.doughnutOptions.holeSize = props.doughnutOptions.holeSize;
    }
    if (props.doughnutOptions.firstSliceAngle !== undefined) {
      chart2.doughnutOptions.firstSliceAngle = props.doughnutOptions.firstSliceAngle;
    }
  }
};
var applyChartTypeResolution = (chart2, resolution) => {
  if (!resolution) {
    return;
  }
  if (resolution.barDirection) {
    chart2.barOptions.direction = resolution.barDirection;
  }
  if (resolution.barGrouping) {
    chart2.barOptions.grouping = resolution.barGrouping;
  }
};

class WorksheetChartOfficeCompat {
  #chart;
  #titleProxy;
  #axesProxy;
  constructor(chart2) {
    this.#chart = chart2;
    const titleProxy = {};
    Object.defineProperty(titleProxy, "text", {
      get: () => this.#chart.titleText,
      set: (value) => {
        this.#chart.titleText = typeof value === "string" ? value : "";
      }
    });
    this.#titleProxy = titleProxy;
    installAxisTitleTextCompat(this.#chart.yAxis);
    installAxisTitleTextCompat(this.#chart.xAxis);
    const axesProxy = {};
    Object.defineProperty(axesProxy, "valueAxis", {
      get: () => this.#chart.yAxis
    });
    Object.defineProperty(axesProxy, "categoryAxis", {
      get: () => this.#chart.xAxis
    });
    this.#axesProxy = axesProxy;
  }
  get title() {
    return this.#titleProxy;
  }
  get axes() {
    return this.#axesProxy;
  }
  get plotArea() {
    return this.#chart.plotArea;
  }
  get chartArea() {
    return this.#chart.chartArea;
  }
  get width() {
    return this.#chart.anchor.extent?.widthPx;
  }
  set width(value) {
    if (!Number.isFinite(value ?? undefined)) {
      return;
    }
    this.#chart.anchor.extent = {
      widthPx: Math.max(0, value)
    };
  }
  get height() {
    return this.#chart.anchor.extent?.heightPx;
  }
  set height(value) {
    if (!Number.isFinite(value ?? undefined)) {
      return;
    }
    this.#chart.anchor.extent = {
      heightPx: Math.max(0, value)
    };
  }
  setPosition(target, end) {
    const address = typeof target === "string" ? target : target?.address;
    if (!address) {
      return;
    }
    const parsed = parseRangeAddress(address);
    if (!parsed) {
      return;
    }
    this.#chart.anchor.from = {
      row: parsed.bounds.startRow,
      col: parsed.bounds.startCol
    };
    if (!end) {
      if (parsed.bounds.endRow !== parsed.bounds.startRow || parsed.bounds.endCol !== parsed.bounds.startCol) {
        this.#chart.anchor.to = {
          row: parsed.bounds.endRow + 1,
          col: parsed.bounds.endCol + 1
        };
      }
      return;
    }
    const endAddress = typeof end === "string" ? end : end?.address;
    if (!endAddress) {
      return;
    }
    const endParsed = parseRangeAddress(endAddress);
    if (!endParsed) {
      return;
    }
    this.#chart.anchor.to = {
      row: endParsed.bounds.endRow + 1,
      col: endParsed.bounds.endCol + 1
    };
  }
  setData(sourceData, seriesBy) {
    this.#chart.setData(sourceData, seriesBy);
  }
}

class WorksheetShape extends Shape2 {
  anchor;
  #onDelete;
  #context;
  #createdInRecorder;
  constructor(context, init, onDelete, options) {
    if ("proto" in init) {
      const elementProto = init.proto.shape ?? {
        id: "",
        name: "",
        type: 5 /* ELEMENT_TYPE_SHAPE */,
        shape: {
          geometry: 5 /* SHAPE_GEOMETRY_RECT */,
          fill: undefined,
          adjustmentList: [],
          rectFormula: undefined,
          customPaths: []
        },
        paragraphs: [],
        effects: [],
        children: [],
        levelsStyles: [],
        citations: []
      };
      super(context, { proto: elementProto });
      if (options?.id) {
        this.data.id = options.id;
      }
      this.#context = context;
      this.#createdInRecorder = options?.createdInRecorder;
      this.anchor = new DrawingAnchor(init.proto);
      this.#onDelete = onDelete;
      this.anchor.setChangeHandler(() => this.#recordShapeSet());
      return;
    }
    const { anchor, ...shapeConfig } = init;
    super(context, shapeConfig);
    if (options?.id) {
      this.data.id = options.id;
    }
    this.#context = context;
    this.#createdInRecorder = options?.createdInRecorder;
    this.anchor = new DrawingAnchor(undefined, anchor);
    this.#onDelete = onDelete;
    this.anchor.setChangeHandler(() => this.#recordShapeSet());
  }
  resolveBoundsPx(layout, options) {
    return this.anchor.resolveBoundsPx(layout, options);
  }
  captureAnchorSnapshot() {
    return this.anchor.captureSnapshot();
  }
  restoreAnchorSnapshot(snapshot) {
    this.anchor.restoreSnapshot(snapshot);
  }
  setPreviewBoundsPx(bounds, layout, options) {
    this.anchor.setPreviewBoundsPx(bounds, layout, options);
  }
  clearPreviewBounds() {
    this.anchor.clearPreviewBounds();
  }
  applyBoundsPx(bounds, layout, options) {
    this.anchor.applyBoundsPx(bounds, layout, options);
  }
  toDrawingProto(options) {
    const { fromAnchor, toAnchor, extentCx, extentCy } = this.anchor.toProtoFields(options);
    const shape2 = this.toProto();
    if (!shape2.bbox) {
      const bbox = buildShapeBbox(this.anchor, options);
      if (bbox) {
        shape2.bbox = bbox;
      }
    }
    return {
      fromAnchor,
      toAnchor,
      extentCx,
      extentCy,
      shape: shape2
    };
  }
  delete() {
    this.#onDelete?.(this);
  }
  recordShapeSet(props) {
    this.#recordShapeSet();
  }
  #recordShapeSet() {
    const recorder = this.#context.getRecorder();
    const sheet = this.#context.getSheetName();
    if (!recorder || !sheet) {
      return;
    }
    if (this.#createdInRecorder === recorder) {
      return;
    }
    recorder.deferOnce(`shape.set:${this.id}`, () => buildShapeSetOpFromShape({ sheet, shape: this }));
  }
}
var buildShapeBbox = (anchor, options) => {
  const protoFields = anchor.toProtoFields(options);
  const extent2 = extentStateFromProto({
    extentCx: protoFields.extentCx,
    extentCy: protoFields.extentCy
  });
  const extentPx = extentSnapshot(extent2);
  if (extentPx?.widthPx && extentPx?.heightPx) {
    return {
      xEmu: 0,
      yEmu: 0,
      widthEmu: Math.round(extentPx.widthPx * EMUS_PER_PIXEL),
      heightEmu: Math.round(extentPx.heightPx * EMUS_PER_PIXEL)
    };
  }
  const fromState = anchorStateFromProto(protoFields.fromAnchor);
  const toState = anchorStateFromProto(protoFields.toAnchor);
  if (!fromState || !toState) {
    return null;
  }
  const from2 = anchorSnapshot(fromState);
  const to = anchorSnapshot(toState);
  if (!to) {
    return null;
  }
  const cols = Math.max(1, to.col - from2.col);
  const rows = Math.max(1, to.row - from2.row);
  const widthPx = cols * FALLBACK_COL_W_PX_RAW + (to.colOffsetPx ?? 0) - (from2.colOffsetPx ?? 0);
  const heightPx = rows * pointsToPx(FALLBACK_ROW_H_PT) + (to.rowOffsetPx ?? 0) - (from2.rowOffsetPx ?? 0);
  return {
    xEmu: 0,
    yEmu: 0,
    widthEmu: Math.round(Math.max(1, widthPx) * EMUS_PER_PIXEL),
    heightEmu: Math.round(Math.max(1, heightPx) * EMUS_PER_PIXEL)
  };
};

class WorksheetChartsStore {
  #root;
  #getRoot;
  #getOrCreateRoot;
  #byId;
  #order;
  constructor(config2) {
    this.#root = config2?.root;
    this.#getRoot = config2?.getRoot;
    this.#getOrCreateRoot = config2?.getOrCreateRoot;
    this.#syncRefs();
  }
  get enabled() {
    return Boolean(this.#root || this.#getRoot || this.#getOrCreateRoot);
  }
  get isEmpty() {
    this.#syncRefs();
    if (!this.enabled) {
      return true;
    }
    return (this.#order?.length ?? 0) === 0 && (this.#byId?.size ?? 0) === 0;
  }
  observe(handler) {
    this.#syncRefs();
    this.#root?.observeDeep((_events, transaction) => handler(transaction));
  }
  ingestBaseline(drawings) {
    if (!this.enabled) {
      return;
    }
    let byId;
    let order;
    let initialized = false;
    for (const drawing of drawings) {
      if (!drawing?.chart) {
        continue;
      }
      if (!initialized) {
        byId = this.#ensureById();
        order = this.#ensureOrder();
        this.#byId = byId;
        this.#order = order;
        initialized = true;
      }
      const entry = buildChartStoreEntry(drawing);
      byId?.set(entry.id, entry);
      order?.push([entry.id]);
    }
  }
  getOrder() {
    this.#syncRefs();
    if (!this.enabled || !this.#order) {
      return [];
    }
    const seen = new Set;
    const ordered = [];
    for (const id2 of this.#order.toArray()) {
      if (seen.has(id2)) {
        continue;
      }
      seen.add(id2);
      if (this.#byId?.has(id2)) {
        ordered.push(id2);
      }
    }
    for (const id2 of this.#byId?.keys() ?? []) {
      if (seen.has(id2)) {
        continue;
      }
      seen.add(id2);
      ordered.push(id2);
    }
    return ordered;
  }
  getEntry(id2) {
    this.#syncRefs();
    if (!this.enabled) {
      return;
    }
    return this.#byId?.get(id2);
  }
  getDrawing(id2) {
    const entry = this.getEntry(id2);
    return entry ? buildDrawingFromStoreEntry(entry) : undefined;
  }
  setEntry(entry, appendOrder = false) {
    if (!this.enabled) {
      return;
    }
    this.#byId = this.#ensureById();
    this.#order = this.#ensureOrder();
    this.#byId.set(entry.id, entry);
    const existingOrder = this.#order.toArray();
    const hasId = existingOrder.includes(entry.id);
    if (!hasId || appendOrder) {
      if (!hasId) {
        this.#order.push([entry.id]);
      }
    }
  }
  delete(id2) {
    this.#syncRefs();
    if (!this.enabled || !this.#byId || !this.#order) {
      return;
    }
    this.#byId.delete(id2);
    const order = this.#order.toArray().filter((candidate) => candidate !== id2);
    this.#order.delete(0, this.#order.length);
    if (order.length > 0) {
      this.#order.insert(0, order);
    }
  }
  clear() {
    this.#syncRefs();
    if (!this.enabled || !this.#byId || !this.#order) {
      return;
    }
    for (const key of this.#byId.keys()) {
      this.#byId.delete(key);
    }
    this.#order.delete(0, this.#order.length);
  }
  toProto() {
    if (!this.enabled) {
      return [];
    }
    const drawings = [];
    for (const id2 of this.getOrder()) {
      const drawing = this.getDrawing(id2);
      if (drawing) {
        drawings.push(drawing);
      }
    }
    return drawings;
  }
  #syncRefs() {
    if (this.#getRoot) {
      this.#root = this.#getRoot();
    }
    this.#byId = this.#getById();
    this.#order = this.#getOrderArray();
  }
  #ensureRoot() {
    if (this.#root) {
      return this.#root;
    }
    this.#root = this.#getOrCreateRoot?.() ?? this.#getRoot?.();
    return this.#root;
  }
  #getById() {
    const existing = this.#root?.get("byId");
    if (existing instanceof YMap) {
      return existing;
    }
    return;
  }
  #ensureById() {
    this.#ensureRoot();
    const existing = this.#getById();
    if (existing) {
      return existing;
    }
    const created = new YMap;
    this.#root?.set("byId", created);
    return created;
  }
  #getOrderArray() {
    const existing = this.#root?.get("order");
    if (existing instanceof YArray) {
      return existing;
    }
    return;
  }
  #ensureOrder() {
    this.#ensureRoot();
    const existing = this.#getOrderArray();
    if (existing) {
      return existing;
    }
    const created = new YArray;
    this.#root?.set("order", created);
    return created;
  }
}
function cloneDrawingProto(drawing) {
  return JSON.parse(JSON.stringify(drawing));
}
function createSeriesId() {
  return `series-${generateAidSuffix()}`;
}
function buildChartStoreEntry(drawing, previous) {
  const cloned = cloneDrawingProto(drawing);
  const chart2 = cloned.chart ?? {};
  const chartId = chart2.id?.trim() ? chart2.id : generateAidSuffix();
  chart2.id = chartId;
  chart2.series ??= [];
  const nextSeriesOrder = [];
  const nextSeriesById = {};
  const sourceSeries = [...chart2.series ?? []];
  const previousOrder = previous?.seriesOrder ?? [];
  for (let index = 0;index < sourceSeries.length; index += 1) {
    const series = sourceSeries[index];
    if (!series) {
      continue;
    }
    const seriesId = previousOrder[index] ?? createSeriesId();
    nextSeriesOrder.push(seriesId);
    nextSeriesById[seriesId] = series;
  }
  chart2.series = [];
  cloned.chart = chart2;
  return {
    id: chartId,
    drawing: cloned,
    seriesById: nextSeriesById,
    seriesOrder: nextSeriesOrder
  };
}
function buildDrawingFromStoreEntry(entry) {
  const drawing = cloneDrawingProto(entry.drawing);
  if (!drawing.chart) {
    return drawing;
  }
  const orderedSeries = entry.seriesOrder.map((seriesId) => entry.seriesById[seriesId]).filter((series) => Boolean(series));
  drawing.chart.series = orderedSeries;
  return drawing;
}

class WorksheetChartCollection {
  #fallbackItems;
  #context;
  #store;
  #itemsById;
  #storeEntryRefsById;
  #createdInRecorder = new WeakMap;
  #deletedInRecorder = new WeakSet;
  constructor(protos, context) {
    this.#context = context;
    this.#fallbackItems = this.#buildFallbackCharts(protos ?? []);
    this.#itemsById = new Map;
    this.#storeEntryRefsById = new Map;
    this.#store = new WorksheetChartsStore({
      root: context?.getChartsState?.(),
      getRoot: context ? () => this.#context?.getChartsState?.() : undefined,
      getOrCreateRoot: context ? () => this.#context?.getOrCreateChartsState?.() : undefined
    });
    if (this.#store.enabled) {
      this.#store.observe((transaction) => this.#handleStoreTransaction(transaction));
      return;
    }
  }
  get items() {
    if (this.#shouldUseFallbackItems()) {
      return [...this.#fallbackItems];
    }
    const store = this.#store;
    if (!store) {
      return [];
    }
    this.#syncFromStore();
    return store.getOrder().map((id2) => this.#itemsById.get(id2)).filter((chart2) => Boolean(chart2));
  }
  getItem(name) {
    const chart2 = this.getItemOrNullObject(name);
    if (chart2.isNullObject) {
      throw new Error(`Chart ${name} not found`);
    }
    return chart2;
  }
  getItemAt(index) {
    const chart2 = this.items[index];
    if (!chart2) {
      throw new Error(`Chart at index ${index} not found`);
    }
    return chart2;
  }
  getItemOrNullObject(name) {
    const normalized = String(name ?? "").trim();
    if (!normalized) {
      return new NullWorksheetChart("");
    }
    for (const chart2 of this.items) {
      const title = chart2.titleText?.trim() ?? "";
      if (title === normalized || chart2.id === normalized) {
        return chart2;
      }
    }
    return new NullWorksheetChart(normalized);
  }
  deleteAll() {
    if (this.#shouldUseFallbackItems()) {
      for (const chart2 of [...this.#fallbackItems]) {
        chart2.delete();
      }
      return;
    }
    for (const chart2 of [...this.items]) {
      chart2.delete();
    }
  }
  clear() {
    this.deleteAll();
  }
  add(typeOrName, anchorOrSource, _seriesBy) {
    let chart2;
    if (isChartPropsInput(anchorOrSource)) {
      const props = anchorOrSource;
      const rawType = props.chartType ?? typeOrName;
      const resolution2 = resolveChartType2(rawType);
      if (!resolution2) {
        throw buildUnsupportedChartTypeError(rawType);
      }
      chart2 = this.#createChart(resolution2.chartType, props.anchor);
      applyChartTypeResolution(chart2, resolution2);
      if (props.title !== undefined) {
        chart2.title = props.title;
      }
      if (props.categories) {
        chart2.categories = [...props.categories];
      }
      if (props.series) {
        applyChartSeriesInputs(chart2, props.series);
      }
      if (props.hasLegend !== undefined) {
        chart2.hasLegend = props.hasLegend;
      } else if (props.legend) {
        chart2.hasLegend = true;
      }
      if (props.legend?.position !== undefined) {
        chart2.legend.position = props.legend.position;
      }
      if (props.dataLabels) {
        const dataLabels = props.dataLabels;
        if (dataLabels.showValue !== undefined) {
          chart2.dataLabels.showValue = dataLabels.showValue;
        }
        if (dataLabels.showSeriesName !== undefined) {
          chart2.dataLabels.showSeriesName = dataLabels.showSeriesName;
        }
        if (dataLabels.showCategoryName !== undefined) {
          chart2.dataLabels.showCategoryName = dataLabels.showCategoryName;
        }
        if (dataLabels.showPercent !== undefined) {
          chart2.dataLabels.showPercent = dataLabels.showPercent;
        }
        if (dataLabels.showLeaderLines !== undefined) {
          chart2.dataLabels.showLeaderLines = dataLabels.showLeaderLines;
        }
      }
      if (props.displayBlanksAs !== undefined) {
        chart2.displayBlanksAs = props.displayBlanksAs;
      }
      applyChartSubtypeOptions(chart2, props);
      return chart2;
    }
    if (isRangeLike(anchorOrSource)) {
      const resolution2 = resolveChartType2(typeOrName);
      if (!resolution2) {
        throw buildUnsupportedChartTypeError(String(typeOrName ?? "unknown"));
      }
      chart2 = this.#createChart(resolution2.chartType);
      applyChartTypeResolution(chart2, resolution2);
      applyChartDataFromRangeLike(chart2, anchorOrSource);
      return chart2;
    }
    const resolution = typeof typeOrName === "string" ? resolveChartType2(typeOrName) : null;
    if (typeof typeOrName === "string" && !resolution) {
      throw buildUnsupportedChartTypeError(typeOrName);
    }
    const chartType = resolution?.chartType ?? typeOrName;
    const anchorConfig = isChartAnchorPropsInput(anchorOrSource) ? anchorOrSource : undefined;
    chart2 = this.#createChart(chartType, anchorConfig);
    applyChartTypeResolution(chart2, resolution);
    if (anchorConfig) {
      if (anchorConfig.title !== undefined)
        chart2.title = anchorConfig.title;
      if (anchorConfig.categories)
        chart2.categories = [...anchorConfig.categories];
      if (anchorConfig.series)
        applyChartSeriesInputs(chart2, anchorConfig.series);
      if (anchorConfig.hasLegend !== undefined) {
        chart2.hasLegend = anchorConfig.hasLegend;
      } else if (anchorConfig.legend) {
        chart2.hasLegend = true;
      }
      if (anchorConfig.legend?.position !== undefined) {
        chart2.legend.position = anchorConfig.legend.position;
      }
      if (anchorConfig.dataLabels) {
        const dataLabels = anchorConfig.dataLabels;
        if (dataLabels.showValue !== undefined)
          chart2.dataLabels.showValue = dataLabels.showValue;
        if (dataLabels.showSeriesName !== undefined)
          chart2.dataLabels.showSeriesName = dataLabels.showSeriesName;
        if (dataLabels.showCategoryName !== undefined)
          chart2.dataLabels.showCategoryName = dataLabels.showCategoryName;
        if (dataLabels.showPercent !== undefined)
          chart2.dataLabels.showPercent = dataLabels.showPercent;
        if (dataLabels.showLeaderLines !== undefined)
          chart2.dataLabels.showLeaderLines = dataLabels.showLeaderLines;
      }
      if (anchorConfig.displayBlanksAs !== undefined) {
        chart2.displayBlanksAs = anchorConfig.displayBlanksAs;
      }
      applyChartSubtypeOptions(chart2, anchorConfig);
    }
    return chart2;
  }
  __addForApply(input) {
    return this.#createChart(input.chartType, input.anchor, input.id);
  }
  #deleteChart(target) {
    this.#recordChartRemove(target);
    if (this.#shouldUseFallbackItems()) {
      this.#fallbackItems = this.#fallbackItems.filter((item) => item !== target);
      return;
    }
    const store = this.#store;
    if (!store || store.isEmpty) {
      return;
    }
    this.#runLocalTransaction(() => store.delete(target.id));
    this.#itemsById.delete(target.id);
    this.#storeEntryRefsById.delete(target.id);
  }
  #createChart(type, anchor, id2) {
    let anchorWithDefaults;
    if (anchor) {
      anchorWithDefaults = { ...anchor };
      const hasExtent = anchor.extent !== undefined;
      const hasTo = anchor.to !== undefined;
      if (!hasExtent && !hasTo) {
        anchorWithDefaults = { ...anchorWithDefaults };
        anchorWithDefaults.to = {
          row: anchorWithDefaults.from.row + 14,
          col: anchorWithDefaults.from.col + 8
        };
      }
    } else {
      anchorWithDefaults = {
        from: { row: 0, col: 0 },
        to: { row: 14, col: 8 }
      };
    }
    const recorder = this.#context?.getRecorder();
    const chart2 = new WorksheetChart(undefined, {
      id: id2,
      type,
      anchor: anchorWithDefaults,
      onDelete: (target) => this.#deleteChart(target),
      onChange: (target) => this.#handleChartChanged(target),
      context: this.#context,
      createdInRecorder: recorder
    });
    if (type === "scatter" && chart2.scatterOptions.style === undefined) {
      chart2.scatterOptions.style = "marker";
    }
    chart2.chartSpaceLine.style = "solid";
    chart2.chartSpaceLine.width = 1;
    chart2.chartSpaceLine.color = "#D9D9D9";
    chart2.xAxis = {
      visible: true,
      tickLabelPosition: "nextToAxis",
      majorGridlines: { color: "#CCCCCC", style: "dashed", weight: 1 }
    };
    chart2.yAxis = {
      majorGridlines: { color: "#CCCCCC", style: "dashed", weight: 1 }
    };
    chart2.hasLegend = true;
    chart2.legend.position = "bottom";
    if (this.#shouldUseFallbackItems()) {
      this.#fallbackItems.push(chart2);
    } else {
      let syncedEntry;
      this.#runLocalTransaction(() => {
        const entry = buildChartStoreEntry(chart2.toDrawingProto());
        this.#store?.setEntry(entry, true);
        syncedEntry = this.#store?.getEntry(entry.id) ?? entry;
      });
      this.#itemsById.set(chart2.id, chart2);
      if (syncedEntry) {
        this.#storeEntryRefsById.set(chart2.id, syncedEntry);
      }
      this.#syncFromStore();
    }
    if (recorder) {
      this.#createdInRecorder.set(chart2, recorder);
      const sheetName = this.#context?.getSheetName();
      if (sheetName) {
        const alias = recorder.assignAlias(chart2, `ch/${chart2.id}`, "chart");
        const fallbackType = type;
        recorder.defer(() => this.#deletedInRecorder.has(chart2) ? null : buildChartAddOp({
          sheet: sheetName,
          chart: chart2,
          fallbackType,
          as: alias
        }));
      }
    }
    return chart2;
  }
  toProto() {
    if (this.#shouldUseFallbackItems()) {
      return this.#fallbackItems.map((chart2) => chart2.toDrawingProto());
    }
    return this.items.map((chart2) => chart2.toDrawingProto());
  }
  hydrateFromFallbackState() {
    if (!this.#store?.enabled || !this.#store.isEmpty) {
      return;
    }
    const fallbackProtos = this.#fallbackItems.map((chart2) => chart2.toDrawingProto());
    this.#runLocalTransaction(() => this.#store?.ingestBaseline(fallbackProtos));
    this.#syncFromStore();
    this.#fallbackItems = [];
  }
  #recordChartRemove(chart2) {
    const recorder = this.#context?.getRecorder();
    const sheet = this.#context?.getSheetName();
    if (!recorder || !sheet) {
      return;
    }
    if (this.#createdInRecorder.get(chart2) === recorder) {
      this.#deletedInRecorder.add(chart2);
      return;
    }
    const op = {
      op: "chart.remove",
      target: {
        sheet,
        selector: buildChartTargetSelector(chart2)
      }
    };
    recorder.record(op);
  }
  #handleChartChanged(chart2) {
    if (this.#shouldUseFallbackItems()) {
      if (!this.#fallbackItems.includes(chart2)) {
        this.#fallbackItems.push(chart2);
      }
      return;
    }
    if (!this.#store?.enabled) {
      return;
    }
    if (this.#store.isEmpty) {
      this.#fallbackItems = this.#fallbackItems.filter((item) => item !== chart2);
    }
    this.#runLocalTransaction(() => {
      const previous = this.#store?.getEntry(chart2.id);
      const entry = buildChartStoreEntry(chart2.toDrawingProto(), previous);
      this.#store?.setEntry(entry, false);
      const syncedEntry = this.#store?.getEntry(chart2.id) ?? entry;
      this.#storeEntryRefsById.set(chart2.id, syncedEntry);
      this.#itemsById.set(chart2.id, chart2);
    });
  }
  #syncFromStore() {
    if (!this.#store?.enabled) {
      return;
    }
    const nextCharts = new Map;
    const nextEntryRefs = new Map;
    for (const id2 of this.#store.getOrder()) {
      const entry = this.#store.getEntry(id2);
      if (!entry) {
        continue;
      }
      const cached2 = this.#itemsById.get(id2);
      const cachedEntry = this.#storeEntryRefsById.get(id2);
      if (cached2 && cachedEntry === entry) {
        nextCharts.set(id2, cached2);
        nextEntryRefs.set(id2, entry);
        continue;
      }
      const drawing = buildDrawingFromStoreEntry(entry);
      nextCharts.set(id2, new WorksheetChart(drawing, {
        onDelete: (chart2) => this.#deleteChart(chart2),
        onChange: (chart2) => this.#handleChartChanged(chart2),
        context: this.#context
      }));
      nextEntryRefs.set(id2, entry);
    }
    this.#itemsById = nextCharts;
    this.#storeEntryRefsById = nextEntryRefs;
  }
  #handleStoreTransaction(transaction) {
    const origins = this.#context?.getCollabOrigins?.();
    if (origins && (transaction.origin === origins.local || transaction.origin === origins.record)) {
      return;
    }
    this.#itemsById.clear();
    this.#storeEntryRefsById.clear();
    this.#syncFromStore();
  }
  #runLocalTransaction(fn) {
    const run = this.#context?.runLocalTransaction;
    if (!run) {
      return fn();
    }
    return run(fn);
  }
  #buildFallbackCharts(protos) {
    return (protos ?? []).filter((drawing) => drawing?.chart).map((drawing) => new WorksheetChart(drawing, {
      onDelete: (chart2) => this.#deleteChart(chart2),
      onChange: (chart2) => this.#handleChartChanged(chart2),
      context: this.#context
    }));
  }
  #shouldUseFallbackItems() {
    if (!this.#store?.enabled) {
      return true;
    }
    if (!this.#context?.isCollaborativeStateReady?.()) {
      return true;
    }
    return false;
  }
}

class WorksheetShapeCollection {
  #context;
  #items;
  #createdInRecorder = new WeakMap;
  #deletedInRecorder = new WeakSet;
  constructor(context, protos) {
    this.#context = context;
    const seenIds = new Set;
    this.#items = (protos ?? []).filter((drawing) => drawing?.shape).map((drawing) => {
      const id2 = this.#resolveShapeId(drawing?.shape?.id, seenIds);
      seenIds.add(id2);
      return new WorksheetShape(this.#context, { proto: drawing }, (shape2) => this.#deleteShape(shape2), { id: id2 });
    });
  }
  get items() {
    return [...this.#items];
  }
  deleteAll() {
    for (const shape2 of [...this.#items]) {
      shape2.delete();
    }
  }
  add(configOrGeometry, anchor) {
    const config2 = resolveWorksheetShapeConfig(configOrGeometry, anchor);
    return this.#addShapeInternal(config2);
  }
  __addForApply(config2) {
    return this.#addShapeInternal(config2, { explicitId: config2.id });
  }
  #addShapeInternal(config2, options) {
    const explicitId = options?.explicitId;
    if (explicitId && this.#items.some((item) => item.id === explicitId)) {
      throw new Error(`Shape id already exists: ${explicitId}`);
    }
    const shapeId = explicitId ?? this.#resolveShapeId(undefined, new Set(this.#items.map((item) => item.id)));
    const recorder = this.#context.getRecorder();
    const shape2 = new WorksheetShape(this.#context, config2, (target) => this.#deleteShape(target), { id: shapeId, createdInRecorder: recorder });
    this.#items.push(shape2);
    const sheet = this.#context.getSheetName();
    if (recorder && sheet && config2.geometry !== "connector") {
      this.#createdInRecorder.set(shape2, recorder);
      const alias = recorder.assignAlias(shape2, `sh/${shape2.id}`, "shape");
      recorder.defer(() => this.#deletedInRecorder.has(shape2) ? null : buildShapeAddOpFromShape({ sheet, shape: shape2, as: alias }));
    }
    this.#context.queueCollaborativePublish?.();
    return shape2;
  }
  toProto() {
    return this.#items.map((shape2) => shape2.toDrawingProto());
  }
  replace(protos) {
    const seenIds = new Set;
    this.#items = (protos ?? []).filter((drawing) => drawing?.shape).map((drawing) => {
      const id2 = this.#resolveShapeId(drawing?.shape?.id, seenIds);
      seenIds.add(id2);
      return new WorksheetShape(this.#context, { proto: drawing }, (shape2) => this.#deleteShape(shape2), { id: id2 });
    });
  }
  #deleteShape(target) {
    this.#recordShapeRemove(target);
    this.#items = this.#items.filter((item) => item !== target);
    this.#context.queueCollaborativePublish?.();
  }
  #recordShapeRemove(shape2) {
    const recorder = this.#context.getRecorder();
    const sheet = this.#context.getSheetName();
    if (!recorder || !sheet) {
      return;
    }
    if (this.#createdInRecorder.get(shape2) === recorder) {
      this.#deletedInRecorder.add(shape2);
      return;
    }
    const op = {
      op: "shape.remove",
      target: {
        sheet,
        selector: buildShapeTargetSelector(shape2)
      }
    };
    recorder.record(op);
  }
  #resolveShapeId(id2, seenIds) {
    const normalized = id2?.trim();
    if (normalized && !seenIds.has(normalized)) {
      return normalized;
    }
    let nextId = generateAidSuffix();
    while (seenIds.has(nextId)) {
      nextId = generateAidSuffix();
    }
    return nextId;
  }
}
var resolveWorksheetShapeConfig = (configOrGeometry, anchor) => {
  if (typeof configOrGeometry === "string") {
    const geometry2 = resolveShapeGeometryName(configOrGeometry);
    if (!geometry2) {
      throw buildUnsupportedShapeGeometryError(configOrGeometry);
    }
    if (geometry2 === "custom" || geometry2 === "connector") {
      throw new Error(`Geometry '${geometry2}' requires a config object with a full shape definition. ` + "Use workbook.help('worksheet.shapes.add') for examples.");
    }
    const resolvedAnchor2 = resolveDrawingAnchor(anchor);
    return resolvedAnchor2 ? { geometry: geometry2, anchor: resolvedAnchor2 } : { geometry: geometry2 };
  }
  if (!isRecord3(configOrGeometry)) {
    throw new Error("worksheet.shapes.add expects a geometry string or a config object. " + "Use workbook.help('worksheet.shapes.add') for examples.");
  }
  const record2 = configOrGeometry;
  const rawGeometry = typeof record2["geometry"] === "string" ? record2["geometry"] : typeof record2["type"] === "string" ? record2["type"] : undefined;
  const geometry = resolveShapeGeometryName(rawGeometry ?? "");
  if (!geometry) {
    throw buildUnsupportedShapeGeometryError(rawGeometry);
  }
  const widthPx = toFiniteNumber(record2["width"]);
  const heightPx = toFiniteNumber(record2["height"]);
  const resolvedAnchor = applyExtentOverrides(resolveDrawingAnchor(record2["anchor"] ?? anchor), widthPx, heightPx);
  return {
    ...configOrGeometry,
    geometry,
    ...resolvedAnchor ? { anchor: resolvedAnchor } : {}
  };
};
var nextWorksheetImageInstanceId = 1;

class WorksheetImage {
  id;
  anchor;
  #imageId;
  #onDelete;
  #context;
  #createdInRecorder;
  constructor(init, onDelete, options) {
    this.id = `worksheet-image-${nextWorksheetImageInstanceId++}`;
    if ("proto" in init) {
      const imageId = init.proto.imageReference?.id;
      if (!imageId) {
        throw new Error("Worksheet image drawing must include an image reference.");
      }
      this.#imageId = imageId;
      this.anchor = new DrawingAnchor(init.proto);
      this.#onDelete = onDelete;
      this.#context = options?.context;
      this.#createdInRecorder = options?.createdInRecorder;
      this.anchor.setChangeHandler((previous) => {
        this.#recordSet({
          sheet: "",
          imageId: this.#imageId,
          anchor: previous
        });
      });
      return;
    }
    this.#imageId = init.imageId;
    this.anchor = new DrawingAnchor(undefined, init.anchor);
    this.#onDelete = onDelete;
    this.#context = options?.context;
    this.#createdInRecorder = options?.createdInRecorder;
    this.anchor.setChangeHandler((previous) => {
      this.#recordSet({
        sheet: "",
        imageId: this.#imageId,
        anchor: previous
      });
    });
  }
  get imageId() {
    return this.#imageId;
  }
  set imageId(value) {
    const previous = {
      sheet: "",
      imageId: this.#imageId,
      anchor: this.anchor.toConfig()
    };
    this.#imageId = value;
    this.#recordSet(previous);
  }
  replace(source) {
    if (!this.#context) {
      throw new Error("Worksheet image replacement requires a workbook context.");
    }
    const previous = {
      sheet: "",
      imageId: this.#imageId,
      anchor: this.anchor.toConfig()
    };
    const imageAsset = this.#context.createImageAsset(source);
    this.#imageId = imageAsset.id;
    this.#recordSet(previous, source);
    this.#context.queueCollaborativePublish?.();
  }
  resolveBoundsPx(layout, options) {
    return this.anchor.resolveBoundsPx(layout, options);
  }
  captureAnchorSnapshot() {
    return this.anchor.captureSnapshot();
  }
  restoreAnchorSnapshot(snapshot) {
    this.anchor.restoreSnapshot(snapshot);
  }
  setPreviewBoundsPx(bounds, layout, options) {
    this.anchor.setPreviewBoundsPx(bounds, layout, options);
  }
  clearPreviewBounds() {
    this.anchor.clearPreviewBounds();
  }
  applyBoundsPx(bounds, layout, options) {
    this.anchor.applyBoundsPx(bounds, layout, options);
  }
  toDrawingProto(options) {
    const { fromAnchor, toAnchor, extentCx, extentCy } = this.anchor.toProtoFields(options);
    return {
      fromAnchor,
      toAnchor,
      extentCx,
      extentCy,
      imageReference: {
        id: this.#imageId
      }
    };
  }
  delete() {
    this.#onDelete?.(this);
  }
  #recordSet(previous, source) {
    const recorder = this.#context?.getRecorder();
    const sheet = this.#context?.getSheetName();
    if (!recorder || !sheet) {
      return;
    }
    if (this.#createdInRecorder === recorder) {
      return;
    }
    const targetImageId = recorder.getAlias(this) ?? previous.imageId;
    recorder.record(buildImageSetOp({
      sheet,
      image: this,
      previous,
      source,
      targetImageId
    }));
  }
}

class WorksheetImageCollection {
  #context;
  #items;
  #createdInRecorder = new WeakMap;
  #deletedInRecorder = new WeakSet;
  constructor(context, protos) {
    this.#context = context;
    this.#items = (protos ?? []).map((drawing) => new WorksheetImage({ proto: drawing }, (image2) => this.#deleteImage(image2), { context }));
  }
  get items() {
    return [...this.#items];
  }
  deleteAll() {
    for (const image2 of [...this.#items]) {
      image2.delete();
    }
  }
  add(config2) {
    const { anchor, ...source } = config2;
    const imageAsset = this.#context.createImageAsset(source);
    const recorder = this.#context.getRecorder();
    const image2 = new WorksheetImage({
      imageId: imageAsset.id,
      anchor
    }, (target) => this.#deleteImage(target), { context: this.#context, createdInRecorder: recorder });
    this.#items.push(image2);
    const sheet = this.#context.getSheetName();
    if (recorder && sheet) {
      this.#createdInRecorder.set(image2, recorder);
      const alias = recorder.assignAlias(image2, `im/${image2.imageId}`, "image");
      recorder.defer(() => {
        if (this.#deletedInRecorder.has(image2)) {
          return null;
        }
        return buildImageAddOp({
          sheet,
          source,
          anchor: image2.anchor.toConfig(),
          as: alias
        });
      });
    }
    this.#context.queueCollaborativePublish?.();
    return image2;
  }
  toProto() {
    return this.#items.map((image2) => image2.toDrawingProto());
  }
  replace(protos) {
    this.#items = (protos ?? []).map((drawing) => new WorksheetImage({ proto: drawing }, (image2) => this.#deleteImage(image2), { context: this.#context }));
  }
  #deleteImage(target) {
    this.#recordImageRemove(target);
    this.#items = this.#items.filter((item) => item !== target);
    this.#context.queueCollaborativePublish?.();
  }
  #recordImageRemove(image2) {
    const recorder = this.#context.getRecorder();
    const sheet = this.#context.getSheetName();
    if (!recorder || !sheet) {
      return;
    }
    if (this.#createdInRecorder.get(image2) === recorder) {
      this.#deletedInRecorder.add(image2);
      return;
    }
    const targetImageId = recorder.getAlias(image2) ?? image2.imageId;
    const op = {
      op: "image.remove",
      target: {
        sheet,
        imageId: targetImageId,
        anchor: image2.anchor.toConfig()
      }
    };
    recorder.record(op);
  }
}

class WorksheetDrawingCollection {
  #charts;
  #shapes;
  #images;
  #others;
  constructor(protos, context) {
    const drawings = protos ?? [];
    const chartProtos = [];
    const shapeProtos = [];
    const imageProtos = [];
    const others = [];
    drawings.forEach((drawing) => {
      if (drawing?.chart) {
        chartProtos.push(drawing);
        return;
      }
      if (drawing?.shape) {
        shapeProtos.push(drawing);
        return;
      }
      if (drawing?.imageReference) {
        imageProtos.push(drawing);
        return;
      }
      others.push({ ...drawing });
    });
    this.#charts = new WorksheetChartCollection(chartProtos, context.chartContext);
    this.#shapes = new WorksheetShapeCollection(context.shapeContext, shapeProtos);
    this.#images = new WorksheetImageCollection(context.imageContext, imageProtos);
    this.#others = others;
  }
  get charts() {
    return this.#charts;
  }
  get shapes() {
    return this.#shapes;
  }
  get images() {
    return this.#images;
  }
  deleteAllKnown() {
    this.#charts.deleteAll();
    this.#shapes.deleteAll();
    this.#images.deleteAll();
  }
  toNonChartProto() {
    return [
      ...this.#shapes.toProto(),
      ...this.#images.toProto(),
      ...this.#others
    ];
  }
  hydrateChartsFromFallbackState() {
    this.#charts.hydrateFromFallbackState();
  }
  replaceNonChartDrawings(protos) {
    const shapeProtos = [];
    const imageProtos = [];
    const others = [];
    for (const drawing of protos ?? []) {
      if (drawing?.chart) {
        continue;
      }
      if (drawing?.shape) {
        shapeProtos.push(drawing);
        continue;
      }
      if (drawing?.imageReference) {
        imageProtos.push(drawing);
        continue;
      }
      others.push({ ...drawing });
    }
    this.#shapes.replace(shapeProtos);
    this.#images.replace(imageProtos);
    this.#others = others;
  }
  toProto() {
    return [
      ...this.#charts.toProto(),
      ...this.#shapes.toProto(),
      ...this.#images.toProto(),
      ...this.#others
    ];
  }
}
function createWorksheetShapeContext() {
  return {
    stub: () => {},
    getTextStyleByName: () => {
      return;
    },
    getImageById: () => {
      return;
    },
    createImageAsset: () => {
      throw new Error("Worksheet drawings do not support image assets yet.");
    },
    getChartById: () => {
      return;
    },
    createChartAsset: (type) => {
      const chart2 = new Chart2({ type: CHART_TYPE_TO_PROTO[type] });
      chart2.hasLegend = true;
      chart2.legend.position = "bottom";
      if (type === "scatter" && chart2.scatterOptions.style === undefined) {
        chart2.scatterOptions.style = "marker";
      }
      return chart2;
    },
    attachChartAsset: (chart2) => chart2
  };
}

// node_modules/@oai/granola/dist/models/spreadsheet/worksheet-drawing-auto-layout.js
init_address_utils();
var DEFAULT_GAP_PX = 16;
var DEFAULT_PADDING_PX = 24;
var DEFAULT_CHART_SIZE = { width: 480, height: 280 };
var DEFAULT_SHAPE_SIZE2 = { width: 260, height: 140 };
var DEFAULT_IMAGE_SIZE = { width: 120, height: 80 };
function autoLayoutWorksheetDrawings(worksheet, items, options = {}) {
  if (items.length === 0) {
    return;
  }
  const layout = worksheet.__getViewportLayout();
  const frame = resolveFrame2(layout, options.frame);
  const gap = Number.isFinite(options.gap) ? options.gap : DEFAULT_GAP_PX;
  const padding = Number.isFinite(options.padding) ? options.padding : DEFAULT_PADDING_PX;
  const direction = options.direction ?? "vertical";
  const align = options.align ?? "start";
  const placements = buildPlacements(items, {
    frame,
    gap,
    padding,
    direction,
    align,
    columns: options.columns,
    layout
  });
  placements.forEach((placement, index) => {
    const item = items[index];
    if (!item) {
      return;
    }
    const { left, top, width, height, hasToAnchor } = placement;
    const from2 = anchorFromPx(layout, left, top);
    item.anchor.from = from2;
    if (hasToAnchor) {
      const to = anchorFromPx(layout, left + width, top + height);
      item.anchor.to = to;
    }
  });
}
var buildPlacements = (items, config2) => {
  const { frame, gap, padding, direction, align, columns, layout } = config2;
  const contentWidth = Math.max(0, frame.width - padding * 2);
  const contentHeight = Math.max(0, frame.height - padding * 2);
  const contentLeft = frame.left + padding;
  const contentTop = frame.top + padding;
  if (direction === "horizontal") {
    let cursorX = contentLeft;
    return items.map((item) => {
      const { rect, hasToAnchor } = resolveDrawingRect(item, layout);
      const top = contentTop + alignOffset(contentHeight, rect.height, align);
      const placement = {
        left: cursorX,
        top,
        width: rect.width,
        height: rect.height,
        hasToAnchor
      };
      cursorX += rect.width + gap;
      return placement;
    });
  }
  if (direction === "grid") {
    const cols = columns && Number.isFinite(columns) && columns > 0 ? Math.floor(columns) : Math.max(1, Math.ceil(Math.sqrt(items.length)));
    const rows = Math.max(1, Math.ceil(items.length / cols));
    const cellWidth = cols > 0 ? (contentWidth - gap * (cols - 1)) / cols : contentWidth;
    const cellHeight = rows > 0 ? (contentHeight - gap * (rows - 1)) / rows : contentHeight;
    return items.map((item, index) => {
      const { rect, hasToAnchor } = resolveDrawingRect(item, layout);
      const colIndex = index % cols;
      const rowIndex2 = Math.floor(index / cols);
      const cellLeft = contentLeft + colIndex * (cellWidth + gap);
      const cellTop = contentTop + rowIndex2 * (cellHeight + gap);
      return {
        left: cellLeft + alignOffset(cellWidth, rect.width, align),
        top: cellTop + alignOffset(cellHeight, rect.height, align),
        width: rect.width,
        height: rect.height,
        hasToAnchor
      };
    });
  }
  let cursorY = contentTop;
  return items.map((item) => {
    const { rect, hasToAnchor } = resolveDrawingRect(item, layout);
    const left = contentLeft + alignOffset(contentWidth, rect.width, align);
    const placement = {
      left,
      top: cursorY,
      width: rect.width,
      height: rect.height,
      hasToAnchor
    };
    cursorY += rect.height + gap;
    return placement;
  });
};
var resolveDrawingRect = (item, layout) => {
  const anchor = item.anchor;
  const from2 = anchor.from;
  const to = anchor.to;
  const hasToAnchor = !!to;
  const left = offsetAt(layout.colOffsetsRawPx, from2.col) + (from2.colOffsetPx ?? 0);
  const top = offsetAt(layout.rowOffsetsPx, from2.row) + (from2.rowOffsetPx ?? 0);
  let width = anchor.extent?.widthPx;
  let height = anchor.extent?.heightPx;
  if ((width == null || height == null) && to) {
    const right = offsetAt(layout.colOffsetsRawPx, to.col) + (to.colOffsetPx ?? 0);
    const bottom = offsetAt(layout.rowOffsetsPx, to.row) + (to.rowOffsetPx ?? 0);
    width = right - left;
    height = bottom - top;
  }
  const fallback = defaultSizeFor(item);
  return {
    rect: {
      left,
      top,
      width: width && width > 0 ? width : fallback.width,
      height: height && height > 0 ? height : fallback.height
    },
    hasToAnchor
  };
};
var defaultSizeFor = (item) => {
  if (isChart(item)) {
    return DEFAULT_CHART_SIZE;
  }
  if (isImage(item)) {
    return DEFAULT_IMAGE_SIZE;
  }
  return DEFAULT_SHAPE_SIZE2;
};
var isChart = (item) => item instanceof WorksheetChart;
var isImage = (item) => item instanceof WorksheetImage;
var resolveFrame2 = (layout, frame) => {
  if (!frame) {
    return {
      left: 0,
      top: 0,
      width: layout.viewTotalWidthPx,
      height: layout.totalHeightPx
    };
  }
  if ("startCell" in frame) {
    const parsed = parseRangeAddress(frame.startCell);
    if (!parsed) {
      return {
        left: 0,
        top: 0,
        width: frame.width,
        height: frame.height
      };
    }
    const left = offsetAt(layout.colOffsetsRawPx, parsed.bounds.startCol);
    const top = offsetAt(layout.rowOffsetsPx, parsed.bounds.startRow);
    return {
      left,
      top,
      width: frame.width,
      height: frame.height
    };
  }
  return frame;
};
var anchorFromPx = (layout, left, top) => {
  const col = indexForOffset2(layout.colOffsetsRawPx, left);
  const row2 = indexForOffset2(layout.rowOffsetsPx, top);
  return {
    row: row2.index,
    col: col.index,
    rowOffsetPx: row2.offset,
    colOffsetPx: col.offset
  };
};
var alignOffset = (space, size2, align) => {
  const remaining = Math.max(0, space - size2);
  if (align === "center") {
    return remaining / 2;
  }
  if (align === "end") {
    return remaining;
  }
  return 0;
};
var offsetAt = (offsets, index) => {
  if (offsets.length === 0) {
    return 0;
  }
  const maxIndex = Math.max(0, offsets.length - 2);
  const safeIndex = Math.min(Math.max(index, 0), maxIndex);
  return offsets[safeIndex] ?? 0;
};
var indexForOffset2 = (offsets, value) => {
  if (offsets.length === 0) {
    return { index: 0, offset: 0 };
  }
  const target = Math.max(0, value);
  let index = 0;
  while (index + 1 < offsets.length) {
    const next = offsets[index + 1];
    if (next === undefined || next > target) {
      break;
    }
    index += 1;
  }
  const offset = target - (offsets[index] ?? 0);
  const maxIndex = Math.max(0, offsets.length - 2);
  return {
    index: Math.min(index, maxIndex),
    offset
  };
};

// node_modules/@oai/granola/dist/models/spreadsheet/worksheet.js
init_address_utils();

// node_modules/@oai/granola/dist/models/spreadsheet/cell.js
class Cell3 {
  static from(cell) {
    return new Cell3(cell);
  }
  static create(address) {
    return new Cell3({ address }).toProto();
  }
  #cell;
  constructor(cell) {
    this.#cell = { ...cell };
    this.#cell.dataType ??= 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
    this.#cell.paragraphs ??= [];
  }
  toProto() {
    return this.#cell;
  }
  get formula() {
    return this.#cell.formula;
  }
  set formula(value) {
    this.#cell.formula = value;
  }
  get sharedFormulaSi() {
    return this.#cell.sharedFormulaSi;
  }
  set sharedFormulaSi(value) {
    this.#cell.sharedFormulaSi = value;
  }
  get formulaType() {
    return this.#cell.formulaType;
  }
  set formulaType(value) {
    this.#cell.formulaType = value;
  }
  get formulaReference() {
    return this.#cell.formulaRef;
  }
  set formulaReference(value) {
    this.#cell.formulaRef = value;
  }
  get alwaysCalculateArray() {
    return this.#cell.formulaAlwaysCalculateArray;
  }
  set alwaysCalculateArray(value) {
    this.#cell.formulaAlwaysCalculateArray = value;
  }
  get dataTableMetadata() {
    const { dataTableRowInput, dataTableColumnInput, dataTableRowOriented, dataTableTwoVariable } = this.#cell;
    if (dataTableRowInput === undefined && dataTableColumnInput === undefined && dataTableRowOriented === undefined && dataTableTwoVariable === undefined) {
      return;
    }
    return {
      rowInput: dataTableRowInput,
      columnInput: dataTableColumnInput,
      rowOriented: dataTableRowOriented,
      twoVariable: dataTableTwoVariable
    };
  }
  set dataTableMetadata(metadata) {
    if (!metadata) {
      this.#cell.dataTableRowInput = undefined;
      this.#cell.dataTableColumnInput = undefined;
      this.#cell.dataTableRowOriented = undefined;
      this.#cell.dataTableTwoVariable = undefined;
      return;
    }
    this.#cell.dataTableRowInput = metadata.rowInput;
    this.#cell.dataTableColumnInput = metadata.columnInput;
    this.#cell.dataTableRowOriented = metadata.rowOriented;
    this.#cell.dataTableTwoVariable = metadata.twoVariable;
  }
  get formulaMetadata() {
    return {
      sharedFormulaSi: this.sharedFormulaSi,
      formulaType: this.formulaType,
      reference: this.formulaReference,
      alwaysCalculateArray: this.alwaysCalculateArray,
      dataTable: this.dataTableMetadata
    };
  }
  updateFormulaMetadata(metadata) {
    if ("sharedFormulaSi" in metadata) {
      this.sharedFormulaSi = metadata.sharedFormulaSi;
    }
    if ("formulaType" in metadata) {
      this.formulaType = metadata.formulaType;
    }
    if ("reference" in metadata) {
      this.formulaReference = metadata.reference;
    }
    if ("alwaysCalculateArray" in metadata) {
      this.alwaysCalculateArray = metadata.alwaysCalculateArray;
    }
    if ("dataTable" in metadata) {
      this.dataTableMetadata = metadata.dataTable;
    }
    return this.formulaMetadata;
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/cell-store.js
var COLS = 16384;

class CellStore {
  #cells;
  #rawValues;
  #excelRawValues;
  constructor() {
    this.#cells = new Map;
    this.#rawValues = new Map;
    this.#excelRawValues = new Map;
  }
  #key(row2, col) {
    return row2 * COLS + col;
  }
  get(row2, col) {
    return this.#cells.get(this.#key(row2, col));
  }
  set(row2, col, cell) {
    this.#cells.set(this.#key(row2, col), cell);
    return cell;
  }
  getOrCreate(row2, col, factory) {
    const existing = this.get(row2, col);
    if (existing) {
      return existing;
    }
    const cell = factory(row2, col);
    this.set(row2, col, cell);
    return cell;
  }
  delete(row2, col) {
    this.#cells.delete(this.#key(row2, col));
    this.#rawValues.delete(this.#key(row2, col));
  }
  *entries() {
    yield* this.#cells.entries();
  }
  *cellsWithCoordinates() {
    for (const [key, cell] of this.#cells.entries()) {
      const row2 = Math.floor(key / COLS);
      const col = key - row2 * COLS;
      yield [row2, col, cell];
    }
  }
  setRawValue(row2, col, value) {
    const key = this.#key(row2, col);
    if (value === undefined) {
      this.#rawValues.delete(key);
      return;
    }
    this.#rawValues.set(key, value);
  }
  getRawValue(row2, col) {
    return this.#rawValues.get(this.#key(row2, col));
  }
  clearRawValue(row2, col) {
    this.#rawValues.delete(this.#key(row2, col));
  }
  setExcelRawValue(row2, col, value) {
    const key = this.#key(row2, col);
    if (value === undefined) {
      this.#excelRawValues.delete(key);
      return;
    }
    this.#excelRawValues.set(key, value);
  }
  getExcelRawValue(row2, col) {
    return this.#excelRawValues.get(this.#key(row2, col));
  }
  hasExcelRawValue(row2, col) {
    return this.#excelRawValues.has(this.#key(row2, col));
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/sparkline/sparkline.js
init_address_utils();

// node_modules/@oai/granola/dist/models/spreadsheet/sparkline/sparkline-preview.js
var READ_ONLY_MESSAGE = "Sparkline previews are read-only. Modify the owning SparklineGroup instead.";

class SparklinePreview {
  #group;
  #projection;
  constructor(group, projection) {
    this.#group = group;
    this.#projection = projection;
  }
  get location() {
    return this.#group.worksheet.getRange(this.#projection.reference);
  }
  set location(_value) {
    throw new Error(READ_ONLY_MESSAGE);
  }
  get reference() {
    return this.#projection.reference;
  }
  get sourceData() {
    return this.#group.worksheet.getRange(this.#projection.sourceAddress);
  }
  set sourceData(_value) {
    throw new Error(READ_ONLY_MESSAGE);
  }
  get formula() {
    return this.#projection.formula;
  }
  set formula(_value) {
    throw new Error(READ_ONLY_MESSAGE);
  }
  get dateAxisRange() {
    return this.#group.dateAxisRange;
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/sparkline/sparkline-axis.js
class SparklineAxis {
  #proto;
  #onChange;
  constructor(proto, onChange) {
    this.#proto = proto;
    this.#onChange = onChange;
  }
  get manualMin() {
    return this.#proto.manualMin ?? undefined;
  }
  set manualMin(value) {
    this.#proto.manualMin = value ?? undefined;
    this.#onChange?.();
  }
  get manualMax() {
    return this.#proto.manualMax ?? undefined;
  }
  set manualMax(value) {
    this.#proto.manualMax = value ?? undefined;
    this.#onChange?.();
  }
  get minMode() {
    return this.#proto.minAxisType ?? 0 /* SPARKLINE_AXIS_MIN_MAX_UNSPECIFIED */;
  }
  set minMode(value) {
    this.#proto.minAxisType = value;
    this.#onChange?.();
  }
  get maxMode() {
    return this.#proto.maxAxisType ?? 0 /* SPARKLINE_AXIS_MIN_MAX_UNSPECIFIED */;
  }
  set maxMode(value) {
    this.#proto.maxAxisType = value;
    this.#onChange?.();
  }
  get showAxis() {
    return Boolean(this.#proto.displayXAxis);
  }
  set showAxis(value) {
    this.#proto.displayXAxis = Boolean(value);
    this.#onChange?.();
  }
  get rightToLeft() {
    return Boolean(this.#proto.rightToLeft);
  }
  set rightToLeft(value) {
    this.#proto.rightToLeft = Boolean(value);
    this.#onChange?.();
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/sparkline/sparkline-markers.js
class SparklineMarkers {
  #proto;
  #onChange;
  constructor(proto, onChange) {
    this.#proto = proto;
    this.#onChange = onChange;
  }
  get show() {
    return Boolean(this.#proto.markers);
  }
  set show(value) {
    this.#proto.markers = Boolean(value);
    this.#onChange?.();
  }
  get high() {
    return Boolean(this.#proto.high);
  }
  set high(value) {
    this.#proto.high = Boolean(value);
    this.#onChange?.();
  }
  get low() {
    return Boolean(this.#proto.low);
  }
  set low(value) {
    this.#proto.low = Boolean(value);
    this.#onChange?.();
  }
  get first() {
    return Boolean(this.#proto.first);
  }
  set first(value) {
    this.#proto.first = Boolean(value);
    this.#onChange?.();
  }
  get last() {
    return Boolean(this.#proto.last);
  }
  set last(value) {
    this.#proto.last = Boolean(value);
    this.#onChange?.();
  }
  get negative() {
    return Boolean(this.#proto.negative);
  }
  set negative(value) {
    this.#proto.negative = Boolean(value);
    this.#onChange?.();
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/sparkline/types.js
var SPARKLINE_GROUP_TYPE_TO_PROTO = {
  line: 1 /* SPARKLINE_TYPE_LINE */,
  column: 2 /* SPARKLINE_TYPE_COLUMN */,
  stacked: 3 /* SPARKLINE_TYPE_STACKED */
};
var SPARKLINE_GROUP_TYPE_FROM_PROTO = {
  [0 /* SPARKLINE_TYPE_UNSPECIFIED */]: undefined,
  [1 /* SPARKLINE_TYPE_LINE */]: "line",
  [2 /* SPARKLINE_TYPE_COLUMN */]: "column",
  [3 /* SPARKLINE_TYPE_STACKED */]: "stacked",
  [-1 /* UNRECOGNIZED */]: undefined
};
var DEFAULT_SPARKLINE_TYPE = "line";

// node_modules/@oai/granola/dist/models/spreadsheet/sparkline/sparkline.js
var hashString = (value) => {
  let hash2 = 2166136261;
  for (let idx = 0;idx < value.length; idx += 1) {
    hash2 ^= value.charCodeAt(idx);
    hash2 = Math.imul(hash2, 16777619);
  }
  return (hash2 >>> 0).toString(36);
};
var deriveSparklineGroupIdFromProto = (proto) => {
  const sparklineKeys = (proto.sparklines ?? []).map((sparkline) => `${sparkline.reference ?? ""}|${sparkline.formula ?? ""}`).filter((value) => value.length > 1);
  if (!sparklineKeys.length && !proto.formula) {
    return;
  }
  const seed = JSON.stringify({
    type: proto.type,
    formula: proto.formula ?? "",
    sparklines: sparklineKeys
  });
  return `spg_${hashString(seed)}`;
};

class SparklineGroup2 {
  #worksheet;
  #proto;
  #uid;
  #id;
  #locationAddress;
  #sourceAddress;
  #dateAxisRangeAddress;
  #sparklineCount = 0;
  #sourceSheetName;
  #projections;
  #markers;
  #axis;
  #renderContext;
  #onChange;
  #createdInRecorder;
  constructor(worksheet, proto, options) {
    this.#worksheet = worksheet;
    this.#proto = proto;
    this.#uid = options?.uid ?? proto.uid ?? generateGuid();
    this.#proto.uid = this.#uid;
    this.#id = options?.id ?? deriveSparklineGroupIdFromProto(proto) ?? generateAidSuffix();
    this.#proto.sparklines = proto.sparklines ?? [];
    this.#proto.type = proto.type ?? 1 /* SPARKLINE_TYPE_LINE */;
    this.#projections = new Map;
    this.#hydrateRangesFromProto();
    this.#hydrateProjectionsFromProto();
    this.#markers = new SparklineMarkers(this.#proto, () => this.#markChanged());
    this.#axis = new SparklineAxis(this.#proto, () => this.#markChanged());
    this.#renderContext = [];
    this.#createdInRecorder = options?.createdInRecorder;
  }
  get id() {
    return this.#id;
  }
  get uid() {
    return this.#uid;
  }
  get type() {
    const protoType = this.#proto.type ?? 1 /* SPARKLINE_TYPE_LINE */;
    return SPARKLINE_GROUP_TYPE_FROM_PROTO[protoType] ?? DEFAULT_SPARKLINE_TYPE;
  }
  set type(value) {
    this.#proto.type = SPARKLINE_GROUP_TYPE_TO_PROTO[value];
    this.#markChanged();
  }
  get locationRange() {
    const address = this.#locationAddress;
    if (!address) {
      throw new Error("Sparkline group has no target range assigned.");
    }
    return this.#worksheet.getRange(address);
  }
  set locationRange(value) {
    const normalized = this.#normalizeRange(value);
    if (!normalized) {
      throw new Error("Invalid sparkline location range.");
    }
    this.#locationAddress = normalized;
    this.#rebuildIfReady();
    this.#markChanged();
  }
  get sourceData() {
    const address = this.#sourceAddress;
    if (!address) {
      throw new Error("Sparkline group has no source range assigned.");
    }
    return this.#worksheet.getRange(address);
  }
  set sourceData(value) {
    const normalized = this.#normalizeRangeWithSheet(value);
    if (!normalized.ref) {
      throw new Error("Invalid sparkline source range.");
    }
    this.#sourceAddress = normalized.ref;
    this.#sourceSheetName = normalized.sheetName;
    this.#rebuildIfReady();
    this.#markChanged();
  }
  get dateAxisRange() {
    if (!this.#dateAxisRangeAddress) {
      return;
    }
    return this.#worksheet.getRange(this.#dateAxisRangeAddress);
  }
  set dateAxisRange(value) {
    if (!value) {
      this.#dateAxisRangeAddress = undefined;
      this.#markChanged();
      return;
    }
    const normalized = this.#normalizeRange(value);
    if (!normalized) {
      throw new Error("Invalid date axis range.");
    }
    this.#dateAxisRangeAddress = normalized;
    this.#markChanged();
  }
  get displayEmptyCellsAs() {
    return this.#proto.displayEmptyCellsAs;
  }
  set displayEmptyCellsAs(value) {
    this.#proto.displayEmptyCellsAs = value ?? 0 /* SPARKLINE_DISPLAY_BLANKS_AS_UNSPECIFIED */;
    this.#markChanged();
  }
  get displayHidden() {
    return Boolean(this.#proto.displayHidden);
  }
  set displayHidden(value) {
    this.#proto.displayHidden = Boolean(value);
    this.#markChanged();
  }
  get lineWeight() {
    return this.#proto.lineWeight;
  }
  set lineWeight(value) {
    this.#proto.lineWeight = value === undefined || Number.isNaN(value) ? undefined : value;
    this.#markChanged();
  }
  get seriesColor() {
    return new Color4({ type: "proto", proto: this.#proto.seriesColor });
  }
  set seriesColor(value) {
    this.#proto.seriesColor = new Color4(value).toProto();
    this.#markChanged();
  }
  get negativeColor() {
    return new Color4({ type: "proto", proto: this.#proto.negativeColor });
  }
  set negativeColor(value) {
    this.#proto.negativeColor = new Color4(value).toProto();
    this.#markChanged();
  }
  get axisColor() {
    return new Color4({ type: "proto", proto: this.#proto.axisColor });
  }
  set axisColor(value) {
    this.#proto.axisColor = new Color4(value).toProto();
    this.#markChanged();
  }
  get markersColor() {
    return new Color4({ type: "proto", proto: this.#proto.markersColor });
  }
  set markersColor(value) {
    this.#proto.markersColor = new Color4(value).toProto();
    this.#markChanged();
  }
  get firstMarkerColor() {
    return new Color4({ type: "proto", proto: this.#proto.firstMarkerColor });
  }
  set firstMarkerColor(value) {
    this.#proto.firstMarkerColor = new Color4(value).toProto();
    this.#markChanged();
  }
  get lastMarkerColor() {
    return new Color4({ type: "proto", proto: this.#proto.lastMarkerColor });
  }
  set lastMarkerColor(value) {
    this.#proto.lastMarkerColor = new Color4(value).toProto();
    this.#markChanged();
  }
  get highMarkerColor() {
    return new Color4({ type: "proto", proto: this.#proto.highMarkerColor });
  }
  set highMarkerColor(value) {
    this.#proto.highMarkerColor = new Color4(value).toProto();
    this.#markChanged();
  }
  get lowMarkerColor() {
    return new Color4({ type: "proto", proto: this.#proto.lowMarkerColor });
  }
  set lowMarkerColor(value) {
    this.#proto.lowMarkerColor = new Color4(value).toProto();
    this.#markChanged();
  }
  get rightToLeft() {
    return this.axis.rightToLeft;
  }
  set rightToLeft(value) {
    this.axis.rightToLeft = value;
  }
  get displayXAxis() {
    return this.axis.showAxis;
  }
  set displayXAxis(value) {
    this.axis.showAxis = value;
  }
  get worksheet() {
    return this.#worksheet;
  }
  get markers() {
    return this.#markers;
  }
  get axis() {
    return this.#axis;
  }
  get formula() {
    return this.#proto.formula;
  }
  set formula(value) {
    this.#proto.formula = value;
    this.#markChanged();
  }
  get sparklineCount() {
    return this.#sparklineCount;
  }
  get renderContext() {
    return this.#renderContext;
  }
  setChangeHandler(handler) {
    this.#onChange = handler;
  }
  updateRenderContext() {
    const specs = [];
    for (const projection of this.#projections.values()) {
      const parsedTarget = parseRangeAddress(projection.reference);
      if (!parsedTarget) {
        continue;
      }
      const sourceSheetName = projection.sourceSheet;
      if (!sourceSheetName) {
        continue;
      }
      const sourceWorksheet = this.#worksheet.workbook.__getWorksheetByName(sourceSheetName);
      if (!sourceWorksheet) {
        continue;
      }
      const sourceRange = sourceWorksheet.getRange(projection.sourceAddress);
      const rowValues = sourceRange.values?.[0] ?? [];
      const normalizedValues = this.#normalizeValues(rowValues);
      const domain2 = this.#computeDomain(normalizedValues);
      const pointMeta = this.#buildPointMeta(normalizedValues);
      const connectGaps = this.displayEmptyCellsAs === 1 /* SPARKLINE_DISPLAY_BLANKS_AS_SPAN */;
      specs.push({
        address: projection.reference,
        row: parsedTarget.bounds.startRow,
        col: parsedTarget.bounds.startCol,
        type: this.type,
        values: normalizedValues,
        displayEmptyCellsAs: this.displayEmptyCellsAs,
        connectGaps,
        rightToLeft: this.axis.rightToLeft,
        showAxis: this.axis.showAxis,
        lineWeight: this.lineWeight,
        domain: domain2,
        colors: {
          series: this.seriesColor?.toProto(),
          negative: this.negativeColor?.toProto(),
          axis: this.axisColor?.toProto(),
          markers: this.markersColor?.toProto(),
          first: this.firstMarkerColor?.toProto(),
          last: this.lastMarkerColor?.toProto(),
          high: this.highMarkerColor?.toProto(),
          low: this.lowMarkerColor?.toProto()
        },
        markers: this.markers,
        pointMeta
      });
    }
    this.#renderContext = specs;
  }
  containsCell(address) {
    const normalized = normalizeAddress(address);
    if (!normalized)
      return false;
    return this.#projections.has(normalized);
  }
  getSparkline(address) {
    const normalized = normalizeAddress(address);
    if (!normalized)
      return;
    const projection = this.#projections.get(normalized);
    if (!projection)
      return;
    return new SparklinePreview(this, projection);
  }
  toProto() {
    return {
      ...this.#proto,
      sparklines: this.#proto.sparklines.map((sparkline) => ({
        formula: sparkline.formula,
        reference: sparkline.reference
      })),
      seriesColor: this.seriesColor?.toProto(),
      negativeColor: this.negativeColor?.toProto(),
      axisColor: this.axisColor?.toProto(),
      markersColor: this.markersColor?.toProto(),
      firstMarkerColor: this.firstMarkerColor?.toProto(),
      lastMarkerColor: this.lastMarkerColor?.toProto(),
      highMarkerColor: this.highMarkerColor?.toProto(),
      lowMarkerColor: this.lowMarkerColor?.toProto()
    };
  }
  #markChanged() {
    this.updateRenderContext();
    this.#recordSet();
    this.#onChange?.(this);
  }
  #recordSet() {
    const recorder = this.#worksheet.workbook.getRecorder();
    if (!recorder) {
      return;
    }
    if (this.#createdInRecorder === recorder) {
      return;
    }
    recorder.deferOnce(`sparkline.set:${this.uid}`, () => buildSparklineGroupSetOp({
      group: this,
      sheetName: this.#worksheet.name
    }));
  }
  #rebuildIfReady() {
    if (!this.#locationAddress || !this.#sourceAddress) {
      return;
    }
    if (!this.#rangesAlign()) {
      this.#renderContext = [];
      return;
    }
    this.#projectSparklines();
    this.updateRenderContext();
  }
  #rangesAlign() {
    if (!this.#locationAddress || !this.#sourceAddress) {
      return false;
    }
    const location2 = parseRangeAddress(this.#locationAddress);
    const source = parseRangeAddress(this.#sourceAddress);
    if (!location2 || !source) {
      return false;
    }
    const targetCells = this.#expandCells(location2.bounds);
    const sourceRows = boundsDimensions(source.bounds).rows;
    return targetCells.length === sourceRows;
  }
  #projectSparklines() {
    const location2 = parseRangeAddress(this.#locationAddress);
    const source = parseRangeAddress(this.#sourceAddress);
    if (!location2 || !source) {
      this.#proto.sparklines = [];
      this.#sparklineCount = 0;
      this.#projections.clear();
      return;
    }
    const targetCells = this.#expandCells(location2.bounds);
    const sourceSize = boundsDimensions(source.bounds);
    if (targetCells.length !== sourceSize.rows) {
      return;
    }
    const sparklines = [];
    const projections = new Map;
    const sourceSheetForProjections = this.#sourceSheetName ?? this.#worksheet.name;
    for (let idx = 0;idx < targetCells.length; idx += 1) {
      const rowBounds = {
        startRow: source.bounds.startRow + idx,
        endRow: source.bounds.startRow + idx,
        startCol: source.bounds.startCol,
        endCol: source.bounds.endCol
      };
      const rowRef = buildRangeRef(rowBounds);
      const qualifiedFormula = this.#qualifyRange(rowRef, this.#sourceSheetName);
      const reference = targetCells[idx];
      if (!reference) {
        continue;
      }
      sparklines.push({
        formula: qualifiedFormula,
        reference
      });
      projections.set(normalizeAddress(reference), {
        formula: qualifiedFormula,
        reference,
        sourceAddress: rowRef,
        sourceSheet: sourceSheetForProjections
      });
    }
    this.#proto.sparklines = sparklines;
    this.#sparklineCount = sparklines.length;
    this.#projections = projections;
  }
  #expandCells(bounds) {
    const cells = [];
    for (let row2 = bounds.startRow;row2 <= bounds.endRow; row2 += 1) {
      for (let col = bounds.startCol;col <= bounds.endCol; col += 1) {
        cells.push(makeCellAddress(row2, col));
      }
    }
    return cells;
  }
  #normalizeRange(value) {
    if (!value)
      return;
    const range2 = typeof value === "string" ? this.#worksheet.getRange(value) : value;
    const parsed = parseRangeAddress(range2.address);
    return parsed?.ref;
  }
  #normalizeRangeWithSheet(value) {
    if (!value) {
      return { ref: undefined, sheetName: undefined };
    }
    if (typeof value === "string") {
      const split = splitSheetAddress(value);
      return { ref: split.ref, sheetName: split.sheetName };
    }
    const range2 = value;
    const parsed = parseRangeAddress(range2.address);
    return { ref: parsed?.ref, sheetName: range2.__getWorksheet()?.name };
  }
  #qualifyRange(rangeRef, sheetName) {
    const targetSheet = sheetName || this.#worksheet.name || "";
    if (!targetSheet) {
      return rangeRef;
    }
    const needsQuote = /[\s'!]/.test(targetSheet);
    const escaped = needsQuote ? `'${targetSheet.replace(/'/g, "''")}'` : targetSheet;
    return `${escaped}!${rangeRef}`;
  }
  #hydrateRangesFromProto() {
    if (this.#proto.sparklines.length > 0) {
      const location2 = this.#deriveRangeFromValues(this.#proto.sparklines.map((sparkline) => sparkline.reference));
      if (location2?.ref) {
        this.#locationAddress = location2.ref;
      }
      const source = this.#proto.formula ? splitSheetAddress(this.#proto.formula) : this.#deriveRangeFromValues(this.#proto.sparklines.map((sparkline) => sparkline.formula));
      if (source?.ref) {
        this.#sourceAddress = source.ref;
        this.#sourceSheetName = source.sheetName;
      }
    }
  }
  #deriveRangeFromValues(values) {
    const bounds = [];
    let sheetName;
    for (const value of values) {
      if (!value)
        continue;
      const split = splitSheetAddress(value);
      const stripped = split.ref;
      if (!stripped)
        continue;
      const parsed = parseRangeAddress(stripped);
      if (!parsed)
        continue;
      bounds.push(parsed.bounds);
      sheetName ??= split.sheetName;
    }
    if (!bounds.length) {
      return;
    }
    const aggregate = {
      startRow: Math.min(...bounds.map((b) => b.startRow)),
      startCol: Math.min(...bounds.map((b) => b.startCol)),
      endRow: Math.max(...bounds.map((b) => b.endRow)),
      endCol: Math.max(...bounds.map((b) => b.endCol))
    };
    return { ref: buildRangeRef(aggregate), sheetName };
  }
  #hydrateProjectionsFromProto() {
    this.#projections.clear();
    for (const sparkline of this.#proto.sparklines) {
      const { ref: referenceAddress } = splitSheetAddress(sparkline.reference ?? "");
      const formula = sparkline.formula ?? "";
      const normalizedReference = referenceAddress ? normalizeAddress(referenceAddress) : null;
      const { ref: strippedFormula, sheetName: formulaSheet } = splitSheetAddress(formula);
      if (!referenceAddress || !normalizedReference || !strippedFormula) {
        continue;
      }
      this.#projections.set(normalizedReference, {
        reference: referenceAddress,
        formula,
        sourceAddress: strippedFormula,
        sourceSheet: formulaSheet
      });
      if (formulaSheet) {
        this.#sourceSheetName = formulaSheet;
      }
    }
    this.#sparklineCount = this.#proto.sparklines.length;
  }
  #normalizeValues(values) {
    return values.map((value) => {
      if (value == null) {
        return null;
      }
      const num = typeof value === "number" ? value : Number(value);
      return Number.isFinite(num) ? num : null;
    });
  }
  #computeDomain(values) {
    const numeric = values.filter((value) => value !== null && Number.isFinite(value));
    let min3 = numeric.length > 0 ? Math.min(...numeric) : 0;
    let max4 = numeric.length > 0 ? Math.max(...numeric) : 0;
    if (this.axis.manualMin !== undefined) {
      min3 = this.axis.manualMin;
    }
    if (this.axis.manualMax !== undefined) {
      max4 = this.axis.manualMax;
    }
    if (this.type !== "line") {
      min3 = Math.min(min3, 0);
      max4 = Math.max(max4, 0);
    }
    if (min3 === max4) {
      min3 -= 1;
      max4 += 1;
    }
    return { min: min3, max: max4 };
  }
  #buildPointMeta(values) {
    let firstIndex = null;
    let lastIndex = null;
    let highValue = Number.NEGATIVE_INFINITY;
    let lowValue = Number.POSITIVE_INFINITY;
    const highIndices = new Set;
    const lowIndices = new Set;
    const negativeIndices = new Set;
    values.forEach((value, idx) => {
      if (value === null || !Number.isFinite(value)) {
        return;
      }
      if (firstIndex === null) {
        firstIndex = idx;
      }
      lastIndex = idx;
      if (value < 0) {
        negativeIndices.add(idx);
      }
      if (value > highValue) {
        highValue = value;
        highIndices.clear();
        highIndices.add(idx);
      } else if (value === highValue) {
        highIndices.add(idx);
      }
      if (value < lowValue) {
        lowValue = value;
        lowIndices.clear();
        lowIndices.add(idx);
      } else if (value === lowValue) {
        lowIndices.add(idx);
      }
    });
    return {
      firstIndex,
      lastIndex,
      highIndices,
      lowIndices,
      negativeIndices
    };
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/sparkline/sparkline-collection.js
class SparklineGroupCollection {
  #worksheet;
  #items = [];
  #renderContext = [];
  #createdInRecorder = new WeakMap;
  #deletedInRecorder = new WeakSet;
  constructor(worksheet, groups) {
    this.#worksheet = worksheet;
    this.#items = groups?.groups?.map((group) => {
      const item = new SparklineGroup2(worksheet, group);
      item.setChangeHandler(() => this.#updateRenderContext());
      return item;
    }) ?? [];
  }
  add(config2) {
    return this.#addInternal(config2);
  }
  __addForApply(config2) {
    return this.#addInternal(config2, {
      explicitId: config2.id,
      explicitUid: config2.uid
    });
  }
  #addInternal(config2, applyOptions) {
    const { type, targetRange, sourceData, ...options } = config2;
    const explicitId = applyOptions?.explicitId;
    const explicitUid = applyOptions?.explicitUid;
    if (explicitId && this.#items.some((item) => item.id === explicitId)) {
      throw new Error(`Sparkline group id already exists: ${explicitId}`);
    }
    if (explicitUid && this.#items.some((item) => item.uid === explicitUid)) {
      throw new Error(`Sparkline group uid already exists: ${explicitUid}`);
    }
    const defaults = {
      displayEmptyCellsAs: options.displayEmptyCellsAs ?? 2 /* SPARKLINE_DISPLAY_BLANKS_AS_GAP */,
      axis: options.axis ?? {
        showAxis: true
      },
      lineWeight: options.lineWeight ?? 1
    };
    const merged = { ...defaults, ...options };
    const proto = {
      sparklines: [],
      type: undefined
    };
    const recorder = this.#worksheet.workbook.getRecorder();
    const group = new SparklineGroup2(this.#worksheet, proto, {
      id: explicitId,
      uid: explicitUid,
      createdInRecorder: recorder
    });
    group.type = type;
    group.locationRange = this.#coerceRange(targetRange);
    group.sourceData = this.#coerceRange(sourceData);
    if (merged.dateAxisRange) {
      group.dateAxisRange = this.#coerceRange(merged.dateAxisRange);
    }
    if (merged.lineWeight !== undefined) {
      group.lineWeight = merged.lineWeight;
    }
    if (merged.displayEmptyCellsAs) {
      group.displayEmptyCellsAs = merged.displayEmptyCellsAs;
    }
    if (merged.displayHidden !== undefined) {
      group.displayHidden = merged.displayHidden;
    }
    if (merged.seriesColor) {
      group.seriesColor = merged.seriesColor;
    }
    if (merged.negativeColor) {
      group.negativeColor = merged.negativeColor;
    }
    if (merged.axisColor) {
      group.axisColor = merged.axisColor;
    }
    if (merged.markersColor) {
      group.markersColor = merged.markersColor;
    }
    if (merged.firstMarkerColor) {
      group.firstMarkerColor = merged.firstMarkerColor;
    }
    if (merged.lastMarkerColor) {
      group.lastMarkerColor = merged.lastMarkerColor;
    }
    if (merged.highMarkerColor) {
      group.highMarkerColor = merged.highMarkerColor;
    }
    if (merged.lowMarkerColor) {
      group.lowMarkerColor = merged.lowMarkerColor;
    }
    if (merged.axis?.manualMin !== undefined) {
      group.axis.manualMin = merged.axis.manualMin;
    }
    if (merged.axis?.manualMax !== undefined) {
      group.axis.manualMax = merged.axis.manualMax;
    }
    if (merged.axis?.minMode) {
      group.axis.minMode = merged.axis.minMode;
    }
    if (merged.axis?.maxMode) {
      group.axis.maxMode = merged.axis.maxMode;
    }
    if (merged.axis?.showAxis !== undefined) {
      group.axis.showAxis = merged.axis.showAxis;
    }
    if (merged.axis?.rightToLeft !== undefined) {
      group.rightToLeft = merged.axis.rightToLeft;
    }
    if (merged.markers) {
      if (merged.markers.show !== undefined) {
        group.markers.show = merged.markers.show;
      }
      if (merged.markers.high !== undefined) {
        group.markers.high = merged.markers.high;
      }
      if (merged.markers.low !== undefined) {
        group.markers.low = merged.markers.low;
      }
      if (merged.markers.first !== undefined) {
        group.markers.first = merged.markers.first;
      }
      if (merged.markers.last !== undefined) {
        group.markers.last = merged.markers.last;
      }
      if (merged.markers.negative !== undefined) {
        group.markers.negative = merged.markers.negative;
      }
    }
    if (recorder) {
      this.#createdInRecorder.set(group, recorder);
      const alias = recorder.assignAlias(group, `sp/${group.uid}`, "sparkline");
      recorder.defer(() => this.#deletedInRecorder.has(group) ? null : buildSparklineGroupAddOp({
        group,
        sheetName: this.#worksheet.name,
        as: alias
      }));
    }
    group.setChangeHandler(() => this.#updateRenderContext());
    this.#items.push(group);
    this.#updateRenderContext();
    return group;
  }
  getAll() {
    return [...this.#items];
  }
  getGroupForCell(address) {
    return this.#items.find((group) => group.containsCell(address));
  }
  clear() {
    for (const group of [...this.#items]) {
      this.delete(group);
    }
  }
  deleteAll() {
    this.clear();
  }
  delete(group) {
    this.#recordGroupRemove(group);
    const index = this.#items.indexOf(group);
    if (index >= 0) {
      this.#items.splice(index, 1);
    }
    this.#updateRenderContext();
  }
  toProto() {
    if (!this.#items.length) {
      return;
    }
    return {
      groups: this.#items.map((group) => group.toProto())
    };
  }
  get renderContext() {
    return this.#renderContext;
  }
  __refreshRenderContext() {
    this.#updateRenderContext();
  }
  replaceFromProto(groups) {
    this.#items = groups?.groups?.map((group) => {
      const item = new SparklineGroup2(this.#worksheet, group);
      item.setChangeHandler(() => this.#updateRenderContext());
      return item;
    }) ?? [];
    this.#updateRenderContext();
  }
  #coerceRange(value) {
    return typeof value === "string" ? this.#worksheet.getRange(value) : value;
  }
  #updateRenderContext() {
    this.#renderContext = this.#items.flatMap((group) => {
      group.updateRenderContext();
      return group.renderContext;
    });
    this.#worksheet.__queueCollaborativePublish();
  }
  #recordGroupRemove(group) {
    const recorder = this.#worksheet.workbook.getRecorder();
    if (!recorder) {
      return;
    }
    if (this.#createdInRecorder.get(group) === recorder) {
      this.#deletedInRecorder.add(group);
      return;
    }
    const op = {
      op: "sparkline.remove",
      target: {
        sheet: this.#worksheet.name,
        uid: group.uid,
        selector: buildSparklineTargetSelector(group, this.#worksheet.name)
      }
    };
    recorder.record(op);
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/worksheet-style-ref-store.js
init_address_utils();
function getWorksheetStyleRefsMapName(sheetId) {
  return `sheet:${sheetId}:styleRefs`;
}

class WorksheetStyleRefStore {
  #isCollaborativeStateReady;
  #styleRefs;
  #runLocalTransaction;
  #getCollabOrigins;
  #resolveStyleIndexForStyleId;
  #getOrCreateStyleIdForStyleIndex;
  #getCurrentStyleIndex;
  #getOrCreateCell;
  #setLogicalStyleIndex;
  #iterateCells;
  #styleRefsByAddress;
  #pendingStyleRefAddresses;
  #unsubscribeFromStyleStore;
  #observer;
  constructor(config2) {
    this.#isCollaborativeStateReady = config2.isCollaborativeStateReady ?? (() => true);
    this.#styleRefs = config2.styleRefsState;
    this.#runLocalTransaction = config2.runLocalTransaction;
    this.#getCollabOrigins = config2.getCollabOrigins;
    this.#resolveStyleIndexForStyleId = config2.resolveStyleIndexForStyleId;
    this.#getOrCreateStyleIdForStyleIndex = config2.getOrCreateStyleIdForStyleIndex;
    this.#getCurrentStyleIndex = config2.getCurrentStyleIndex;
    this.#getOrCreateCell = config2.getOrCreateCell;
    this.#setLogicalStyleIndex = config2.setLogicalStyleIndex;
    this.#iterateCells = config2.iterateCells;
    this.#styleRefsByAddress = new Map;
    this.#pendingStyleRefAddresses = new Set;
    this.#observer = (event, transaction) => {
      this.#handleStyleRefEvent(event, transaction);
    };
    this.#unsubscribeFromStyleStore = config2.subscribeToStyleStore(() => {
      this.#retryPendingStyleRefs();
    });
    this.#styleRefs.observe(this.#observer);
    this.#applyAllStyleRefs();
  }
  disconnect() {
    this.#unsubscribeFromStyleStore?.();
    this.#styleRefs.unobserve(this.#observer);
  }
  setCellStyleRef(rowIdx, colIdx, styleId) {
    const address = makeCellAddress(rowIdx, colIdx);
    this.#styleRefsByAddress.set(address, styleId);
    if (!this.#isCollaborativeStateReady()) {
      return;
    }
    if (this.#styleRefs.get(address) === styleId) {
      return;
    }
    this.#runLocalTransaction(() => {
      this.#styleRefs.set(address, styleId);
    });
  }
  getCellStyleRef(rowIdx, colIdx) {
    const address = makeCellAddress(rowIdx, colIdx);
    const cached2 = this.#styleRefsByAddress.get(address);
    if (cached2) {
      return cached2;
    }
    const fromState = this.#styleRefs.get(address);
    if (fromState) {
      this.#styleRefsByAddress.set(address, fromState);
      return fromState;
    }
    return;
  }
  syncCellStyleRefFromStyleIndex(rowIdx, colIdx, styleIndex) {
    const styleId = this.#getOrCreateStyleIdForStyleIndex(styleIndex);
    this.setCellStyleRef(rowIdx, colIdx, styleId);
    return styleId;
  }
  hydrateFromCells() {
    if (!this.#isCollaborativeStateReady()) {
      return;
    }
    this.#seedStyleRefsFromCells();
    this.#applyAllStyleRefs();
  }
  #applyAllStyleRefs() {
    for (const [address, styleId] of this.#styleRefs.entries()) {
      this.#applyStyleRefFromYjs(address, styleId);
    }
  }
  #seedStyleRefsFromCells() {
    const seeds = [];
    for (const cell of this.#iterateCells()) {
      const coord = addressToIndices(cell.address);
      if (!coord) {
        continue;
      }
      const styleIndex = this.#getCurrentStyleIndex(coord.row, coord.col);
      if (styleIndex == null) {
        continue;
      }
      const styleId = this.#getOrCreateStyleIdForStyleIndex(styleIndex);
      const address = makeCellAddress(coord.row, coord.col);
      seeds.push({ address, styleId });
      this.#styleRefsByAddress.set(address, styleId);
    }
    if (seeds.length === 0) {
      return;
    }
    this.#runLocalTransaction(() => {
      for (const seed of seeds) {
        if (this.#styleRefs.get(seed.address) !== seed.styleId) {
          this.#styleRefs.set(seed.address, seed.styleId);
        }
      }
    });
  }
  #handleStyleRefEvent(event, transaction) {
    const origins = this.#getCollabOrigins();
    if (transaction.origin === origins.record || transaction.origin === origins.local) {
      return;
    }
    for (const address of event.keysChanged) {
      this.#applyStyleRefFromYjs(address, this.#styleRefs.get(address));
    }
  }
  #applyStyleRefFromYjs(address, styleId) {
    const coord = addressToIndices(address);
    if (!coord) {
      return;
    }
    const normalizedAddress = makeCellAddress(coord.row, coord.col);
    if (!styleId) {
      this.#styleRefsByAddress.delete(normalizedAddress);
      this.#pendingStyleRefAddresses.delete(normalizedAddress);
      return;
    }
    const styleIndex = this.#resolveStyleIndexForStyleId(styleId);
    if (styleIndex == null) {
      this.#styleRefsByAddress.set(normalizedAddress, styleId);
      this.#pendingStyleRefAddresses.add(normalizedAddress);
      return;
    }
    const cell = this.#getOrCreateCell(coord.row, coord.col);
    cell.styleIndex = styleIndex;
    this.#setLogicalStyleIndex(coord.row, coord.col, styleIndex);
    this.#styleRefsByAddress.set(normalizedAddress, styleId);
    this.#pendingStyleRefAddresses.delete(normalizedAddress);
  }
  #retryPendingStyleRefs() {
    if (this.#pendingStyleRefAddresses.size === 0) {
      return;
    }
    for (const address of Array.from(this.#pendingStyleRefAddresses)) {
      this.#applyStyleRefFromYjs(address, this.#styleRefs.get(address));
    }
  }
}
function addressToIndices(address) {
  if (!address) {
    return null;
  }
  const match = /^(\$?[A-Za-z]+)(\$?\d+)$/.exec(address);
  if (!match) {
    return null;
  }
  const [, rawCol, rawRow] = match;
  if (!rawCol || !rawRow) {
    return null;
  }
  const col = columnLabelToNumber(rawCol.replace(/\$/g, ""));
  const row2 = Number(rawRow.replace(/\$/g, ""));
  if (!col || !row2) {
    return null;
  }
  return { row: row2 - 1, col: col - 1 };
}

// node_modules/@oai/granola/dist/models/pivot-table-collab-store.js
class WorksheetPivotTablesCollabStore {
  #store;
  constructor(config2) {
    this.#store = new JsonSnapshotBranchStore({
      root: config2.root,
      prefix: config2.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION,
      runLocalTransaction: config2.runLocalTransaction,
      getCollabOrigins: config2.getCollabOrigins,
      readSnapshotFromOwner: config2.readPivotTables,
      applySnapshotToOwner: (items) => config2.applyPivotTables(items ?? []),
      encodeSnapshot: (items) => items,
      decodeSnapshot: (items) => items
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/slicer-collab-store.js
class WorksheetSlicersCollabStore {
  #store;
  constructor(config2) {
    this.#store = new JsonSnapshotBranchStore({
      root: config2.root,
      prefix: config2.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION,
      runLocalTransaction: config2.runLocalTransaction,
      getCollabOrigins: config2.getCollabOrigins,
      readSnapshotFromOwner: config2.readSlicers,
      applySnapshotToOwner: (items) => config2.applySlicers(items ?? []),
      encodeSnapshot: (items) => items,
      decodeSnapshot: (items) => items
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/table-collab-store.js
class WorksheetTablesCollabStore {
  #store;
  constructor(config2) {
    this.#store = new JsonSnapshotBranchStore({
      root: config2.root,
      prefix: config2.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION,
      runLocalTransaction: config2.runLocalTransaction,
      getCollabOrigins: config2.getCollabOrigins,
      readSnapshotFromOwner: config2.readTables,
      applySnapshotToOwner: (items) => config2.applyTables(items ?? []),
      encodeSnapshot: (items) => items,
      decodeSnapshot: (items) => items
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/worksheet-structure-collab-store.js
class WorksheetStructureCollabStore {
  #store;
  constructor(config2) {
    this.#store = new JsonSnapshotBranchStore({
      root: config2.root,
      prefix: config2.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION,
      runLocalTransaction: config2.runLocalTransaction,
      getCollabOrigins: config2.getCollabOrigins,
      readSnapshotFromOwner: config2.readStructure,
      applySnapshotToOwner: (snapshot) => {
        if (snapshot) {
          config2.applyStructure(snapshot);
        }
      },
      encodeSnapshot: (snapshot) => snapshot,
      decodeSnapshot: (snapshot) => snapshot
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/conditional-formatting-collab-store.js
class WorksheetConditionalFormattingCollabStore {
  #store;
  constructor(config2) {
    this.#store = new JsonSnapshotBranchStore({
      root: config2.root,
      prefix: config2.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION,
      runLocalTransaction: config2.runLocalTransaction,
      getCollabOrigins: config2.getCollabOrigins,
      readSnapshotFromOwner: config2.readConditionalFormattings,
      applySnapshotToOwner: (items) => config2.applyConditionalFormattings(items ?? []),
      encodeSnapshot: (items) => items,
      decodeSnapshot: (items) => items
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/data-validation-collab-store.js
class WorksheetDataValidationCollabStore {
  #store;
  constructor(config2) {
    this.#store = new JsonSnapshotBranchStore({
      root: config2.root,
      prefix: config2.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION,
      runLocalTransaction: config2.runLocalTransaction,
      getCollabOrigins: config2.getCollabOrigins,
      readSnapshotFromOwner: config2.readDataValidations,
      applySnapshotToOwner: (items) => config2.applyDataValidations(items ?? []),
      encodeSnapshot: (items) => items,
      decodeSnapshot: (items) => items
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/drawings-collab-store.js
class WorksheetDrawingsCollabStore {
  #store;
  constructor(config2) {
    this.#store = new JsonSnapshotBranchStore({
      root: config2.root,
      prefix: config2.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION,
      runLocalTransaction: config2.runLocalTransaction,
      getCollabOrigins: config2.getCollabOrigins,
      readSnapshotFromOwner: config2.readDrawings,
      applySnapshotToOwner: (drawings) => config2.applyDrawings(drawings ?? []),
      encodeSnapshot: (drawings) => drawings,
      decodeSnapshot: (drawings) => drawings
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/sparkline/sparkline-groups-collab-store.js
class WorksheetSparklineGroupsCollabStore {
  #store;
  constructor(config2) {
    this.#store = new JsonSnapshotBranchStore({
      root: config2.root,
      prefix: config2.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION,
      runLocalTransaction: config2.runLocalTransaction,
      getCollabOrigins: config2.getCollabOrigins,
      readSnapshotFromOwner: config2.readSparklineGroups,
      applySnapshotToOwner: config2.applySparklineGroups,
      encodeSnapshot: (groups) => groups,
      decodeSnapshot: (groups) => groups
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/worksheet-collab-state.js
class WorksheetCollabState {
  #stores;
  constructor(config2) {
    this.#stores = [
      new WorksheetStructureCollabStore({
        root: config2.root,
        prefix: "sheetStructure",
        runLocalTransaction: config2.runLocalTransaction,
        getCollabOrigins: config2.getCollabOrigins,
        readStructure: config2.readStructure,
        applyStructure: config2.applyStructure
      }),
      new WorksheetConditionalFormattingCollabStore({
        root: config2.root,
        prefix: "conditionalFormatting",
        runLocalTransaction: config2.runLocalTransaction,
        getCollabOrigins: config2.getCollabOrigins,
        readConditionalFormattings: config2.readConditionalFormattings,
        applyConditionalFormattings: config2.applyConditionalFormattings
      }),
      new WorksheetDataValidationCollabStore({
        root: config2.root,
        prefix: "dataValidations",
        runLocalTransaction: config2.runLocalTransaction,
        getCollabOrigins: config2.getCollabOrigins,
        readDataValidations: config2.readDataValidations,
        applyDataValidations: config2.applyDataValidations
      }),
      new WorksheetTablesCollabStore({
        root: config2.root,
        prefix: "tables",
        runLocalTransaction: config2.runLocalTransaction,
        getCollabOrigins: config2.getCollabOrigins,
        readTables: config2.readTables,
        applyTables: config2.applyTables
      }),
      new WorksheetPivotTablesCollabStore({
        root: config2.root,
        prefix: "pivotTables",
        runLocalTransaction: config2.runLocalTransaction,
        getCollabOrigins: config2.getCollabOrigins,
        readPivotTables: config2.readPivotTables,
        applyPivotTables: config2.applyPivotTables
      }),
      new WorksheetSlicersCollabStore({
        root: config2.root,
        prefix: "slicers",
        runLocalTransaction: config2.runLocalTransaction,
        getCollabOrigins: config2.getCollabOrigins,
        readSlicers: config2.readSlicers,
        applySlicers: config2.applySlicers
      }),
      new WorksheetSparklineGroupsCollabStore({
        root: config2.root,
        prefix: "sparklineGroups",
        runLocalTransaction: config2.runLocalTransaction,
        getCollabOrigins: config2.getCollabOrigins,
        readSparklineGroups: config2.readSparklineGroups,
        applySparklineGroups: config2.applySparklineGroups
      }),
      new WorksheetDrawingsCollabStore({
        root: config2.root,
        prefix: "drawings",
        runLocalTransaction: config2.runLocalTransaction,
        getCollabOrigins: config2.getCollabOrigins,
        readDrawings: config2.readDrawings,
        applyDrawings: config2.applyDrawings
      })
    ];
  }
  activate(config2) {
    activateWorksheetCollabRoot({
      root: config2.root,
      runLocalTransaction: config2.runLocalTransaction
    });
    for (const store of this.#stores) {
      store.activate();
    }
  }
  dispose() {
    for (const store of this.#stores) {
      store.dispose();
    }
  }
  flushFromOwner() {
    for (const store of this.#stores) {
      store.flushFromOwner();
    }
  }
}

// node_modules/@oai/granola/dist/spreadsheet/table-style-rendering.js
var SPREADSHEET_COLOR_OPTIONS5 = { colorSpace: "spreadsheetml" };

class TableStyleResolver {
  #context;
  #themeMap;
  #cellCache = new Map;
  constructor(context, themeMap) {
    this.#context = context;
    this.#themeMap = themeMap;
  }
  get startRow() {
    return this.#context.startRow;
  }
  get endRow() {
    return this.#context.endRow;
  }
  get startCol() {
    return this.#context.startCol;
  }
  get endCol() {
    return this.#context.endCol;
  }
  get headerRows() {
    return this.#context.headerRows;
  }
  get totalRows() {
    return this.#context.totalRows;
  }
  get showRowStripes() {
    return this.#context.showRowStripes;
  }
  get showColumnStripes() {
    return this.#context.showColumnStripes;
  }
  get showFirstColumn() {
    return this.#context.showFirstColumn;
  }
  get showLastColumn() {
    return this.#context.showLastColumn;
  }
  get tableStyle() {
    return this.#context.tableStyle;
  }
  contains(row2, col) {
    return row2 >= this.#context.startRow && row2 <= this.#context.endRow && col >= this.#context.startCol && col <= this.#context.endCol;
  }
  resolveCell(row2, col) {
    const key = `${row2}:${col}`;
    if (this.#cellCache.has(key)) {
      return this.#cellCache.get(key);
    }
    const resolved = getTableCellStyle(this.#context, row2, col, this.#themeMap);
    this.#cellCache.set(key, resolved);
    return resolved;
  }
  resolveFont(row2, col) {
    return getTableCellFontOverrides(this.#context, row2, col);
  }
  resolveBorders(row2, col) {
    return getTableCellBorderOverrides(this.#context, row2, col, this.#themeMap);
  }
  getBandFills() {
    return this.#context.fills;
  }
}
function pickDxf(tableStyle, key) {
  const idx = tableStyle.tableStyles[key];
  if (idx == null)
    return;
  return tableStyle.dxfs[idx];
}
function resolveTableStyle(name) {
  return getTableStyle(name) ?? getTableStyle(DEFAULT_RENDER_TABLE_STYLE_NAME);
}
function parseTableBounds(table2) {
  const ref = table2.ref ?? "";
  const [start, end] = ref.split(":");
  const startCol = columnIndex(start || "A1");
  const startRow = rowIndex(start || "A1");
  const endCol = end ? columnIndex(end) : startCol;
  const endRow = end ? rowIndex(end) : startRow;
  const headerRows = getEffectiveTableHeaderRowCount(table2);
  const totalRows = getEffectiveTableTotalsRowCount(table2);
  return {
    startRow: Math.min(startRow, endRow),
    endRow: Math.max(startRow, endRow),
    startCol: Math.min(startCol, endCol),
    endCol: Math.max(startCol, endCol),
    headerRows,
    totalRows
  };
}
function fillToCss(fill2, themeMap) {
  if (!fill2 || fill2.type !== 1 /* FILL_TYPE_SOLID */ || !fill2.color) {
    return;
  }
  return resolveColor(fill2.color, themeMap, SPREADSHEET_COLOR_OPTIONS5);
}
function resolveLine(line, themeMap) {
  if (!line?.style) {
    return;
  }
  return {
    style: line.style,
    colorCss: resolveColor(line.color, themeMap, {
      ...SPREADSHEET_COLOR_OPTIONS5,
      defaultFill: "#cccccc"
    })
  };
}
function pickStripeDxf(index, first, second) {
  if (first && second) {
    return index % 2 === 0 ? first : second;
  }
  if (!first && !second) {
    return;
  }
  return index % 2 === 0 ? first ?? second : undefined;
}
function getTableCellElements(ctx, r, c) {
  if (r < ctx.startRow || r > ctx.endRow || c < ctx.startCol || c > ctx.endCol) {
    return;
  }
  const style = ctx.tableStyle;
  const whole = pickDxf(style, "wholeTable");
  const header = pickDxf(style, "headerRow");
  const total = pickDxf(style, "totalRow");
  const firstColumn = pickDxf(style, "firstColumn");
  const lastColumn = pickDxf(style, "lastColumn");
  const firstRowStripe = pickDxf(style, "firstRowStripe");
  const secondRowStripe = pickDxf(style, "secondRowStripe");
  const firstColumnStripe = pickDxf(style, "firstColumnStripe");
  const secondColumnStripe = pickDxf(style, "secondColumnStripe");
  const dataStart = ctx.startRow + ctx.headerRows;
  const dataEnd = ctx.endRow - ctx.totalRows;
  const isHeader = r >= ctx.startRow && r < ctx.startRow + ctx.headerRows;
  const isTotals = ctx.totalRows > 0 && r >= ctx.endRow - ctx.totalRows + 1;
  const isData = !isHeader && !isTotals && r >= dataStart && r <= dataEnd;
  return {
    whole,
    rowStripe: isData && ctx.showRowStripes ? pickStripeDxf(r - dataStart, firstRowStripe, secondRowStripe) : undefined,
    columnStripe: isData && ctx.showColumnStripes ? pickStripeDxf(c - ctx.startCol, firstColumnStripe, secondColumnStripe) : undefined,
    firstColumn: ctx.showFirstColumn && c === ctx.startCol ? firstColumn : undefined,
    lastColumn: ctx.showLastColumn && c === ctx.endCol ? lastColumn : undefined,
    header: isHeader ? header : undefined,
    total: isTotals ? total : undefined
  };
}
function mergeFont(target, dxf) {
  const font = dxf?.font;
  if (!font) {
    return target;
  }
  const next = target ? { ...target } : {};
  if (font.bold != null) {
    next.bold = font.bold;
  }
  if (font.fill?.color) {
    next.color = font.fill.color;
  }
  return next.bold === undefined && !next.color ? undefined : next;
}
function mergeDirectBorders(target, dxf, themeMap) {
  const border = dxf?.border;
  if (!border) {
    return;
  }
  const edges = ["top", "bottom", "left", "right"];
  for (const edge of edges) {
    const line = resolveLine(border[edge], themeMap);
    if (line) {
      target[edge] = line;
    }
  }
}
function applyWholeTableBorders(target, ctx, r, c, whole, themeMap) {
  const border = whole?.border;
  if (!border) {
    return;
  }
  if (r === ctx.startRow) {
    const top = resolveLine(border.top, themeMap);
    if (top) {
      target.top = top;
    }
  } else {
    const horizontal = resolveLine(border.horizontal, themeMap);
    if (horizontal) {
      target.top = horizontal;
    }
  }
  if (r === ctx.endRow) {
    const bottom = resolveLine(border.bottom, themeMap);
    if (bottom) {
      target.bottom = bottom;
    }
  }
  if (c === ctx.startCol) {
    const left = resolveLine(border.left, themeMap);
    if (left) {
      target.left = left;
    }
  } else {
    const vertical = resolveLine(border.vertical, themeMap);
    if (vertical) {
      target.left = vertical;
    }
  }
  if (c === ctx.endCol) {
    const right = resolveLine(border.right, themeMap);
    if (right) {
      target.right = right;
    }
  }
}
function buildTableStyleContexts(sheetTables, themeMap) {
  if (!sheetTables || sheetTables.length === 0)
    return [];
  return sheetTables.map((t) => {
    const style = resolveTableStyle(t.style?.name);
    if (!style)
      return;
    const bounds = parseTableBounds(t);
    const header = pickDxf(style, "headerRow");
    const firstRowStripe = pickDxf(style, "firstRowStripe");
    const firstColStripe = pickDxf(style, "firstColumnStripe");
    const totalRow = pickDxf(style, "totalRow");
    return {
      ...bounds,
      showRowStripes: !!t.style?.showRowStripes,
      showColumnStripes: !!t.style?.showColumnStripes,
      showFirstColumn: !!t.style?.showFirstColumn,
      showLastColumn: !!t.style?.showLastColumn,
      tableStyle: style,
      fills: {
        header: fillToCss(header?.fill, themeMap),
        rowStripe: fillToCss(firstRowStripe?.fill, themeMap),
        columnStripe: fillToCss(firstColStripe?.fill, themeMap),
        total: fillToCss(totalRow?.fill, themeMap)
      }
    };
  }).filter((ctx) => !!ctx && ctx.startCol <= ctx.endCol && ctx.startRow <= ctx.endRow && (ctx.headerRows > 0 || ctx.endRow >= ctx.startRow));
}
function buildTableStyleResolvers(sheetTables, themeMap) {
  return buildTableStyleContexts(sheetTables, themeMap).map((context) => new TableStyleResolver(context, themeMap));
}
function getTableCellStyle(ctx, r, c, themeMap) {
  const elements = getTableCellElements(ctx, r, c);
  if (!elements) {
    return;
  }
  let fillCss = fillToCss(elements.whole?.fill, themeMap);
  let font = mergeFont(undefined, elements.whole);
  const borders = {};
  applyWholeTableBorders(borders, ctx, r, c, elements.whole, themeMap);
  const overlays = [
    elements.rowStripe,
    elements.columnStripe,
    elements.firstColumn,
    elements.lastColumn,
    elements.header,
    elements.total
  ];
  for (const dxf of overlays) {
    const overlayFill = fillToCss(dxf?.fill, themeMap);
    if (overlayFill) {
      fillCss = overlayFill;
    }
    font = mergeFont(font, dxf);
    mergeDirectBorders(borders, dxf, themeMap);
  }
  return {
    fillCss,
    font,
    borders
  };
}
function getTableCellFontOverrides(ctx, r, c) {
  const elements = getTableCellElements(ctx, r, c);
  if (!elements) {
    return;
  }
  let font = mergeFont(undefined, elements.whole);
  font = mergeFont(font, elements.rowStripe);
  font = mergeFont(font, elements.columnStripe);
  font = mergeFont(font, elements.firstColumn);
  font = mergeFont(font, elements.lastColumn);
  font = mergeFont(font, elements.header);
  font = mergeFont(font, elements.total);
  return font;
}
function getTableCellBorderOverrides(ctx, r, c, themeMap) {
  return getTableCellStyle(ctx, r, c, themeMap)?.borders ?? {};
}

// node_modules/@oai/granola/dist/models/spreadsheet/address-indices.js
var MAX_ADDRESS_INDEX_CACHE_ENTRIES = 50000;
var addressIndicesCache = new Map;
function parseAddressIndices(address) {
  if (!address) {
    return null;
  }
  let index = 0;
  if (address[index] === "$") {
    index += 1;
  }
  let col = 0;
  let sawColumnLetter = false;
  while (index < address.length) {
    const code = address.charCodeAt(index);
    let digit = 0;
    if (code >= 65 && code <= 90) {
      digit = code - 64;
    } else if (code >= 97 && code <= 122) {
      digit = code - 96;
    } else {
      break;
    }
    col = col * 26 + digit;
    sawColumnLetter = true;
    index += 1;
  }
  if (!sawColumnLetter) {
    return null;
  }
  if (address[index] === "$") {
    index += 1;
  }
  let row2 = 0;
  let sawRowDigit = false;
  while (index < address.length) {
    const code = address.charCodeAt(index);
    if (code < 48 || code > 57) {
      return null;
    }
    row2 = row2 * 10 + (code - 48);
    sawRowDigit = true;
    index += 1;
  }
  if (!sawRowDigit || row2 <= 0 || col <= 0) {
    return null;
  }
  return { row: row2 - 1, col: col - 1 };
}
function getAddressIndices(address) {
  if (addressIndicesCache.has(address)) {
    return addressIndicesCache.get(address) ?? null;
  }
  const parsed = parseAddressIndices(address);
  if (addressIndicesCache.size >= MAX_ADDRESS_INDEX_CACHE_ENTRIES) {
    addressIndicesCache.clear();
  }
  addressIndicesCache.set(address, parsed);
  return parsed;
}

// node_modules/@oai/granola/dist/models/spreadsheet/worksheet.js
var FREEZE_PANES_PROTO_KEY = "__oaiPopcornFreezePanes";
function normalizeFreezeCount(value) {
  if (!Number.isFinite(value)) {
    return 0;
  }
  return Math.max(0, Math.trunc(value));
}
function readWorksheetFreezePanes(proto) {
  const extension = proto[FREEZE_PANES_PROTO_KEY];
  return {
    rowCount: normalizeFreezeCount(extension?.rowCount ?? 0),
    columnCount: normalizeFreezeCount(extension?.columnCount ?? 0)
  };
}

class WorksheetFreezePanes {
  #worksheet;
  #state;
  constructor(worksheet, initialState = {
    rowCount: 0,
    columnCount: 0
  }) {
    this.#worksheet = worksheet;
    this.#state = {
      rowCount: normalizeFreezeCount(initialState.rowCount),
      columnCount: normalizeFreezeCount(initialState.columnCount)
    };
  }
  get state() {
    return { ...this.#state };
  }
  freezeRows(rowCount) {
    const normalized = normalizeFreezeCount(rowCount);
    if (normalized === this.#state.rowCount) {
      return;
    }
    this.#state.rowCount = normalized;
    this.#worksheet?.__invalidateViewportLayout();
  }
  freezeColumns(columnCount) {
    const normalized = normalizeFreezeCount(columnCount);
    if (normalized === this.#state.columnCount) {
      return;
    }
    this.#state.columnCount = normalized;
    this.#worksheet?.__invalidateViewportLayout();
  }
  unfreeze() {
    if (this.#state.rowCount === 0 && this.#state.columnCount === 0) {
      return;
    }
    this.#state = {
      rowCount: 0,
      columnCount: 0
    };
    this.#worksheet?.__invalidateViewportLayout();
  }
}
var DEFAULT_COL_WIDTH = 12.71;
function stripSheetPrefix(value) {
  const trimmed = value.trim();
  const bang = trimmed.lastIndexOf("!");
  const withoutSheet = bang >= 0 ? trimmed.slice(bang + 1) : trimmed;
  return withoutSheet.replace(/\$/g, "");
}
function parseSqrefRanges(sqref) {
  const out = [];
  const parts = sqref.trim().split(/\s+/);
  for (const part of parts) {
    if (!part) {
      continue;
    }
    const [startRaw, endRaw] = part.split(":");
    if (!startRaw) {
      continue;
    }
    const startAddress = stripSheetPrefix(startRaw);
    const endAddress = stripSheetPrefix(endRaw || startRaw);
    out.push({ startAddress, endAddress, sheetName: "" });
  }
  return out;
}

class Worksheet {
  #context;
  #state;
  #tabColor;
  #defaultColWidthExplicit;
  #collections;
  #ranges;
  #cellStore;
  #rowIndex;
  #columnExtents;
  #rowExtents;
  #pivotTables;
  #slicers;
  #tables;
  #dataTables;
  #cells;
  #logicalStyleIndex;
  #styleRefStore;
  #sparklineGroups;
  #drawings;
  #conditionalFormattings;
  #dataValidations;
  #freezePanes;
  #collabState;
  #ySheetState;
  #yCells;
  #yRowSizes;
  #yColSizes;
  #yCharts;
  #rowSizeObserver;
  #colSizeObserver;
  #viewportLayoutCache;
  #viewportLayoutCacheKey;
  #viewportLayoutDirty = true;
  #spreadsheetRenderMetadataCache;
  #spreadsheetRenderMetadataCacheKey;
  constructor(proto, context) {
    const worksheetId = proto.id ?? generateAidSuffix();
    const sheetId = proto.sheetId;
    this.#context = context;
    this.#defaultColWidthExplicit = proto.defaultColWidth != null;
    this.#state = {
      id: worksheetId,
      sheetId,
      index: proto.index ?? 0,
      name: proto.name ?? "",
      innerXml: proto.innerXml ?? "",
      outerXml: proto.outerXml ?? "",
      defaultRowHeight: proto.defaultRowHeight ?? 15,
      defaultColWidth: proto.defaultColWidth ?? DEFAULT_COL_WIDTH,
      baseColWidth: proto.baseColWidth,
      showGridLines: proto.showGridLines
    };
    this.#tabColor = proto.tabColor;
    this.#collections = {
      rows: proto.rows ?? [],
      columns: proto.columns ?? [],
      mergedCells: proto.mergedCells ?? [],
      conditionalFormattings: proto.conditionalFormattings ?? [],
      dataValidations: proto.dataValidations?.items ?? [],
      sharedFormulas: proto.sharedFormulas ?? [],
      tables: proto.tables ?? [],
      pivotTables: proto.pivotTables ?? [],
      slicers: proto.slicers ?? [],
      timelines: proto.timelines ?? [],
      drawings: proto.drawings ?? []
    };
    this.#ranges = new Map;
    this.#cellStore = new CellStore;
    this.#rowIndex = new Map;
    this.#columnExtents = new Map;
    this.#rowExtents = new Map;
    this.#logicalStyleIndex = new Map;
    if (sheetId && sheetId.length > 0) {
      this.#ySheetState = this.#context.getOrCreateWorksheetState(sheetId);
      this.#yCells = this.#getOrCreateCellInputState(this.#ySheetState);
      this.#yCells.observe((event, transaction) => {
        this.#handleCellInputEvent(event, transaction);
      });
    } else {
      console.warn(`Worksheet "${proto.name ?? ""}" is missing a required sheetId.`);
    }
    const pendingDataTables = [];
    for (const row2 of this.#collections.rows) {
      const rIdx = Math.max(0, (row2.index ?? 1) - 1);
      this.#rowIndex.set(rIdx, row2);
      if (!row2.cells) {
        row2.cells = [];
      }
      for (const cell of row2.cells) {
        if (!cell.address) {
          continue;
        }
        const coord = addressToIndices2(cell.address);
        if (!coord) {
          continue;
        }
        const hydratedCell = Cell3.from(cell).toProto();
        this.#cellStore.set(coord.row, coord.col, hydratedCell);
        this.#trackExtents(coord.row, coord.col);
        if (hydratedCell.styleIndex !== undefined) {
          this.__setLogicalStyleIndex(coord.row, coord.col, hydratedCell.styleIndex);
        }
        if (hydratedCell.formulaType === 3 /* CELL_FORMULA_TYPE_DATA_TABLE */) {
          pendingDataTables.push({
            row: coord.row,
            col: coord.col,
            formulaRef: hydratedCell.formulaRef ?? null,
            rowInput: hydratedCell.dataTableRowInput ?? undefined,
            columnInput: hydratedCell.dataTableColumnInput ?? undefined,
            rowOriented: hydratedCell.dataTableRowOriented ?? undefined,
            twoVariable: hydratedCell.dataTableTwoVariable ?? undefined
          });
        }
      }
    }
    this.#pivotTables = new PivotTableCollection({
      workbook: this.#context.workbook,
      worksheet: this,
      context: this.#context.pivotTables
    });
    this.#slicers = new SlicerCollection({
      workbook: this.#context.workbook,
      worksheet: this,
      context: this.#context.slicers
    });
    this.#tables = new TableCollection(this);
    this.#dataTables = new WorksheetDataTableCollection(this);
    if (this.#ySheetState && sheetId) {
      this.#styleRefStore = new WorksheetStyleRefStore({
        isCollaborativeStateReady: () => this.#context.workbook.isCollaborativeStateReady(),
        styleRefsState: this.#context.getOrCreateWorksheetStyleRefsState(sheetId),
        runLocalTransaction: (fn) => this.#context.workbook.runLocalCollabTransaction(fn),
        getCollabOrigins: () => this.#context.workbook.getCollabOrigins(),
        resolveStyleIndexForStyleId: (styleId) => this.#context.workbook.__resolveStyleIndexForStyleId(styleId),
        getOrCreateStyleIdForStyleIndex: (styleIndex) => this.#context.workbook.__getOrCreateStyleIdForStyleIndex(styleIndex),
        subscribeToStyleStore: (listener) => this.#context.workbook.__subscribeToCollaborativeStyles(listener),
        getCurrentStyleIndex: (rowIdx, colIdx) => this.__getLogicalStyleIndex(rowIdx, colIdx) ?? this.__getCell(rowIdx, colIdx)?.styleIndex,
        getOrCreateCell: (rowIdx, colIdx) => this.__getOrCreateCell(rowIdx, colIdx),
        setLogicalStyleIndex: (rowIdx, colIdx, styleIndex) => this.__setLogicalStyleIndex(rowIdx, colIdx, styleIndex),
        iterateCells: () => function* (entries) {
          for (const [, cell] of entries) {
            yield cell;
          }
        }(this.#cellStore.entries())
      });
    }
    if (this.#ySheetState) {
      this.#rowSizeObserver = (event, transaction) => {
        this.#handleRowSizeEvent(event, transaction);
      };
      this.#colSizeObserver = (event, transaction) => {
        this.#handleColumnSizeEvent(event, transaction);
      };
      this.#setRowSizeState(this.#getRowSizeState(this.#ySheetState));
      this.#setColumnSizeState(this.#getColumnSizeState(this.#ySheetState));
    }
    this.#drawings = new WorksheetDrawingCollection(proto.drawings ?? [], {
      shapeContext: {
        ...createWorksheetShapeContext(),
        getRecorder: () => this.#context.workbook.getRecorder(),
        getSheetName: () => this.name,
        queueCollaborativePublish: () => this.__queueCollaborativePublish()
      },
      imageContext: {
        createImageAsset: (options) => this.#context.workbook.createImageAsset(options),
        getRecorder: () => this.#context.workbook.getRecorder(),
        getSheetName: () => this.name,
        queueCollaborativePublish: () => this.__queueCollaborativePublish()
      },
      chartContext: {
        getRecorder: () => this.#context.workbook.getRecorder(),
        getSheetName: () => this.name,
        getChartsState: () => this.__getChartsState(),
        getOrCreateChartsState: () => this.__getOrCreateChartsState(),
        isCollaborativeStateReady: () => this.#context.workbook.isCollaborativeStateReady(),
        runLocalTransaction: (fn) => this.#context.workbook.runLocalCollabTransaction(fn),
        getCollabOrigins: () => this.#context.workbook.getCollabOrigins()
      }
    });
    this.#conditionalFormattings = new WorksheetConditionalFormattingCollection(this);
    this.#dataValidations = new WorksheetDataValidationCollection(this);
    this.#freezePanes = new WorksheetFreezePanes(this, readWorksheetFreezePanes(proto));
    this.#sparklineGroups = new SparklineGroupCollection(this, proto.sparklineGroups);
    for (const dataTable of pendingDataTables) {
      this.#dataTables.__hydrateFromProto({
        anchor: { row: dataTable.row, col: dataTable.col },
        formulaRef: dataTable.formulaRef,
        rowInput: dataTable.rowInput,
        columnInput: dataTable.columnInput,
        rowOriented: dataTable.rowOriented,
        twoVariable: dataTable.twoVariable
      });
    }
    if (this.#ySheetState) {
      this.#collabState = this.#createWorksheetCollabState(this.#ySheetState);
    }
    this.#applyExistingSizingRefsFromState();
    this.#cells = new WorksheetCells(this);
    this.#hydrateCellInputsFromState();
  }
  get workbook() {
    return this.#context.workbook;
  }
  #createWorksheetCollabState(root) {
    return new WorksheetCollabState({
      root,
      runLocalTransaction: (fn) => this.#context.workbook.runLocalCollabTransaction(fn),
      getCollabOrigins: () => this.#context.workbook.getCollabOrigins(),
      readStructure: () => this.#buildCollabStructureSnapshot(),
      applyStructure: (snapshot) => {
        this.#applyCollabStructureSnapshot(snapshot);
        this.#context.workbook.__invalidateCalcStateFromCollab();
      },
      readConditionalFormattings: () => this.#collections.conditionalFormattings,
      applyConditionalFormattings: (items) => {
        this.#collections.conditionalFormattings = items;
        this.#context.workbook.invalidateConditionalFormattingCache(this.name);
      },
      readDataValidations: () => this.#collections.dataValidations,
      applyDataValidations: (items) => {
        this.#collections.dataValidations = items;
        this.__invalidateViewportLayout();
      },
      readTables: () => this.#collections.tables,
      applyTables: (items) => {
        this.#collections.tables = items;
        this.#tables.replaceFromProto();
        this.__invalidateViewportLayout();
        this.#context.workbook.__invalidateCalcStateFromCollab();
      },
      readPivotTables: () => this.#collections.pivotTables,
      applyPivotTables: (items) => {
        this.#collections.pivotTables = items;
        this.#pivotTables.reload();
        this.__invalidateViewportLayout();
        this.#context.workbook.__reloadPivotCollectionsFromCollab();
      },
      readSlicers: () => this.#collections.slicers,
      applySlicers: (items) => {
        this.#collections.slicers = items;
        this.#slicers.reload();
        this.__invalidateViewportLayout();
        this.#context.workbook.__reloadSlicerCollectionsFromCollab();
      },
      readSparklineGroups: () => this.#sparklineGroups.toProto(),
      applySparklineGroups: (groups) => {
        this.#sparklineGroups.replaceFromProto(groups);
        this.__invalidateViewportLayout();
        this.#context.workbook.__refreshSparklineRenderContextsFromCollab();
      },
      readDrawings: () => this.#drawings.toNonChartProto(),
      applyDrawings: (drawings) => {
        this.#drawings.replaceNonChartDrawings(drawings);
        this.__invalidateViewportLayout();
      }
    });
  }
  get names() {
    return this.#context.workbook.__getNamesFacadeForSheet(this.name);
  }
  get id() {
    return this.#state.id;
  }
  get name() {
    return this.#state.name;
  }
  get isNullObject() {
    return false;
  }
  set name(value) {
    this.writeName(value);
  }
  get index() {
    return this.#state.index;
  }
  get sheetId() {
    return this.#state.sheetId;
  }
  get tabColor() {
    return this.#tabColor;
  }
  get showGridLines() {
    return this.#state.showGridLines;
  }
  set showGridLines(value) {
    this.#state.showGridLines = value;
    this.__queueCollaborativePublish();
  }
  get defaultRowHeight() {
    return this.#state.defaultRowHeight;
  }
  get defaultColWidth() {
    return this.#state.defaultColWidth;
  }
  get baseColWidth() {
    return this.#state.baseColWidth;
  }
  get innerXml() {
    return this.#state.innerXml;
  }
  get outerXml() {
    return this.#state.outerXml;
  }
  set index(value) {
    this.writeIndex(value);
  }
  writeName(value, options = {}) {
    const shouldRecord = options.record ?? true;
    const previous = this.#state.name || undefined;
    if (previous === value) {
      return;
    }
    this.#state.name = value;
    this.#context.onNameChange?.(this, previous, value);
    if (!shouldRecord) {
      return;
    }
    const recorder = this.workbook.getRecorder();
    if (!recorder) {
      return;
    }
    const op = {
      op: "sheet.set",
      target: previous ?? value,
      props: {
        name: value
      }
    };
    recorder.record(op);
  }
  writeIndex(value, options = {}) {
    const shouldNotifyCollection = options.notifyCollection ?? true;
    const shouldRecord = options.record ?? true;
    const normalized = Number.isFinite(value) ? Math.max(0, Math.floor(value)) : this.#state.index;
    const previous = this.#state.index;
    if (previous === normalized) {
      return;
    }
    if (shouldNotifyCollection && this.#context.onIndexChange) {
      this.#context.onIndexChange(this, previous, normalized);
    } else {
      this.#state.index = normalized;
    }
    if (!shouldRecord) {
      return;
    }
    const recorder = this.workbook.getRecorder();
    if (!recorder) {
      return;
    }
    const op = {
      op: "sheet.set",
      target: this.name,
      props: {
        index: normalized
      }
    };
    recorder.record(op);
  }
  getRange(address, ...rest) {
    if (typeof address !== "string") {
      const types = [address, ...rest].map((arg) => typeof arg);
      const display = types.length ? `(${types.join(", ")})` : "(unknown)";
      throw new Error(`getRange(address) requires an A1 string; you passed ${display}. ` + `Use sheet.getRange("A1") / "A1:B2"; getRange(row,col) is not supported.`);
    }
    if (!this.#ranges.has(address)) {
      this.#ranges.set(address, new Range({ address, worksheet: this }));
    }
    return this.#ranges.get(address);
  }
  getRangeByIndexes(startRow, startColumn, rowCount, columnCount) {
    const values = [startRow, startColumn, rowCount, columnCount];
    if (values.some((value) => !Number.isFinite(value))) {
      throw new Error("getRangeByIndexes(startRow, startColumn, rowCount, columnCount) requires numeric arguments.");
    }
    if (!Number.isInteger(startRow) || !Number.isInteger(startColumn) || !Number.isInteger(rowCount) || !Number.isInteger(columnCount)) {
      throw new Error("getRangeByIndexes(startRow, startColumn, rowCount, columnCount) requires integer arguments.");
    }
    if (startRow < 0 || startColumn < 0 || rowCount < 1 || columnCount < 1) {
      throw new Error("getRangeByIndexes(startRow, startColumn, rowCount, columnCount) requires non-negative indexes and positive sizes; " + `got (${startRow}, ${startColumn}, ${rowCount}, ${columnCount}).`);
    }
    const address = buildRangeRef({
      startRow,
      startCol: startColumn,
      endRow: startRow + rowCount - 1,
      endCol: startColumn + columnCount - 1
    });
    return this.getRange(address);
  }
  getCell(row2, column2) {
    return this.getRangeByIndexes(row2, column2, 1, 1);
  }
  getUsedRange(valuesOnly) {
    if (valuesOnly) {
      const bounds = this.#getValuesUsedBounds();
      if (!bounds) {
        return this.getRangeByIndexes(0, 0, 1, 1);
      }
      return this.getRangeByIndexes(bounds.startRow, bounds.startCol, bounds.endRow - bounds.startRow + 1, bounds.endCol - bounds.startCol + 1);
    }
    if (this.#rowExtents.size === 0) {
      return this.getRangeByIndexes(0, 0, 1, 1);
    }
    let minRow = Number.POSITIVE_INFINITY;
    let maxRow = -1;
    let minCol = Number.POSITIVE_INFINITY;
    let maxCol = -1;
    for (const [rowIdx, extent2] of this.#rowExtents.entries()) {
      minRow = Math.min(minRow, rowIdx);
      maxRow = Math.max(maxRow, rowIdx);
      minCol = Math.min(minCol, extent2.min);
      maxCol = Math.max(maxCol, extent2.max);
    }
    if (!Number.isFinite(minRow) || !Number.isFinite(minCol) || maxRow < 0) {
      return this.getRangeByIndexes(0, 0, 1, 1);
    }
    return this.getRangeByIndexes(minRow, minCol, maxRow - minRow + 1, maxCol - minCol + 1);
  }
  reset(options) {
    const clear = options?.clear ?? "used";
    const applyTo = options?.applyTo ?? "all";
    const deleteTables = options?.deleteTables ?? true;
    const deleteCharts = options?.deleteCharts ?? true;
    const deleteDrawings = options?.deleteDrawings ?? true;
    const deleteSparklines = options?.deleteSparklines ?? true;
    if (clear === "used") {
      this.getUsedRange(false).clear({ applyTo });
    } else if (clear !== "none") {
      throw new Error('worksheet.reset clear must be "used" or "none".');
    }
    if (deleteTables) {
      this.tables.deleteAll();
    }
    if (deleteCharts) {
      this.charts.deleteAll();
    }
    if (deleteDrawings) {
      this.deleteAllDrawings();
    }
    if (deleteSparklines) {
      this.sparklineGroups.clear();
    }
  }
  mergeCells(address) {
    const { sheetName, ref } = splitSheetAddress(address);
    if (sheetName && sheetName !== this.name) {
      throw new Error(`Merge range must target "${this.name}", received "${sheetName}".`);
    }
    const parsed = parseRangeAddress(ref);
    if (!parsed) {
      throw new Error(`Invalid range address: ${address}`);
    }
    const { startRow, startCol, endRow, endCol } = parsed.bounds;
    if (startRow === endRow && startCol === endCol) {
      return;
    }
    const startAddress = makeCellAddress(startRow, startCol);
    const endAddress = makeCellAddress(endRow, endCol);
    const existing = this.#collections.mergedCells.some((merge2) => merge2.startAddress === startAddress && (merge2.endAddress ?? merge2.startAddress) === endAddress);
    if (existing) {
      return;
    }
    const merged = {
      sheetName: this.name,
      sheetId: this.id ?? "",
      startAddress,
      endAddress
    };
    this.#collections.mergedCells = [...this.#collections.mergedCells, merged];
    this.__queueCollaborativePublish();
  }
  unmergeCells(address) {
    const { sheetName, ref } = splitSheetAddress(address);
    if (sheetName && sheetName !== this.name) {
      throw new Error(`Unmerge range must target "${this.name}", received "${sheetName}".`);
    }
    const parsed = parseRangeAddress(ref);
    if (!parsed) {
      throw new Error(`Invalid range address: ${address}`);
    }
    const target = parsed.bounds;
    const intersects = (a, b) => a.startRow <= b.endRow && a.endRow >= b.startRow && a.startCol <= b.endCol && a.endCol >= b.startCol;
    const next = this.#collections.mergedCells.filter((merge2) => {
      const start = merge2.startAddress;
      if (!start) {
        return true;
      }
      const end = merge2.endAddress ?? start;
      const mergeParsed = parseRangeAddress(`${start}:${end}`);
      if (!mergeParsed) {
        return true;
      }
      return !intersects(mergeParsed.bounds, target);
    });
    if (next.length !== this.#collections.mergedCells.length) {
      this.#collections.mergedCells = next;
      this.__queueCollaborativePublish();
    }
  }
  get pivotTables() {
    return this.#pivotTables;
  }
  get slicers() {
    return this.#slicers;
  }
  get sparklineGroups() {
    return this.#sparklineGroups;
  }
  get charts() {
    return this.#drawings.charts;
  }
  get shapes() {
    return this.#drawings.shapes;
  }
  get images() {
    return this.#drawings.images;
  }
  deleteAllDrawings() {
    this.#drawings.deleteAllKnown();
  }
  autoLayoutDrawings(items, options = {}) {
    autoLayoutWorksheetDrawings(this, items, options);
  }
  get conditionalFormattings() {
    return this.#conditionalFormattings;
  }
  get dataValidations() {
    return this.#dataValidations;
  }
  get freezePanes() {
    return this.#freezePanes;
  }
  get sparklines() {
    return this.#sparklineGroups;
  }
  get tables() {
    return this.#tables;
  }
  get dataTables() {
    return this.#dataTables;
  }
  get cells() {
    return this.#cells;
  }
  __getWorksheetByName(name) {
    return this.#context.getWorksheetByName?.(name);
  }
  __refreshSparklineRenderContext() {
    this.#sparklineGroups.__refreshRenderContext();
  }
  __queueCollaborativePublish() {
    if (!this.sheetId) {
      return;
    }
    this.#context.workbook.queueWorksheetCollabPublish(this.sheetId);
  }
  flushCollaborativeState() {
    if (!this.#collabState || !this.#ySheetState) {
      return;
    }
    this.#collabState.activate({
      root: this.#ySheetState,
      runLocalTransaction: (fn) => this.#context.workbook.runLocalCollabTransaction(fn)
    });
    this.#collabState.flushFromOwner();
  }
  __invalidateViewportLayout() {
    this.#viewportLayoutDirty = true;
    this.#viewportLayoutCache = undefined;
    this.#viewportLayoutCacheKey = undefined;
    this.#spreadsheetRenderMetadataCache = undefined;
    this.#spreadsheetRenderMetadataCacheKey = undefined;
  }
  __getViewportLayout(options = {}) {
    const maxCols = Math.max(1, options.maxCols ?? 500);
    const maxRows = Math.max(1, options.maxRows ?? 500);
    const showFormulas = options.showFormulas ?? false;
    const colWidthOverridesPx = options.colWidthOverridesPx;
    const rowHeightOverridesPx = options.rowHeightOverridesPx;
    if (!this.#viewportLayoutDirty && this.#viewportLayoutCacheKey) {
      const key = this.#viewportLayoutCacheKey;
      if (key.maxCols === maxCols && key.maxRows === maxRows && key.showFormulas === showFormulas && key.colWidthOverridesPx === colWidthOverridesPx && key.rowHeightOverridesPx === rowHeightOverridesPx && this.#viewportLayoutCache) {
        return this.#viewportLayoutCache;
      }
    }
    const paddingChars = 5 / 7;
    const fallbackColWidth = typeof this.#state.defaultColWidth === "number" && this.#state.defaultColWidth > 0 ? this.#state.defaultColWidth : typeof this.#state.baseColWidth === "number" && this.#state.baseColWidth > 0 ? this.#state.baseColWidth + paddingChars : DEFAULT_COL_WIDTH;
    const defaultColWidthPx = colWidthToPx(fallbackColWidth);
    const colWidthsPx = Array(maxCols).fill(defaultColWidthPx);
    for (const colDef of this.__getColumns()) {
      const min3 = Math.max(0, (colDef.min ?? 1) - 1);
      const max4 = Math.max(min3, (colDef.max ?? colDef.min ?? 1) - 1);
      const isHidden = !!colDef.hidden;
      const isNoopDefaultColumn = !isHidden && colDef.customWidth !== true && (!(typeof colDef.width === "number" && Number.isFinite(colDef.width)) || colDef.width <= 0);
      if (isNoopDefaultColumn) {
        continue;
      }
      const widthPx = isHidden ? 0 : colWidthToPx(colDef.width);
      for (let c = min3;c <= max4 && c < colWidthsPx.length; c += 1) {
        colWidthsPx[c] = widthPx;
      }
    }
    if (colWidthOverridesPx) {
      for (const [key, value] of Object.entries(colWidthOverridesPx)) {
        const idx = Number(key);
        if (Number.isFinite(idx) && idx >= 0 && idx < colWidthsPx.length && typeof value === "number" && !Number.isNaN(value)) {
          colWidthsPx[idx] = value;
        }
      }
    }
    const defaultRowHeightPt = this.#state.defaultRowHeight && this.#state.defaultRowHeight !== 0 ? this.#state.defaultRowHeight : FALLBACK_ROW_H_PT;
    const rowHeightsPx = Array(maxRows).fill(pointsToPx(defaultRowHeightPt));
    for (const row2 of this.__getRows()) {
      const idx = (row2.index ?? 1) - 1;
      if (idx < 0 || idx >= rowHeightsPx.length)
        continue;
      if (row2.hidden) {
        rowHeightsPx[idx] = 0;
        continue;
      }
      if ((row2.customHeight || row2.height !== 0) && row2.height != null) {
        rowHeightsPx[idx] = pointsToPx(row2.height);
      }
    }
    if (rowHeightOverridesPx) {
      for (const [key, value] of Object.entries(rowHeightOverridesPx)) {
        const idx = Number(key);
        if (Number.isFinite(idx) && idx >= 0 && idx < rowHeightsPx.length && typeof value === "number" && !Number.isNaN(value)) {
          rowHeightsPx[idx] = value;
        }
      }
    }
    let viewColWidthsPx = colWidthsPx;
    if (showFormulas) {
      const colsWithFormula = new Set;
      for (const row2 of this.__getRows()) {
        for (const cell of row2.cells ?? []) {
          if (cell.formula && cell.formula !== "" || typeof cell.sharedFormulaSi === "number") {
            const coord = addressToIndices2(cell.address ?? "");
            if (coord) {
              colsWithFormula.add(coord.col);
            }
          }
        }
      }
      if (colsWithFormula.size > 0) {
        viewColWidthsPx = colWidthsPx.slice();
        colsWithFormula.forEach((idx) => {
          if (colWidthOverridesPx && Object.prototype.hasOwnProperty.call(colWidthOverridesPx, idx)) {
            return;
          }
          if (idx >= 0 && idx < viewColWidthsPx.length) {
            viewColWidthsPx[idx] = viewColWidthsPx[idx] * 2;
          }
        });
      }
    }
    const colOffsetsPx = [0];
    for (let i = 0;i < viewColWidthsPx.length; i += 1) {
      colOffsetsPx[i + 1] = (colOffsetsPx[i] ?? 0) + (viewColWidthsPx[i] ?? 0);
    }
    const colOffsetsRawPx = [0];
    for (let i = 0;i < viewColWidthsPx.length; i += 1) {
      const uiWidth = viewColWidthsPx[i] ?? 0;
      const rawWidth = Math.max(0, uiWidth - 5);
      colOffsetsRawPx[i + 1] = (colOffsetsRawPx[i] ?? 0) + rawWidth;
    }
    const rowOffsetsPx = [0];
    for (let i = 0;i < rowHeightsPx.length; i += 1) {
      rowOffsetsPx[i + 1] = (rowOffsetsPx[i] ?? 0) + (rowHeightsPx[i] ?? 0);
    }
    const layout = {
      colWidthsPx,
      viewColWidthsPx,
      rowHeightsPx,
      colOffsetsPx,
      rowOffsetsPx,
      colOffsetsRawPx,
      viewTotalWidthPx: colOffsetsPx[colOffsetsPx.length - 1] ?? 0,
      totalHeightPx: rowOffsetsPx[rowOffsetsPx.length - 1] ?? 0
    };
    this.#viewportLayoutDirty = false;
    this.#viewportLayoutCacheKey = {
      maxCols,
      maxRows,
      showFormulas,
      colWidthOverridesPx,
      rowHeightOverridesPx
    };
    this.#viewportLayoutCache = layout;
    return layout;
  }
  delete() {
    const recorder = this.workbook.getRecorder();
    if (recorder) {
      const op = {
        op: "sheet.remove",
        target: this.name
      };
      recorder.record(op);
    }
    this.#context.onDelete?.(this);
  }
  toProto() {
    const rowsByIdx = new Map;
    const colIndexByCell = new WeakMap;
    for (const [idx, row2] of this.#rowIndex.entries()) {
      row2.cells = [];
      rowsByIdx.set(idx, row2);
    }
    for (const [rowIdx, colIdx, cell] of this.#cellStore.cellsWithCoordinates()) {
      let row2 = rowsByIdx.get(rowIdx);
      if (!row2) {
        row2 = this.__getOrCreateRow(rowIdx);
        row2.cells = [];
        rowsByIdx.set(rowIdx, row2);
      }
      row2.cells.push(cell);
      colIndexByCell.set(cell, colIdx);
    }
    for (const row2 of rowsByIdx.values()) {
      if (!row2.cells) {
        continue;
      }
      row2.cells.sort((a, b) => {
        const aCol = colIndexByCell.get(a) ?? addressToIndices2(a.address ?? "")?.col ?? 0;
        const bCol = colIndexByCell.get(b) ?? addressToIndices2(b.address ?? "")?.col ?? 0;
        if (aCol !== bCol) {
          return aCol - bCol;
        }
        return (a.address ?? "").localeCompare(b.address ?? "");
      });
    }
    this.#collections.rows = [...rowsByIdx.values()].sort((a, b) => (a.index ?? 0) - (b.index ?? 0));
    const proto = {
      id: this.#state.id,
      sheetId: this.#state.sheetId,
      index: this.#state.index,
      name: this.#state.name,
      innerXml: this.#state.innerXml,
      outerXml: this.#state.outerXml,
      defaultRowHeight: this.#state.defaultRowHeight,
      defaultColWidth: this.#state.defaultColWidth,
      baseColWidth: this.#state.baseColWidth,
      showGridLines: this.#state.showGridLines,
      tabColor: this.#tabColor,
      rows: this.#collections.rows,
      columns: this.#collections.columns,
      mergedCells: this.#collections.mergedCells,
      conditionalFormattings: this.#collections.conditionalFormattings,
      dataValidations: this.#collections.dataValidations.length > 0 ? { items: this.#collections.dataValidations } : undefined,
      sharedFormulas: this.#collections.sharedFormulas,
      tables: this.#collections.tables,
      pivotTables: this.#collections.pivotTables,
      slicers: this.#collections.slicers,
      timelines: this.#collections.timelines,
      drawings: this.#drawings.toProto(),
      sparklineGroups: this.#sparklineGroups.toProto()
    };
    if (!this.#defaultColWidthExplicit) {
      proto.defaultColWidth = 0;
    }
    const freezePanes = this.#freezePanes.state;
    if (freezePanes.rowCount > 0 || freezePanes.columnCount > 0) {
      proto[FREEZE_PANES_PROTO_KEY] = freezePanes;
    }
    return proto;
  }
  __notifyCellFormulaChanged(address, formulaText) {
    this.__invalidateViewportLayout();
    const coord = getAddressIndices(address);
    if (coord) {
      invalidateRows(this, [coord.row]);
    }
    this.#context.notifyCellFormulaChanged(this, address, formulaText);
  }
  __notifyCellValueChanged(address) {
    this.__invalidateViewportLayout();
    const coord = getAddressIndices(address);
    if (coord) {
      invalidateRows(this, [coord.row]);
    }
    this.#context.notifyCellValueChanged(this, address);
  }
  writeCellInputToYjs(cell) {
    const address = cell.address;
    if (!address || !this.#yCells || !this.#context.workbook.isCollaborativeStateReady()) {
      return;
    }
    const input = this.#buildCellInput(cell);
    if (!input) {
      this.#yCells.delete(address);
      return;
    }
    this.#yCells.set(address, input);
  }
  __getRows() {
    return this.#collections.rows;
  }
  __getColumns() {
    return this.#collections.columns;
  }
  __getMergedCells() {
    return this.#collections.mergedCells;
  }
  __getSharedFormulas() {
    this.__queueCollaborativePublish();
    return this.#collections.sharedFormulas;
  }
  __getDrawings() {
    return this.#collections.drawings;
  }
  __getConditionalFormattings() {
    return this.#collections.conditionalFormattings;
  }
  __getDataValidations() {
    return this.#collections.dataValidations;
  }
  __getTables() {
    return this.#collections.tables;
  }
  __getSpreadsheetRenderMetadata(themeMap) {
    const columnsRef = this.#collections.columns;
    const dataValidationsRef = this.#collections.dataValidations;
    const sharedFormulasRef = this.#collections.sharedFormulas;
    const tablesRef = this.#collections.tables;
    const key = this.#spreadsheetRenderMetadataCacheKey;
    if (key && this.#spreadsheetRenderMetadataCache && key.themeMap === themeMap && key.columnsRef === columnsRef && key.columnsLength === columnsRef.length && key.dataValidationsRef === dataValidationsRef && key.dataValidationsLength === dataValidationsRef.length && key.sharedFormulasRef === sharedFormulasRef && key.sharedFormulasLength === sharedFormulasRef.length && key.tablesRef === tablesRef && key.tablesLength === tablesRef.length) {
      return this.#spreadsheetRenderMetadataCache;
    }
    const sharedFormulaMap = new Map;
    for (const sharedFormula of sharedFormulasRef) {
      if (typeof sharedFormula.si === "number" && sharedFormula.base && sharedFormula.anchor) {
        sharedFormulaMap.set(sharedFormula.si, {
          base: sharedFormula.base,
          anchor: sharedFormula.anchor
        });
      }
    }
    const colStyleIndices = [];
    for (const colDef of columnsRef) {
      const styleIndex = typeof colDef.styleIndex === "number" ? colDef.styleIndex : undefined;
      if (styleIndex == null) {
        continue;
      }
      const min0 = Math.max(0, (colDef.min ?? 1) - 1);
      const max0 = Math.max(min0, (colDef.max ?? colDef.min ?? 1) - 1);
      for (let col = min0;col <= max0; col += 1) {
        if (colStyleIndices[col] == null) {
          colStyleIndices[col] = styleIndex;
        }
      }
    }
    const listValidationEntries = [];
    for (const item of dataValidationsRef) {
      if (!showsListValidationDropdown(item))
        continue;
      if (!item.sqref) {
        continue;
      }
      const ranges = parseSqrefRanges(item.sqref);
      if (ranges.length === 0) {
        continue;
      }
      const options = this.#resolveListValidationOptions(item.formula1);
      listValidationEntries.push({ ranges, options });
    }
    const tableResolvers = buildTableStyleResolvers(tablesRef, themeMap);
    const tableResolversByRow = new Map;
    const tableHorizontalBoundaries = new Set;
    for (const tableResolver of tableResolvers) {
      for (let boundaryRow = tableResolver.startRow + 1;boundaryRow <= tableResolver.endRow; boundaryRow += 1) {
        for (let col = tableResolver.startCol;col <= tableResolver.endCol; col += 1) {
          tableHorizontalBoundaries.add(`${boundaryRow}:${col}`);
        }
      }
      for (let row2 = tableResolver.startRow;row2 <= tableResolver.endRow; row2 += 1) {
        const existing = tableResolversByRow.get(row2);
        if (existing) {
          existing.push(tableResolver);
        } else {
          tableResolversByRow.set(row2, [tableResolver]);
        }
      }
    }
    const metadata = {
      sharedFormulaMap,
      colStyleIndices,
      listValidationEntries,
      tableResolvers,
      tableResolversByRow,
      tableHorizontalBoundaries
    };
    this.#spreadsheetRenderMetadataCache = metadata;
    this.#spreadsheetRenderMetadataCacheKey = {
      themeMap,
      columnsRef,
      columnsLength: columnsRef.length,
      dataValidationsRef,
      dataValidationsLength: dataValidationsRef.length,
      sharedFormulasRef,
      sharedFormulasLength: sharedFormulasRef.length,
      tablesRef,
      tablesLength: tablesRef.length
    };
    return metadata;
  }
  #resolveListValidationOptions(formula) {
    const raw = formula ? String(formula).trim() : "";
    if (!raw) {
      return [];
    }
    const normalized = raw.startsWith("=") ? raw.slice(1).trim() : raw;
    if (normalized.startsWith('"') && normalized.endsWith('"')) {
      const inner = normalized.slice(1, -1);
      return inner.split(",").map((value) => value.trim()).filter((value) => value.length > 0);
    }
    try {
      const values = this.getRange(normalized).values ?? [];
      const out = [];
      for (const row2 of values) {
        if (!Array.isArray(row2)) {
          continue;
        }
        for (const cellValue of row2) {
          if (cellValue == null) {
            continue;
          }
          const text2 = String(cellValue);
          if (text2.length > 0) {
            out.push(text2);
          }
        }
      }
      return out;
    } catch {
      return [];
    }
  }
  __getDataTables() {
    return this.#dataTables.__getDefinitions();
  }
  __getPivotTables() {
    return this.#collections.pivotTables;
  }
  __getSlicers() {
    return this.#collections.slicers;
  }
  #buildCollabStructureSnapshot() {
    return {
      sheetProps: {
        defaultRowHeight: this.#state.defaultRowHeight,
        defaultColWidth: this.#state.defaultColWidth,
        defaultColWidthExplicit: this.#defaultColWidthExplicit,
        baseColWidth: this.#state.baseColWidth,
        showGridLines: this.#state.showGridLines,
        tabColor: this.#tabColor
      },
      rowMeta: this.#collections.rows.map((row2) => stripRowSizingForCollab(row2)),
      colMeta: this.#collections.columns.map((column2) => stripColumnSizingForCollab(column2)),
      mergedCells: this.#collections.mergedCells.map((merge2) => ({ ...merge2 })),
      sharedFormulas: this.#collections.sharedFormulas.map((formula) => ({
        ...formula
      }))
    };
  }
  #applyCollabStructureSnapshot(snapshot) {
    this.#defaultColWidthExplicit = snapshot.sheetProps.defaultColWidthExplicit;
    this.#state.defaultRowHeight = snapshot.sheetProps.defaultRowHeight;
    this.#state.defaultColWidth = snapshot.sheetProps.defaultColWidth;
    this.#state.baseColWidth = snapshot.sheetProps.baseColWidth;
    this.#state.showGridLines = snapshot.sheetProps.showGridLines;
    this.#tabColor = snapshot.sheetProps.tabColor;
    const existingRows = new Map;
    for (const [rowIdx, row2] of this.#rowIndex.entries()) {
      existingRows.set(rowIdx, row2);
    }
    const nextRows = [];
    const nextRowIndex = new Map;
    for (const rowMeta of snapshot.rowMeta) {
      const rowIdx = Math.max(0, (rowMeta.index ?? 1) - 1);
      const existing = existingRows.get(rowIdx);
      const nextRow = {
        ...rowMeta,
        height: existing?.height ?? 0,
        customHeight: existing?.customHeight ?? false,
        hidden: existing?.hidden ?? false,
        cells: existing?.cells ?? []
      };
      nextRows.push(nextRow);
      nextRowIndex.set(rowIdx, nextRow);
    }
    this.#collections.rows = nextRows;
    this.#rowIndex = nextRowIndex;
    const existingColumns = new Map;
    for (const column2 of this.#collections.columns) {
      existingColumns.set(columnSpanKey(column2), column2);
    }
    this.#collections.columns = snapshot.colMeta.map((columnMeta) => {
      const existing = existingColumns.get(columnSpanKey(columnMeta));
      return {
        ...columnMeta,
        width: existing?.width ?? 0,
        customWidth: existing?.customWidth ?? false,
        hidden: existing?.hidden ?? false
      };
    });
    this.#collections.mergedCells = snapshot.mergedCells.map((merge2) => ({
      ...merge2
    }));
    this.#collections.sharedFormulas = snapshot.sharedFormulas.map((formula) => ({
      ...formula
    }));
    this.__invalidateViewportLayout();
  }
  __setLogicalStyleIndex(rowIdx, colIdx, styleIndex) {
    const key = this.#cellAddressKey(rowIdx, colIdx);
    this.#logicalStyleIndex.set(key, styleIndex);
  }
  __getLogicalStyleIndex(rowIdx, colIdx) {
    const key = this.#cellAddressKey(rowIdx, colIdx);
    return this.#logicalStyleIndex.get(key);
  }
  __setCellStyleRef(rowIdx, colIdx, styleId) {
    this.#styleRefStore?.setCellStyleRef(rowIdx, colIdx, styleId);
  }
  __getCellStyleRef(rowIdx, colIdx) {
    return this.#styleRefStore?.getCellStyleRef(rowIdx, colIdx);
  }
  __getOrCreateRow(rowIdx) {
    let row2 = this.#rowIndex.get(rowIdx);
    if (!row2) {
      row2 = {
        index: rowIdx + 1,
        cells: [],
        height: 0,
        customHeight: false
      };
      this.#rowIndex.set(rowIdx, row2);
      this.#collections.rows.push(row2);
      this.#collections.rows.sort((a, b) => (a.index ?? 0) - (b.index ?? 0));
    }
    if (!row2.cells) {
      row2.cells = [];
    }
    this.__queueCollaborativePublish();
    return row2;
  }
  __getOrCreateSingleColumn(colIdx) {
    const columnIndex2 = colIdx + 1;
    const columns = this.__getColumns();
    const existing = this.#findExactColumnForIndex(colIdx);
    if (existing) {
      this.__queueCollaborativePublish();
      return existing;
    }
    const created = {
      min: columnIndex2,
      max: columnIndex2,
      width: 0,
      customWidth: false
    };
    columns.push(created);
    this.__queueCollaborativePublish();
    return created;
  }
  #findExactColumnForIndex(colIdx) {
    const columnIndex2 = colIdx + 1;
    return this.__getColumns().find((column2) => column2.min === columnIndex2 && (column2.max ?? column2.min) === columnIndex2);
  }
  #findEffectiveColumnForIndex(colIdx) {
    const columnIndex2 = colIdx + 1;
    let match;
    for (const column2 of this.__getColumns()) {
      const min3 = column2.min ?? 1;
      const max4 = column2.max ?? min3;
      if (columnIndex2 >= min3 && columnIndex2 <= max4) {
        match = column2;
      }
    }
    return match;
  }
  __getRow(rowIdx) {
    return this.#rowIndex.get(rowIdx);
  }
  __syncRowSizeRef(rowIdx) {
    const rowSizes = this.#ensureRowSizeState();
    if (!rowSizes) {
      return;
    }
    const row2 = this.__getOrCreateRow(rowIdx);
    const next = {
      height: row2.height,
      customHeight: row2.customHeight,
      hidden: row2.hidden
    };
    const key = String(rowIdx);
    if (rowSizeEquals(rowSizes.get(key), next)) {
      return;
    }
    this.#context.workbook.runLocalCollabTransaction(() => {
      rowSizes.set(key, next);
    });
  }
  __syncColumnSizeRef(colIdx) {
    const colSizes = this.#ensureColumnSizeState();
    if (!colSizes) {
      return;
    }
    const column2 = this.#findEffectiveColumnForIndex(colIdx);
    const next = {
      width: column2?.width,
      customWidth: column2?.customWidth,
      hidden: column2?.hidden
    };
    const key = String(colIdx);
    if (columnSizeEquals(colSizes.get(key), next)) {
      return;
    }
    this.#context.workbook.runLocalCollabTransaction(() => {
      colSizes.set(key, next);
    });
  }
  __getOrCreateCell(rowIdx, colIdx) {
    const existing = this.#cellStore.get(rowIdx, colIdx);
    if (existing) {
      return existing;
    }
    const row2 = this.__getOrCreateRow(rowIdx);
    const cell = this.#cellStore.getOrCreate(rowIdx, colIdx, (r, c) => {
      const colLabel = columnNumberToLabel(c + 1);
      return Cell3.create(`${colLabel}${r + 1}`);
    });
    row2.cells.push(cell);
    row2.cells.sort((a, b) => {
      const aCoord = addressToIndices2(a.address);
      const bCoord = addressToIndices2(b.address);
      const aCol = aCoord?.col ?? 0;
      const bCol = bCoord?.col ?? 0;
      if (aCol !== bCol) {
        return aCol - bCol;
      }
      return a.address.localeCompare(b.address);
    });
    this.#trackExtents(rowIdx, colIdx);
    return cell;
  }
  __getCell(rowIdx, colIdx) {
    return this.#cellStore.get(rowIdx, colIdx);
  }
  #getValuesUsedBounds() {
    let minRow = Number.POSITIVE_INFINITY;
    let maxRow = -1;
    let minCol = Number.POSITIVE_INFINITY;
    let maxCol = -1;
    for (const [row2, col, cell] of this.#cellStore.cellsWithCoordinates()) {
      if (!cellCountsAsValueUsed(cell)) {
        continue;
      }
      minRow = Math.min(minRow, row2);
      maxRow = Math.max(maxRow, row2);
      minCol = Math.min(minCol, col);
      maxCol = Math.max(maxCol, col);
    }
    if (!Number.isFinite(minRow) || !Number.isFinite(minCol) || maxRow < 0) {
      return null;
    }
    return {
      startRow: minRow,
      startCol: minCol,
      endRow: maxRow,
      endCol: maxCol
    };
  }
  __setRawValue(rowIdx, colIdx, value) {
    if (value === undefined) {
      this.#cellStore.clearRawValue(rowIdx, colIdx);
      return;
    }
    this.#cellStore.setRawValue(rowIdx, colIdx, value);
  }
  __getRawValue(rowIdx, colIdx) {
    return this.#cellStore.getRawValue(rowIdx, colIdx);
  }
  __getDisplayFormula(rowIdx, colIdx) {
    const sheetName = this.name;
    if (!sheetName) {
      return "";
    }
    return this.#context.workbook.__getDisplayFormulaForCell(sheetName, rowIdx, colIdx);
  }
  __getFormulaPresence(rowIdx, colIdx) {
    const sheetName = this.name;
    if (!sheetName) {
      return;
    }
    return this.#context.workbook.__getFormulaPresenceForCell(sheetName, rowIdx, colIdx);
  }
  __clearRawValue(rowIdx, colIdx) {
    this.#cellStore.clearRawValue(rowIdx, colIdx);
  }
  __setExcelRawValue(rowIdx, colIdx, value) {
    this.#cellStore.setExcelRawValue(rowIdx, colIdx, value);
  }
  __getExcelRawValue(rowIdx, colIdx) {
    return this.#cellStore.getExcelRawValue(rowIdx, colIdx);
  }
  __hasExcelRawValue(rowIdx, colIdx) {
    return this.#cellStore.hasExcelRawValue(rowIdx, colIdx);
  }
  #getOrCreateCellInputState(sheetState) {
    return sheetState;
  }
  #getOrCreateRowSizeState(sheetState) {
    const existing = this.#getRowSizeState(sheetState);
    if (existing) {
      return existing;
    }
    const created = new YMap;
    sheetState.set("rowSizes", created);
    return created;
  }
  #getRowSizeState(sheetState) {
    const existing = sheetState.get("rowSizes");
    if (existing instanceof YMap) {
      return existing;
    }
    return;
  }
  #getOrCreateColumnSizeState(sheetState) {
    const existing = this.#getColumnSizeState(sheetState);
    if (existing) {
      return existing;
    }
    const created = new YMap;
    sheetState.set("colSizes", created);
    return created;
  }
  #getColumnSizeState(sheetState) {
    const existing = sheetState.get("colSizes");
    if (existing instanceof YMap) {
      return existing;
    }
    return;
  }
  #applyExistingSizingRefsFromState() {
    if (this.#yRowSizes) {
      for (const [key, sizing] of this.#yRowSizes.entries()) {
        this.#applyRowSizingFromYjs(key, sizing);
      }
    }
    if (this.#yColSizes) {
      for (const [key, sizing] of this.#yColSizes.entries()) {
        this.#applyColumnSizingFromYjs(key, sizing);
      }
    }
  }
  hydrateCollaborativeRefsFromProto() {
    this.#styleRefStore?.hydrateFromCells();
    for (const row2 of this.#collections.rows) {
      if (!this.#shouldSyncRowSizeRef(row2)) {
        continue;
      }
      const rowIdx = Math.max(0, (row2.index ?? 1) - 1);
      this.__syncRowSizeRef(rowIdx);
    }
    for (const column2 of this.#collections.columns) {
      if (!this.#shouldSyncColumnSizeRef(column2)) {
        continue;
      }
      const min3 = Math.max(0, (column2.min ?? 1) - 1);
      const max4 = Math.max(min3, (column2.max ?? column2.min ?? 1) - 1);
      for (let colIdx = min3;colIdx <= max4; colIdx += 1) {
        this.__syncColumnSizeRef(colIdx);
      }
    }
    this.#drawings.hydrateChartsFromFallbackState();
  }
  #hydrateCellInputsFromState() {
    if (!this.#yCells) {
      return;
    }
    for (const [address, input] of this.#yCells.entries()) {
      this.#applyCellInputFromYjs(address, input);
    }
  }
  #handleCellInputEvent(event, transaction) {
    const origins = this.#context.workbook.getCollabOrigins();
    if (transaction.origin === origins.record || transaction.origin === origins.local) {
      return;
    }
    let shouldInvalidateViewportLayout = false;
    for (const address of event.keysChanged) {
      if (address === "rowSizes") {
        const rowSizes = this.#getRowSizeState(this.#ySheetState);
        if (rowSizes !== this.#yRowSizes) {
          this.#setRowSizeState(rowSizes);
        }
        if (rowSizes) {
          for (const [key, sizing] of rowSizes.entries()) {
            shouldInvalidateViewportLayout = this.#applyRowSizingFromYjs(key, sizing) || shouldInvalidateViewportLayout;
          }
        }
        continue;
      }
      if (address === "colSizes") {
        const colSizes = this.#getColumnSizeState(this.#ySheetState);
        if (colSizes !== this.#yColSizes) {
          this.#setColumnSizeState(colSizes);
        }
        if (colSizes) {
          for (const [key, sizing] of colSizes.entries()) {
            shouldInvalidateViewportLayout = this.#applyColumnSizingFromYjs(key, sizing) || shouldInvalidateViewportLayout;
          }
        }
        continue;
      }
      const input = this.#yCells?.get(address);
      this.#applyCellInputFromYjs(address, input);
    }
    if (shouldInvalidateViewportLayout) {
      this.__invalidateViewportLayout();
    }
  }
  #handleRowSizeEvent(event, transaction) {
    const origins = this.#context.workbook.getCollabOrigins();
    if (transaction.origin === origins.record || transaction.origin === origins.local) {
      return;
    }
    let changed = false;
    for (const key of event.keysChanged) {
      changed = this.#applyRowSizingFromYjs(key, this.#yRowSizes?.get(key)) || changed;
    }
    if (changed) {
      this.__invalidateViewportLayout();
    }
  }
  #handleColumnSizeEvent(event, transaction) {
    const origins = this.#context.workbook.getCollabOrigins();
    if (transaction.origin === origins.record || transaction.origin === origins.local) {
      return;
    }
    let changed = false;
    for (const key of event.keysChanged) {
      changed = this.#applyColumnSizingFromYjs(key, this.#yColSizes?.get(key)) || changed;
    }
    if (changed) {
      this.__invalidateViewportLayout();
    }
  }
  #setRowSizeState(next) {
    if (next === this.#yRowSizes) {
      return;
    }
    if (this.#yRowSizes && this.#rowSizeObserver) {
      this.#yRowSizes.unobserve(this.#rowSizeObserver);
    }
    this.#yRowSizes = next;
    if (this.#yRowSizes && this.#rowSizeObserver) {
      this.#yRowSizes.observe(this.#rowSizeObserver);
    }
  }
  #setColumnSizeState(next) {
    if (next === this.#yColSizes) {
      return;
    }
    if (this.#yColSizes && this.#colSizeObserver) {
      this.#yColSizes.unobserve(this.#colSizeObserver);
    }
    this.#yColSizes = next;
    if (this.#yColSizes && this.#colSizeObserver) {
      this.#yColSizes.observe(this.#colSizeObserver);
    }
  }
  #ensureRowSizeState() {
    if (this.#yRowSizes) {
      return this.#yRowSizes;
    }
    if (!this.#ySheetState) {
      return;
    }
    const rowSizes = this.#getOrCreateRowSizeState(this.#ySheetState);
    this.#setRowSizeState(rowSizes);
    return rowSizes;
  }
  #ensureColumnSizeState() {
    if (this.#yColSizes) {
      return this.#yColSizes;
    }
    if (!this.#ySheetState) {
      return;
    }
    const colSizes = this.#getOrCreateColumnSizeState(this.#ySheetState);
    this.#setColumnSizeState(colSizes);
    return colSizes;
  }
  #shouldSyncRowSizeRef(row2) {
    return row2.customHeight === true || row2.hidden === true || typeof row2.height === "number" && Number.isFinite(row2.height) && row2.height !== this.#state.defaultRowHeight;
  }
  #shouldSyncColumnSizeRef(column2) {
    return column2.customWidth === true || column2.hidden === true || typeof column2.width === "number" && Number.isFinite(column2.width) && column2.width !== this.#state.defaultColWidth;
  }
  #applyRowSizingFromYjs(key, sizing) {
    const rowIdx = parseSizingIndex(key);
    if (rowIdx == null || !sizing) {
      return false;
    }
    const row2 = this.__getOrCreateRow(rowIdx);
    let changed = false;
    if (typeof sizing.height === "number" && Number.isFinite(sizing.height) && row2.height !== sizing.height) {
      row2.height = sizing.height;
      changed = true;
    }
    if (typeof sizing.customHeight === "boolean" && row2.customHeight !== sizing.customHeight) {
      row2.customHeight = sizing.customHeight;
      changed = true;
    }
    if (typeof sizing.hidden === "boolean" && row2.hidden !== sizing.hidden) {
      row2.hidden = sizing.hidden;
      changed = true;
    }
    return changed;
  }
  #applyColumnSizingFromYjs(key, sizing) {
    const colIdx = parseSizingIndex(key);
    if (colIdx == null || !sizing) {
      return false;
    }
    const exactColumn = this.#findExactColumnForIndex(colIdx);
    const effectiveColumn = exactColumn ?? this.#findEffectiveColumnForIndex(colIdx);
    if (!exactColumn && effectiveColumn && columnSizeEquals({
      width: effectiveColumn.width,
      customWidth: effectiveColumn.customWidth,
      hidden: effectiveColumn.hidden
    }, sizing)) {
      return false;
    }
    const column2 = exactColumn ?? this.__getOrCreateSingleColumn(colIdx);
    let changed = false;
    if (typeof sizing.width === "number" && Number.isFinite(sizing.width) && column2.width !== sizing.width) {
      column2.width = sizing.width;
      changed = true;
    }
    if (typeof sizing.customWidth === "boolean" && column2.customWidth !== sizing.customWidth) {
      column2.customWidth = sizing.customWidth;
      changed = true;
    }
    if (typeof sizing.hidden === "boolean" && column2.hidden !== sizing.hidden) {
      column2.hidden = sizing.hidden;
      changed = true;
    }
    return changed;
  }
  #applyCellInputFromYjs(address, input) {
    const coord = addressToIndices2(address);
    if (!coord) {
      return;
    }
    const cell = this.__getOrCreateCell(coord.row, coord.col);
    const hadFormula = Boolean(cell.formula?.trim());
    if (input?.f) {
      cell.formula = input.f;
      cell.value = undefined;
      cell.dataType = 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
      this.__setRawValue(coord.row, coord.col, undefined);
      this.__notifyCellFormulaChanged(address, input.f);
      return;
    }
    if (input && input.v !== undefined) {
      cell.formula = undefined;
      cell.value = input.v;
      cell.dataType = input.dt ?? 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
      const rawValue = coerceCellValue(cell);
      this.__setRawValue(coord.row, coord.col, rawValue);
      this.#applyCheckboxStyleFromValue(rawValue, cell, coord.row, coord.col);
      this.__notifyCellValueChanged(address);
      return;
    }
    cell.formula = undefined;
    cell.value = undefined;
    cell.dataType = 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
    this.__setRawValue(coord.row, coord.col, null);
    this.#applyCheckboxStyleFromValue(null, cell, coord.row, coord.col);
    if (hadFormula) {
      this.__notifyCellFormulaChanged(address, "");
    } else {
      this.__notifyCellValueChanged(address);
    }
  }
  #buildCellInput(cell) {
    const formula = cell.formula?.trim();
    if (formula) {
      return { f: formula };
    }
    if (cell.value === undefined || cell.value === null) {
      return null;
    }
    return {
      v: String(cell.value),
      dt: cell.dataType ?? 0 /* CELL_DATA_TYPE_UNSPECIFIED */
    };
  }
  #applyCheckboxStyleFromValue(value, cell, rowIdx, colIdx) {
    const workbook = this.#context.workbook;
    const currentStyleIndex = this.__getLogicalStyleIndex(rowIdx, colIdx) ?? cell.styleIndex ?? 0;
    if (typeof value === "boolean") {
      const nextStyleIndex2 = workbook.__resolveCheckboxStyleIndex(currentStyleIndex);
      if (nextStyleIndex2 !== currentStyleIndex) {
        cell.styleIndex = nextStyleIndex2;
        this.__setLogicalStyleIndex(rowIdx, colIdx, nextStyleIndex2);
        this.#styleRefStore?.syncCellStyleRefFromStyleIndex(rowIdx, colIdx, nextStyleIndex2);
      }
      return;
    }
    const nextStyleIndex = workbook.__removeCheckboxStyleIndex(currentStyleIndex);
    if (nextStyleIndex !== currentStyleIndex) {
      cell.styleIndex = nextStyleIndex;
      this.__setLogicalStyleIndex(rowIdx, colIdx, nextStyleIndex);
      this.#styleRefStore?.syncCellStyleRefFromStyleIndex(rowIdx, colIdx, nextStyleIndex);
    }
  }
  #trackExtents(rowIdx, colIdx) {
    const columnExtent = this.#columnExtents.get(colIdx);
    if (columnExtent) {
      columnExtent.min = Math.min(columnExtent.min, rowIdx);
      columnExtent.max = Math.max(columnExtent.max, rowIdx);
    } else {
      this.#columnExtents.set(colIdx, { min: rowIdx, max: rowIdx });
    }
    const rowExtent = this.#rowExtents.get(rowIdx);
    if (rowExtent) {
      rowExtent.min = Math.min(rowExtent.min, colIdx);
      rowExtent.max = Math.max(rowExtent.max, colIdx);
    } else {
      this.#rowExtents.set(rowIdx, { min: colIdx, max: colIdx });
    }
  }
  #cellAddressKey(rowIdx, colIdx) {
    const colLabel = columnNumberToLabel(colIdx + 1);
    return `${colLabel}${rowIdx + 1}`;
  }
  __getColumnExtent(colIdx) {
    const extent2 = this.#columnExtents.get(colIdx);
    if (!extent2) {
      return null;
    }
    return { minRow: extent2.min, maxRow: extent2.max };
  }
  __getRowExtent(rowIdx) {
    const extent2 = this.#rowExtents.get(rowIdx);
    if (!extent2) {
      return null;
    }
    return { minCol: extent2.min, maxCol: extent2.max };
  }
  __createCellIterator() {
    function* iterator(worksheet) {
      for (const [row2, col, cell] of worksheet.#cellStore.cellsWithCoordinates()) {
        yield new WorksheetCellView(worksheet, cell, row2, col);
      }
    }
    return iterator(this);
  }
  __removePivotTable(proto) {
    this.#collections.pivotTables = this.#collections.pivotTables.filter((candidate) => candidate !== proto);
  }
  __removeSlicer(proto) {
    this.#collections.slicers = this.#collections.slicers.filter((candidate) => candidate !== proto);
  }
  __getOrCreateChartsState() {
    if (!this.#ySheetState || !this.#context.workbook.isCollaborativeStateReady()) {
      return;
    }
    const existing = this.#ySheetState.get("charts");
    if (existing instanceof YMap) {
      this.#yCharts = existing;
      return this.#yCharts;
    }
    const created = new YMap;
    this.#ySheetState.set("charts", created);
    this.#yCharts = created;
    return created;
  }
  __getChartsState() {
    if (!this.#ySheetState) {
      return;
    }
    const existing = this.#ySheetState.get("charts");
    if (existing instanceof YMap) {
      this.#yCharts = existing;
      return this.#yCharts;
    }
    return;
  }
}
var buildNullWorksheetProto = (name) => ({
  name,
  index: 0
});

class NullWorksheet extends Worksheet {
  #missingName;
  constructor(name, context) {
    super(buildNullWorksheetProto(name), context);
    this.#missingName = name;
  }
  get isNullObject() {
    return true;
  }
  getRange(_address, ..._rest) {
    return this.#throwMissing();
  }
  getRangeByIndexes(_startRow, _startColumn, _rowCount, _columnCount) {
    return this.#throwMissing();
  }
  getCell(_row, _column) {
    return this.#throwMissing();
  }
  delete() {
    this.#throwMissing();
  }
  #throwMissing() {
    const label = this.#missingName || "Unknown";
    throw new Error(`Worksheet "${label}" not found.`);
  }
}
function addressToIndices2(address) {
  return getAddressIndices(address);
}
function parseSizingIndex(value) {
  const parsed = Number(value);
  if (!Number.isInteger(parsed) || parsed < 0) {
    return;
  }
  return parsed;
}
function rowSizeEquals(left, right) {
  return left?.height === right?.height && left?.customHeight === right?.customHeight && left?.hidden === right?.hidden;
}
function columnSizeEquals(left, right) {
  return left?.width === right?.width && left?.customWidth === right?.customWidth && left?.hidden === right?.hidden;
}
function stripRowSizingForCollab(row2) {
  const { cells: _cells, height: _height, customHeight: _customHeight, hidden: _hidden, ...rest } = row2;
  return { ...rest };
}
function stripColumnSizingForCollab(column2) {
  const { width: _width, customWidth: _customWidth, hidden: _hidden, ...rest } = column2;
  return { ...rest };
}
function columnSpanKey(column2) {
  return `${column2.min ?? 0}:${column2.max ?? column2.min ?? 0}`;
}
function cellCountsAsValueUsed(cell) {
  const formula = cell.formula ?? "";
  if (typeof formula === "string" && formula.trim()) {
    return true;
  }
  const value = cell.value ?? "";
  if (typeof value === "string" && value !== "") {
    return true;
  }
  return false;
}

class WorksheetCells {
  #worksheet;
  constructor(worksheet) {
    this.#worksheet = worksheet;
  }
  [Symbol.iterator]() {
    return this.#worksheet.__createCellIterator();
  }
}

class WorksheetCellView {
  #worksheet;
  #cell;
  #rowIdx;
  #colIdx;
  constructor(worksheet, cell, rowIdx, colIdx) {
    this.#worksheet = worksheet;
    this.#cell = cell;
    this.#rowIdx = rowIdx;
    this.#colIdx = colIdx;
  }
  get address() {
    return this.#cell.address;
  }
  get formula() {
    const text2 = this.#cell.formula ?? "";
    if (!text2) {
      return "";
    }
    return text2.startsWith("=") ? text2 : `=${text2}`;
  }
  get value() {
    return this.#formatDisplayValue().value;
  }
  get dataType() {
    return this.#formatDisplayValue().dataType;
  }
  get rawValue() {
    const raw = this.#worksheet.__getRawValue(this.#rowIdx, this.#colIdx);
    if (raw !== undefined && raw !== null) {
      return raw;
    }
    if (raw === null) {
      return null;
    }
    if (this.#worksheet.__hasExcelRawValue(this.#rowIdx, this.#colIdx)) {
      return this.#worksheet.__getExcelRawValue(this.#rowIdx, this.#colIdx) ?? null;
    }
    return coerceCellValue(this.#cell);
  }
  #formatDisplayValue() {
    return this.#worksheet.workbook.__formatRawValueForDisplay(this.rawValue);
  }
}
function coerceCellValue(cell) {
  if (!cell) {
    return null;
  }
  if (cell.value == null) {
    return null;
  }
  switch (cell.dataType) {
    case 5 /* CELL_DATA_TYPE_NUMBER */:
      return Number(cell.value);
    case 4 /* CELL_DATA_TYPE_BOOLEAN */:
      return cell.value === "TRUE" || cell.value === "1";
    case 7 /* CELL_DATA_TYPE_DATE */:
      if (typeof cell.value === "string") {
        const serial = Number(cell.value);
        if (Number.isFinite(serial)) {
          const excelEpoch = Date.UTC(1899, 11, 30);
          const msPerDay = 24 * 60 * 60 * 1000;
          return new Date(excelEpoch + serial * msPerDay);
        }
        return new Date(cell.value);
      }
      if (typeof cell.value === "number" && Number.isFinite(cell.value)) {
        const excelEpoch = Date.UTC(1899, 11, 30);
        const msPerDay = 24 * 60 * 60 * 1000;
        return new Date(excelEpoch + cell.value * msPerDay);
      }
      return new Date(String(cell.value));
    case 6 /* CELL_DATA_TYPE_ERROR */:
      return {
        kind: "Error",
        code: cell.value
      };
    default:
      return cell.value;
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/worksheet-collection.js
class WorksheetCollection {
  #context;
  #items;
  #byName;
  #bySheetId;
  #activeName;
  #nextSheetNumber;
  #nextSheetId;
  constructor(protoSheets, context) {
    this.#context = context;
    this.#items = [];
    this.#byName = new Map;
    this.#bySheetId = new Map;
    this.#nextSheetNumber = 1;
    this.#nextSheetId = 1;
    protoSheets.forEach((sheet) => {
      const worksheetName = this.#resolveWorksheetName(sheet.name);
      this.#createWorksheet({ ...sheet, name: worksheetName });
    });
    const first = this.#items[0];
    this.#activeName = first?.name;
  }
  getSheetCount() {
    return this.#items.length;
  }
  getSheetIndex(name) {
    const worksheet = this.#byName.get(name);
    if (!worksheet) {
      return null;
    }
    return worksheet.index;
  }
  getSheetNameByIndex(index) {
    if (index < 0 || index >= this.#items.length) {
      return null;
    }
    return this.#items[index]?.name ?? null;
  }
  getItemAt(index) {
    const worksheet = this.#items[index];
    if (!worksheet) {
      throw new Error(`Worksheet at index ${index} not found`);
    }
    return worksheet;
  }
  getFirst() {
    return this.getItemAt(0);
  }
  getOrAdd(name, options) {
    const trimmed = name?.trim();
    if (!trimmed) {
      throw new Error("worksheets.getOrAdd(name) requires a non-empty name.");
    }
    const existing = this.#byName.get(trimmed);
    if (existing) {
      return existing;
    }
    if (options?.renameFirstIfOnlyNewSpreadsheet) {
      const only = this.#items.length === 1 ? this.#items[0] : undefined;
      if (only && only.name === "New spreadsheet") {
        only.name = trimmed;
        return only;
      }
    }
    return this.add(trimmed);
  }
  add(name) {
    const trimmedName = name?.trim();
    if (trimmedName) {
      const existing = this.#byName.get(trimmedName);
      if (existing) {
        logger.warn("validation", `Worksheet "${trimmedName}" already exists. Returning existing worksheet.`);
        return existing;
      }
    }
    const sheetCount = this.#items.length;
    const finalName = this.#resolveWorksheetName(trimmedName);
    const sheetId = String(this.#nextSheetId);
    this.#nextSheetId += 1;
    const worksheet = this.#createWorksheet({
      name: finalName,
      sheetId,
      index: sheetCount
    });
    this.#activeName = worksheet.name;
    const recorder = this.#context.workbook.getRecorder();
    if (recorder) {
      const alias = recorder.assignAlias(worksheet, worksheet.name, "sheet");
      const op = {
        op: "sheet.add",
        name: worksheet.name,
        as: alias
      };
      recorder.record(op);
    }
    this.#notifyCollectionChanged("add");
    return worksheet;
  }
  getItem(name) {
    const worksheet = this.#byName.get(name);
    if (!worksheet) {
      const existing = this.#items.map((sheet) => sheet.name).filter(Boolean);
      const suffix = existing.length > 0 ? ` (available: ${existing.join(", ")})` : "";
      throw new Error(`Worksheet ${name} not found${suffix}`);
    }
    return worksheet;
  }
  getItemOrNullObject(name) {
    return this.#byName.get(name) ?? new NullWorksheet(name, this.#context);
  }
  getItemBySheetId(sheetId) {
    return this.#bySheetId.get(sheetId);
  }
  getTopologyEntries() {
    const entries = [];
    for (const worksheet of this.#items) {
      const sheetId = worksheet.sheetId?.trim();
      if (!sheetId) {
        continue;
      }
      entries.push({
        sheetId,
        name: worksheet.name,
        index: entries.length
      });
    }
    return entries;
  }
  syncTopology(entries) {
    const normalizedEntries = normalizeTopologyEntries(entries);
    if (normalizedEntries.length === 0) {
      return;
    }
    const targetSheetIds = new Set(normalizedEntries.map((entry) => entry.sheetId));
    for (const entry of normalizedEntries) {
      let worksheet = this.#bySheetId.get(entry.sheetId);
      if (!worksheet) {
        const targetName = this.#resolveWorksheetName(entry.name);
        worksheet = this.#createWorksheet({
          name: targetName,
          sheetId: entry.sheetId,
          index: entry.index
        });
      }
      if (worksheet.name !== entry.name) {
        worksheet.writeName(entry.name, { record: false });
      }
    }
    const deleted = this.#items.filter((worksheet) => {
      const sheetId = worksheet.sheetId?.trim();
      return !sheetId || !targetSheetIds.has(sheetId);
    });
    for (const worksheet of deleted) {
      this.#deleteWorksheet(worksheet, { notify: false });
    }
    const orderedItems = [];
    for (const entry of normalizedEntries) {
      const worksheet = this.#bySheetId.get(entry.sheetId);
      if (worksheet) {
        orderedItems.push(worksheet);
      }
    }
    if (orderedItems.length === 0) {
      return;
    }
    this.#items = orderedItems;
    this.#reindex();
    if (!this.#activeName || !this.#byName.has(this.#activeName)) {
      this.#activeName = this.#items[0]?.name;
    }
    this.#notifyCollectionChanged("topology-sync");
  }
  get items() {
    return [...this.#items];
  }
  getActiveWorksheet() {
    if (this.#activeName) {
      const active = this.#byName.get(this.#activeName);
      if (active) {
        return active;
      }
    }
    const first = this.#items[0];
    if (!first) {
      throw new Error("No worksheets available");
    }
    this.#activeName = first.name;
    return first;
  }
  getActive() {
    return this.getActiveWorksheet();
  }
  setActiveWorksheet(name) {
    if (!this.#byName.has(name)) {
      throw new Error(`Worksheet ${name} not found`);
    }
    this.#activeName = name;
  }
  toProto() {
    return this.#items.slice().sort((a, b) => a.index - b.index).map((worksheet) => worksheet.toProto());
  }
  [Symbol.iterator]() {
    return this.#items[Symbol.iterator]();
  }
  #createWorksheet(proto) {
    const worksheet = new Worksheet(proto, {
      workbook: this.#context.workbook,
      pivotTables: this.#context.pivotTables,
      slicers: this.#context.slicers,
      getOrCreateWorksheetState: this.#context.getOrCreateWorksheetState,
      getOrCreateWorksheetStyleRefsState: this.#context.getOrCreateWorksheetStyleRefsState,
      notifyCellFormulaChanged: this.#context.notifyCellFormulaChanged,
      notifyCellValueChanged: this.#context.notifyCellValueChanged,
      onDelete: (target) => this.#deleteWorksheet(target),
      onNameChange: (target, previous, next) => this.#handleNameChange(target, previous, next),
      onIndexChange: (target, previous, next) => this.#moveWorksheet(target, previous, next)
    });
    this.#items.push(worksheet);
    this.#byName.set(worksheet.name, worksheet);
    const sheetId = worksheet.sheetId?.trim();
    if (sheetId) {
      this.#bySheetId.set(sheetId, worksheet);
      const numericSheetId = Number(sheetId);
      if (Number.isFinite(numericSheetId) && numericSheetId >= this.#nextSheetId) {
        this.#nextSheetId = numericSheetId + 1;
      }
    }
    return worksheet;
  }
  #notifyCollectionChanged(reason) {
    this.#context.onWorksheetCollectionChanged?.(reason);
  }
  #generateSheetName() {
    let candidate;
    do {
      candidate = `Sheet ${this.#nextSheetNumber++}`;
    } while (this.#byName.has(candidate));
    return candidate;
  }
  #resolveWorksheetName(name) {
    if (name && name.trim()) {
      return this.#dedupeProvidedName(name.trim());
    }
    const generated = this.#generateSheetName();
    logger.warn("validation", `Worksheet missing a name. Assigned "${generated}".`);
    return generated;
  }
  #dedupeProvidedName(name) {
    if (!this.#byName.has(name)) {
      return name;
    }
    let suffix = 2;
    let candidate = `${name} (${suffix})`;
    while (this.#byName.has(candidate)) {
      suffix += 1;
      candidate = `${name} (${suffix})`;
    }
    logger.warn("validation", `Worksheet "${name}" already exists. Assigned "${candidate}".`);
    return candidate;
  }
  #deleteWorksheet(target, options) {
    const targetName = target.name;
    const targetSheetId = target.sheetId?.trim();
    const awareness = this.#context.workbook.awareness;
    const deletedActive = awareness.activeSheetName === targetName;
    this.#items = this.#items.filter((item) => item !== target);
    if (targetName) {
      this.#byName.delete(targetName);
    }
    if (targetSheetId) {
      this.#bySheetId.delete(targetSheetId);
    }
    this.#reindex();
    if (targetName) {
      awareness.forgetSheet(targetName);
    }
    if (this.#activeName === targetName) {
      this.#activeName = this.#items[0]?.name;
    }
    if (deletedActive) {
      awareness.setActiveSheetName(this.#items[0]?.name ?? null);
    }
    if (options?.notify !== false) {
      this.#notifyCollectionChanged("delete");
    }
  }
  #handleNameChange(target, previous, next) {
    if (previous) {
      const mapped = this.#byName.get(previous);
      if (mapped === target) {
        this.#byName.delete(previous);
        const remaining = this.#items.find((worksheet) => worksheet !== target && worksheet.name === previous);
        if (remaining) {
          this.#byName.set(previous, remaining);
        }
      }
    }
    if (next) {
      this.#byName.set(next, target);
    }
    if (this.#activeName === previous) {
      this.#activeName = next;
    }
    if (previous) {
      this.#context.workbook.awareness.renameSheet(previous, next);
    }
    if (previous !== next) {
      this.#notifyCollectionChanged("rename");
    }
  }
  #reindex() {
    this.#items.forEach((worksheet, idx) => {
      worksheet.writeIndex(idx, {
        notifyCollection: false,
        record: false
      });
    });
  }
  #moveWorksheet(target, _previous, next) {
    const currentIndex = this.#items.indexOf(target);
    if (currentIndex < 0) {
      return;
    }
    const clamped = Math.max(0, Math.min(next, this.#items.length - 1));
    if (currentIndex === clamped) {
      target.writeIndex(clamped, {
        notifyCollection: false,
        record: false
      });
      return;
    }
    this.#items.splice(currentIndex, 1);
    this.#items.splice(clamped, 0, target);
    this.#reindex();
    this.#notifyCollectionChanged("move");
  }
}
function normalizeTopologyEntries(entries) {
  const normalizedEntries = [...entries].map((entry, index) => {
    const sheetId = entry.sheetId?.trim();
    const name = entry.name?.trim();
    const rawIndex = Number.isFinite(entry.index) ? entry.index : index;
    if (!sheetId || !name) {
      return null;
    }
    return { sheetId, name, index: rawIndex };
  }).filter((entry) => entry != null).sort((left, right) => left.index - right.index);
  const seen = new Set;
  const deduped = [];
  for (const entry of normalizedEntries) {
    if (seen.has(entry.sheetId)) {
      continue;
    }
    seen.add(entry.sheetId);
    deduped.push({
      sheetId: entry.sheetId,
      name: entry.name,
      index: deduped.length
    });
  }
  return deduped;
}
// node_modules/@oai/granola/dist/models/theme.js
class Theme3 {
  colorScheme;
  backgroundFillStyleList;
  lineStyleList;
  effectStyleList;
  constructor(theme) {
    const defaults = DEFAULT_XLSX_THEME;
    const schemeSource = theme?.colorScheme?.colors && theme.colorScheme.colors.length > 0 ? theme.colorScheme : defaults.colorScheme;
    this.colorScheme = cloneColorScheme(schemeSource);
    this.backgroundFillStyleList = cloneArray(theme?.backgroundFillStyleList && theme.backgroundFillStyleList.length > 0 ? theme.backgroundFillStyleList : defaults.backgroundFillStyleList);
    this.lineStyleList = cloneArray(theme?.lineStyleList && theme.lineStyleList.length > 0 ? theme.lineStyleList : defaults.lineStyleList);
    this.effectStyleList = cloneArray(theme?.effectStyleList && theme.effectStyleList.length > 0 ? theme.effectStyleList : defaults.effectStyleList);
  }
  replace(theme) {
    const next = new Theme3(theme);
    this.colorScheme = next.colorScheme;
    this.backgroundFillStyleList = next.backgroundFillStyleList;
    this.lineStyleList = next.lineStyleList;
    this.effectStyleList = next.effectStyleList;
  }
  toProto() {
    return {
      colorScheme: this.colorScheme,
      backgroundFillStyleList: this.backgroundFillStyleList,
      lineStyleList: this.lineStyleList,
      effectStyleList: this.effectStyleList
    };
  }
  setColorScheme(partial2) {
    if (!partial2)
      return;
    if (partial2.name)
      this.colorScheme.name = partial2.name;
    if (partial2.colors && partial2.colors.length > 0) {
      const overrides = new Map;
      for (const entry of partial2.colors) {
        if (!entry?.name)
          continue;
        overrides.set(entry.name, cloneThemeColor(entry));
      }
      const result = [];
      const consumed = new Set;
      for (const existing of this.colorScheme.colors ?? []) {
        if (!existing?.name)
          continue;
        const override = overrides.get(existing.name);
        if (override) {
          result.push(override);
          consumed.add(existing.name);
        } else {
          result.push(existing);
        }
      }
      for (const [name, entry] of overrides) {
        if (consumed.has(name))
          continue;
        result.push(entry);
      }
      this.colorScheme.colors = result;
    }
  }
}
function cloneColorScheme(scheme) {
  return {
    name: scheme?.name ?? "Custom",
    colors: (scheme?.colors ?? []).map(cloneThemeColor)
  };
}
function cloneThemeColor(color2) {
  return {
    name: color2.name,
    color: color2.color ? {
      ...color2.color,
      transform: color2.color.transform ? { ...color2.color.transform } : undefined
    } : undefined
  };
}
function cloneArray(items) {
  if (!items)
    return [];
  return items.map((item) => {
    if (item && typeof item === "object") {
      return { ...item };
    }
    return item;
  });
}

// node_modules/@oai/granola/dist/models/spreadsheet/engine/calculation-chain.js
function buildCalculationChain(graph, formulaCells) {
  const inDegree = new Map;
  const order = [];
  const queue = [];
  for (const cell of formulaCells) {
    let degree = 0;
    const precedents = graph.precedents.get(cell);
    if (precedents) {
      for (const precedent of precedents) {
        if (formulaCells.has(precedent)) {
          degree += 1;
        }
      }
    }
    inDegree.set(cell, degree);
    if (degree === 0) {
      queue.push(cell);
    }
  }
  let queueIndex = 0;
  while (queueIndex < queue.length) {
    const cell = queue[queueIndex];
    queueIndex += 1;
    order.push(cell);
    const dependents = graph.dependents.get(cell);
    if (!dependents) {
      continue;
    }
    for (const dependent of dependents) {
      if (!formulaCells.has(dependent)) {
        continue;
      }
      const currentDegree = inDegree.get(dependent);
      if (currentDegree === undefined) {
        continue;
      }
      const nextDegree = currentDegree - 1;
      inDegree.set(dependent, nextDegree);
      if (nextDegree === 0) {
        queue.push(dependent);
      }
    }
  }
  const unresolved = new Set;
  for (const [cell, degree] of inDegree.entries()) {
    if (degree && degree > 0) {
      unresolved.add(cell);
    }
  }
  const circular = unresolved.size > 0 ? computeCycles(graph, formulaCells, unresolved) : [];
  return { order, circular };
}
function computeCycles(graph, formulaCells, unresolved) {
  const adjacency = new Map;
  for (const cell of formulaCells) {
    const dependents = graph.dependents.get(cell);
    if (!dependents) {
      continue;
    }
    for (const dependent of dependents) {
      if (!formulaCells.has(dependent)) {
        continue;
      }
      let list = adjacency.get(cell);
      if (!list) {
        list = [];
        adjacency.set(cell, list);
      }
      list.push(dependent);
    }
  }
  const result = [];
  const indexMap = new Map;
  const lowLink = new Map;
  const stack = [];
  const onStack = new Set;
  let index = 0;
  const stronglyConnect = (node) => {
    indexMap.set(node, index);
    lowLink.set(node, index);
    index += 1;
    stack.push(node);
    onStack.add(node);
    for (const neighbor of adjacency.get(node) ?? []) {
      if (!unresolved.has(neighbor)) {
        continue;
      }
      if (!indexMap.has(neighbor)) {
        stronglyConnect(neighbor);
        const neighborLow = lowLink.get(neighbor);
        const nodeLow = lowLink.get(node);
        if (neighborLow !== undefined && nodeLow !== undefined) {
          lowLink.set(node, Math.min(nodeLow, neighborLow));
        }
      } else if (onStack.has(neighbor)) {
        const neighborIndex = indexMap.get(neighbor);
        const nodeLow = lowLink.get(node);
        if (neighborIndex !== undefined && nodeLow !== undefined) {
          lowLink.set(node, Math.min(nodeLow, neighborIndex));
        }
      }
    }
    if (lowLink.get(node) === indexMap.get(node)) {
      const component = [];
      while (stack.length > 0) {
        const candidate = stack.pop();
        onStack.delete(candidate);
        component.push(candidate);
        if (candidate === node) {
          break;
        }
      }
      if (component.length > 1) {
        result.push(component);
      } else {
        const only = component[0];
        const neighbors = adjacency.get(only) ?? [];
        if (neighbors.includes(only)) {
          result.push(component);
        }
      }
    }
  };
  for (const node of unresolved) {
    if (!indexMap.has(node)) {
      stronglyConnect(node);
    }
  }
  return result;
}

// node_modules/@oai/granola/dist/models/spreadsheet/engine/dependency-graph.js
function collectRangeRefs(expr) {
  const refs = [];
  const visit2 = (node) => {
    if (!node) {
      return;
    }
    switch (node.kind) {
      case "RangeRef":
        refs.push(node.ref);
        break;
      case "UnaryOp":
        visit2(node.expr);
        break;
      case "BinaryOp":
        visit2(node.left);
        visit2(node.right);
        break;
      case "FunctionCall":
        for (const arg of node.args) {
          visit2(arg);
        }
        break;
      case "ArrayLiteral":
        for (const row2 of node.elements) {
          for (const item of row2) {
            visit2(item);
          }
        }
        break;
      default:
        break;
    }
  };
  visit2(expr);
  return refs;
}
function updateDependenciesForFormula(graph, formulaCellKey, expr, ctx, activeCellAddress) {
  const fallbackSheet = sheetNameFromCellKey(formulaCellKey);
  const oldPrecedents = graph.precedents.get(formulaCellKey);
  if (oldPrecedents) {
    for (const key of oldPrecedents) {
      const dependents = graph.dependents.get(key);
      if (dependents) {
        dependents.delete(formulaCellKey);
        if (dependents.size === 0) {
          graph.dependents.delete(key);
        }
      }
    }
    graph.precedents.delete(formulaCellKey);
  }
  const precedentKeys = new Set;
  for (const rangeRef of collectRangeRefs(expr)) {
    if (rangeRef.kind === "WholeColumn" && ctx.columnDependencyKey) {
      const sheetName = rangeRef.sheet?.sheetName ?? fallbackSheet;
      if (sheetName) {
        precedentKeys.add(ctx.columnDependencyKey(sheetName, rangeRef.col));
      }
    } else if (rangeRef.kind === "WholeRow" && ctx.rowDependencyKey) {
      const sheetName = rangeRef.sheet?.sheetName ?? fallbackSheet;
      if (sheetName) {
        precedentKeys.add(ctx.rowDependencyKey(sheetName, rangeRef.row));
      }
    }
    const cells = ctx.expandRange(rangeRef, activeCellAddress);
    for (const addr of cells) {
      const key = ctx.cellAddressToKey(addr);
      if (key) {
        precedentKeys.add(key);
      }
    }
  }
  graph.precedents.set(formulaCellKey, precedentKeys);
  for (const key of precedentKeys) {
    let dependents = graph.dependents.get(key);
    if (!dependents) {
      dependents = new Set;
      graph.dependents.set(key, dependents);
    }
    dependents.add(formulaCellKey);
  }
}
function sheetNameFromCellKey(cellKey) {
  const bang = cellKey.indexOf("!");
  if (bang === -1) {
    return "";
  }
  return cellKey.slice(0, bang);
}

// node_modules/@oai/granola/dist/models/spreadsheet/engine/function-registry.js
var SSF6 = __toESM(require_ssf(), 1);

// node_modules/@formulajs/formulajs/lib/esm/index.mjs
var import_jstat = __toESM(require_jstat(), 1);
var import_bessel = __toESM(require_bessel(), 1);
var nil = new Error("#NULL!");
var div0 = new Error("#DIV/0!");
var value = new Error("#VALUE!");
var ref = new Error("#REF!");
var name = new Error("#NAME?");
var num = new Error("#NUM!");
var na = new Error("#N/A");
var error48 = new Error("#ERROR!");
var data = new Error("#GETTING_DATA");
var calc = new Error("#CALC!");
var errors4 = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  calc,
  data,
  div0,
  error: error48,
  na,
  name,
  nil,
  num,
  ref,
  value
});
var returnSerial = false;
function useSerial() {
  returnSerial = true;
}
function useDate() {
  returnSerial = false;
}
function serialToDate(serial) {
  if (serial < 60) {
    serial += 1;
  }
  const utc_days = Math.floor(serial - 25569);
  const utc_value = utc_days * 86400;
  const date_info = new Date(utc_value * 1000);
  const fractional_day = serial - Math.floor(serial) + 0.0000001;
  let total_seconds = Math.floor(86400 * fractional_day);
  const seconds = total_seconds % 60;
  total_seconds -= seconds;
  const hours = Math.floor(total_seconds / (60 * 60));
  const minutes = Math.floor(total_seconds / 60) % 60;
  let days = date_info.getUTCDate();
  let month = date_info.getUTCMonth();
  if (serial >= 60 && serial < 61) {
    days = 29;
    month = 1;
  }
  return new Date(date_info.getUTCFullYear(), month, days, hours, minutes, seconds);
}
function dateToSerial(date5) {
  const d1900 = new Date(1900, 0, 1);
  const addOn = date5 > -2203891200000 ? 2 : 1;
  return Math.ceil((date5 - d1900) / 86400000) + addOn;
}
var date5 = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  dateToSerial,
  get returnSerial() {
    return returnSerial;
  },
  serialToDate,
  useDate,
  useSerial
});
var defaultOperator = "=";
var validSymbols = [">", ">=", "<", "<=", "=", "<>"];
var _TOKEN_TYPE_OPERATOR = "operator";
var _TOKEN_TYPE_LITERAL = "literal";
var SUPPORTED_TOKENS = [_TOKEN_TYPE_OPERATOR, _TOKEN_TYPE_LITERAL];
var TOKEN_TYPE_OPERATOR = _TOKEN_TYPE_OPERATOR;
var TOKEN_TYPE_LITERAL = _TOKEN_TYPE_LITERAL;
function createToken(value2, type) {
  if (SUPPORTED_TOKENS.indexOf(type) === -1) {
    throw new Error("Unsupported token type: " + type);
  }
  return {
    value: value2,
    type
  };
}
function castValueToCorrectType(value2) {
  if (typeof value2 !== "string") {
    return value2;
  }
  if (/^\d+(\.\d+)?$/.test(value2)) {
    value2 = value2.indexOf(".") === -1 ? parseInt(value2, 10) : parseFloat(value2);
  }
  return value2;
}
function tokenizeExpression(expression2) {
  const expressionLength = expression2.length;
  const tokens = [];
  let cursorIndex = 0;
  let processedValue = "";
  let processedSymbol = "";
  while (cursorIndex < expressionLength) {
    const char = expression2.charAt(cursorIndex);
    switch (char) {
      case ">":
      case "<":
      case "=":
        processedSymbol = processedSymbol + char;
        if (processedValue.length > 0) {
          tokens.push(processedValue);
          processedValue = "";
        }
        break;
      default:
        if (processedSymbol.length > 0) {
          tokens.push(processedSymbol);
          processedSymbol = "";
        }
        processedValue = processedValue + char;
        break;
    }
    cursorIndex++;
  }
  if (processedValue.length > 0) {
    tokens.push(processedValue);
  }
  if (processedSymbol.length > 0) {
    tokens.push(processedSymbol);
  }
  return tokens;
}
function analyzeTokens(tokens) {
  let literalValue = "";
  const analyzedTokens = [];
  for (let i = 0;i < tokens.length; i++) {
    const token = tokens[i];
    if (i === 0 && validSymbols.indexOf(token) >= 0) {
      analyzedTokens.push(createToken(token, TOKEN_TYPE_OPERATOR));
    } else {
      literalValue += token;
    }
  }
  if (literalValue.length > 0) {
    analyzedTokens.push(createToken(castValueToCorrectType(literalValue), TOKEN_TYPE_LITERAL));
  }
  if (analyzedTokens.length > 0 && analyzedTokens[0].type !== TOKEN_TYPE_OPERATOR) {
    analyzedTokens.unshift(createToken(defaultOperator, TOKEN_TYPE_OPERATOR));
  }
  return analyzedTokens;
}
function computeExpression(tokens) {
  const values = [];
  let operator;
  for (let i = 0;i < tokens.length; i++) {
    const token = tokens[i];
    switch (token.type) {
      case TOKEN_TYPE_OPERATOR:
        operator = token.value;
        break;
      case TOKEN_TYPE_LITERAL:
        values.push(token.value);
        break;
    }
  }
  return evaluate(values, operator);
}
function evaluate(values, operator) {
  let result = false;
  switch (operator) {
    case ">":
      result = values[0] > values[1];
      break;
    case ">=":
      result = values[0] >= values[1];
      break;
    case "<":
      result = values[0] < values[1];
      break;
    case "<=":
      result = values[0] <= values[1];
      break;
    case "=":
      result = values[0] == values[1];
      break;
    case "<>":
      result = values[0] != values[1];
      break;
  }
  return result;
}
function parse5(expression2) {
  return analyzeTokens(tokenizeExpression(expression2));
}
var compute = computeExpression;
function argsToArray(args2) {
  const result = [];
  arrayEach(args2, (value2) => {
    result.push(value2);
  });
  return result;
}
function arrayEach(array3, iteratee) {
  let index = -1;
  const length2 = array3.length;
  while (++index < length2) {
    if (iteratee(array3[index], index, array3) === false) {
      break;
    }
  }
  return array3;
}
function arrayValuesToNumbers(arr) {
  let n = arr.length;
  let el;
  while (n--) {
    el = arr[n];
    if (typeof el === "number") {
      continue;
    }
    if (el === true) {
      arr[n] = 1;
      continue;
    }
    if (el === false) {
      arr[n] = 0;
      continue;
    }
    if (typeof el === "string") {
      const number6 = parseNumber(el);
      arr[n] = number6 instanceof Error ? 0 : number6;
    }
  }
  return arr;
}
function fillMatrix(matrix, fill_value) {
  if (!matrix) {
    return value;
  }
  if (!matrix.every((el) => Array.isArray(el)) || matrix.length === 0) {
    matrix = [[...matrix]];
  }
  matrix.map((arr, i) => {
    arr.map((a, j) => {
      if (!a) {
        matrix[i][j] = 0;
      }
    });
  });
  const longestArrayIndex = matrix.reduce((acc, arr, i) => arr.length > matrix[acc].length ? i : acc, 0);
  const longestArrayLength = matrix[longestArrayIndex].length;
  return matrix.map((el) => [...el, ...Array(longestArrayLength - el.length).fill(0)]);
}
function flatten() {
  let result;
  if (arguments.length === 1) {
    const argument = arguments[0];
    result = isArrayLike(argument) ? argsToArray.apply(null, arguments) : [argument];
  } else {
    result = Array.from(arguments);
  }
  while (!isFlat(result)) {
    result = flattenShallow(result);
  }
  return result;
}
function flattenShallow(array3) {
  if (!array3 || !array3.reduce) {
    return [array3];
  }
  return array3.reduce((a, b) => {
    const aIsArray = Array.isArray(a);
    const bIsArray = Array.isArray(b);
    if (aIsArray && bIsArray) {
      return a.concat(b);
    }
    if (aIsArray) {
      a.push(b);
      return a;
    }
    if (bIsArray) {
      return [a].concat(b);
    }
    return [a, b];
  });
}
function initial(array3, idx) {
  idx = idx || 1;
  if (!array3 || typeof array3.slice !== "function") {
    return array3;
  }
  return array3.slice(0, array3.length - idx);
}
function isArrayLike(a) {
  return a != null && typeof a.length === "number" && typeof a !== "string";
}
function isFlat(array3) {
  if (!array3) {
    return false;
  }
  for (let i = 0;i < array3.length; ++i) {
    if (Array.isArray(array3[i])) {
      return false;
    }
  }
  return true;
}
function rest(array3, idx) {
  idx = idx || 1;
  if (!array3 || typeof array3.slice !== "function") {
    return array3;
  }
  return array3.slice(idx);
}
function transpose(matrix) {
  if (!matrix) {
    return value;
  }
  return matrix[0].map((col, i) => matrix.map((row2) => row2[i]));
}
function findField(database, title) {
  let index = null;
  arrayEach(database, (value2, i) => {
    if (value2[0] === title) {
      index = i;
      return false;
    }
  });
  if (index == null) {
    return value;
  }
  return index;
}
function anyError() {
  for (let n = 0;n < arguments.length; n++) {
    if (arguments[n] instanceof Error) {
      return arguments[n];
    }
  }
  return;
}
function anyIsError() {
  let n = arguments.length;
  while (n--) {
    if (arguments[n] instanceof Error) {
      return true;
    }
  }
  return false;
}
function cleanFloat(number6) {
  const power = 100000000000000;
  return Math.round(number6 * power) / power;
}
function numbers2() {
  const possibleNumbers = flatten.apply(null, arguments);
  return possibleNumbers.filter((el) => typeof el === "number");
}
function parseBool(bool) {
  if (typeof bool === "boolean") {
    return bool;
  }
  if (bool instanceof Error) {
    return bool;
  }
  if (typeof bool === "number") {
    return bool !== 0;
  }
  if (typeof bool === "string") {
    const up = bool.toUpperCase();
    if (up === "TRUE") {
      return true;
    }
    if (up === "FALSE") {
      return false;
    }
  }
  if (bool instanceof Date && !isNaN(bool)) {
    return true;
  }
  return value;
}
function parseDate(date6) {
  if (!isNaN(date6)) {
    if (date6 instanceof Date) {
      return new Date(date6);
    }
    const d = parseFloat(date6);
    if (d < 0 || d >= 2958466) {
      return num;
    }
    return serialToDate(d);
  }
  if (typeof date6 === "string") {
    date6 = /(\d{4})-(\d\d?)-(\d\d?)$/.test(date6) ? new Date(date6 + "T00:00:00.000") : new Date(date6);
    if (!isNaN(date6)) {
      return date6;
    }
  }
  return value;
}
function parseDateArray(arr) {
  let len = arr.length;
  let parsed;
  while (len--) {
    parsed = parseDate(arr[len]);
    if (parsed === value) {
      return parsed;
    }
    arr[len] = parsed;
  }
  return arr;
}
function parseNumber(string4) {
  if (string4 instanceof Error) {
    return string4;
  }
  if (string4 === undefined || string4 === null) {
    return 0;
  }
  if (typeof string4 === "boolean") {
    string4 = +string4;
  }
  if (!isNaN(string4) && string4 !== "") {
    return parseFloat(string4);
  }
  return value;
}
function parseNumberArray(arr) {
  let len;
  if (!arr || (len = arr.length) === 0) {
    return value;
  }
  let parsed;
  while (len--) {
    if (arr[len] instanceof Error) {
      return arr[len];
    }
    parsed = parseNumber(arr[len]);
    if (parsed instanceof Error) {
      return parsed;
    }
    arr[len] = parsed;
  }
  return arr;
}
function parseString(string4) {
  if (string4 instanceof Error) {
    return string4;
  }
  if (string4 === undefined || string4 === null) {
    return "";
  }
  return string4.toString();
}
function anyIsString() {
  let n = arguments.length;
  while (n--) {
    if (typeof arguments[n] === "string") {
      return true;
    }
  }
  return false;
}
function applyCriteria() {
  const args2 = argsToArray(arguments);
  const range2 = parseNumberArray(flatten(args2.shift()));
  if (range2 instanceof Error) {
    return range2;
  }
  const criterias = args2;
  const criteriaLength = criterias.length / 2;
  for (let i = 0;i < criteriaLength; i++) {
    criterias[i * 2] = flatten(criterias[i * 2]);
  }
  let values = [];
  for (let i = 0;i < range2.length; i++) {
    let isMetCondition = false;
    for (let j = 0;j < criteriaLength; j++) {
      const valueToTest = criterias[j * 2][i];
      const criteria = criterias[j * 2 + 1];
      const isWildcard = criteria === undefined || criteria === "*";
      let computedResult = false;
      if (isWildcard) {
        computedResult = true;
      } else {
        const tokenizedCriteria = parse5(criteria + "");
        const tokens = [createToken(valueToTest, TOKEN_TYPE_LITERAL)].concat(tokenizedCriteria);
        computedResult = compute(tokens);
      }
      if (!computedResult) {
        isMetCondition = false;
        break;
      }
      isMetCondition = true;
    }
    if (isMetCondition) {
      values.push(range2[i]);
    }
  }
  return values;
}
function isDefined(arg) {
  return arg !== undefined && arg !== null;
}
var ERROR = {};
ERROR.TYPE = (error_val) => {
  switch (error_val) {
    case nil:
      return 1;
    case div0:
      return 2;
    case value:
      return 3;
    case ref:
      return 4;
    case name:
      return 5;
    case num:
      return 6;
    case na:
      return 7;
    case data:
      return 8;
  }
  return na;
};
function ISERR(value$1) {
  return [value, ref, div0, num, name, nil].indexOf(value$1) >= 0 || typeof value$1 === "number" && (isNaN(value$1) || !isFinite(value$1));
}
function ISERROR(value2) {
  return ISERR(value2) || value2 === na;
}
function ISEVEN(number6) {
  return !(Math.floor(Math.abs(number6)) & 1);
}
function ISLOGICAL(value2) {
  return value2 === true || value2 === false;
}
function ISNA(value2) {
  return value2 === na;
}
function ISNONTEXT(value2) {
  return typeof value2 !== "string";
}
function ISNUMBER(value2) {
  return typeof value2 === "number" && !isNaN(value2) && isFinite(value2);
}
function ISODD(value2) {
  return !!(Math.floor(Math.abs(value2)) & 1);
}
function ISTEXT(value2) {
  return typeof value2 === "string";
}
function N(value2) {
  if (ISNUMBER(value2)) {
    return value2;
  }
  if (value2 instanceof Date) {
    return value2.getTime();
  }
  if (value2 === true) {
    return 1;
  }
  if (value2 === false) {
    return 0;
  }
  if (ISERROR(value2)) {
    return value2;
  }
  return 0;
}
function NA() {
  return na;
}
function TYPE(value2) {
  if (ISNUMBER(value2)) {
    return 1;
  }
  if (ISTEXT(value2)) {
    return 2;
  }
  if (ISLOGICAL(value2)) {
    return 4;
  }
  if (ISERROR(value2)) {
    return 16;
  }
  if (Array.isArray(value2)) {
    return 64;
  }
}
function CHOOSE() {
  if (arguments.length < 2) {
    return na;
  }
  const index = arguments[0];
  if (index < 1 || index > 254) {
    return value;
  }
  if (arguments.length < index + 1) {
    return value;
  }
  return arguments[index];
}
function COLUMN(reference, index) {
  if (arguments.length !== 2) {
    return na;
  }
  if (index < 0) {
    return num;
  }
  if (!(reference instanceof Array) || typeof index !== "number") {
    return value;
  }
  if (reference.length === 0) {
    return;
  }
  return import_jstat.default.col(reference, index);
}
function COLUMNS(array3) {
  if (arguments.length !== 1) {
    return na;
  }
  if (!(array3 instanceof Array)) {
    return value;
  }
  if (array3.length === 0) {
    return 0;
  }
  return import_jstat.default.cols(array3);
}
function HLOOKUP(lookup_value, table_array, row_index_num, range_lookup) {
  return VLOOKUP(lookup_value, transpose(table_array), row_index_num, range_lookup);
}
function INDEX(array3, row_num, column_num) {
  const someError = anyError(array3, row_num, column_num);
  if (someError) {
    return someError;
  }
  if (!Array.isArray(array3)) {
    return value;
  }
  const isOneDimensionRange = array3.length > 0 && !Array.isArray(array3[0]);
  if (isOneDimensionRange && !column_num) {
    column_num = row_num;
    row_num = 1;
  } else {
    column_num = column_num || 1;
    row_num = row_num || 1;
  }
  if (column_num < 0 || row_num < 0) {
    return value;
  }
  if (isOneDimensionRange && row_num === 1 && column_num <= array3.length) {
    return array3[column_num - 1];
  } else if (row_num <= array3.length && column_num <= array3[row_num - 1].length) {
    return array3[row_num - 1][column_num - 1];
  }
  return ref;
}
function LOOKUP(lookup_value, array3, result_array) {
  array3 = flatten(array3);
  result_array = result_array ? flatten(result_array) : array3;
  const isNumberLookup = typeof lookup_value === "number";
  let result = na;
  for (let i = 0;i < array3.length; i++) {
    if (array3[i] === lookup_value) {
      return result_array[i];
    } else if (isNumberLookup && array3[i] <= lookup_value || typeof array3[i] === "string" && array3[i].localeCompare(lookup_value) < 0) {
      result = result_array[i];
    } else if (isNumberLookup && array3[i] > lookup_value) {
      return result;
    }
  }
  return result;
}
function MATCH(lookup_value, lookup_array, match_type) {
  if (!lookup_value && lookup_value !== 0 || !lookup_array) {
    return na;
  }
  if (arguments.length === 2) {
    match_type = 1;
  }
  lookup_array = flatten(lookup_array);
  if (!(lookup_array instanceof Array)) {
    return na;
  }
  if (match_type !== -1 && match_type !== 0 && match_type !== 1) {
    return na;
  }
  let index;
  let indexValue;
  for (let idx = 0;idx < lookup_array.length; idx++) {
    if (match_type === 1) {
      if (lookup_array[idx] === lookup_value) {
        return idx + 1;
      } else if (lookup_array[idx] < lookup_value) {
        if (!indexValue) {
          index = idx + 1;
          indexValue = lookup_array[idx];
        } else if (lookup_array[idx] > indexValue) {
          index = idx + 1;
          indexValue = lookup_array[idx];
        }
      }
    } else if (match_type === 0) {
      if (typeof lookup_value === "string" && typeof lookup_array[idx] === "string") {
        const lookupValueStr = lookup_value.toLowerCase().replace(/\?/g, ".").replace(/\*/g, ".*").replace(/~/g, "\\").replace(/\+/g, "\\+").replace(/\(/g, "\\(").replace(/\)/g, "\\)").replace(/\[/g, "\\[").replace(/\]/g, "\\]");
        const regex = new RegExp("^" + lookupValueStr + "$");
        if (regex.test(lookup_array[idx].toLowerCase())) {
          return idx + 1;
        }
      } else {
        if (lookup_array[idx] === lookup_value) {
          return idx + 1;
        }
      }
    } else if (match_type === -1) {
      if (lookup_array[idx] === lookup_value) {
        return idx + 1;
      } else if (lookup_array[idx] > lookup_value) {
        if (!indexValue) {
          index = idx + 1;
          indexValue = lookup_array[idx];
        } else if (lookup_array[idx] < indexValue) {
          index = idx + 1;
          indexValue = lookup_array[idx];
        }
      }
    }
  }
  return index || na;
}
function ROWS(array3) {
  if (arguments.length !== 1) {
    return na;
  }
  if (!(array3 instanceof Array)) {
    return value;
  }
  if (array3.length === 0) {
    return 0;
  }
  return import_jstat.default.rows(array3);
}
function TRANSPOSE(array3) {
  if (!array3) {
    return na;
  }
  const matrix = fillMatrix(array3);
  return transpose(matrix);
}
function UNIQUE() {
  const result = [];
  for (let i = 0;i < arguments.length; ++i) {
    let hasElement = false;
    const element = arguments[i];
    for (let j = 0;j < result.length; ++j) {
      hasElement = result[j] === element;
      if (hasElement) {
        break;
      }
    }
    if (!hasElement) {
      result.push(element);
    }
  }
  return result;
}
function VLOOKUP(lookup_value, table_array, col_index_num, range_lookup) {
  if (!table_array || !col_index_num) {
    return na;
  }
  range_lookup = !(range_lookup === 0 || range_lookup === false);
  let result = na;
  let exactMatchOnly = false;
  const isNumberLookup = typeof lookup_value === "number";
  const lookupValue = typeof lookup_value === "string" ? lookup_value.toLowerCase() : lookup_value;
  for (let i = 0;i < table_array.length; i++) {
    const row2 = table_array[i];
    const rowValue = typeof row2[0] === "string" ? row2[0].toLowerCase() : row2[0];
    if (rowValue === lookupValue) {
      result = col_index_num < row2.length + 1 ? row2[col_index_num - 1] : ref;
      break;
    } else if (!exactMatchOnly && (isNumberLookup && range_lookup && rowValue <= lookup_value || range_lookup && typeof rowValue === "string" && rowValue.localeCompare(lookup_value) < 0)) {
      result = col_index_num < row2.length + 1 ? row2[col_index_num - 1] : ref;
    }
    if (isNumberLookup && rowValue > lookup_value) {
      exactMatchOnly = true;
    }
  }
  return result;
}
function CHAR(number6) {
  number6 = parseNumber(number6);
  if (number6 === 0) {
    return value;
  }
  if (number6 instanceof Error) {
    return number6;
  }
  return String.fromCharCode(number6);
}
function CLEAN(text2) {
  if (anyIsError(text2)) {
    return text2;
  }
  text2 = text2 || "";
  const re2 = /[\0-\x1F]/g;
  return text2.replace(re2, "");
}
function CODE(text2) {
  if (anyIsError(text2)) {
    return text2;
  }
  text2 = text2 || "";
  let result = text2.charCodeAt(0);
  if (isNaN(result)) {
    result = value;
  }
  return result;
}
function CONCATENATE() {
  const args2 = flatten(arguments);
  const someError = anyError.apply(undefined, args2);
  if (someError) {
    return someError;
  }
  let trueFound = 0;
  while ((trueFound = args2.indexOf(true)) > -1) {
    args2[trueFound] = "TRUE";
  }
  let falseFound = 0;
  while ((falseFound = args2.indexOf(false)) > -1) {
    args2[falseFound] = "FALSE";
  }
  return args2.join("");
}
var CONCAT = CONCATENATE;
function DOLLAR(number6, decimals = 2) {
  number6 = parseNumber(number6);
  if (isNaN(number6)) {
    return value;
  }
  number6 = ROUND(number6, decimals);
  const options = {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: decimals >= 0 ? decimals : 0,
    maximumFractionDigits: decimals >= 0 ? decimals : 0
  };
  const formattedNumber = number6.toLocaleString("en-US", options);
  if (number6 < 0) {
    return "$(" + formattedNumber.slice(2) + ")";
  }
  return formattedNumber;
}
function EXACT(text1, text2) {
  if (arguments.length !== 2) {
    return na;
  }
  const someError = anyError(text1, text2);
  if (someError) {
    return someError;
  }
  text1 = parseString(text1);
  text2 = parseString(text2);
  return text1 === text2;
}
function FIND(find_text, within_text, start_num) {
  if (arguments.length < 2) {
    return na;
  }
  find_text = parseString(find_text);
  within_text = parseString(within_text);
  start_num = start_num === undefined ? 0 : start_num;
  const found_index = within_text.indexOf(find_text, start_num - 1);
  if (found_index === -1) {
    return value;
  }
  return found_index + 1;
}
function FIXED(number6, decimals = 2, no_commas = false) {
  number6 = parseNumber(number6);
  if (isNaN(number6)) {
    return value;
  }
  decimals = parseNumber(decimals);
  if (isNaN(decimals)) {
    return value;
  }
  if (decimals < 0) {
    const factor = Math.pow(10, -decimals);
    number6 = Math.round(number6 / factor) * factor;
  } else {
    number6 = number6.toFixed(decimals);
  }
  if (no_commas) {
    number6 = number6.toString().replace(/,/g, "");
  } else {
    const parts = number6.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+$)/g, ",");
    number6 = parts.join(".");
  }
  return number6;
}
function LEFT(text2, num_chars) {
  const someError = anyError(text2, num_chars);
  if (someError) {
    return someError;
  }
  text2 = parseString(text2);
  num_chars = num_chars === undefined ? 1 : num_chars;
  num_chars = parseNumber(num_chars);
  if (num_chars instanceof Error || typeof text2 !== "string") {
    return value;
  }
  return text2.substring(0, num_chars);
}
function LEN(text2) {
  if (arguments.length === 0) {
    return error48;
  }
  if (text2 instanceof Error) {
    return text2;
  }
  if (Array.isArray(text2)) {
    return value;
  }
  const textAsString = parseString(text2);
  return textAsString.length;
}
function LOWER(text2) {
  if (arguments.length !== 1) {
    return value;
  }
  text2 = parseString(text2);
  if (anyIsError(text2)) {
    return text2;
  }
  return text2.toLowerCase();
}
function MID(text2, start_num, num_chars) {
  if (anyIsError(text2, start_num, num_chars)) {
    return anyError(text2, start_num, num_chars);
  }
  const numArgs = [start_num, num_chars].map((num2) => parseNumber(num2));
  const validNumArgs = numArgs.every((numArg) => {
    return !(numArg instanceof Error) && numArg > 0;
  });
  if (!validNumArgs)
    return value;
  if (!isDefined(text2)) {
    text2 = "";
  } else if (typeof text2 !== "string") {
    text2 = String(text2);
  }
  [start_num, num_chars] = numArgs;
  const begin = start_num - 1;
  const end = begin + num_chars;
  return text2.substring(begin, end);
}
function NUMBERVALUE(text2, decimal_separator, group_separator) {
  text2 = isDefined(text2) ? text2 : "";
  if (typeof text2 === "number") {
    return text2;
  }
  if (typeof text2 !== "string") {
    return na;
  }
  decimal_separator = typeof decimal_separator === "undefined" ? "." : decimal_separator;
  group_separator = typeof group_separator === "undefined" ? "," : group_separator;
  return Number(text2.replace(decimal_separator, ".").replace(group_separator, ""));
}
function PROPER(text2) {
  if (anyIsError(text2)) {
    return text2;
  }
  if (isNaN(text2) && typeof text2 === "number") {
    return value;
  }
  text2 = parseString(text2);
  return text2.replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());
}
function REPLACE(old_text, num_chars, length2, new_text) {
  num_chars = parseNumber(num_chars);
  length2 = parseNumber(length2);
  if (anyIsError(num_chars, length2) || typeof old_text !== "string" || typeof new_text !== "string") {
    return value;
  }
  return old_text.substr(0, num_chars - 1) + new_text + old_text.substr(num_chars - 1 + length2);
}
function REPT(text2, number_times) {
  const someError = anyError(text2, number_times);
  if (someError) {
    return someError;
  }
  text2 = parseString(text2);
  number_times = parseNumber(number_times);
  if (number_times instanceof Error) {
    return number_times;
  }
  return new Array(number_times + 1).join(text2);
}
function RIGHT(text2, num_chars) {
  const someError = anyError(text2, num_chars);
  if (someError) {
    return someError;
  }
  text2 = parseString(text2);
  num_chars = num_chars === undefined ? 1 : num_chars;
  num_chars = parseNumber(num_chars);
  if (num_chars instanceof Error) {
    return num_chars;
  }
  return text2.substring(text2.length - num_chars);
}
function SEARCH(find_text, within_text, start_num) {
  let foundAt;
  if (typeof find_text !== "string" || typeof within_text !== "string") {
    return value;
  }
  start_num = start_num === undefined ? 0 : start_num;
  foundAt = within_text.toLowerCase().indexOf(find_text.toLowerCase(), start_num - 1) + 1;
  return foundAt === 0 ? value : foundAt;
}
function SUBSTITUTE(text2, old_text, new_text, instance_num) {
  if (arguments.length < 3) {
    return na;
  }
  if (!text2 || !old_text) {
    return text2;
  } else if (instance_num === undefined) {
    return text2.split(old_text).join(new_text);
  } else {
    instance_num = Math.floor(Number(instance_num));
    if (Number.isNaN(instance_num) || instance_num <= 0) {
      return value;
    }
    let index = 0;
    let i = 0;
    while (index > -1 && text2.indexOf(old_text, index) > -1) {
      index = text2.indexOf(old_text, index + 1);
      i++;
      if (index > -1 && i === instance_num) {
        return text2.substring(0, index) + new_text + text2.substring(index + old_text.length);
      }
    }
    return text2;
  }
}
function T(value2) {
  if (value2 instanceof Error) {
    return value2;
  }
  return typeof value2 === "string" ? value2 : "";
}
function TEXT(value$1, format_text) {
  if (value$1 === undefined || value$1 instanceof Error || format_text instanceof Error) {
    return na;
  }
  if (value$1 instanceof Date) {
    return value$1.toISOString().slice(0, 10);
  }
  if (format_text === undefined || format_text === null) {
    return "";
  }
  if (typeof format_text === "number") {
    return String(format_text);
  }
  if (typeof format_text !== "string") {
    return value;
  }
  const currencySymbol = format_text.startsWith("$") ? "$" : "";
  const isPercent = format_text.endsWith("%");
  format_text = format_text.replace(/%/g, "").replace(/\$/g, "");
  const decimalPlaces = format_text.includes(".") ? format_text.split(".")[1].match(/0/g).length : 0;
  const noCommas = !format_text.includes(",");
  if (isPercent) {
    value$1 = value$1 * 100;
  }
  value$1 = FIXED(value$1, decimalPlaces, noCommas);
  if (value$1.startsWith("-")) {
    value$1 = value$1.replace("-", "");
    value$1 = "-" + currencySymbol + value$1;
  } else {
    value$1 = currencySymbol + value$1;
  }
  if (isPercent) {
    value$1 = value$1 + "%";
  }
  return value$1;
}
function TEXTJOIN(delimiter, ignore_empty, ...args2) {
  if (typeof ignore_empty !== "boolean") {
    ignore_empty = parseBool(ignore_empty);
  }
  if (arguments.length < 3) {
    return na;
  }
  delimiter = delimiter !== null && delimiter !== undefined ? delimiter : "";
  let flatArgs = flatten(args2);
  let textToJoin = ignore_empty ? flatArgs.filter((text2) => text2) : flatArgs;
  if (Array.isArray(delimiter)) {
    delimiter = flatten(delimiter);
    let chunks = textToJoin.map((item) => [item]);
    let index = 0;
    for (let i = 0;i < chunks.length - 1; i++) {
      chunks[i].push(delimiter[index]);
      index++;
      if (index === delimiter.length) {
        index = 0;
      }
    }
    textToJoin = flatten(chunks);
    return textToJoin.join("");
  }
  return textToJoin.join(delimiter);
}
function TRIM(text2) {
  text2 = parseString(text2);
  if (text2 instanceof Error) {
    return text2;
  }
  return text2.replace(/\s+/g, " ").trim();
}
var UNICHAR = CHAR;
var UNICODE = CODE;
function UPPER(text2) {
  text2 = parseString(text2);
  if (text2 instanceof Error) {
    return text2;
  }
  return text2.toUpperCase();
}
function VALUE(text2) {
  const anyError$1 = anyError(text2);
  if (anyError$1) {
    return anyError$1;
  }
  if (typeof text2 === "number") {
    return text2;
  }
  if (!isDefined(text2)) {
    text2 = "";
  }
  if (typeof text2 !== "string") {
    return value;
  }
  const isPercent = /(%)$/.test(text2) || /^(%)/.test(text2);
  text2 = text2.replace(/^[^0-9-]{0,3}/, "");
  text2 = text2.replace(/[^0-9]{0,3}$/, "");
  text2 = text2.replace(/[ ,]/g, "");
  if (text2 === "") {
    return 0;
  }
  let output = Number(text2);
  if (isNaN(output)) {
    return value;
  }
  output = output || 0;
  if (isPercent) {
    output = output * 0.01;
  }
  return output;
}
var SQRT2PI = 2.5066282746310002;
function AVEDEV() {
  const flatArguments = flatten(arguments);
  const flatArgumentsDefined = flatArguments.filter(isDefined);
  if (flatArgumentsDefined.length === 0) {
    return num;
  }
  const range2 = parseNumberArray(flatArgumentsDefined);
  if (range2 instanceof Error) {
    return range2;
  }
  return import_jstat.default.sum(import_jstat.default(range2).subtract(import_jstat.default.mean(range2)).abs()[0]) / range2.length;
}
function AVERAGE() {
  const flatArguments = flatten(arguments);
  const flatArgumentsDefined = flatArguments.filter(isDefined);
  if (flatArgumentsDefined.length === 0) {
    return div0;
  }
  const someError = anyError.apply(undefined, flatArgumentsDefined);
  if (someError) {
    return someError;
  }
  const range2 = numbers2(flatArgumentsDefined);
  const n = range2.length;
  let sum2 = 0;
  let count3 = 0;
  let result;
  for (let i = 0;i < n; i++) {
    sum2 += range2[i];
    count3 += 1;
  }
  result = sum2 / count3;
  if (isNaN(result)) {
    result = num;
  }
  return result;
}
function AVERAGEA() {
  const flatArguments = flatten(arguments);
  const flatArgumentsDefined = flatArguments.filter(isDefined);
  if (flatArgumentsDefined.length === 0) {
    return div0;
  }
  const someError = anyError.apply(undefined, flatArgumentsDefined);
  if (someError) {
    return someError;
  }
  const range2 = flatArgumentsDefined;
  const n = range2.length;
  let sum2 = 0;
  let count3 = 0;
  let result;
  for (let i = 0;i < n; i++) {
    const el = range2[i];
    if (typeof el === "number") {
      sum2 += el;
    }
    if (el === true) {
      sum2++;
    }
    if (el !== null) {
      count3++;
    }
  }
  result = sum2 / count3;
  if (isNaN(result)) {
    result = num;
  }
  return result;
}
function AVERAGEIFS() {
  const values = applyCriteria(...arguments);
  const result = values.reduce((acc, value2) => acc + value2, 0);
  const average = result / values.length;
  return isNaN(average) ? 0 : average;
}
var BETA = {};
BETA.DIST = function(x2, alpha, beta, cumulative, a, b) {
  if (arguments.length < 4) {
    return value;
  }
  a = a === undefined ? 0 : a;
  b = b === undefined ? 1 : b;
  x2 = parseNumber(x2);
  alpha = parseNumber(alpha);
  beta = parseNumber(beta);
  a = parseNumber(a);
  b = parseNumber(b);
  if (anyIsError(x2, alpha, beta, a, b)) {
    return value;
  }
  x2 = (x2 - a) / (b - a);
  return cumulative ? import_jstat.default.beta.cdf(x2, alpha, beta) : import_jstat.default.beta.pdf(x2, alpha, beta);
};
BETA.INV = (probability, alpha, beta, a, b) => {
  a = a === undefined ? 0 : a;
  b = b === undefined ? 1 : b;
  probability = parseNumber(probability);
  alpha = parseNumber(alpha);
  beta = parseNumber(beta);
  a = parseNumber(a);
  b = parseNumber(b);
  if (anyIsError(probability, alpha, beta, a, b)) {
    return value;
  }
  return import_jstat.default.beta.inv(probability, alpha, beta) * (b - a) + a;
};
var BINOM = {};
BINOM.DIST = (number_s, trials, probability_s, cumulative) => {
  number_s = parseNumber(number_s);
  trials = parseNumber(trials);
  probability_s = parseNumber(probability_s);
  cumulative = parseNumber(cumulative);
  if (anyIsError(number_s, trials, probability_s, cumulative)) {
    return value;
  }
  return cumulative ? import_jstat.default.binomial.cdf(number_s, trials, probability_s) : import_jstat.default.binomial.pdf(number_s, trials, probability_s);
};
BINOM.DIST.RANGE = (trials, probability_s, number_s, number_s2) => {
  number_s2 = number_s2 === undefined ? number_s : number_s2;
  trials = parseNumber(trials);
  probability_s = parseNumber(probability_s);
  number_s = parseNumber(number_s);
  number_s2 = parseNumber(number_s2);
  if (anyIsError(trials, probability_s, number_s, number_s2)) {
    return value;
  }
  let result = 0;
  for (let i = number_s;i <= number_s2; i++) {
    result += COMBIN(trials, i) * Math.pow(probability_s, i) * Math.pow(1 - probability_s, trials - i);
  }
  return result;
};
BINOM.INV = (trials, probability_s, alpha) => {
  trials = parseNumber(trials);
  probability_s = parseNumber(probability_s);
  alpha = parseNumber(alpha);
  if (anyIsError(trials, probability_s, alpha)) {
    return value;
  }
  let x2 = 0;
  while (x2 <= trials) {
    if (import_jstat.default.binomial.cdf(x2, trials, probability_s) >= alpha) {
      return x2;
    }
    x2++;
  }
};
var CHISQ = {};
CHISQ.DIST = (x2, deg_freedom, cumulative) => {
  x2 = parseNumber(x2);
  deg_freedom = parseNumber(deg_freedom);
  if (anyIsError(x2, deg_freedom)) {
    return value;
  }
  return cumulative ? import_jstat.default.chisquare.cdf(x2, deg_freedom) : import_jstat.default.chisquare.pdf(x2, deg_freedom);
};
CHISQ.DIST.RT = (x2, deg_freedom) => {
  if (!x2 | !deg_freedom) {
    return na;
  }
  if (x2 < 1 || deg_freedom > Math.pow(10, 10)) {
    return num;
  }
  if (typeof x2 !== "number" || typeof deg_freedom !== "number") {
    return value;
  }
  return 1 - import_jstat.default.chisquare.cdf(x2, deg_freedom);
};
CHISQ.INV = (probability, deg_freedom) => {
  probability = parseNumber(probability);
  deg_freedom = parseNumber(deg_freedom);
  if (anyIsError(probability, deg_freedom)) {
    return value;
  }
  return import_jstat.default.chisquare.inv(probability, deg_freedom);
};
CHISQ.INV.RT = (probability, deg_freedom) => {
  if (!probability | !deg_freedom) {
    return na;
  }
  if (probability < 0 || probability > 1 || deg_freedom < 1 || deg_freedom > Math.pow(10, 10)) {
    return num;
  }
  if (typeof probability !== "number" || typeof deg_freedom !== "number") {
    return value;
  }
  return import_jstat.default.chisquare.inv(1 - probability, deg_freedom);
};
CHISQ.TEST = function(actual_range, expected_range) {
  if (arguments.length !== 2) {
    return na;
  }
  if (!(actual_range instanceof Array) || !(expected_range instanceof Array)) {
    return value;
  }
  if (actual_range.length !== expected_range.length) {
    return value;
  }
  if (actual_range[0] && expected_range[0] && actual_range[0].length !== expected_range[0].length) {
    return value;
  }
  const row2 = actual_range.length;
  let tmp, i, j;
  for (i = 0;i < row2; i++) {
    if (!(actual_range[i] instanceof Array)) {
      tmp = actual_range[i];
      actual_range[i] = [];
      actual_range[i].push(tmp);
    }
    if (!(expected_range[i] instanceof Array)) {
      tmp = expected_range[i];
      expected_range[i] = [];
      expected_range[i].push(tmp);
    }
  }
  const col = actual_range[0].length;
  const dof = col === 1 ? row2 - 1 : (row2 - 1) * (col - 1);
  let xsqr = 0;
  const Pi = Math.PI;
  for (i = 0;i < row2; i++) {
    for (j = 0;j < col; j++) {
      xsqr += Math.pow(actual_range[i][j] - expected_range[i][j], 2) / expected_range[i][j];
    }
  }
  function ChiSq(xsqr2, dof2) {
    let p = Math.exp(-0.5 * xsqr2);
    if (dof2 % 2 === 1) {
      p = p * Math.sqrt(2 * xsqr2 / Pi);
    }
    let k = dof2;
    while (k >= 2) {
      p = p * xsqr2 / k;
      k = k - 2;
    }
    let t = p;
    let a = dof2;
    while (t > 0.0000000001 * p) {
      a = a + 2;
      t = t * xsqr2 / a;
      p = p + t;
    }
    return 1 - p;
  }
  return Math.round(ChiSq(xsqr, dof) * 1e6) / 1e6;
};
var CONFIDENCE = {};
CONFIDENCE.NORM = (alpha, standard_dev, size2) => {
  alpha = parseNumber(alpha);
  standard_dev = parseNumber(standard_dev);
  size2 = parseNumber(size2);
  if (anyIsError(alpha, standard_dev, size2)) {
    return value;
  }
  return import_jstat.default.normalci(1, alpha, standard_dev, size2)[1] - 1;
};
CONFIDENCE.T = (alpha, standard_dev, size2) => {
  alpha = parseNumber(alpha);
  standard_dev = parseNumber(standard_dev);
  size2 = parseNumber(size2);
  if (anyIsError(alpha, standard_dev, size2)) {
    return value;
  }
  return import_jstat.default.tci(1, alpha, standard_dev, size2)[1] - 1;
};
function CORREL(array1, array22) {
  array1 = parseNumberArray(flatten(array1));
  array22 = parseNumberArray(flatten(array22));
  if (anyIsError(array1, array22)) {
    return value;
  }
  return import_jstat.default.corrcoeff(array1, array22);
}
function COUNT() {
  const flatArguments = flatten(arguments);
  return numbers2(flatArguments).length;
}
function COUNTA() {
  const flatArguments = flatten(arguments);
  return flatArguments.length - COUNTBLANK(flatArguments);
}
function COUNTBLANK() {
  const range2 = flatten(arguments);
  let blanks = 0;
  let element;
  for (let i = 0;i < range2.length; i++) {
    element = range2[i];
    if (element === undefined || element === null || element === "") {
      blanks++;
    }
  }
  return blanks;
}
function COUNTIF(range2, criteria) {
  range2 = flatten(range2);
  const isWildcard = criteria === undefined || criteria === "*";
  if (isWildcard) {
    return range2.length;
  }
  let matches = 0;
  const tokenizedCriteria = parse5(criteria + "");
  for (let i = 0;i < range2.length; i++) {
    const value2 = range2[i];
    const tokens = [createToken(value2, TOKEN_TYPE_LITERAL)].concat(tokenizedCriteria);
    if (compute(tokens)) {
      matches++;
    }
  }
  return matches;
}
function COUNTIFS() {
  const args2 = argsToArray(arguments);
  const results = new Array(flatten(args2[0]).length);
  for (let i = 0;i < results.length; i++) {
    results[i] = true;
  }
  for (let i = 0;i < args2.length; i += 2) {
    const range2 = flatten(args2[i]);
    const criteria = args2[i + 1];
    const isWildcard = criteria === undefined || criteria === "*";
    if (!isWildcard) {
      const tokenizedCriteria = parse5(criteria + "");
      for (let j = 0;j < range2.length; j++) {
        const value2 = range2[j];
        const tokens = [createToken(value2, TOKEN_TYPE_LITERAL)].concat(tokenizedCriteria);
        results[j] = results[j] && compute(tokens);
      }
    }
  }
  let result = 0;
  for (let i = 0;i < results.length; i++) {
    if (results[i]) {
      result++;
    }
  }
  return result;
}
var COVARIANCE = {};
COVARIANCE.P = (array1, array22) => {
  array1 = parseNumberArray(flatten(array1));
  array22 = parseNumberArray(flatten(array22));
  if (anyIsError(array1, array22)) {
    return value;
  }
  const mean1 = import_jstat.default.mean(array1);
  const mean22 = import_jstat.default.mean(array22);
  let result = 0;
  const n = array1.length;
  for (let i = 0;i < n; i++) {
    result += (array1[i] - mean1) * (array22[i] - mean22);
  }
  return result / n;
};
COVARIANCE.S = (array1, array22) => {
  array1 = parseNumberArray(flatten(array1));
  array22 = parseNumberArray(flatten(array22));
  if (anyIsError(array1, array22)) {
    return value;
  }
  return import_jstat.default.covariance(array1, array22);
};
function DEVSQ() {
  const range2 = parseNumberArray(flatten(arguments));
  if (range2 instanceof Error) {
    return range2;
  }
  const mean3 = import_jstat.default.mean(range2);
  let result = 0;
  for (let i = 0;i < range2.length; i++) {
    result += Math.pow(range2[i] - mean3, 2);
  }
  return result;
}
var EXPON = {};
EXPON.DIST = (x2, lambda, cumulative) => {
  x2 = parseNumber(x2);
  lambda = parseNumber(lambda);
  if (anyIsError(x2, lambda)) {
    return value;
  }
  return cumulative ? import_jstat.default.exponential.cdf(x2, lambda) : import_jstat.default.exponential.pdf(x2, lambda);
};
var F = {};
F.DIST = (x2, deg_freedom1, deg_freedom2, cumulative) => {
  x2 = parseNumber(x2);
  deg_freedom1 = parseNumber(deg_freedom1);
  deg_freedom2 = parseNumber(deg_freedom2);
  if (anyIsError(x2, deg_freedom1, deg_freedom2)) {
    return value;
  }
  return cumulative ? import_jstat.default.centralF.cdf(x2, deg_freedom1, deg_freedom2) : import_jstat.default.centralF.pdf(x2, deg_freedom1, deg_freedom2);
};
F.DIST.RT = function(x2, deg_freedom1, deg_freedom2) {
  if (arguments.length !== 3) {
    return na;
  }
  if (x2 < 0 || deg_freedom1 < 1 || deg_freedom2 < 1) {
    return num;
  }
  if (typeof x2 !== "number" || typeof deg_freedom1 !== "number" || typeof deg_freedom2 !== "number") {
    return value;
  }
  return 1 - import_jstat.default.centralF.cdf(x2, deg_freedom1, deg_freedom2);
};
F.INV = (probability, deg_freedom1, deg_freedom2) => {
  probability = parseNumber(probability);
  deg_freedom1 = parseNumber(deg_freedom1);
  deg_freedom2 = parseNumber(deg_freedom2);
  if (anyIsError(probability, deg_freedom1, deg_freedom2)) {
    return value;
  }
  if (probability <= 0 || probability > 1) {
    return num;
  }
  return import_jstat.default.centralF.inv(probability, deg_freedom1, deg_freedom2);
};
F.INV.RT = function(probability, deg_freedom1, deg_freedom2) {
  if (arguments.length !== 3) {
    return na;
  }
  if (probability < 0 || probability > 1 || deg_freedom1 < 1 || deg_freedom1 > Math.pow(10, 10) || deg_freedom2 < 1 || deg_freedom2 > Math.pow(10, 10)) {
    return num;
  }
  if (typeof probability !== "number" || typeof deg_freedom1 !== "number" || typeof deg_freedom2 !== "number") {
    return value;
  }
  return import_jstat.default.centralF.inv(1 - probability, deg_freedom1, deg_freedom2);
};
F.TEST = (array1, array22) => {
  if (!array1 || !array22) {
    return na;
  }
  if (!(array1 instanceof Array) || !(array22 instanceof Array)) {
    return na;
  }
  if (array1.length < 2 || array22.length < 2) {
    return div0;
  }
  const sumOfSquares = (values, x12) => {
    let sum3 = 0;
    for (let i = 0;i < values.length; i++) {
      sum3 += Math.pow(values[i] - x12, 2);
    }
    return sum3;
  };
  const x1 = SUM(array1) / array1.length;
  const x2 = SUM(array22) / array22.length;
  const sum1 = sumOfSquares(array1, x1) / (array1.length - 1);
  const sum2 = sumOfSquares(array22, x2) / (array22.length - 1);
  return sum1 / sum2;
};
function FISHER(x2) {
  x2 = parseNumber(x2);
  if (x2 instanceof Error) {
    return x2;
  }
  return Math.log((1 + x2) / (1 - x2)) / 2;
}
function FISHERINV(y2) {
  y2 = parseNumber(y2);
  if (y2 instanceof Error) {
    return y2;
  }
  const e2y = Math.exp(2 * y2);
  return (e2y - 1) / (e2y + 1);
}
function FORECAST(x2, known_ys, known_xs) {
  x2 = parseNumber(x2);
  known_ys = parseNumberArray(flatten(known_ys));
  known_xs = parseNumberArray(flatten(known_xs));
  if (anyIsError(x2, known_ys, known_xs)) {
    return value;
  }
  const xmean = import_jstat.default.mean(known_xs);
  const ymean = import_jstat.default.mean(known_ys);
  const n = known_xs.length;
  let num2 = 0;
  let den = 0;
  for (let i = 0;i < n; i++) {
    num2 += (known_xs[i] - xmean) * (known_ys[i] - ymean);
    den += Math.pow(known_xs[i] - xmean, 2);
  }
  const b = num2 / den;
  const a = ymean - b * xmean;
  return a + b * x2;
}
function FREQUENCY(data_array, bins_array) {
  data_array = parseNumberArray(flatten(data_array));
  bins_array = parseNumberArray(flatten(bins_array));
  if (anyIsError(data_array, bins_array)) {
    return value;
  }
  const n = data_array.length;
  const b = bins_array.length;
  const r = [];
  for (let i = 0;i <= b; i++) {
    r[i] = 0;
    for (let j = 0;j < n; j++) {
      if (i === 0) {
        if (data_array[j] <= bins_array[0]) {
          r[0] += 1;
        }
      } else if (i < b) {
        if (data_array[j] > bins_array[i - 1] && data_array[j] <= bins_array[i]) {
          r[i] += 1;
        }
      } else if (i === b) {
        if (data_array[j] > bins_array[b - 1]) {
          r[b] += 1;
        }
      }
    }
  }
  return r;
}
function GAMMA(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  if (number6 === 0) {
    return num;
  }
  if (parseInt(number6, 10) === number6 && number6 < 0) {
    return num;
  }
  return import_jstat.default.gammafn(number6);
}
GAMMA.DIST = function(value$1, alpha, beta, cumulative) {
  if (arguments.length !== 4) {
    return na;
  }
  if (value$1 < 0 || alpha <= 0 || beta <= 0) {
    return value;
  }
  if (typeof value$1 !== "number" || typeof alpha !== "number" || typeof beta !== "number") {
    return value;
  }
  return cumulative ? import_jstat.default.gamma.cdf(value$1, alpha, beta, true) : import_jstat.default.gamma.pdf(value$1, alpha, beta, false);
};
GAMMA.INV = function(probability, alpha, beta) {
  if (arguments.length !== 3) {
    return na;
  }
  if (probability < 0 || probability > 1 || alpha <= 0 || beta <= 0) {
    return num;
  }
  if (typeof probability !== "number" || typeof alpha !== "number" || typeof beta !== "number") {
    return value;
  }
  return import_jstat.default.gamma.inv(probability, alpha, beta);
};
function GAMMALN(x2) {
  x2 = parseNumber(x2);
  if (x2 instanceof Error) {
    return x2;
  }
  return import_jstat.default.gammaln(x2);
}
GAMMALN.PRECISE = function(x2) {
  if (arguments.length !== 1) {
    return na;
  }
  if (x2 <= 0) {
    return num;
  }
  if (typeof x2 !== "number") {
    return value;
  }
  return import_jstat.default.gammaln(x2);
};
function GAUSS(z2) {
  z2 = parseNumber(z2);
  if (z2 instanceof Error) {
    return z2;
  }
  return import_jstat.default.normal.cdf(z2, 0, 1) - 0.5;
}
function GEOMEAN() {
  const args2 = parseNumberArray(flatten(arguments));
  if (args2 instanceof Error) {
    return args2;
  }
  return import_jstat.default.geomean(args2);
}
function GROWTH(known_y, known_x, new_x, use_const) {
  known_y = parseNumberArray(flatten(known_y));
  if (known_y instanceof Error) {
    return known_y;
  }
  let i;
  if (known_x === undefined) {
    known_x = [];
    for (i = 1;i <= known_y.length; i++) {
      known_x.push(i);
    }
  }
  if (new_x === undefined) {
    new_x = known_x;
  }
  known_x = parseNumberArray(flatten(known_x));
  new_x = parseNumberArray(flatten(new_x));
  if (anyIsError(known_x, new_x)) {
    return value;
  }
  if (use_const === undefined) {
    use_const = true;
  }
  const n = known_y.length;
  let avg_x = 0;
  let avg_y = 0;
  let avg_xy = 0;
  let avg_xx = 0;
  for (i = 0;i < n; i++) {
    const x2 = known_x[i];
    const y2 = Math.log(known_y[i]);
    avg_x += x2;
    avg_y += y2;
    avg_xy += x2 * y2;
    avg_xx += x2 * x2;
  }
  avg_x /= n;
  avg_y /= n;
  avg_xy /= n;
  avg_xx /= n;
  let beta;
  let alpha;
  if (use_const) {
    beta = (avg_xy - avg_x * avg_y) / (avg_xx - avg_x * avg_x);
    alpha = avg_y - beta * avg_x;
  } else {
    beta = avg_xy / avg_xx;
    alpha = 0;
  }
  const new_y = [];
  for (i = 0;i < new_x.length; i++) {
    new_y.push(Math.exp(alpha + beta * new_x[i]));
  }
  return new_y;
}
function HARMEAN() {
  const range2 = parseNumberArray(flatten(arguments));
  if (range2 instanceof Error) {
    return range2;
  }
  const n = range2.length;
  let den = 0;
  for (let i = 0;i < n; i++) {
    den += 1 / range2[i];
  }
  return n / den;
}
var HYPGEOM = {};
HYPGEOM.DIST = (sample_s, number_sample, population_s, number_pop, cumulative) => {
  sample_s = parseNumber(sample_s);
  number_sample = parseNumber(number_sample);
  population_s = parseNumber(population_s);
  number_pop = parseNumber(number_pop);
  if (anyIsError(sample_s, number_sample, population_s, number_pop)) {
    return value;
  }
  function pdf(x2, n, M, N2) {
    return COMBIN(M, x2) * COMBIN(N2 - M, n - x2) / COMBIN(N2, n);
  }
  function cdf(x2, n, M, N2) {
    let result = 0;
    for (let i = 0;i <= x2; i++) {
      result += pdf(i, n, M, N2);
    }
    return result;
  }
  return cumulative ? cdf(sample_s, number_sample, population_s, number_pop) : pdf(sample_s, number_sample, population_s, number_pop);
};
function INTERCEPT(known_y, known_x) {
  known_y = parseNumberArray(known_y);
  known_x = parseNumberArray(known_x);
  if (anyIsError(known_y, known_x)) {
    return value;
  }
  if (known_y.length !== known_x.length) {
    return na;
  }
  return FORECAST(0, known_y, known_x);
}
function KURT() {
  const range2 = parseNumberArray(flatten(arguments));
  if (range2 instanceof Error) {
    return range2;
  }
  const mean3 = import_jstat.default.mean(range2);
  const n = range2.length;
  let sigma = 0;
  for (let i = 0;i < n; i++) {
    sigma += Math.pow(range2[i] - mean3, 4);
  }
  sigma = sigma / Math.pow(import_jstat.default.stdev(range2, true), 4);
  return n * (n + 1) / ((n - 1) * (n - 2) * (n - 3)) * sigma - 3 * (n - 1) * (n - 1) / ((n - 2) * (n - 3));
}
function LARGE(array3, k) {
  const someError = anyError.apply(undefined, array3);
  if (someError) {
    return someError;
  }
  if (anyIsError(k)) {
    return k;
  }
  array3 = numbers2(flatten(array3));
  k = parseNumber(k);
  if (k < 0 || array3.length < k) {
    return value;
  }
  return array3.sort((a, b) => b - a)[k - 1];
}
function LINEST(known_y, known_x) {
  known_y = parseNumberArray(flatten(known_y));
  known_x = parseNumberArray(flatten(known_x));
  if (anyIsError(known_y, known_x)) {
    return value;
  }
  const ymean = import_jstat.default.mean(known_y);
  const xmean = import_jstat.default.mean(known_x);
  const n = known_x.length;
  let num2 = 0;
  let den = 0;
  for (let i = 0;i < n; i++) {
    num2 += (known_x[i] - xmean) * (known_y[i] - ymean);
    den += Math.pow(known_x[i] - xmean, 2);
  }
  const m = num2 / den;
  const b = ymean - m * xmean;
  return [m, b];
}
function LOGEST(known_y, known_x) {
  known_y = parseNumberArray(flatten(known_y));
  known_x = parseNumberArray(flatten(known_x));
  if (anyIsError(known_y, known_x)) {
    return value;
  }
  if (known_y.length !== known_x.length) {
    return value;
  }
  for (let i = 0;i < known_y.length; i++) {
    known_y[i] = Math.log(known_y[i]);
  }
  const result = LINEST(known_y, known_x);
  result[0] = Math.round(Math.exp(result[0]) * 1e6) / 1e6;
  result[1] = Math.round(Math.exp(result[1]) * 1e6) / 1e6;
  return result;
}
var LOGNORM = {};
LOGNORM.DIST = (x2, mean3, standard_dev, cumulative) => {
  x2 = parseNumber(x2);
  mean3 = parseNumber(mean3);
  standard_dev = parseNumber(standard_dev);
  if (anyIsError(x2, mean3, standard_dev)) {
    return value;
  }
  return cumulative ? import_jstat.default.lognormal.cdf(x2, mean3, standard_dev) : import_jstat.default.lognormal.pdf(x2, mean3, standard_dev);
};
LOGNORM.INV = (probability, mean3, standard_dev) => {
  probability = parseNumber(probability);
  mean3 = parseNumber(mean3);
  standard_dev = parseNumber(standard_dev);
  if (anyIsError(probability, mean3, standard_dev)) {
    return value;
  }
  return import_jstat.default.lognormal.inv(probability, mean3, standard_dev);
};
function MAX() {
  const flatArguments = flatten(arguments);
  const someError = anyError.apply(undefined, flatArguments);
  if (someError) {
    return someError;
  }
  const range2 = numbers2(flatArguments);
  return range2.length === 0 ? 0 : Math.max.apply(Math, range2);
}
function MAXA() {
  const flatArguments = flatten(arguments);
  const someError = anyError.apply(undefined, flatArguments);
  if (someError) {
    return someError;
  }
  let range2 = arrayValuesToNumbers(flatArguments);
  range2 = range2.map((value2) => value2 === undefined || value2 === null ? 0 : value2);
  return range2.length === 0 ? 0 : Math.max.apply(Math, range2);
}
function MAXIFS() {
  const values = applyCriteria(...arguments);
  return values.length === 0 ? 0 : Math.max.apply(Math, values);
}
function MEDIAN() {
  const flatArguments = flatten(arguments);
  const someError = anyError.apply(undefined, flatArguments);
  if (someError) {
    return someError;
  }
  const range2 = arrayValuesToNumbers(flatArguments);
  let result = import_jstat.default.median(range2);
  if (isNaN(result)) {
    result = num;
  }
  return result;
}
function MIN() {
  const flatArguments = flatten(arguments);
  const someError = anyError.apply(undefined, flatArguments);
  if (someError) {
    return someError;
  }
  const range2 = numbers2(flatArguments);
  return range2.length === 0 ? 0 : Math.min.apply(Math, range2);
}
function MINA() {
  const flatArguments = flatten(arguments);
  const someError = anyError.apply(undefined, flatArguments);
  if (someError) {
    return someError;
  }
  let range2 = arrayValuesToNumbers(flatArguments);
  range2 = range2.map((value2) => value2 === undefined || value2 === null ? 0 : value2);
  return range2.length === 0 ? 0 : Math.min.apply(Math, range2);
}
function MINIFS() {
  const values = applyCriteria(...arguments);
  return values.length === 0 ? 0 : Math.min.apply(Math, values);
}
var MODE = {};
MODE.MULT = function() {
  const range2 = parseNumberArray(flatten(arguments));
  if (range2 instanceof Error) {
    return range2;
  }
  const n = range2.length;
  const count3 = {};
  let maxItems = [];
  let max4 = 0;
  let currentItem;
  for (let i = 0;i < n; i++) {
    currentItem = range2[i];
    count3[currentItem] = count3[currentItem] ? count3[currentItem] + 1 : 1;
    if (count3[currentItem] > max4) {
      max4 = count3[currentItem];
      maxItems = [];
    }
    if (count3[currentItem] === max4) {
      maxItems[maxItems.length] = currentItem;
    }
  }
  return maxItems;
};
MODE.SNGL = function() {
  const range2 = parseNumberArray(flatten(arguments));
  if (range2 instanceof Error) {
    return range2;
  }
  return MODE.MULT(range2).sort((a, b) => a - b)[0];
};
var NEGBINOM = {};
NEGBINOM.DIST = (number_f, number_s, probability_s, cumulative) => {
  number_f = parseNumber(number_f);
  number_s = parseNumber(number_s);
  probability_s = parseNumber(probability_s);
  if (anyIsError(number_f, number_s, probability_s)) {
    return value;
  }
  return cumulative ? import_jstat.default.negbin.cdf(number_f, number_s, probability_s) : import_jstat.default.negbin.pdf(number_f, number_s, probability_s);
};
var NORM = {};
NORM.DIST = (x2, mean3, standard_dev, cumulative) => {
  x2 = parseNumber(x2);
  mean3 = parseNumber(mean3);
  standard_dev = parseNumber(standard_dev);
  if (anyIsError(x2, mean3, standard_dev)) {
    return value;
  }
  if (standard_dev <= 0) {
    return num;
  }
  return cumulative ? import_jstat.default.normal.cdf(x2, mean3, standard_dev) : import_jstat.default.normal.pdf(x2, mean3, standard_dev);
};
NORM.INV = (probability, mean3, standard_dev) => {
  probability = parseNumber(probability);
  mean3 = parseNumber(mean3);
  standard_dev = parseNumber(standard_dev);
  if (anyIsError(probability, mean3, standard_dev)) {
    return value;
  }
  return import_jstat.default.normal.inv(probability, mean3, standard_dev);
};
NORM.S = {};
NORM.S.DIST = (z2, cumulative) => {
  z2 = parseNumber(z2);
  if (z2 instanceof Error) {
    return value;
  }
  return cumulative ? import_jstat.default.normal.cdf(z2, 0, 1) : import_jstat.default.normal.pdf(z2, 0, 1);
};
NORM.S.INV = (probability) => {
  probability = parseNumber(probability);
  if (probability instanceof Error) {
    return value;
  }
  return import_jstat.default.normal.inv(probability, 0, 1);
};
function PEARSON(array1, array22) {
  array22 = parseNumberArray(flatten(array22));
  array1 = parseNumberArray(flatten(array1));
  if (anyIsError(array22, array1)) {
    return value;
  }
  const xmean = import_jstat.default.mean(array1);
  const ymean = import_jstat.default.mean(array22);
  const n = array1.length;
  let num2 = 0;
  let den1 = 0;
  let den2 = 0;
  for (let i = 0;i < n; i++) {
    num2 += (array1[i] - xmean) * (array22[i] - ymean);
    den1 += Math.pow(array1[i] - xmean, 2);
    den2 += Math.pow(array22[i] - ymean, 2);
  }
  return num2 / Math.sqrt(den1 * den2);
}
var PERCENTILE = {};
PERCENTILE.EXC = (array3, k) => {
  array3 = parseNumberArray(flatten(array3));
  k = parseNumber(k);
  if (anyIsError(array3, k)) {
    return value;
  }
  array3 = array3.sort((a, b) => a - b);
  const n = array3.length;
  if (k < 1 / (n + 1) || k > 1 - 1 / (n + 1)) {
    return num;
  }
  const l = k * (n + 1) - 1;
  const fl = Math.floor(l);
  return cleanFloat(l === fl ? array3[l] : array3[fl] + (l - fl) * (array3[fl + 1] - array3[fl]));
};
PERCENTILE.INC = (array3, k) => {
  array3 = parseNumberArray(flatten(array3));
  k = parseNumber(k);
  if (anyIsError(array3, k)) {
    return value;
  }
  array3 = array3.sort((a, b) => a - b);
  const n = array3.length;
  const l = k * (n - 1);
  const fl = Math.floor(l);
  return cleanFloat(l === fl ? array3[l] : array3[fl] + (l - fl) * (array3[fl + 1] - array3[fl]));
};
var PERCENTRANK = {};
PERCENTRANK.EXC = (array3, x2, significance) => {
  significance = significance === undefined ? 3 : significance;
  array3 = parseNumberArray(flatten(array3));
  x2 = parseNumber(x2);
  significance = parseNumber(significance);
  if (anyIsError(array3, x2, significance)) {
    return value;
  }
  array3 = array3.sort((a, b) => a - b);
  const uniques = UNIQUE.apply(null, array3);
  const n = array3.length;
  const m = uniques.length;
  const power = Math.pow(10, significance);
  let result = 0;
  let match = false;
  let i = 0;
  while (!match && i < m) {
    if (x2 === uniques[i]) {
      result = (array3.indexOf(uniques[i]) + 1) / (n + 1);
      match = true;
    } else if (x2 >= uniques[i] && (x2 < uniques[i + 1] || i === m - 1)) {
      result = (array3.indexOf(uniques[i]) + 1 + (x2 - uniques[i]) / (uniques[i + 1] - uniques[i])) / (n + 1);
      match = true;
    }
    i++;
  }
  return Math.floor(result * power) / power;
};
PERCENTRANK.INC = (array3, x2, significance) => {
  significance = significance === undefined ? 3 : significance;
  array3 = parseNumberArray(flatten(array3));
  x2 = parseNumber(x2);
  significance = parseNumber(significance);
  if (anyIsError(array3, x2, significance)) {
    return value;
  }
  array3 = array3.sort((a, b) => a - b);
  const uniques = UNIQUE.apply(null, array3);
  const n = array3.length;
  const m = uniques.length;
  const power = Math.pow(10, significance);
  let result = 0;
  let match = false;
  let i = 0;
  while (!match && i < m) {
    if (x2 === uniques[i]) {
      result = array3.indexOf(uniques[i]) / (n - 1);
      match = true;
    } else if (x2 >= uniques[i] && (x2 < uniques[i + 1] || i === m - 1)) {
      result = (array3.indexOf(uniques[i]) + (x2 - uniques[i]) / (uniques[i + 1] - uniques[i])) / (n - 1);
      match = true;
    }
    i++;
  }
  return Math.floor(result * power) / power;
};
function PERMUT(number6, number_chosen) {
  number6 = parseNumber(number6);
  number_chosen = parseNumber(number_chosen);
  if (anyIsError(number6, number_chosen)) {
    return value;
  }
  return FACT(number6) / FACT(number6 - number_chosen);
}
function PERMUTATIONA(number6, number_chosen) {
  number6 = parseNumber(number6);
  number_chosen = parseNumber(number_chosen);
  if (anyIsError(number6, number_chosen)) {
    return value;
  }
  return Math.pow(number6, number_chosen);
}
function PHI2(x2) {
  x2 = parseNumber(x2);
  if (x2 instanceof Error) {
    return value;
  }
  return Math.exp(-0.5 * x2 * x2) / SQRT2PI;
}
var POISSON = {};
POISSON.DIST = (x2, mean3, cumulative) => {
  x2 = parseNumber(x2);
  mean3 = parseNumber(mean3);
  if (anyIsError(x2, mean3)) {
    return value;
  }
  return cumulative ? import_jstat.default.poisson.cdf(x2, mean3) : import_jstat.default.poisson.pdf(x2, mean3);
};
function PROB(x_range, prob_range, lower_limit, upper_limit) {
  if (lower_limit === undefined) {
    return 0;
  }
  upper_limit = upper_limit === undefined ? lower_limit : upper_limit;
  x_range = parseNumberArray(flatten(x_range));
  prob_range = parseNumberArray(flatten(prob_range));
  lower_limit = parseNumber(lower_limit);
  upper_limit = parseNumber(upper_limit);
  if (anyIsError(x_range, prob_range, lower_limit, upper_limit)) {
    return value;
  }
  if (lower_limit === upper_limit) {
    return x_range.indexOf(lower_limit) >= 0 ? prob_range[x_range.indexOf(lower_limit)] : 0;
  }
  const sorted = x_range.sort((a, b) => a - b);
  const n = sorted.length;
  let result = 0;
  for (let i = 0;i < n; i++) {
    if (sorted[i] >= lower_limit && sorted[i] <= upper_limit) {
      result += prob_range[x_range.indexOf(sorted[i])];
    }
  }
  return result;
}
var QUARTILE = {};
QUARTILE.EXC = (range2, quart) => {
  range2 = parseNumberArray(numbers2(flatten(range2)));
  quart = parseNumber(quart);
  if (anyIsError(range2, quart)) {
    return value;
  }
  switch (quart) {
    case 1:
      return PERCENTILE.EXC(range2, 0.25);
    case 2:
      return PERCENTILE.EXC(range2, 0.5);
    case 3:
      return PERCENTILE.EXC(range2, 0.75);
    default:
      return num;
  }
};
QUARTILE.INC = (range2, quart) => {
  range2 = parseNumberArray(numbers2(flatten(range2)));
  quart = parseNumber(quart);
  if (anyIsError(range2, quart)) {
    return value;
  }
  switch (quart) {
    case 1:
      return PERCENTILE.INC(range2, 0.25);
    case 2:
      return PERCENTILE.INC(range2, 0.5);
    case 3:
      return PERCENTILE.INC(range2, 0.75);
    default:
      return num;
  }
};
var RANK = {};
RANK.AVG = (number6, ref2, order) => {
  number6 = parseNumber(number6);
  ref2 = parseNumberArray(flatten(ref2));
  if (anyIsError(number6, ref2)) {
    return value;
  }
  ref2 = flatten(ref2);
  order = order || false;
  const sort = order ? (a, b) => a - b : (a, b) => b - a;
  ref2 = ref2.sort(sort);
  const length2 = ref2.length;
  let count3 = 0;
  for (let i = 0;i < length2; i++) {
    if (ref2[i] === number6) {
      count3++;
    }
  }
  return count3 > 1 ? (2 * ref2.indexOf(number6) + count3 + 1) / 2 : ref2.indexOf(number6) + 1;
};
RANK.EQ = (number6, ref2, order) => {
  number6 = parseNumber(number6);
  ref2 = parseNumberArray(flatten(ref2));
  if (anyIsError(number6, ref2)) {
    return value;
  }
  order = order || false;
  const sort = order ? (a, b) => a - b : (a, b) => b - a;
  ref2 = ref2.sort(sort);
  return ref2.indexOf(number6) + 1;
};
function ROW(reference, index) {
  if (arguments.length !== 2) {
    return na;
  }
  if (index < 0) {
    return num;
  }
  if (!(reference instanceof Array) || typeof index !== "number") {
    return value;
  }
  if (reference.length === 0) {
    return;
  }
  return import_jstat.default.row(reference, index);
}
function RSQ(known_y, known_x) {
  known_y = parseNumberArray(flatten(known_y));
  known_x = parseNumberArray(flatten(known_x));
  if (anyIsError(known_y, known_x)) {
    return value;
  }
  return Math.pow(PEARSON(known_y, known_x), 2);
}
function SKEW() {
  const range2 = parseNumberArray(flatten(arguments));
  if (range2 instanceof Error) {
    return range2;
  }
  const mean3 = import_jstat.default.mean(range2);
  const n = range2.length;
  let sigma = 0;
  for (let i = 0;i < n; i++) {
    sigma += Math.pow(range2[i] - mean3, 3);
  }
  return n * sigma / ((n - 1) * (n - 2) * Math.pow(import_jstat.default.stdev(range2, true), 3));
}
SKEW.P = function() {
  const range2 = parseNumberArray(flatten(arguments));
  if (range2 instanceof Error) {
    return range2;
  }
  const mean3 = import_jstat.default.mean(range2);
  const n = range2.length;
  let m2 = 0;
  let m3 = 0;
  for (let i = 0;i < n; i++) {
    m3 += Math.pow(range2[i] - mean3, 3);
    m2 += Math.pow(range2[i] - mean3, 2);
  }
  m3 = m3 / n;
  m2 = m2 / n;
  return m3 / Math.pow(m2, 3 / 2);
};
function SLOPE(known_y, known_x) {
  known_y = parseNumberArray(flatten(known_y));
  known_x = parseNumberArray(flatten(known_x));
  if (anyIsError(known_y, known_x)) {
    return value;
  }
  const xmean = import_jstat.default.mean(known_x);
  const ymean = import_jstat.default.mean(known_y);
  const n = known_x.length;
  let num2 = 0;
  let den = 0;
  for (let i = 0;i < n; i++) {
    num2 += (known_x[i] - xmean) * (known_y[i] - ymean);
    den += Math.pow(known_x[i] - xmean, 2);
  }
  return num2 / den;
}
function SMALL(array3, k) {
  array3 = parseNumberArray(flatten(array3));
  k = parseNumber(k);
  if (anyIsError(array3, k)) {
    return array3;
  }
  return array3.sort((a, b) => a - b)[k - 1];
}
function STANDARDIZE(x2, mean3, standard_dev) {
  x2 = parseNumber(x2);
  mean3 = parseNumber(mean3);
  standard_dev = parseNumber(standard_dev);
  if (anyIsError(x2, mean3, standard_dev)) {
    return value;
  }
  return (x2 - mean3) / standard_dev;
}
var STDEV = {};
STDEV.P = function() {
  const v = VAR.P.apply(this, arguments);
  let result = Math.sqrt(v);
  if (isNaN(result)) {
    result = num;
  }
  return result;
};
STDEV.S = function() {
  const v = VAR.S.apply(this, arguments);
  const result = Math.sqrt(v);
  return result;
};
function STDEVA() {
  const v = VARA.apply(this, arguments);
  const result = Math.sqrt(v);
  return result;
}
function STDEVPA() {
  const v = VARPA.apply(this, arguments);
  let result = Math.sqrt(v);
  if (isNaN(result)) {
    result = num;
  }
  return result;
}
function STEYX(known_y, known_x) {
  known_y = parseNumberArray(flatten(known_y));
  known_x = parseNumberArray(flatten(known_x));
  if (anyIsError(known_y, known_x)) {
    return value;
  }
  const xmean = import_jstat.default.mean(known_x);
  const ymean = import_jstat.default.mean(known_y);
  const n = known_x.length;
  let lft = 0;
  let num2 = 0;
  let den = 0;
  for (let i = 0;i < n; i++) {
    lft += Math.pow(known_y[i] - ymean, 2);
    num2 += (known_x[i] - xmean) * (known_y[i] - ymean);
    den += Math.pow(known_x[i] - xmean, 2);
  }
  return Math.sqrt((lft - num2 * num2 / den) / (n - 2));
}
T.DIST = (x2, deg_freedom, cumulative) => {
  if (cumulative !== 1 && cumulative !== 2) {
    return num;
  }
  return cumulative === 1 ? T.DIST.RT(x2, deg_freedom) : T.DIST["2T"](x2, deg_freedom);
};
T.DIST["2T"] = function(x2, deg_freedom) {
  if (arguments.length !== 2) {
    return na;
  }
  if (x2 < 0 || deg_freedom < 1) {
    return num;
  }
  if (typeof x2 !== "number" || typeof deg_freedom !== "number") {
    return value;
  }
  return (1 - import_jstat.default.studentt.cdf(x2, deg_freedom)) * 2;
};
T.DIST.RT = function(x2, deg_freedom) {
  if (arguments.length !== 2) {
    return na;
  }
  if (x2 < 0 || deg_freedom < 1) {
    return num;
  }
  if (typeof x2 !== "number" || typeof deg_freedom !== "number") {
    return value;
  }
  return 1 - import_jstat.default.studentt.cdf(x2, deg_freedom);
};
T.INV = (probability, deg_freedom) => {
  probability = parseNumber(probability);
  deg_freedom = parseNumber(deg_freedom);
  if (anyIsError(probability, deg_freedom)) {
    return value;
  }
  return import_jstat.default.studentt.inv(probability, deg_freedom);
};
T.INV["2T"] = (probability, deg_freedom) => {
  probability = parseNumber(probability);
  deg_freedom = parseNumber(deg_freedom);
  if (probability <= 0 || probability > 1 || deg_freedom < 1) {
    return num;
  }
  if (anyIsError(probability, deg_freedom)) {
    return value;
  }
  return Math.abs(import_jstat.default.studentt.inv(probability / 2, deg_freedom));
};
T.TEST = (array1, array22) => {
  array1 = parseNumberArray(flatten(array1));
  array22 = parseNumberArray(flatten(array22));
  if (anyIsError(array1, array22)) {
    return value;
  }
  const mean_x = import_jstat.default.mean(array1);
  const mean_y = import_jstat.default.mean(array22);
  let s_x = 0;
  let s_y = 0;
  let i;
  for (i = 0;i < array1.length; i++) {
    s_x += Math.pow(array1[i] - mean_x, 2);
  }
  for (i = 0;i < array22.length; i++) {
    s_y += Math.pow(array22[i] - mean_y, 2);
  }
  s_x = s_x / (array1.length - 1);
  s_y = s_y / (array22.length - 1);
  const t = Math.abs(mean_x - mean_y) / Math.sqrt(s_x / array1.length + s_y / array22.length);
  return T.DIST["2T"](t, array1.length + array22.length - 2);
};
function TREND(known_ys, known_xs, new_xs) {
  known_ys = parseNumberArray(flatten(known_ys));
  known_xs = parseNumberArray(flatten(known_xs));
  new_xs = parseNumberArray(flatten(new_xs));
  if (anyIsError(known_ys, known_xs, new_xs)) {
    return value;
  }
  const linest = LINEST(known_ys, known_xs);
  const m = linest[0];
  const b = linest[1];
  const result = [];
  new_xs.forEach((x2) => {
    result.push(m * x2 + b);
  });
  return result;
}
function TRIMMEAN(range2, percent) {
  range2 = parseNumberArray(flatten(range2));
  percent = parseNumber(percent);
  if (anyIsError(range2, percent)) {
    return value;
  }
  const trim = FLOOR(range2.length * percent, 2) / 2;
  return import_jstat.default.mean(initial(rest(range2.sort((a, b) => a - b), trim), trim));
}
var VAR = {};
VAR.P = function() {
  const range2 = numbers2(flatten(arguments));
  const n = range2.length;
  let sigma = 0;
  const mean3 = AVERAGE(range2);
  let result;
  for (let i = 0;i < n; i++) {
    sigma += Math.pow(range2[i] - mean3, 2);
  }
  result = sigma / n;
  if (isNaN(result)) {
    result = num;
  }
  return result;
};
VAR.S = function() {
  const range2 = numbers2(flatten(arguments));
  const n = range2.length;
  let sigma = 0;
  const mean3 = AVERAGE(range2);
  for (let i = 0;i < n; i++) {
    sigma += Math.pow(range2[i] - mean3, 2);
  }
  return sigma / (n - 1);
};
function VARA() {
  const range2 = flatten(arguments);
  const n = range2.length;
  let sigma = 0;
  let count3 = 0;
  const mean3 = AVERAGEA(range2);
  for (let i = 0;i < n; i++) {
    const el = range2[i];
    if (typeof el === "number") {
      sigma += Math.pow(el - mean3, 2);
    } else if (el === true) {
      sigma += Math.pow(1 - mean3, 2);
    } else {
      sigma += Math.pow(0 - mean3, 2);
    }
    if (el !== null) {
      count3++;
    }
  }
  return sigma / (count3 - 1);
}
function VARPA() {
  const range2 = flatten(arguments);
  const n = range2.length;
  let sigma = 0;
  let count3 = 0;
  const mean3 = AVERAGEA(range2);
  let result;
  for (let i = 0;i < n; i++) {
    const el = range2[i];
    if (typeof el === "number") {
      sigma += Math.pow(el - mean3, 2);
    } else if (el === true) {
      sigma += Math.pow(1 - mean3, 2);
    } else {
      sigma += Math.pow(0 - mean3, 2);
    }
    if (el !== null) {
      count3++;
    }
  }
  result = sigma / count3;
  if (isNaN(result)) {
    result = num;
  }
  return result;
}
var WEIBULL = {};
WEIBULL.DIST = (x2, alpha, beta, cumulative) => {
  x2 = parseNumber(x2);
  alpha = parseNumber(alpha);
  beta = parseNumber(beta);
  if (anyIsError(x2, alpha, beta)) {
    return value;
  }
  return cumulative ? 1 - Math.exp(-Math.pow(x2 / beta, alpha)) : Math.pow(x2, alpha - 1) * Math.exp(-Math.pow(x2 / beta, alpha)) * alpha / Math.pow(beta, alpha);
};
var Z = {};
Z.TEST = (array3, x2, sigma) => {
  array3 = parseNumberArray(flatten(array3));
  x2 = parseNumber(x2);
  if (anyIsError(array3, x2)) {
    return value;
  }
  sigma = sigma || STDEV.S(array3);
  const n = array3.length;
  return 1 - NORM.S.DIST((AVERAGE(array3) - x2) / (sigma / Math.sqrt(n)), true);
};
function ABS(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  const result = Math.abs(number6);
  return result;
}
function ACOS(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  let result = Math.acos(number6);
  if (isNaN(result)) {
    result = num;
  }
  return result;
}
function ACOSH(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  let result = Math.log(number6 + Math.sqrt(number6 * number6 - 1));
  if (isNaN(result)) {
    result = num;
  }
  return result;
}
function ACOT(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  const result = Math.atan(1 / number6);
  return result;
}
function ACOTH(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  let result = 0.5 * Math.log((number6 + 1) / (number6 - 1));
  if (isNaN(result)) {
    result = num;
  }
  return result;
}
function AGGREGATE(function_num, options, ref1, ref2) {
  function_num = parseNumber(function_num);
  options = parseNumber(function_num);
  if (anyIsError(function_num, options)) {
    return value;
  }
  switch (function_num) {
    case 1:
      return AVERAGE(ref1);
    case 2:
      return COUNT(ref1);
    case 3:
      return COUNTA(ref1);
    case 4:
      return MAX(ref1);
    case 5:
      return MIN(ref1);
    case 6:
      return PRODUCT(ref1);
    case 7:
      return STDEV.S(ref1);
    case 8:
      return STDEV.P(ref1);
    case 9:
      return SUM(ref1);
    case 10:
      return VAR.S(ref1);
    case 11:
      return VAR.P(ref1);
    case 12:
      return MEDIAN(ref1);
    case 13:
      return MODE.SNGL(ref1);
    case 14:
      return LARGE(ref1, ref2);
    case 15:
      return SMALL(ref1, ref2);
    case 16:
      return PERCENTILE.INC(ref1, ref2);
    case 17:
      return QUARTILE.INC(ref1, ref2);
    case 18:
      return PERCENTILE.EXC(ref1, ref2);
    case 19:
      return QUARTILE.EXC(ref1, ref2);
  }
}
function ARABIC(text2) {
  if (text2 === undefined || text2 === null) {
    return 0;
  }
  if (text2 instanceof Error) {
    return text2;
  }
  if (!/^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/.test(text2)) {
    return value;
  }
  let r = 0;
  text2.replace(/[MDLV]|C[MD]?|X[CL]?|I[XV]?/g, (i) => {
    r += {
      M: 1000,
      CM: 900,
      D: 500,
      CD: 400,
      C: 100,
      XC: 90,
      L: 50,
      XL: 40,
      X: 10,
      IX: 9,
      V: 5,
      IV: 4,
      I: 1
    }[i];
  });
  return r;
}
function ASIN(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  let result = Math.asin(number6);
  if (isNaN(result)) {
    result = num;
  }
  return result;
}
function ASINH(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  return Math.log(number6 + Math.sqrt(number6 * number6 + 1));
}
function ATAN(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  return Math.atan(number6);
}
function ATAN2(x_num, y_num) {
  x_num = parseNumber(x_num);
  y_num = parseNumber(y_num);
  const anyError$1 = anyError(x_num, y_num);
  if (anyError$1) {
    return anyError$1;
  }
  return Math.atan2(x_num, y_num);
}
function ATANH(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  let result = Math.log((1 + number6) / (1 - number6)) / 2;
  if (isNaN(result)) {
    result = num;
  }
  return result;
}
function CEILING(number6, significance) {
  number6 = parseNumber(number6);
  significance = parseNumber(significance);
  const anyError$1 = anyError(number6, significance);
  if (anyError$1) {
    return anyError$1;
  }
  if (significance === 0) {
    return 0;
  }
  if (number6 > 0 && significance < 0) {
    return num;
  }
  return Math.ceil(number6 / significance) * significance;
}
CEILING.MATH = (number6, significance, mode = 0) => {
  if (significance === undefined) {
    significance = number6 > 0 ? 1 : -1;
  }
  number6 = parseNumber(number6);
  significance = parseNumber(significance);
  mode = parseNumber(mode);
  const anyError$1 = anyError(number6, significance, mode);
  if (anyError$1) {
    return anyError$1;
  }
  if (significance === 0) {
    return 0;
  }
  significance = Math.abs(significance);
  if (mode === 0) {
    return Math.ceil(number6 / significance) * significance;
  } else {
    return number6 > 0 ? Math.ceil(number6 / significance) * significance : Math.floor(number6 / significance) * significance;
  }
};
CEILING.PRECISE = (number6, significance) => {
  return CEILING.MATH(number6, significance);
};
function COMBIN(number6, number_chosen) {
  number6 = parseNumber(number6);
  number_chosen = parseNumber(number_chosen);
  const anyError$1 = anyError(number6, number_chosen);
  if (anyError$1) {
    return anyError$1;
  }
  if (number6 < number_chosen) {
    return num;
  }
  return FACT(number6) / (FACT(number_chosen) * FACT(number6 - number_chosen));
}
function COMBINA(number6, number_chosen) {
  number6 = parseNumber(number6);
  number_chosen = parseNumber(number_chosen);
  const anyError$1 = anyError(number6, number_chosen);
  if (anyError$1) {
    return anyError$1;
  }
  if (number6 < number_chosen) {
    return num;
  }
  return number6 === 0 && number_chosen === 0 ? 1 : COMBIN(number6 + number_chosen - 1, number6 - 1);
}
function COS(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  return Math.cos(number6);
}
function COSH(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  return (Math.exp(number6) + Math.exp(-number6)) / 2;
}
function COT(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  if (number6 === 0) {
    return div0;
  }
  return 1 / Math.tan(number6);
}
function COTH(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  if (number6 === 0) {
    return div0;
  }
  const e22 = Math.exp(2 * number6);
  return (e22 + 1) / (e22 - 1);
}
function CSC(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  if (number6 === 0) {
    return div0;
  }
  return 1 / Math.sin(number6);
}
function CSCH(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  if (number6 === 0) {
    return div0;
  }
  return 2 / (Math.exp(number6) - Math.exp(-number6));
}
function DECIMAL(text2, radix) {
  if (arguments.length < 2) {
    return na;
  }
  text2 = text2 || "0";
  radix = parseNumber(radix);
  const anyError$1 = anyError(text2, radix);
  if (anyError$1) {
    return anyError$1;
  }
  if (radix === 0) {
    return num;
  }
  const result = parseInt(text2, radix);
  if (isNaN(result)) {
    return num;
  }
  return result;
}
function DEGREES(angle) {
  angle = parseNumber(angle);
  if (angle instanceof Error) {
    return angle;
  }
  return angle * 180 / Math.PI;
}
function EVEN(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  return CEILING.MATH(number6, -2, -1);
}
function EXP(number6) {
  if (arguments.length < 1) {
    return na;
  }
  if (arguments.length > 1) {
    return error48;
  }
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  number6 = Math.exp(number6);
  return number6;
}
var MEMOIZED_FACT = [];
function FACT(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  const n = Math.floor(number6);
  if (n === 0 || n === 1) {
    return 1;
  } else if (MEMOIZED_FACT[n] > 0) {
    return MEMOIZED_FACT[n];
  } else {
    MEMOIZED_FACT[n] = FACT(n - 1) * n;
    return MEMOIZED_FACT[n];
  }
}
function FLOOR(number6, significance) {
  number6 = parseNumber(number6);
  significance = parseNumber(significance);
  const anyError$1 = anyError(number6, significance);
  if (anyError$1) {
    return anyError$1;
  }
  if (!significance) {
    return div0;
  }
  if (number6 > 0 && significance < 0) {
    return num;
  }
  return Math.floor(number6 / significance) * significance;
}
FLOOR.MATH = (number6, significance = 1, mode = 0) => {
  number6 = parseNumber(number6);
  significance = parseNumber(significance);
  mode = parseNumber(mode);
  const anyError$1 = anyError(number6, significance, mode);
  if (anyError$1) {
    return anyError$1;
  }
  if (significance === 0) {
    return 0;
  }
  significance = Math.abs(significance);
  if (mode === 0) {
    return Math.floor(number6 / significance) * significance;
  } else {
    return number6 > 0 ? Math.floor(number6 / significance) * significance : Math.ceil(number6 / significance) * significance;
  }
};
FLOOR.PRECISE = (number6, significance) => {
  return FLOOR.MATH(number6, significance);
};
function GCD() {
  const range2 = parseNumberArray(flatten(arguments));
  if (range2 instanceof Error) {
    return range2;
  }
  const n = range2.length;
  const r0 = range2[0];
  let x2 = r0 < 0 ? -r0 : r0;
  for (let i = 1;i < n; i++) {
    const ri = range2[i];
    let y2 = ri < 0 ? -ri : ri;
    while (x2 && y2) {
      if (x2 > y2) {
        x2 %= y2;
      } else {
        y2 %= x2;
      }
    }
    x2 += y2;
  }
  return x2;
}
function INT(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  return Math.floor(number6);
}
function LCM() {
  const o = parseNumberArray(flatten(arguments));
  if (o instanceof Error) {
    return o;
  }
  for (var i, j, n, d, r = 1;(n = o.pop()) !== undefined; ) {
    if (n === 0) {
      return 0;
    }
    while (n > 1) {
      if (n % 2) {
        for (i = 3, j = Math.floor(Math.sqrt(n));i <= j && n % i; i += 2) {}
        d = i <= j ? i : n;
      } else {
        d = 2;
      }
      for (n /= d, r *= d, i = o.length;i; o[--i] % d === 0 && (o[i] /= d) === 1 && o.splice(i, 1)) {}
    }
  }
  return r;
}
function LN(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  if (number6 === 0) {
    return num;
  }
  return Math.log(number6);
}
function LOG(number6, base) {
  number6 = parseNumber(number6);
  base = base ? parseNumber(base) : 10;
  const anyError$1 = anyError(number6, base);
  if (anyError$1) {
    return anyError$1;
  }
  if (number6 === 0 || base === 0) {
    return num;
  }
  return Math.log(number6) / Math.log(base);
}
function LOG10(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  if (number6 === 0) {
    return num;
  }
  return Math.log(number6) / Math.log(10);
}
function MMULT(array1, array22) {
  if (!Array.isArray(array1) || !Array.isArray(array22) || array1.some((el) => !el.length) || array22.some((el) => !el.length) || flattenShallow(array1).some((el) => typeof el !== "number") || flattenShallow(array22).some((el) => typeof el !== "number") || array1[0].length !== array22.length) {
    return value;
  }
  const matrix = Array(array1.length).fill(0).map(() => Array(array22[0].length).fill(0));
  return matrix.map((row2, i) => row2.map((_, j) => array1[i].reduce((sum2, el, k) => sum2 + el * array22[k][j], 0)));
}
function MOD(number6, divisor) {
  number6 = parseNumber(number6);
  divisor = parseNumber(divisor);
  const anyError$1 = anyError(number6, divisor);
  if (anyError$1) {
    return anyError$1;
  }
  if (divisor === 0) {
    return div0;
  }
  let modulus = Math.abs(number6 % divisor);
  modulus = number6 < 0 ? divisor - modulus : modulus;
  return divisor > 0 ? modulus : -modulus;
}
function MROUND(number6, multiple) {
  number6 = parseNumber(number6);
  multiple = parseNumber(multiple);
  const anyError$1 = anyError(number6, multiple);
  if (anyError$1) {
    return anyError$1;
  }
  if (number6 * multiple === 0) {
    return 0;
  }
  if (number6 * multiple < 0) {
    return num;
  }
  return Math.round(number6 / multiple) * multiple;
}
function MULTINOMIAL() {
  const args2 = parseNumberArray(flatten(arguments));
  if (args2 instanceof Error) {
    return args2;
  }
  let sum2 = 0;
  let divisor = 1;
  for (let i = 0;i < args2.length; i++) {
    sum2 += args2[i];
    divisor *= FACT(args2[i]);
  }
  return FACT(sum2) / divisor;
}
function MUNIT(dimension) {
  if (arguments.length > 1) {
    return na;
  }
  dimension = parseInt(dimension);
  if (!dimension || dimension <= 0) {
    return value;
  }
  return Array(dimension).fill(0).map(() => Array(dimension).fill(0)).map((el, i) => {
    el[i] = 1;
    return el;
  });
}
function ODD(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  let temp = Math.ceil(Math.abs(number6));
  temp = temp & 1 ? temp : temp + 1;
  return number6 >= 0 ? temp : -temp;
}
function PI() {
  return Math.PI;
}
function POWER(number6, power) {
  number6 = parseNumber(number6);
  power = parseNumber(power);
  const anyError$1 = anyError(number6, power);
  if (anyError$1) {
    return anyError$1;
  }
  if (number6 === 0 && power === 0) {
    return num;
  }
  const result = Math.pow(number6, power);
  if (isNaN(result)) {
    return num;
  }
  return result;
}
function PRODUCT() {
  const flatArguments = flatten(arguments);
  const flatArgumentsDefined = flatArguments.filter((arg) => arg !== undefined && arg !== null);
  if (flatArgumentsDefined.length === 0) {
    return 0;
  }
  const args2 = parseNumberArray(flatArgumentsDefined);
  if (args2 instanceof Error) {
    return args2;
  }
  let result = 1;
  for (let i = 0;i < args2.length; i++) {
    result *= args2[i];
  }
  return result;
}
function RADIANS(angle) {
  angle = parseNumber(angle);
  if (angle instanceof Error) {
    return angle;
  }
  return angle * Math.PI / 180;
}
function RAND() {
  return Math.random();
}
function ROMAN(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  const digits = String(number6).split("");
  const key = [
    "",
    "C",
    "CC",
    "CCC",
    "CD",
    "D",
    "DC",
    "DCC",
    "DCCC",
    "CM",
    "",
    "X",
    "XX",
    "XXX",
    "XL",
    "L",
    "LX",
    "LXX",
    "LXXX",
    "XC",
    "",
    "I",
    "II",
    "III",
    "IV",
    "V",
    "VI",
    "VII",
    "VIII",
    "IX"
  ];
  let roman = "";
  let i = 3;
  while (i--) {
    roman = (key[+digits.pop() + i * 10] || "") + roman;
  }
  return new Array(+digits.join("") + 1).join("M") + roman;
}
function roundBase(number6, num_digits, roundFn) {
  number6 = parseNumber(number6);
  num_digits = parseNumber(num_digits);
  const anyError$1 = anyError(number6, num_digits);
  if (anyError$1) {
    return anyError$1;
  }
  const sign2 = number6 >= 0 ? 1 : -1;
  const val = Math.abs(number6);
  let pair = (val + "e" + num_digits).split("e");
  const shifted = roundFn(pair[0] + "e" + pair[1]);
  pair = (shifted + "e" + -num_digits).split("e");
  const rounded = Number(pair[0] + "e" + pair[1]);
  return rounded * sign2;
}
function ROUND(number6, num_digits) {
  return roundBase(number6, num_digits, Math.round);
}
function ROUNDDOWN(number6, num_digits) {
  return roundBase(number6, num_digits, Math.floor);
}
function ROUNDUP(number6, num_digits) {
  return roundBase(number6, num_digits, Math.ceil);
}
function SEC(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  return 1 / Math.cos(number6);
}
function SECH(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  return 2 / (Math.exp(number6) + Math.exp(-number6));
}
function SERIESSUM(x2, n, m, coefficients) {
  x2 = parseNumber(x2);
  n = parseNumber(n);
  m = parseNumber(m);
  coefficients = parseNumberArray(coefficients);
  if (anyIsError(x2, n, m, coefficients)) {
    return value;
  }
  let result = coefficients[0] * Math.pow(x2, n);
  for (let i = 1;i < coefficients.length; i++) {
    result += coefficients[i] * Math.pow(x2, n + i * m);
  }
  return result;
}
function SIGN(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  if (number6 < 0) {
    return -1;
  } else if (number6 === 0) {
    return 0;
  } else {
    return 1;
  }
}
function SIN(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  return Math.sin(number6);
}
function SINH(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  return (Math.exp(number6) - Math.exp(-number6)) / 2;
}
function SQRT(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  if (number6 < 0) {
    return num;
  }
  return Math.sqrt(number6);
}
function SQRTPI(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  return Math.sqrt(number6 * Math.PI);
}
function SUBTOTAL(function_num, ref1) {
  function_num = parseNumber(function_num);
  if (function_num instanceof Error) {
    return function_num;
  }
  switch (function_num) {
    case 1:
      return AVERAGE(ref1);
    case 2:
      return COUNT(ref1);
    case 3:
      return COUNTA(ref1);
    case 4:
      return MAX(ref1);
    case 5:
      return MIN(ref1);
    case 6:
      return PRODUCT(ref1);
    case 7:
      return STDEV.S(ref1);
    case 8:
      return STDEV.P(ref1);
    case 9:
      return SUM(ref1);
    case 10:
      return VAR.S(ref1);
    case 11:
      return VAR.P(ref1);
    case 101:
      return AVERAGE(ref1);
    case 102:
      return COUNT(ref1);
    case 103:
      return COUNTA(ref1);
    case 104:
      return MAX(ref1);
    case 105:
      return MIN(ref1);
    case 106:
      return PRODUCT(ref1);
    case 107:
      return STDEV.S(ref1);
    case 108:
      return STDEV.P(ref1);
    case 109:
      return SUM(ref1);
    case 110:
      return VAR.S(ref1);
    case 111:
      return VAR.P(ref1);
  }
}
function SUM() {
  let result = 0;
  arrayEach(argsToArray(arguments), (value2) => {
    if (result instanceof Error) {
      return false;
    } else if (value2 instanceof Error) {
      result = value2;
    } else if (typeof value2 === "number") {
      result += value2;
    } else if (typeof value2 === "string") {
      const parsed = parseFloat(value2);
      !isNaN(parsed) && (result += parsed);
    } else if (Array.isArray(value2)) {
      const inner_result = SUM.apply(null, value2);
      if (inner_result instanceof Error) {
        result = inner_result;
      } else {
        result += inner_result;
      }
    }
  });
  return result;
}
function SUMIFS() {
  const values = applyCriteria(...arguments);
  return SUM(values);
}
function SUMX2MY2(array_x, array_y) {
  array_x = parseNumberArray(flatten(array_x));
  array_y = parseNumberArray(flatten(array_y));
  if (anyIsError(array_x, array_y)) {
    return value;
  }
  let result = 0;
  for (let i = 0;i < array_x.length; i++) {
    result += array_x[i] * array_x[i] - array_y[i] * array_y[i];
  }
  return result;
}
function SUMX2PY2(array_x, array_y) {
  array_x = parseNumberArray(flatten(array_x));
  array_y = parseNumberArray(flatten(array_y));
  if (anyIsError(array_x, array_y)) {
    return value;
  }
  let result = 0;
  array_x = parseNumberArray(flatten(array_x));
  array_y = parseNumberArray(flatten(array_y));
  for (let i = 0;i < array_x.length; i++) {
    result += array_x[i] * array_x[i] + array_y[i] * array_y[i];
  }
  return result;
}
function SUMXMY2(array_x, array_y) {
  array_x = parseNumberArray(flatten(array_x));
  array_y = parseNumberArray(flatten(array_y));
  if (anyIsError(array_x, array_y)) {
    return value;
  }
  let result = 0;
  array_x = flatten(array_x);
  array_y = flatten(array_y);
  for (let i = 0;i < array_x.length; i++) {
    result += Math.pow(array_x[i] - array_y[i], 2);
  }
  return result;
}
function TAN(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  return Math.tan(number6);
}
function TANH(number6) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  const e22 = Math.exp(2 * number6);
  return (e22 - 1) / (e22 + 1);
}
function TRUNC(number6, num_digits) {
  number6 = parseNumber(number6);
  num_digits = parseNumber(num_digits);
  const anyError$1 = anyError(number6, num_digits);
  if (anyError$1) {
    return anyError$1;
  }
  const sign2 = number6 > 0 ? 1 : -1;
  return sign2 * Math.floor(Math.abs(number6) * Math.pow(10, num_digits)) / Math.pow(10, num_digits);
}
function ADD(num1, num2) {
  if (arguments.length !== 2) {
    return na;
  }
  num1 = parseNumber(num1);
  num2 = parseNumber(num2);
  const anyError$1 = anyError(num1, num2);
  if (anyError$1) {
    return anyError$1;
  }
  return num1 + num2;
}
function DIVIDE(dividend, divisor) {
  if (arguments.length !== 2) {
    return na;
  }
  dividend = parseNumber(dividend);
  divisor = parseNumber(divisor);
  const anyError$1 = anyError(dividend, divisor);
  if (anyError$1) {
    return anyError$1;
  }
  if (divisor === 0) {
    return div0;
  }
  return dividend / divisor;
}
function EQ(value1, value2) {
  if (arguments.length !== 2) {
    return na;
  }
  if (value1 instanceof Error) {
    return value1;
  }
  if (value2 instanceof Error) {
    return value2;
  }
  if (value1 === null) {
    value1 = undefined;
  }
  if (value2 === null) {
    value2 = undefined;
  }
  return value1 === value2;
}
function GT(num1, num2) {
  if (arguments.length !== 2) {
    return na;
  }
  if (num1 instanceof Error) {
    return num1;
  }
  if (num2 instanceof Error) {
    return num2;
  }
  if (anyIsString(num1, num2)) {
    num1 = parseString(num1);
    num2 = parseString(num2);
  } else {
    num1 = parseNumber(num1);
    num2 = parseNumber(num2);
  }
  const anyError$1 = anyError(num1, num2);
  if (anyError$1) {
    return anyError$1;
  }
  return num1 > num2;
}
function GTE(num1, num2) {
  if (arguments.length !== 2) {
    return na;
  }
  if (anyIsString(num1, num2)) {
    num1 = parseString(num1);
    num2 = parseString(num2);
  } else {
    num1 = parseNumber(num1);
    num2 = parseNumber(num2);
  }
  const anyError$1 = anyError(num1, num2);
  if (anyError$1) {
    return anyError$1;
  }
  return num1 >= num2;
}
function LT(num1, num2) {
  if (arguments.length !== 2) {
    return na;
  }
  if (anyIsString(num1, num2)) {
    num1 = parseString(num1);
    num2 = parseString(num2);
  } else {
    num1 = parseNumber(num1);
    num2 = parseNumber(num2);
  }
  const anyError$1 = anyError(num1, num2);
  if (anyError$1) {
    return anyError$1;
  }
  return num1 < num2;
}
function LTE(num1, num2) {
  if (arguments.length !== 2) {
    return na;
  }
  if (anyIsString(num1, num2)) {
    num1 = parseString(num1);
    num2 = parseString(num2);
  } else {
    num1 = parseNumber(num1);
    num2 = parseNumber(num2);
  }
  const anyError$1 = anyError(num1, num2);
  if (anyError$1) {
    return anyError$1;
  }
  return num1 <= num2;
}
function MINUS(num1, num2) {
  if (arguments.length !== 2) {
    return na;
  }
  num1 = parseNumber(num1);
  num2 = parseNumber(num2);
  const anyError$1 = anyError(num1, num2);
  if (anyError$1) {
    return anyError$1;
  }
  return num1 - num2;
}
function MULTIPLY(factor1, factor2) {
  if (arguments.length !== 2) {
    return na;
  }
  factor1 = parseNumber(factor1);
  factor2 = parseNumber(factor2);
  const anyError$1 = anyError(factor1, factor2);
  if (anyError$1) {
    return anyError$1;
  }
  return factor1 * factor2;
}
function NE(value1, value2) {
  if (arguments.length !== 2) {
    return na;
  }
  if (value1 instanceof Error) {
    return value1;
  }
  if (value2 instanceof Error) {
    return value2;
  }
  if (value1 === null) {
    value1 = undefined;
  }
  if (value2 === null) {
    value2 = undefined;
  }
  return value1 !== value2;
}
function POW(base, exponent) {
  if (arguments.length !== 2) {
    return na;
  }
  return POWER(base, exponent);
}
var symbols = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  ADD,
  DIVIDE,
  EQ,
  GT,
  GTE,
  LT,
  LTE,
  MINUS,
  MULTIPLY,
  NE,
  POW
});
var WEEK_STARTS = [
  undefined,
  0,
  1,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  1,
  2,
  3,
  4,
  5,
  6,
  0
];
var WEEK_TYPES = [
  [],
  [1, 2, 3, 4, 5, 6, 7],
  [7, 1, 2, 3, 4, 5, 6],
  [6, 0, 1, 2, 3, 4, 5],
  [],
  [],
  [],
  [],
  [],
  [],
  [],
  [7, 1, 2, 3, 4, 5, 6],
  [6, 7, 1, 2, 3, 4, 5],
  [5, 6, 7, 1, 2, 3, 4],
  [4, 5, 6, 7, 1, 2, 3],
  [3, 4, 5, 6, 7, 1, 2],
  [2, 3, 4, 5, 6, 7, 1],
  [1, 2, 3, 4, 5, 6, 7]
];
var WEEKEND_TYPES = [
  [],
  [6, 0],
  [0, 1],
  [1, 2],
  [2, 3],
  [3, 4],
  [4, 5],
  [5, 6],
  undefined,
  undefined,
  undefined,
  [0, 0],
  [1, 1],
  [2, 2],
  [3, 3],
  [4, 4],
  [5, 5],
  [6, 6]
];
function DATE(year, month, day) {
  let result;
  year = parseNumber(year);
  month = parseNumber(month);
  day = parseNumber(day);
  if (anyIsError(year, month, day)) {
    result = value;
  } else {
    result = new Date(year, month - 1, day);
    if (result.getFullYear() < 0) {
      result = num;
    }
  }
  return returnSerial ? dateToSerial(result) : result;
}
function DATEDIF(start_date, end_date, unit2) {
  unit2 = unit2.toUpperCase();
  start_date = parseDate(start_date);
  end_date = parseDate(end_date);
  const start_date_year = start_date.getFullYear();
  const start_date_month = start_date.getMonth();
  const start_date_day = start_date.getDate();
  const end_date_year = end_date.getFullYear();
  const end_date_month = end_date.getMonth();
  const end_date_day = end_date.getDate();
  let result;
  switch (unit2) {
    case "Y":
      result = Math.floor(YEARFRAC(start_date, end_date));
      break;
    case "D":
      result = DAYS(end_date, start_date);
      break;
    case "M":
      result = end_date_month - start_date_month + 12 * (end_date_year - start_date_year);
      if (end_date_day < start_date_day) {
        result--;
      }
      break;
    case "MD":
      if (start_date_day <= end_date_day) {
        result = end_date_day - start_date_day;
      } else {
        if (end_date_month === 0) {
          start_date.setFullYear(end_date_year - 1);
          start_date.setMonth(12);
        } else {
          start_date.setFullYear(end_date_year);
          start_date.setMonth(end_date_month - 1);
        }
        result = DAYS(end_date, start_date);
      }
      break;
    case "YM":
      result = end_date_month - start_date_month + 12 * (end_date_year - start_date_year);
      if (end_date_day < start_date_day) {
        result--;
      }
      result = result % 12;
      break;
    case "YD":
      if (end_date_month > start_date_month || end_date_month === start_date_month && end_date_day < start_date_day) {
        start_date.setFullYear(end_date_year);
      } else {
        start_date.setFullYear(end_date_year - 1);
      }
      result = DAYS(end_date, start_date);
      break;
  }
  return result;
}
function DATEVALUE(date_text) {
  if (typeof date_text !== "string") {
    return value;
  }
  const date6 = Date.parse(date_text);
  if (isNaN(date6)) {
    return value;
  }
  const dateValue = new Date(date_text);
  return returnSerial ? dateToSerial(dateValue) : dateValue;
}
function DAY(serial_number) {
  const date6 = parseDate(serial_number);
  if (date6 instanceof Error) {
    return date6;
  }
  return date6.getDate();
}
function startOfDay(date6) {
  const newDate = new Date(date6);
  newDate.setHours(0, 0, 0, 0);
  return newDate;
}
function DAYS(end_date, start_date) {
  end_date = parseDate(end_date);
  start_date = parseDate(start_date);
  if (end_date instanceof Error) {
    return end_date;
  }
  if (start_date instanceof Error) {
    return start_date;
  }
  return dateToSerial(startOfDay(end_date)) - dateToSerial(startOfDay(start_date));
}
function DAYS360(start_date, end_date, method) {
  method = parseBool(method || "false");
  start_date = parseDate(start_date);
  end_date = parseDate(end_date);
  if (start_date instanceof Error) {
    return start_date;
  }
  if (end_date instanceof Error) {
    return end_date;
  }
  if (method instanceof Error) {
    return method;
  }
  const sm = start_date.getMonth();
  let em = end_date.getMonth();
  let sd, ed;
  if (method) {
    sd = start_date.getDate() === 31 ? 30 : start_date.getDate();
    ed = end_date.getDate() === 31 ? 30 : end_date.getDate();
  } else {
    const smd = new Date(start_date.getFullYear(), sm + 1, 0).getDate();
    const emd = new Date(end_date.getFullYear(), em + 1, 0).getDate();
    sd = start_date.getDate() === smd ? 30 : start_date.getDate();
    if (end_date.getDate() === emd) {
      if (sd < 30) {
        em++;
        ed = 1;
      } else {
        ed = 30;
      }
    } else {
      ed = end_date.getDate();
    }
  }
  return 360 * (end_date.getFullYear() - start_date.getFullYear()) + 30 * (em - sm) + (ed - sd);
}
function EDATE(start_date, months) {
  start_date = parseDate(start_date);
  if (start_date instanceof Error) {
    return start_date;
  }
  if (isNaN(months)) {
    return value;
  }
  let storedDay = start_date.getDate();
  start_date.setDate(1);
  months = parseInt(months, 10);
  start_date.setMonth(start_date.getMonth() + months);
  let targetMonth = start_date.getMonth();
  if (storedDay > 28) {
    let daysInTargetMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][targetMonth];
    let targetYear = start_date.getFullYear();
    if (targetMonth === 1 && (targetYear % 4 === 0 && targetYear % 100 !== 0 || targetYear % 400 === 0)) {
      daysInTargetMonth = 29;
    }
    storedDay = Math.min(storedDay, daysInTargetMonth);
  }
  start_date.setDate(storedDay);
  return returnSerial ? dateToSerial(start_date) : start_date;
}
function EOMONTH(start_date, months) {
  start_date = parseDate(start_date);
  if (start_date instanceof Error) {
    return start_date;
  }
  if (isNaN(months)) {
    return value;
  }
  months = parseInt(months, 10);
  const eoMonth = new Date(start_date.getFullYear(), start_date.getMonth() + months + 1, 0);
  return returnSerial ? dateToSerial(eoMonth) : eoMonth;
}
function HOUR(serial_number) {
  serial_number = parseDate(serial_number);
  if (serial_number instanceof Error) {
    return serial_number;
  }
  return serial_number.getHours();
}
function ISOWEEKNUM(date6) {
  date6 = parseDate(date6);
  if (date6 instanceof Error) {
    return date6;
  }
  date6 = startOfDay(date6);
  date6.setDate(date6.getDate() + 4 - (date6.getDay() || 7));
  const yearStart = new Date(date6.getFullYear(), 0, 1);
  return Math.ceil(((date6 - yearStart) / 86400000 + 1) / 7);
}
function MINUTE(serial_number) {
  serial_number = parseDate(serial_number);
  if (serial_number instanceof Error) {
    return serial_number;
  }
  return serial_number.getMinutes();
}
function MONTH(serial_number) {
  serial_number = parseDate(serial_number);
  if (serial_number instanceof Error) {
    return serial_number;
  }
  return serial_number.getMonth() + 1;
}
function NETWORKDAYS(start_date, end_date, holidays) {
  return NETWORKDAYS.INTL(start_date, end_date, 1, holidays);
}
NETWORKDAYS.INTL = (start_date, end_date, weekend, holidays) => {
  start_date = parseDate(start_date);
  if (start_date instanceof Error) {
    return start_date;
  }
  end_date = parseDate(end_date);
  if (end_date instanceof Error) {
    return end_date;
  }
  let isMask = false;
  const maskDays = [];
  const maskIndex = [1, 2, 3, 4, 5, 6, 0];
  const maskRegex = new RegExp("^[0|1]{7}$");
  if (weekend === undefined) {
    weekend = WEEKEND_TYPES[1];
  } else if (typeof weekend === "string" && maskRegex.test(weekend)) {
    isMask = true;
    weekend = weekend.split("");
    for (let i = 0;i < weekend.length; i++) {
      if (weekend[i] === "1") {
        maskDays.push(maskIndex[i]);
      }
    }
  } else {
    weekend = WEEKEND_TYPES[weekend];
  }
  if (!(weekend instanceof Array)) {
    return value;
  }
  if (holidays === undefined) {
    holidays = [];
  } else if (!(holidays instanceof Array)) {
    holidays = [holidays];
  }
  for (let i = 0;i < holidays.length; i++) {
    const h = parseDate(holidays[i]);
    if (h instanceof Error) {
      return h;
    }
    holidays[i] = h;
  }
  const days = Math.round((end_date - start_date) / (1000 * 60 * 60 * 24)) + 1;
  let total = days;
  const day = start_date;
  for (let i = 0;i < days; i++) {
    const d = new Date().getTimezoneOffset() > 0 ? day.getUTCDay() : day.getDay();
    let dec = isMask ? maskDays.includes(d) : d === weekend[0] || d === weekend[1];
    for (let j = 0;j < holidays.length; j++) {
      const holiday = holidays[j];
      if (holiday.getDate() === day.getDate() && holiday.getMonth() === day.getMonth() && holiday.getFullYear() === day.getFullYear()) {
        dec = true;
        break;
      }
    }
    if (dec) {
      total--;
    }
    day.setDate(day.getDate() + 1);
  }
  return total;
};
function NOW() {
  return returnSerial ? dateToSerial(new Date) : new Date;
}
function SECOND(serial_number) {
  serial_number = parseDate(serial_number);
  if (serial_number instanceof Error) {
    return serial_number;
  }
  return serial_number.getSeconds();
}
function TIME(hour, minute, second) {
  hour = parseNumber(hour);
  minute = parseNumber(minute);
  second = parseNumber(second);
  if (anyIsError(hour, minute, second)) {
    return value;
  }
  if (hour < 0 || minute < 0 || second < 0) {
    return num;
  }
  return (3600 * hour + 60 * minute + second) / 86400;
}
function TIMEVALUE(time_text) {
  time_text = parseDate(time_text);
  if (time_text instanceof Error) {
    return time_text;
  }
  return (3600 * time_text.getHours() + 60 * time_text.getMinutes() + time_text.getSeconds()) / 86400;
}
function TODAY() {
  const today = startOfDay(new Date);
  return returnSerial ? dateToSerial(today) : today;
}
function WEEKDAY(serial_number, return_type) {
  serial_number = parseDate(serial_number);
  if (serial_number instanceof Error) {
    return serial_number;
  }
  if (return_type === undefined) {
    return_type = 1;
  }
  const day = serial_number.getDay();
  return WEEK_TYPES[return_type][day];
}
function WEEKNUM(serial_number, return_type) {
  serial_number = parseDate(serial_number);
  if (serial_number instanceof Error) {
    return serial_number;
  }
  if (return_type === undefined) {
    return_type = 1;
  }
  if (return_type === 21) {
    return ISOWEEKNUM(serial_number);
  }
  const week_start = WEEK_STARTS[return_type];
  let jan = new Date(serial_number.getFullYear(), 0, 1);
  const inc = jan.getDay() < week_start ? 1 : 0;
  jan -= Math.abs(jan.getDay() - week_start) * 24 * 60 * 60 * 1000;
  return Math.floor((serial_number - jan) / (1000 * 60 * 60 * 24) / 7 + 1) + inc;
}
function WORKDAY(start_date, days, holidays) {
  return WORKDAY.INTL(start_date, days, 1, holidays);
}
WORKDAY.INTL = (start_date, days, weekend, holidays) => {
  start_date = parseDate(start_date);
  if (start_date instanceof Error) {
    return start_date;
  }
  days = parseNumber(days);
  if (days instanceof Error) {
    return days;
  }
  if (weekend === undefined) {
    weekend = WEEKEND_TYPES[1];
  } else {
    weekend = WEEKEND_TYPES[weekend];
  }
  if (!(weekend instanceof Array)) {
    return value;
  }
  if (holidays === undefined) {
    holidays = [];
  } else if (!(holidays instanceof Array)) {
    holidays = [holidays];
  }
  for (let i = 0;i < holidays.length; i++) {
    const h = parseDate(holidays[i]);
    if (h instanceof Error) {
      return h;
    }
    holidays[i] = h;
  }
  let d = 0;
  const sign2 = Math.sign(days);
  while (d < days * sign2) {
    start_date.setDate(start_date.getDate() + sign2);
    const day = start_date.getDay();
    if (day === weekend[0] || day === weekend[1]) {
      continue;
    }
    for (let j = 0;j < holidays.length; j++) {
      const holiday = holidays[j];
      if (holiday.getDate() === start_date.getDate() && holiday.getMonth() === start_date.getMonth() && holiday.getFullYear() === start_date.getFullYear()) {
        d--;
        break;
      }
    }
    d++;
  }
  if (start_date.getFullYear() < 1900) {
    return value;
  }
  return start_date;
};
function YEAR(serial_number) {
  serial_number = parseDate(serial_number);
  if (serial_number instanceof Error) {
    return serial_number;
  }
  return serial_number.getFullYear();
}
function isLeapYear(year) {
  return new Date(year, 1, 29).getMonth() === 1;
}
function daysBetween(start_date, end_date) {
  return Math.ceil((end_date - start_date) / 1000 / 60 / 60 / 24);
}
function YEARFRAC(start_date, end_date, basis2) {
  start_date = parseDate(start_date);
  if (start_date instanceof Error) {
    return start_date;
  }
  end_date = parseDate(end_date);
  if (end_date instanceof Error) {
    return end_date;
  }
  basis2 = basis2 || 0;
  let sd = start_date.getDate();
  const sm = start_date.getMonth() + 1;
  const sy = start_date.getFullYear();
  let ed = end_date.getDate();
  const em = end_date.getMonth() + 1;
  const ey = end_date.getFullYear();
  switch (basis2) {
    case 0:
      if (sd === 31 && ed === 31) {
        sd = 30;
        ed = 30;
      } else if (sd === 31) {
        sd = 30;
      } else if (sd === 30 && ed === 31) {
        ed = 30;
      }
      return (ed + em * 30 + ey * 360 - (sd + sm * 30 + sy * 360)) / 360;
    case 1: {
      const feb29Between = (date1, date22) => {
        const year1 = date1.getFullYear();
        const mar1year1 = new Date(year1, 2, 1);
        if (isLeapYear(year1) && date1 < mar1year1 && date22 >= mar1year1) {
          return true;
        }
        const year2 = date22.getFullYear();
        const mar1year2 = new Date(year2, 2, 1);
        return isLeapYear(year2) && date22 >= mar1year2 && date1 < mar1year2;
      };
      let ylength = 365;
      if (sy === ey || sy + 1 === ey && (sm > em || sm === em && sd >= ed)) {
        if (sy === ey && isLeapYear(sy) || feb29Between(start_date, end_date) || em === 1 && ed === 29) {
          ylength = 366;
        }
        return daysBetween(start_date, end_date) / ylength;
      }
      const years = ey - sy + 1;
      const days = (new Date(ey + 1, 0, 1) - new Date(sy, 0, 1)) / 1000 / 60 / 60 / 24;
      const average = days / years;
      return daysBetween(start_date, end_date) / average;
    }
    case 2:
      return daysBetween(start_date, end_date) / 360;
    case 3:
      return daysBetween(start_date, end_date) / 365;
    case 4:
      return (ed + em * 30 + ey * 360 - (sd + sm * 30 + sy * 360)) / 360;
  }
}
function isValidBinaryNumber(number6) {
  return /^[01]{1,10}$/.test(number6);
}
function BESSELI(x2, n) {
  x2 = parseNumber(x2);
  n = parseNumber(n);
  if (anyIsError(x2, n)) {
    return value;
  }
  return import_bessel.default.besseli(x2, n);
}
function BESSELJ(x2, n) {
  x2 = parseNumber(x2);
  n = parseNumber(n);
  if (anyIsError(x2, n)) {
    return value;
  }
  return import_bessel.default.besselj(x2, n);
}
function BESSELK(x2, n) {
  x2 = parseNumber(x2);
  n = parseNumber(n);
  if (anyIsError(x2, n)) {
    return value;
  }
  return import_bessel.default.besselk(x2, n);
}
function BESSELY(x2, n) {
  x2 = parseNumber(x2);
  n = parseNumber(n);
  if (anyIsError(x2, n)) {
    return value;
  }
  return import_bessel.default.bessely(x2, n);
}
function BIN2DEC(number6) {
  if (!isValidBinaryNumber(number6)) {
    return num;
  }
  const result = parseInt(number6, 2);
  const stringified = number6.toString();
  if (stringified.length === 10 && stringified.substring(0, 1) === "1") {
    return parseInt(stringified.substring(1), 2) - 512;
  } else {
    return result;
  }
}
function BIN2HEX(number6, places) {
  if (!isValidBinaryNumber(number6)) {
    return num;
  }
  const stringified = number6.toString();
  if (stringified.length === 10 && stringified.substring(0, 1) === "1") {
    return (1099511627264 + parseInt(stringified.substring(1), 2)).toString(16);
  }
  const result = parseInt(number6, 2).toString(16);
  if (places === undefined) {
    return result;
  } else {
    if (isNaN(places)) {
      return value;
    }
    if (places < 0) {
      return num;
    }
    places = Math.floor(places);
    return places >= result.length ? REPT("0", places - result.length) + result : num;
  }
}
function BIN2OCT(number6, places) {
  if (!isValidBinaryNumber(number6)) {
    return num;
  }
  const stringified = number6.toString();
  if (stringified.length === 10 && stringified.substring(0, 1) === "1") {
    return (1073741312 + parseInt(stringified.substring(1), 2)).toString(8);
  }
  const result = parseInt(number6, 2).toString(8);
  if (places === undefined) {
    return result;
  } else {
    if (isNaN(places)) {
      return value;
    }
    if (places < 0) {
      return num;
    }
    places = Math.floor(places);
    return places >= result.length ? REPT("0", places - result.length) + result : num;
  }
}
function BITAND(number1, number22) {
  number1 = parseNumber(number1);
  number22 = parseNumber(number22);
  if (anyIsError(number1, number22)) {
    return value;
  }
  if (number1 < 0 || number22 < 0) {
    return num;
  }
  if (Math.floor(number1) !== number1 || Math.floor(number22) !== number22) {
    return num;
  }
  if (number1 > 281474976710655 || number22 > 281474976710655) {
    return num;
  }
  return number1 & number22;
}
function BITLSHIFT(number6, shift_amount) {
  number6 = parseNumber(number6);
  shift_amount = parseNumber(shift_amount);
  if (anyIsError(number6, shift_amount)) {
    return value;
  }
  if (number6 < 0) {
    return num;
  }
  if (Math.floor(number6) !== number6) {
    return num;
  }
  if (number6 > 281474976710655) {
    return num;
  }
  if (Math.abs(shift_amount) > 53) {
    return num;
  }
  return shift_amount >= 0 ? number6 << shift_amount : number6 >> -shift_amount;
}
function BITOR(number1, number22) {
  number1 = parseNumber(number1);
  number22 = parseNumber(number22);
  if (anyIsError(number1, number22)) {
    return value;
  }
  if (number1 < 0 || number22 < 0) {
    return num;
  }
  if (Math.floor(number1) !== number1 || Math.floor(number22) !== number22) {
    return num;
  }
  if (number1 > 281474976710655 || number22 > 281474976710655) {
    return num;
  }
  return number1 | number22;
}
function BITRSHIFT(number6, shift_amount) {
  number6 = parseNumber(number6);
  shift_amount = parseNumber(shift_amount);
  if (anyIsError(number6, shift_amount)) {
    return value;
  }
  if (number6 < 0) {
    return num;
  }
  if (Math.floor(number6) !== number6) {
    return num;
  }
  if (number6 > 281474976710655) {
    return num;
  }
  if (Math.abs(shift_amount) > 53) {
    return num;
  }
  return shift_amount >= 0 ? number6 >> shift_amount : number6 << -shift_amount;
}
function BITXOR(number1, number22) {
  number1 = parseNumber(number1);
  number22 = parseNumber(number22);
  if (anyIsError(number1, number22)) {
    return value;
  }
  if (number1 < 0 || number22 < 0) {
    return num;
  }
  if (Math.floor(number1) !== number1 || Math.floor(number22) !== number22) {
    return num;
  }
  if (number1 > 281474976710655 || number22 > 281474976710655) {
    return num;
  }
  return number1 ^ number22;
}
function COMPLEX(real_num, i_num, suffix) {
  real_num = parseNumber(real_num);
  i_num = parseNumber(i_num);
  if (anyIsError(real_num, i_num)) {
    return real_num;
  }
  suffix = suffix === undefined ? "i" : suffix;
  if (suffix !== "i" && suffix !== "j") {
    return value;
  }
  if (real_num === 0 && i_num === 0) {
    return 0;
  } else if (real_num === 0) {
    return i_num === 1 ? suffix : i_num.toString() + suffix;
  } else if (i_num === 0) {
    return real_num.toString();
  } else {
    const sign2 = i_num > 0 ? "+" : "";
    return real_num.toString() + sign2 + (i_num === 1 ? suffix : i_num.toString() + suffix);
  }
}
function CONVERT(number6, from_unit, to_unit) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  const units = [
    ["a.u. of action", "?", null, "action", false, false, 0.000000000000000000000000000000000105457168181818],
    ["a.u. of charge", "e", null, "electric_charge", false, false, 0.000000000000000000160217653141414],
    ["a.u. of energy", "Eh", null, "energy", false, false, 0.00000000000000000435974417757576],
    ["a.u. of length", "a?", null, "length", false, false, 0.0000000000529177210818182],
    ["a.u. of mass", "m?", null, "mass", false, false, 0.000000000000000000000000000000910938261616162],
    ["a.u. of time", "?/Eh", null, "time", false, false, 0.0000000000000000241888432650516],
    ["admiralty knot", "admkn", null, "speed", false, true, 0.514773333],
    ["ampere", "A", null, "electric_current", true, false, 1],
    ["ampere per meter", "A/m", null, "magnetic_field_intensity", true, false, 1],
    ["ångström", "Å", ["ang"], "length", false, true, 0.0000000001],
    ["are", "ar", null, "area", false, true, 100],
    ["astronomical unit", "ua", null, "length", false, false, 0.0000000000149597870691667],
    ["bar", "bar", null, "pressure", false, false, 1e5],
    ["barn", "b", null, "area", false, false, 0.0000000000000000000000000001],
    ["becquerel", "Bq", null, "radioactivity", true, false, 1],
    ["bit", "bit", ["b"], "information", false, true, 1],
    ["btu", "BTU", ["btu"], "energy", false, true, 1055.05585262],
    ["byte", "byte", null, "information", false, true, 8],
    ["candela", "cd", null, "luminous_intensity", true, false, 1],
    ["candela per square metre", "cd/m?", null, "luminance", true, false, 1],
    ["coulomb", "C", null, "electric_charge", true, false, 1],
    ["cubic ångström", "ang3", ["ang^3"], "volume", false, true, 0.000000000000000000000000000001],
    ["cubic foot", "ft3", ["ft^3"], "volume", false, true, 0.028316846592],
    ["cubic inch", "in3", ["in^3"], "volume", false, true, 0.000016387064],
    ["cubic light-year", "ly3", ["ly^3"], "volume", false, true, 0.0000000000000000000000000000000000000000000000846786664623715],
    ["cubic metre", "m3", ["m^3"], "volume", true, true, 1],
    ["cubic mile", "mi3", ["mi^3"], "volume", false, true, 4168181825.44058],
    ["cubic nautical mile", "Nmi3", ["Nmi^3"], "volume", false, true, 6352182208],
    ["cubic Pica", "Pica3", ["Picapt3", "Pica^3", "Picapt^3"], "volume", false, true, 0.0000000758660370370369],
    ["cubic yard", "yd3", ["yd^3"], "volume", false, true, 0.764554857984],
    ["cup", "cup", null, "volume", false, true, 0.0002365882365],
    ["dalton", "Da", ["u"], "mass", false, false, 0.00000000000000000000000000166053886282828],
    ["day", "d", ["day"], "time", false, true, 86400],
    ["degree", "°", null, "angle", false, false, 0.0174532925199433],
    ["degrees Rankine", "Rank", null, "temperature", false, true, 0.555555555555556],
    ["dyne", "dyn", ["dy"], "force", false, true, 0.00001],
    ["electronvolt", "eV", ["ev"], "energy", false, true, 1.60217656514141],
    ["ell", "ell", null, "length", false, true, 1.143],
    ["erg", "erg", ["e"], "energy", false, true, 0.0000001],
    ["farad", "F", null, "electric_capacitance", true, false, 1],
    ["fluid ounce", "oz", null, "volume", false, true, 0.0000295735295625],
    ["foot", "ft", null, "length", false, true, 0.3048],
    ["foot-pound", "flb", null, "energy", false, true, 1.3558179483314],
    ["gal", "Gal", null, "acceleration", false, false, 0.01],
    ["gallon", "gal", null, "volume", false, true, 0.003785411784],
    ["gauss", "G", ["ga"], "magnetic_flux_density", false, true, 1],
    ["grain", "grain", null, "mass", false, true, 0.0000647989],
    ["gram", "g", null, "mass", false, true, 0.001],
    ["gray", "Gy", null, "absorbed_dose", true, false, 1],
    ["gross registered ton", "GRT", ["regton"], "volume", false, true, 2.8316846592],
    ["hectare", "ha", null, "area", false, true, 1e4],
    ["henry", "H", null, "inductance", true, false, 1],
    ["hertz", "Hz", null, "frequency", true, false, 1],
    ["horsepower", "HP", ["h"], "power", false, true, 745.69987158227],
    ["horsepower-hour", "HPh", ["hh", "hph"], "energy", false, true, 2684519.538],
    ["hour", "h", ["hr"], "time", false, true, 3600],
    ["imperial gallon (U.K.)", "uk_gal", null, "volume", false, true, 0.00454609],
    ["imperial hundredweight", "lcwt", ["uk_cwt", "hweight"], "mass", false, true, 50.802345],
    ["imperial quart (U.K)", "uk_qt", null, "volume", false, true, 0.0011365225],
    ["imperial ton", "brton", ["uk_ton", "LTON"], "mass", false, true, 1016.046909],
    ["inch", "in", null, "length", false, true, 0.0254],
    ["international acre", "uk_acre", null, "area", false, true, 4046.8564224],
    ["IT calorie", "cal", null, "energy", false, true, 4.1868],
    ["joule", "J", null, "energy", true, true, 1],
    ["katal", "kat", null, "catalytic_activity", true, false, 1],
    ["kelvin", "K", ["kel"], "temperature", true, true, 1],
    ["kilogram", "kg", null, "mass", true, true, 1],
    ["knot", "kn", null, "speed", false, true, 0.514444444444444],
    ["light-year", "ly", null, "length", false, true, 9460730472580800],
    ["litre", "L", ["l", "lt"], "volume", false, true, 0.001],
    ["lumen", "lm", null, "luminous_flux", true, false, 1],
    ["lux", "lx", null, "illuminance", true, false, 1],
    ["maxwell", "Mx", null, "magnetic_flux", false, false, 0.000000000000000001],
    ["measurement ton", "MTON", null, "volume", false, true, 1.13267386368],
    ["meter per hour", "m/h", ["m/hr"], "speed", false, true, 0.00027777777777778],
    ["meter per second", "m/s", ["m/sec"], "speed", true, true, 1],
    ["meter per second squared", "m?s??", null, "acceleration", true, false, 1],
    ["parsec", "pc", ["parsec"], "length", false, true, 30856775814671900],
    ["meter squared per second", "m?/s", null, "kinematic_viscosity", true, false, 1],
    ["metre", "m", null, "length", true, true, 1],
    ["miles per hour", "mph", null, "speed", false, true, 0.44704],
    ["millimetre of mercury", "mmHg", null, "pressure", false, false, 133.322],
    ["minute", "?", null, "angle", false, false, 0.000290888208665722],
    ["minute", "min", ["mn"], "time", false, true, 60],
    ["modern teaspoon", "tspm", null, "volume", false, true, 0.000005],
    ["mole", "mol", null, "amount_of_substance", true, false, 1],
    ["morgen", "Morgen", null, "area", false, true, 2500],
    ["n.u. of action", "?", null, "action", false, false, 0.000000000000000000000000000000000105457168181818],
    ["n.u. of mass", "m?", null, "mass", false, false, 0.000000000000000000000000000000910938261616162],
    ["n.u. of speed", "c?", null, "speed", false, false, 299792458],
    ["n.u. of time", "?/(me?c??)", null, "time", false, false, 0.00000000000000000000128808866778687],
    ["nautical mile", "M", ["Nmi"], "length", false, true, 1852],
    ["newton", "N", null, "force", true, true, 1],
    ["œrsted", "Oe ", null, "magnetic_field_intensity", false, false, 79.5774715459477],
    ["ohm", "Ω", null, "electric_resistance", true, false, 1],
    ["ounce mass", "ozm", null, "mass", false, true, 0.028349523125],
    ["pascal", "Pa", null, "pressure", true, false, 1],
    ["pascal second", "Pa?s", null, "dynamic_viscosity", true, false, 1],
    ["pferdestärke", "PS", null, "power", false, true, 735.49875],
    ["phot", "ph", null, "illuminance", false, false, 0.0001],
    ["pica (1/6 inch)", "pica", null, "length", false, true, 0.00035277777777778],
    ["pica (1/72 inch)", "Pica", ["Picapt"], "length", false, true, 0.00423333333333333],
    ["poise", "P", null, "dynamic_viscosity", false, false, 0.1],
    ["pond", "pond", null, "force", false, true, 0.00980665],
    ["pound force", "lbf", null, "force", false, true, 4.4482216152605],
    ["pound mass", "lbm", null, "mass", false, true, 0.45359237],
    ["quart", "qt", null, "volume", false, true, 0.000946352946],
    ["radian", "rad", null, "angle", true, false, 1],
    ["second", "?", null, "angle", false, false, 0.00000484813681109536],
    ["second", "s", ["sec"], "time", true, true, 1],
    ["short hundredweight", "cwt", ["shweight"], "mass", false, true, 45.359237],
    ["siemens", "S", null, "electrical_conductance", true, false, 1],
    ["sievert", "Sv", null, "equivalent_dose", true, false, 1],
    ["slug", "sg", null, "mass", false, true, 14.59390294],
    ["square ångström", "ang2", ["ang^2"], "area", false, true, 0.00000000000000000001],
    ["square foot", "ft2", ["ft^2"], "area", false, true, 0.09290304],
    ["square inch", "in2", ["in^2"], "area", false, true, 0.00064516],
    ["square light-year", "ly2", ["ly^2"], "area", false, true, 89505421074818900000000000000000],
    ["square meter", "m?", null, "area", true, true, 1],
    ["square mile", "mi2", ["mi^2"], "area", false, true, 2589988.110336],
    ["square nautical mile", "Nmi2", ["Nmi^2"], "area", false, true, 3429904],
    ["square Pica", "Pica2", ["Picapt2", "Pica^2", "Picapt^2"], "area", false, true, 0.00001792111111111],
    ["square yard", "yd2", ["yd^2"], "area", false, true, 0.83612736],
    ["statute mile", "mi", null, "length", false, true, 1609.344],
    ["steradian", "sr", null, "solid_angle", true, false, 1],
    ["stilb", "sb", null, "luminance", false, false, 0.0001],
    ["stokes", "St", null, "kinematic_viscosity", false, false, 0.0001],
    ["stone", "stone", null, "mass", false, true, 6.35029318],
    ["tablespoon", "tbs", null, "volume", false, true, 0.0000147868],
    ["teaspoon", "tsp", null, "volume", false, true, 0.00000492892],
    ["tesla", "T", null, "magnetic_flux_density", true, true, 1],
    ["thermodynamic calorie", "c", null, "energy", false, true, 4.184],
    ["ton", "ton", null, "mass", false, true, 907.18474],
    ["tonne", "t", null, "mass", false, false, 1000],
    ["U.K. pint", "uk_pt", null, "volume", false, true, 0.00056826125],
    ["U.S. bushel", "bushel", null, "volume", false, true, 0.03523907],
    ["U.S. oil barrel", "barrel", null, "volume", false, true, 0.158987295],
    ["U.S. pint", "pt", ["us_pt"], "volume", false, true, 0.000473176473],
    ["U.S. survey mile", "survey_mi", null, "length", false, true, 1609.347219],
    ["U.S. survey/statute acre", "us_acre", null, "area", false, true, 4046.87261],
    ["volt", "V", null, "voltage", true, false, 1],
    ["watt", "W", null, "power", true, true, 1],
    ["watt-hour", "Wh", ["wh"], "energy", false, true, 3600],
    ["weber", "Wb", null, "magnetic_flux", true, false, 1],
    ["yard", "yd", null, "length", false, true, 0.9144],
    ["year", "yr", null, "time", false, true, 31557600]
  ];
  const binary_prefixes = {
    Yi: ["yobi", 80, 1208925819614629200000000, "Yi", "yotta"],
    Zi: ["zebi", 70, 1180591620717411300000, "Zi", "zetta"],
    Ei: ["exbi", 60, 1152921504606847000, "Ei", "exa"],
    Pi: ["pebi", 50, 1125899906842624, "Pi", "peta"],
    Ti: ["tebi", 40, 1099511627776, "Ti", "tera"],
    Gi: ["gibi", 30, 1073741824, "Gi", "giga"],
    Mi: ["mebi", 20, 1048576, "Mi", "mega"],
    ki: ["kibi", 10, 1024, "ki", "kilo"]
  };
  const unit_prefixes = {
    Y: ["yotta", 1000000000000000000000000, "Y"],
    Z: ["zetta", 1000000000000000000000, "Z"],
    E: ["exa", 1000000000000000000, "E"],
    P: ["peta", 1000000000000000, "P"],
    T: ["tera", 1000000000000, "T"],
    G: ["giga", 1e9, "G"],
    M: ["mega", 1e6, "M"],
    k: ["kilo", 1000, "k"],
    h: ["hecto", 100, "h"],
    e: ["dekao", 10, "e"],
    d: ["deci", 0.1, "d"],
    c: ["centi", 0.01, "c"],
    m: ["milli", 0.001, "m"],
    u: ["micro", 0.000001, "u"],
    n: ["nano", 0.000000001, "n"],
    p: ["pico", 0.000000000001, "p"],
    f: ["femto", 0.000000000000001, "f"],
    a: ["atto", 0.000000000000000001, "a"],
    z: ["zepto", 0.000000000000000000001, "z"],
    y: ["yocto", 0.000000000000000000000001, "y"]
  };
  let from2 = null;
  let to = null;
  let base_from_unit = from_unit;
  let base_to_unit = to_unit;
  let from_multiplier = 1;
  let to_multiplier = 1;
  let alt;
  for (let i = 0;i < units.length; i++) {
    alt = units[i][2] === null ? [] : units[i][2];
    if (units[i][1] === base_from_unit || alt.indexOf(base_from_unit) >= 0) {
      from2 = units[i];
    }
    if (units[i][1] === base_to_unit || alt.indexOf(base_to_unit) >= 0) {
      to = units[i];
    }
  }
  if (from2 === null) {
    const from_binary_prefix = binary_prefixes[from_unit.substring(0, 2)];
    let from_unit_prefix = unit_prefixes[from_unit.substring(0, 1)];
    if (from_unit.substring(0, 2) === "da") {
      from_unit_prefix = ["dekao", 10, "da"];
    }
    if (from_binary_prefix) {
      from_multiplier = from_binary_prefix[2];
      base_from_unit = from_unit.substring(2);
    } else if (from_unit_prefix) {
      from_multiplier = from_unit_prefix[1];
      base_from_unit = from_unit.substring(from_unit_prefix[2].length);
    }
    for (let j = 0;j < units.length; j++) {
      alt = units[j][2] === null ? [] : units[j][2];
      if (units[j][1] === base_from_unit || alt.indexOf(base_from_unit) >= 0) {
        from2 = units[j];
      }
    }
  }
  if (to === null) {
    const to_binary_prefix = binary_prefixes[to_unit.substring(0, 2)];
    let to_unit_prefix = unit_prefixes[to_unit.substring(0, 1)];
    if (to_unit.substring(0, 2) === "da") {
      to_unit_prefix = ["dekao", 10, "da"];
    }
    if (to_binary_prefix) {
      to_multiplier = to_binary_prefix[2];
      base_to_unit = to_unit.substring(2);
    } else if (to_unit_prefix) {
      to_multiplier = to_unit_prefix[1];
      base_to_unit = to_unit.substring(to_unit_prefix[2].length);
    }
    for (let k = 0;k < units.length; k++) {
      alt = units[k][2] === null ? [] : units[k][2];
      if (units[k][1] === base_to_unit || alt.indexOf(base_to_unit) >= 0) {
        to = units[k];
      }
    }
  }
  if (from2 === null || to === null) {
    return na;
  }
  if (from2[3] !== to[3]) {
    return na;
  }
  return number6 * from2[6] * from_multiplier / (to[6] * to_multiplier);
}
function DEC2BIN(number6, places) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  if (!/^-?[0-9]{1,3}$/.test(number6) || number6 < -512 || number6 > 511) {
    return num;
  }
  if (number6 < 0) {
    return "1" + REPT("0", 9 - (512 + number6).toString(2).length) + (512 + number6).toString(2);
  }
  const result = parseInt(number6, 10).toString(2);
  if (typeof places === "undefined") {
    return result;
  } else {
    if (isNaN(places)) {
      return value;
    }
    if (places < 0) {
      return num;
    }
    places = Math.floor(places);
    return places >= result.length ? REPT("0", places - result.length) + result : num;
  }
}
function DEC2HEX(number6, places) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  if (!/^-?[0-9]{1,12}$/.test(number6) || number6 < -549755813888 || number6 > 549755813887) {
    return num;
  }
  if (number6 < 0) {
    return (1099511627776 + number6).toString(16);
  }
  const result = parseInt(number6, 10).toString(16);
  if (typeof places === "undefined") {
    return result;
  } else {
    if (isNaN(places)) {
      return value;
    }
    if (places < 0) {
      return num;
    }
    places = Math.floor(places);
    return places >= result.length ? REPT("0", places - result.length) + result : num;
  }
}
function DEC2OCT(number6, places) {
  number6 = parseNumber(number6);
  if (number6 instanceof Error) {
    return number6;
  }
  if (!/^-?[0-9]{1,9}$/.test(number6) || number6 < -536870912 || number6 > 536870911) {
    return num;
  }
  if (number6 < 0) {
    return (1073741824 + number6).toString(8);
  }
  const result = parseInt(number6, 10).toString(8);
  if (typeof places === "undefined") {
    return result;
  } else {
    if (isNaN(places)) {
      return value;
    }
    if (places < 0) {
      return num;
    }
    places = Math.floor(places);
    return places >= result.length ? REPT("0", places - result.length) + result : num;
  }
}
function DELTA(number1, number22) {
  number22 = number22 === undefined ? 0 : number22;
  number1 = parseNumber(number1);
  number22 = parseNumber(number22);
  if (anyIsError(number1, number22)) {
    return value;
  }
  return number1 === number22 ? 1 : 0;
}
function ERF(lower_limit, upper_limit) {
  upper_limit = upper_limit === undefined ? 0 : upper_limit;
  lower_limit = parseNumber(lower_limit);
  upper_limit = parseNumber(upper_limit);
  if (anyIsError(lower_limit, upper_limit)) {
    return value;
  }
  return import_jstat.default.erf(lower_limit);
}
function ERFC(x2) {
  if (isNaN(x2)) {
    return value;
  }
  return import_jstat.default.erfc(x2);
}
function GESTEP(number6, step) {
  step = step || 0;
  number6 = parseNumber(number6);
  if (anyIsError(step, number6)) {
    return number6;
  }
  return number6 >= step ? 1 : 0;
}
function HEX2BIN(number6, places) {
  if (!/^[0-9A-Fa-f]{1,10}$/.test(number6)) {
    return num;
  }
  const negative = !!(number6.length === 10 && number6.substring(0, 1).toLowerCase() === "f");
  const decimal = negative ? parseInt(number6, 16) - 1099511627776 : parseInt(number6, 16);
  if (decimal < -512 || decimal > 511) {
    return num;
  }
  if (negative) {
    return "1" + REPT("0", 9 - (512 + decimal).toString(2).length) + (512 + decimal).toString(2);
  }
  const result = decimal.toString(2);
  if (places === undefined) {
    return result;
  } else {
    if (isNaN(places)) {
      return value;
    }
    if (places < 0) {
      return num;
    }
    places = Math.floor(places);
    return places >= result.length ? REPT("0", places - result.length) + result : num;
  }
}
function HEX2DEC(number6) {
  if (!/^[0-9A-Fa-f]{1,10}$/.test(number6)) {
    return num;
  }
  const decimal = parseInt(number6, 16);
  return decimal >= 549755813888 ? decimal - 1099511627776 : decimal;
}
function HEX2OCT(number6, places) {
  if (!/^[0-9A-Fa-f]{1,10}$/.test(number6)) {
    return num;
  }
  const decimal = parseInt(number6, 16);
  if (decimal > 536870911 && decimal < 1098974756864) {
    return num;
  }
  if (decimal >= 1098974756864) {
    return (decimal - 1098437885952).toString(8);
  }
  const result = decimal.toString(8);
  if (places === undefined) {
    return result;
  } else {
    if (isNaN(places)) {
      return value;
    }
    if (places < 0) {
      return num;
    }
    places = Math.floor(places);
    return places >= result.length ? REPT("0", places - result.length) + result : num;
  }
}
function IMABS(inumber) {
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return value;
  }
  return Math.sqrt(Math.pow(x2, 2) + Math.pow(y2, 2));
}
function IMAGINARY(inumber) {
  if (inumber === undefined || inumber === true || inumber === false) {
    return value;
  }
  if (inumber === 0 || inumber === "0") {
    return 0;
  }
  if (["i", "j"].indexOf(inumber) >= 0) {
    return 1;
  }
  inumber = inumber + "";
  inumber = inumber.replace("+i", "+1i").replace("-i", "-1i").replace("+j", "+1j").replace("-j", "-1j");
  let plus = inumber.indexOf("+");
  let minus = inumber.indexOf("-");
  if (plus === 0) {
    plus = inumber.indexOf("+", 1);
  }
  if (minus === 0) {
    minus = inumber.indexOf("-", 1);
  }
  const last2 = inumber.substring(inumber.length - 1, inumber.length);
  const unit2 = last2 === "i" || last2 === "j";
  if (plus >= 0 || minus >= 0) {
    if (!unit2) {
      return num;
    }
    if (plus >= 0) {
      return isNaN(inumber.substring(0, plus)) || isNaN(inumber.substring(plus + 1, inumber.length - 1)) ? num : Number(inumber.substring(plus + 1, inumber.length - 1));
    } else {
      return isNaN(inumber.substring(0, minus)) || isNaN(inumber.substring(minus + 1, inumber.length - 1)) ? num : -Number(inumber.substring(minus + 1, inumber.length - 1));
    }
  } else {
    if (unit2) {
      return isNaN(inumber.substring(0, inumber.length - 1)) ? num : inumber.substring(0, inumber.length - 1);
    } else {
      return isNaN(inumber) ? num : 0;
    }
  }
}
function IMARGUMENT(inumber) {
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return value;
  }
  if (x2 === 0 && y2 === 0) {
    return div0;
  }
  if (x2 === 0 && y2 > 0) {
    return Math.PI / 2;
  }
  if (x2 === 0 && y2 < 0) {
    return -Math.PI / 2;
  }
  if (y2 === 0 && x2 > 0) {
    return 0;
  }
  if (y2 === 0 && x2 < 0) {
    return -Math.PI;
  }
  if (x2 > 0) {
    return Math.atan(y2 / x2);
  } else if (x2 < 0 && y2 >= 0) {
    return Math.atan(y2 / x2) + Math.PI;
  } else {
    return Math.atan(y2 / x2) - Math.PI;
  }
}
function IMCONJUGATE(inumber) {
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return value;
  }
  let unit2 = inumber.substring(inumber.length - 1);
  unit2 = unit2 === "i" || unit2 === "j" ? unit2 : "i";
  return y2 !== 0 ? COMPLEX(x2, -y2, unit2) : inumber;
}
function IMCOS(inumber) {
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return value;
  }
  let unit2 = inumber.substring(inumber.length - 1);
  unit2 = unit2 === "i" || unit2 === "j" ? unit2 : "i";
  return COMPLEX(Math.cos(x2) * (Math.exp(y2) + Math.exp(-y2)) / 2, -Math.sin(x2) * (Math.exp(y2) - Math.exp(-y2)) / 2, unit2);
}
function IMCOSH(inumber) {
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return value;
  }
  let unit2 = inumber.substring(inumber.length - 1);
  unit2 = unit2 === "i" || unit2 === "j" ? unit2 : "i";
  return COMPLEX(Math.cos(y2) * (Math.exp(x2) + Math.exp(-x2)) / 2, Math.sin(y2) * (Math.exp(x2) - Math.exp(-x2)) / 2, unit2);
}
function IMCOT(inumber) {
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return value;
  }
  return IMDIV(IMCOS(inumber), IMSIN(inumber));
}
function IMDIV(inumber1, inumber2) {
  const a = IMREAL(inumber1);
  const b = IMAGINARY(inumber1);
  const c = IMREAL(inumber2);
  const d = IMAGINARY(inumber2);
  if (anyIsError(a, b, c, d)) {
    return value;
  }
  const unit1 = inumber1.substring(inumber1.length - 1);
  const unit2 = inumber2.substring(inumber2.length - 1);
  let unit3 = "i";
  if (unit1 === "j") {
    unit3 = "j";
  } else if (unit2 === "j") {
    unit3 = "j";
  }
  if (c === 0 && d === 0) {
    return num;
  }
  const den = c * c + d * d;
  return COMPLEX((a * c + b * d) / den, (b * c - a * d) / den, unit3);
}
function IMEXP(inumber) {
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return value;
  }
  let unit2 = inumber.substring(inumber.length - 1);
  unit2 = unit2 === "i" || unit2 === "j" ? unit2 : "i";
  const e = Math.exp(x2);
  return COMPLEX(e * Math.cos(y2), e * Math.sin(y2), unit2);
}
function IMLN(inumber) {
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return value;
  }
  let unit2 = inumber.substring(inumber.length - 1);
  unit2 = unit2 === "i" || unit2 === "j" ? unit2 : "i";
  return COMPLEX(Math.log(Math.sqrt(x2 * x2 + y2 * y2)), Math.atan(y2 / x2), unit2);
}
function IMLOG10(inumber) {
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return value;
  }
  let unit2 = inumber.substring(inumber.length - 1);
  unit2 = unit2 === "i" || unit2 === "j" ? unit2 : "i";
  return COMPLEX(Math.log(Math.sqrt(x2 * x2 + y2 * y2)) / Math.log(10), Math.atan(y2 / x2) / Math.log(10), unit2);
}
function IMLOG2(inumber) {
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return value;
  }
  let unit2 = inumber.substring(inumber.length - 1);
  unit2 = unit2 === "i" || unit2 === "j" ? unit2 : "i";
  return COMPLEX(Math.log(Math.sqrt(x2 * x2 + y2 * y2)) / Math.log(2), Math.atan(y2 / x2) / Math.log(2), unit2);
}
function IMPOWER(inumber, number6) {
  number6 = parseNumber(number6);
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(number6, x2, y2)) {
    return value;
  }
  let unit2 = inumber.substring(inumber.length - 1);
  unit2 = unit2 === "i" || unit2 === "j" ? unit2 : "i";
  const p = Math.pow(IMABS(inumber), number6);
  const t = IMARGUMENT(inumber);
  return COMPLEX(p * Math.cos(number6 * t), p * Math.sin(number6 * t), unit2);
}
function IMPRODUCT() {
  let result = arguments[0];
  if (!arguments.length) {
    return value;
  }
  for (let i = 1;i < arguments.length; i++) {
    const a = IMREAL(result);
    const b = IMAGINARY(result);
    const c = IMREAL(arguments[i]);
    const d = IMAGINARY(arguments[i]);
    if (anyIsError(a, b, c, d)) {
      return value;
    }
    result = COMPLEX(a * c - b * d, a * d + b * c);
  }
  return result;
}
function IMREAL(inumber) {
  if (inumber === undefined || inumber === true || inumber === false) {
    return value;
  }
  if (inumber === 0 || inumber === "0") {
    return 0;
  }
  if (["i", "+i", "1i", "+1i", "-i", "-1i", "j", "+j", "1j", "+1j", "-j", "-1j"].indexOf(inumber) >= 0) {
    return 0;
  }
  inumber = inumber + "";
  let plus = inumber.indexOf("+");
  let minus = inumber.indexOf("-");
  if (plus === 0) {
    plus = inumber.indexOf("+", 1);
  }
  if (minus === 0) {
    minus = inumber.indexOf("-", 1);
  }
  const last2 = inumber.substring(inumber.length - 1, inumber.length);
  const unit2 = last2 === "i" || last2 === "j";
  if (plus >= 0 || minus >= 0) {
    if (!unit2) {
      return num;
    }
    if (plus >= 0) {
      return isNaN(inumber.substring(0, plus)) || isNaN(inumber.substring(plus + 1, inumber.length - 1)) ? num : Number(inumber.substring(0, plus));
    } else {
      return isNaN(inumber.substring(0, minus)) || isNaN(inumber.substring(minus + 1, inumber.length - 1)) ? num : Number(inumber.substring(0, minus));
    }
  } else {
    if (unit2) {
      return isNaN(inumber.substring(0, inumber.length - 1)) ? num : 0;
    } else {
      return isNaN(inumber) ? num : inumber;
    }
  }
}
function IMSEC(inumber) {
  if (inumber === true || inumber === false) {
    return value;
  }
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return value;
  }
  return IMDIV("1", IMCOS(inumber));
}
function IMSECH(inumber) {
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return value;
  }
  return IMDIV("1", IMCOSH(inumber));
}
function IMSIN(inumber) {
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return value;
  }
  let unit2 = inumber.substring(inumber.length - 1);
  unit2 = unit2 === "i" || unit2 === "j" ? unit2 : "i";
  return COMPLEX(Math.sin(x2) * (Math.exp(y2) + Math.exp(-y2)) / 2, Math.cos(x2) * (Math.exp(y2) - Math.exp(-y2)) / 2, unit2);
}
function IMSINH(inumber) {
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return value;
  }
  let unit2 = inumber.substring(inumber.length - 1);
  unit2 = unit2 === "i" || unit2 === "j" ? unit2 : "i";
  return COMPLEX(Math.cos(y2) * (Math.exp(x2) - Math.exp(-x2)) / 2, Math.sin(y2) * (Math.exp(x2) + Math.exp(-x2)) / 2, unit2);
}
function IMSQRT(inumber) {
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return value;
  }
  let unit2 = inumber.substring(inumber.length - 1);
  unit2 = unit2 === "i" || unit2 === "j" ? unit2 : "i";
  const s = Math.sqrt(IMABS(inumber));
  const t = IMARGUMENT(inumber);
  return COMPLEX(s * Math.cos(t / 2), s * Math.sin(t / 2), unit2);
}
function IMCSC(inumber) {
  if (inumber === true || inumber === false) {
    return value;
  }
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return num;
  }
  return IMDIV("1", IMSIN(inumber));
}
function IMCSCH(inumber) {
  if (inumber === true || inumber === false) {
    return value;
  }
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return num;
  }
  return IMDIV("1", IMSINH(inumber));
}
function IMSUB(inumber1, inumber2) {
  const a = IMREAL(inumber1);
  const b = IMAGINARY(inumber1);
  const c = IMREAL(inumber2);
  const d = IMAGINARY(inumber2);
  if (anyIsError(a, b, c, d)) {
    return value;
  }
  const unit1 = inumber1.substring(inumber1.length - 1);
  const unit2 = inumber2.substring(inumber2.length - 1);
  let unit3 = "i";
  if (unit1 === "j") {
    unit3 = "j";
  } else if (unit2 === "j") {
    unit3 = "j";
  }
  return COMPLEX(a - c, b - d, unit3);
}
function IMSUM() {
  if (!arguments.length) {
    return value;
  }
  const args2 = flatten(arguments);
  let numberSum = 0;
  let imaginarySum = 0;
  for (const arg of args2) {
    const realPart = +IMREAL(arg);
    const imaginaryPart = +IMAGINARY(arg);
    if (anyIsError(realPart, imaginaryPart)) {
      return value;
    }
    numberSum += realPart;
    imaginarySum += imaginaryPart;
  }
  return COMPLEX(numberSum, imaginarySum, "i");
}
function IMTAN(inumber) {
  if (inumber === true || inumber === false) {
    return value;
  }
  const x2 = IMREAL(inumber);
  const y2 = IMAGINARY(inumber);
  if (anyIsError(x2, y2)) {
    return value;
  }
  return IMDIV(IMSIN(inumber), IMCOS(inumber));
}
function OCT2BIN(number6, places) {
  if (!/^[0-7]{1,10}$/.test(number6)) {
    return num;
  }
  const negative = !!(number6.length === 10 && number6.substring(0, 1) === "7");
  const decimal = negative ? parseInt(number6, 8) - 1073741824 : parseInt(number6, 8);
  if (decimal < -512 || decimal > 511) {
    return num;
  }
  if (negative) {
    return "1" + REPT("0", 9 - (512 + decimal).toString(2).length) + (512 + decimal).toString(2);
  }
  const result = decimal.toString(2);
  if (typeof places === "undefined") {
    return result;
  } else {
    if (isNaN(places)) {
      return value;
    }
    if (places < 0) {
      return num;
    }
    places = Math.floor(places);
    return places >= result.length ? REPT("0", places - result.length) + result : num;
  }
}
function OCT2DEC(number6) {
  if (!/^[0-7]{1,10}$/.test(number6)) {
    return num;
  }
  const decimal = parseInt(number6, 8);
  return decimal >= 536870912 ? decimal - 1073741824 : decimal;
}
function OCT2HEX(number6, places) {
  if (!/^[0-7]{1,10}$/.test(number6)) {
    return num;
  }
  const decimal = parseInt(number6, 8);
  if (decimal >= 536870912) {
    return "ff" + (decimal + 3221225472).toString(16);
  }
  const result = decimal.toString(16);
  if (places === undefined) {
    return result;
  } else {
    if (isNaN(places)) {
      return value;
    }
    if (places < 0) {
      return num;
    }
    places = Math.floor(places);
    return places >= result.length ? REPT("0", places - result.length) + result : num;
  }
}
var BETADIST = BETA.DIST;
var BETAINV = BETA.INV;
var BINOMDIST = BINOM.DIST;
var CEILINGMATH = CEILING.MATH;
var CEILINGPRECISE = CEILING.PRECISE;
var CHIDIST = CHISQ.DIST;
var CHIDISTRT = CHISQ.DIST.RT;
var CHIINV = CHISQ.INV;
var CHIINVRT = CHISQ.INV.RT;
var CHITEST = CHISQ.TEST;
var COVAR = COVARIANCE.P;
var COVARIANCEP = COVARIANCE.P;
var COVARIANCES = COVARIANCE.S;
var CRITBINOM = BINOM.INV;
var ERFCPRECISE = ERFC.PRECISE;
var ERFPRECISE = ERF.PRECISE;
var EXPONDIST = EXPON.DIST;
var FDIST = F.DIST;
var FDISTRT = F.DIST.RT;
var FINV = F.INV;
var FINVRT = F.INV.RT;
var FLOORMATH = FLOOR.MATH;
var FLOORPRECISE = FLOOR.PRECISE;
var FTEST = F.TEST;
var GAMMADIST = GAMMA.DIST;
var GAMMAINV = GAMMA.INV;
var GAMMALNPRECISE = GAMMALN.PRECISE;
var HYPGEOMDIST = HYPGEOM.DIST;
var LOGINV = LOGNORM.INV;
var LOGNORMDIST = LOGNORM.DIST;
var LOGNORMINV = LOGNORM.INV;
var MODEMULT = MODE.MULT;
var MODESNGL = MODE.SNGL;
var NEGBINOMDIST = NEGBINOM.DIST;
var NETWORKDAYSINTL = NETWORKDAYS.INTL;
var NORMDIST = NORM.DIST;
var NORMINV = NORM.INV;
var NORMSDIST = NORM.S.DIST;
var NORMSINV = NORM.S.INV;
var PERCENTILEEXC = PERCENTILE.EXC;
var PERCENTILEINC = PERCENTILE.INC;
var PERCENTRANKEXC = PERCENTRANK.EXC;
var PERCENTRANKINC = PERCENTRANK.INC;
var POISSONDIST = POISSON.DIST;
var QUARTILEEXC = QUARTILE.EXC;
var QUARTILEINC = QUARTILE.INC;
var RANKAVG = RANK.AVG;
var RANKEQ = RANK.EQ;
var SKEWP = SKEW.P;
var STDEVP = STDEV.P;
var STDEVS = STDEV.S;
var TDIST = T.DIST;
var TDISTRT = T.DIST.RT;
var TINV = T.INV;
var TTEST = T.TEST;
var VARP = VAR.P;
var VARS = VAR.S;
var WEIBULLDIST = WEIBULL.DIST;
var WORKDAYINTL = WORKDAY.INTL;
var ZTEST = Z.TEST;
function compact(array3) {
  const result = [];
  arrayEach(array3, (value2) => {
    if (value2) {
      result.push(value2);
    }
  });
  return result;
}
function findResultIndex(database, criterias) {
  const matches = {};
  for (let i = 1;i < database[0].length; ++i) {
    matches[i] = true;
  }
  let maxCriteriaLength = criterias[0].length;
  for (let i = 1;i < criterias.length; ++i) {
    if (criterias[i].length > maxCriteriaLength) {
      maxCriteriaLength = criterias[i].length;
    }
  }
  for (let k = 1;k < database.length; ++k) {
    for (let l = 1;l < database[k].length; ++l) {
      let currentCriteriaResult = false;
      let hasMatchingCriteria = false;
      for (let j = 0;j < criterias.length; ++j) {
        const criteria = criterias[j];
        if (criteria.length < maxCriteriaLength) {
          continue;
        }
        const criteriaField = criteria[0];
        if (database[k][0] !== criteriaField) {
          continue;
        }
        hasMatchingCriteria = true;
        for (let p = 1;p < criteria.length; ++p) {
          if (!currentCriteriaResult) {
            const isWildcard = criteria[p] === undefined || criteria[p] === "*";
            if (isWildcard) {
              currentCriteriaResult = true;
            } else {
              const tokenizedCriteria = parse5(criteria[p] + "");
              const tokens = [createToken(database[k][l], TOKEN_TYPE_LITERAL)].concat(tokenizedCriteria);
              currentCriteriaResult = compute(tokens);
            }
          }
        }
      }
      if (hasMatchingCriteria) {
        matches[l] = matches[l] && currentCriteriaResult;
      }
    }
  }
  const result = [];
  for (let n = 0;n < database[0].length; ++n) {
    if (matches[n]) {
      result.push(n - 1);
    }
  }
  return result;
}
function DAVERAGE(database, field, criteria) {
  if (isNaN(field) && typeof field !== "string") {
    return value;
  }
  const resultIndexes = findResultIndex(database, criteria);
  let targetFields = [];
  if (typeof field === "string") {
    const index = findField(database, field);
    targetFields = rest(database[index]);
  } else {
    targetFields = rest(database[field]);
  }
  let sum2 = 0;
  arrayEach(resultIndexes, (value2) => {
    sum2 += targetFields[value2];
  });
  return resultIndexes.length === 0 ? div0 : sum2 / resultIndexes.length;
}
function DCOUNT(database, field, criteria) {
  if (isNaN(field) && typeof field !== "string") {
    return value;
  }
  const resultIndexes = findResultIndex(database, criteria);
  let targetFields = [];
  if (typeof field === "string") {
    const index = findField(database, field);
    targetFields = rest(database[index]);
  } else {
    targetFields = rest(database[field]);
  }
  const targetValues = [];
  arrayEach(resultIndexes, (value2) => {
    targetValues.push(targetFields[value2]);
  });
  return COUNT(targetValues);
}
function DCOUNTA(database, field, criteria) {
  if (isNaN(field) && typeof field !== "string") {
    return value;
  }
  const resultIndexes = findResultIndex(database, criteria);
  let targetFields = [];
  if (typeof field === "string") {
    const index = findField(database, field);
    targetFields = rest(database[index]);
  } else {
    targetFields = rest(database[field]);
  }
  const targetValues = [];
  arrayEach(resultIndexes, (value2) => {
    targetValues.push(targetFields[value2]);
  });
  return COUNTA(targetValues);
}
function DGET(database, field, criteria) {
  if (isNaN(field) && typeof field !== "string") {
    return value;
  }
  const resultIndexes = findResultIndex(database, criteria);
  let targetFields = [];
  if (typeof field === "string") {
    const index = findField(database, field);
    targetFields = rest(database[index]);
  } else {
    targetFields = rest(database[field]);
  }
  if (resultIndexes.length === 0) {
    return value;
  }
  if (resultIndexes.length > 1) {
    return num;
  }
  return targetFields[resultIndexes[0]];
}
function DMAX(database, field, criteria) {
  if (isNaN(field) && typeof field !== "string") {
    return value;
  }
  const resultIndexes = findResultIndex(database, criteria);
  let targetFields = [];
  if (typeof field === "string") {
    const index = findField(database, field);
    targetFields = rest(database[index]);
  } else {
    targetFields = rest(database[field]);
  }
  let maxValue = targetFields[resultIndexes[0]];
  arrayEach(resultIndexes, (value2) => {
    if (maxValue < targetFields[value2]) {
      maxValue = targetFields[value2];
    }
  });
  return maxValue;
}
function DMIN(database, field, criteria) {
  if (isNaN(field) && typeof field !== "string") {
    return value;
  }
  const resultIndexes = findResultIndex(database, criteria);
  let targetFields = [];
  if (typeof field === "string") {
    const index = findField(database, field);
    targetFields = rest(database[index]);
  } else {
    targetFields = rest(database[field]);
  }
  let minValue = targetFields[resultIndexes[0]];
  arrayEach(resultIndexes, (value2) => {
    if (minValue > targetFields[value2]) {
      minValue = targetFields[value2];
    }
  });
  return minValue;
}
function DPRODUCT(database, field, criteria) {
  if (isNaN(field) && typeof field !== "string") {
    return value;
  }
  const resultIndexes = findResultIndex(database, criteria);
  let targetFields = [];
  if (typeof field === "string") {
    const index = findField(database, field);
    targetFields = rest(database[index]);
  } else {
    targetFields = rest(database[field]);
  }
  let targetValues = [];
  arrayEach(resultIndexes, (value2) => {
    targetValues.push(targetFields[value2]);
  });
  targetValues = compact(targetValues);
  let result = 1;
  arrayEach(targetValues, (value2) => {
    result *= value2;
  });
  return result;
}
function DSTDEV(database, field, criteria) {
  if (isNaN(field) && typeof field !== "string") {
    return value;
  }
  const resultIndexes = findResultIndex(database, criteria);
  let targetFields = [];
  if (typeof field === "string") {
    const index = findField(database, field);
    targetFields = rest(database[index]);
  } else {
    targetFields = rest(database[field]);
  }
  let targetValues = [];
  arrayEach(resultIndexes, (value2) => {
    targetValues.push(targetFields[value2]);
  });
  targetValues = compact(targetValues);
  return STDEV.S(targetValues);
}
function DSTDEVP(database, field, criteria) {
  if (isNaN(field) && typeof field !== "string") {
    return value;
  }
  const resultIndexes = findResultIndex(database, criteria);
  let targetFields = [];
  if (typeof field === "string") {
    const index = findField(database, field);
    targetFields = rest(database[index]);
  } else {
    targetFields = rest(database[field]);
  }
  let targetValues = [];
  arrayEach(resultIndexes, (value2) => {
    targetValues.push(targetFields[value2]);
  });
  targetValues = compact(targetValues);
  return STDEV.P(targetValues);
}
function DVAR(database, field, criteria) {
  if (isNaN(field) && typeof field !== "string") {
    return value;
  }
  const resultIndexes = findResultIndex(database, criteria);
  let targetFields = [];
  if (typeof field === "string") {
    const index = findField(database, field);
    targetFields = rest(database[index]);
  } else {
    targetFields = rest(database[field]);
  }
  const targetValues = [];
  arrayEach(resultIndexes, (value2) => {
    targetValues.push(targetFields[value2]);
  });
  return VAR.S(targetValues);
}
function DVARP(database, field, criteria) {
  if (isNaN(field) && typeof field !== "string") {
    return value;
  }
  const resultIndexes = findResultIndex(database, criteria);
  let targetFields = [];
  if (typeof field === "string") {
    const index = findField(database, field);
    targetFields = rest(database[index]);
  } else {
    targetFields = rest(database[field]);
  }
  const targetValues = [];
  arrayEach(resultIndexes, (value2) => {
    targetValues.push(targetFields[value2]);
  });
  return VAR.P(targetValues);
}
function validDate(d) {
  return d && d.getTime && !isNaN(d.getTime());
}
function ensureDate(d) {
  return d instanceof Date ? d : new Date(d);
}
function lastCoupDateBeforeSettlement(settlement, maturity, frequency) {
  let date6 = parseDate(maturity);
  date6.setFullYear(settlement.getFullYear());
  if (date6 < settlement) {
    date6.setFullYear(date6.getFullYear() + 1);
  }
  while (date6 > settlement) {
    date6.setMonth(date6.getMonth() + -12 / frequency);
  }
  return date6;
}
function validateFrequency(frequency) {
  frequency = parseNumber(frequency);
  if ([1, 2, 4].indexOf(frequency) === -1) {
    return num;
  }
  return frequency;
}
function validateBasis(basis2) {
  basis2 = parseNumber(basis2);
  if ([0, 1, 2, 3, 4].indexOf(basis2) === -1) {
    return num;
  }
  return basis2;
}
function ACCRINT(issue2, first_interest, settlement, rate, par, frequency, basis2) {
  issue2 = ensureDate(issue2);
  first_interest = ensureDate(first_interest);
  settlement = ensureDate(settlement);
  frequency = validateFrequency(frequency);
  basis2 = validateBasis(basis2);
  if (anyError(frequency, basis2)) {
    return num;
  }
  if (!validDate(issue2) || !validDate(first_interest) || !validDate(settlement)) {
    return value;
  }
  if (rate <= 0 || par <= 0) {
    return num;
  }
  if (settlement <= issue2) {
    return num;
  }
  par = par || 0;
  basis2 = basis2 || 0;
  return par * rate * YEARFRAC(issue2, settlement, basis2);
}
function COUPDAYS(settlement, maturity, frequency, basis2) {
  basis2 = validateBasis(basis2);
  frequency = validateFrequency(frequency);
  settlement = parseDate(settlement);
  maturity = parseDate(maturity);
  if (anyError(settlement, maturity)) {
    return value;
  }
  if (anyError(frequency, basis2) || settlement >= maturity) {
    return num;
  }
  if (basis2 === 1) {
    let date6 = lastCoupDateBeforeSettlement(settlement, maturity, frequency);
    let nextDate = parseDate(date6);
    nextDate.setMonth(nextDate.getMonth() + 12 / frequency);
    return DATEDIF(date6, nextDate, "D");
  }
  let numOfDays;
  switch (basis2) {
    case 0:
    case 2:
    case 4:
      numOfDays = 360;
      break;
    case 3:
      numOfDays = 365;
      break;
    default:
      return num;
  }
  return numOfDays / frequency;
}
function CUMIPMT(rate, nper, pv, start_period, end_period, type) {
  rate = parseNumber(rate);
  nper = parseNumber(nper);
  pv = parseNumber(pv);
  if (anyIsError(rate, nper, pv)) {
    return value;
  }
  if (rate <= 0 || nper <= 0 || pv <= 0) {
    return num;
  }
  if (start_period < 1 || end_period < 1 || start_period > end_period) {
    return num;
  }
  if (type !== 0 && type !== 1) {
    return num;
  }
  const payment = PMT(rate, nper, pv, 0, type);
  let interest = 0;
  if (start_period === 1) {
    if (type === 0) {
      interest = -pv;
    }
    start_period++;
  }
  for (let i = start_period;i <= end_period; i++) {
    interest += type === 1 ? FV(rate, i - 2, payment, pv, 1) - payment : FV(rate, i - 1, payment, pv, 0);
  }
  interest *= rate;
  return interest;
}
function CUMPRINC(rate, nper, pv, start_period, end, type) {
  rate = parseNumber(rate);
  nper = parseNumber(nper);
  pv = parseNumber(pv);
  if (anyIsError(rate, nper, pv)) {
    return value;
  }
  if (rate <= 0 || nper <= 0 || pv <= 0) {
    return num;
  }
  if (start_period < 1 || end < 1 || start_period > end) {
    return num;
  }
  if (type !== 0 && type !== 1) {
    return num;
  }
  const payment = PMT(rate, nper, pv, 0, type);
  let principal = 0;
  if (start_period === 1) {
    principal = type === 0 ? payment + pv * rate : payment;
    start_period++;
  }
  for (let i = start_period;i <= end; i++) {
    principal += type > 0 ? payment - (FV(rate, i - 2, payment, pv, 1) - payment) * rate : payment - FV(rate, i - 1, payment, pv, 0) * rate;
  }
  return principal;
}
function DB(cost, salvage, life, period, month) {
  month = month === undefined ? 12 : month;
  cost = parseNumber(cost);
  salvage = parseNumber(salvage);
  life = parseNumber(life);
  period = parseNumber(period);
  month = parseNumber(month);
  if (anyIsError(cost, salvage, life, period, month)) {
    return value;
  }
  if (cost < 0 || salvage < 0 || life < 0 || period < 0) {
    return num;
  }
  if ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].indexOf(month) === -1) {
    return num;
  }
  if (period > life) {
    return num;
  }
  if (salvage >= cost) {
    return 0;
  }
  const rate = (1 - Math.pow(salvage / cost, 1 / life)).toFixed(3);
  const initial2 = cost * rate * month / 12;
  let total = initial2;
  let current = 0;
  const ceiling = period === life ? life - 1 : period;
  for (let i = 2;i <= ceiling; i++) {
    current = (cost - total) * rate;
    total += current;
  }
  if (period === 1) {
    return initial2;
  } else if (period === life) {
    return (cost - total) * rate;
  } else {
    return current;
  }
}
function DDB(cost, salvage, life, period, factor) {
  factor = factor === undefined ? 2 : factor;
  cost = parseNumber(cost);
  salvage = parseNumber(salvage);
  life = parseNumber(life);
  period = parseNumber(period);
  factor = parseNumber(factor);
  if (anyIsError(cost, salvage, life, period, factor)) {
    return value;
  }
  if (cost < 0 || salvage < 0 || life < 0 || period < 0 || factor <= 0) {
    return num;
  }
  if (period > life) {
    return num;
  }
  if (salvage >= cost) {
    return 0;
  }
  let total = 0;
  let current = 0;
  for (let i = 1;i <= period; i++) {
    current = Math.min((cost - total) * (factor / life), cost - salvage - total);
    total += current;
  }
  return current;
}
function DISC(settlement, maturity, pr, redemption, basis2) {
  settlement = parseDate(settlement);
  maturity = parseDate(maturity);
  pr = parseNumber(pr);
  redemption = parseNumber(redemption);
  basis2 = parseNumber(basis2);
  basis2 = basis2 || 0;
  if (anyIsError(settlement, maturity, pr, redemption, basis2)) {
    return value;
  }
  if (pr <= 0 || redemption <= 0) {
    return num;
  }
  if (settlement >= maturity) {
    return value;
  }
  let basisVal, diff;
  switch (basis2) {
    case 0:
      basisVal = 360;
      diff = DAYS360(settlement, maturity, false);
      break;
    case 1:
      basisVal = 365;
      diff = DATEDIF(settlement, maturity, "D");
      break;
    case 2:
      basisVal = 360;
      diff = DATEDIF(settlement, maturity, "D");
      break;
    case 3:
      basisVal = 365;
      diff = DATEDIF(settlement, maturity, "D");
      break;
    case 4:
      basisVal = 360;
      diff = DAYS360(settlement, maturity, true);
      break;
    default:
      return num;
  }
  return (redemption - pr) / redemption * basisVal / diff;
}
function DOLLARDE(fractional_dollar, fraction) {
  fractional_dollar = parseNumber(fractional_dollar);
  fraction = parseNumber(fraction);
  if (anyIsError(fractional_dollar, fraction)) {
    return value;
  }
  if (fraction < 0) {
    return num;
  }
  if (fraction >= 0 && fraction < 1) {
    return div0;
  }
  fraction = parseInt(fraction, 10);
  let result = parseInt(fractional_dollar, 10);
  result += fractional_dollar % 1 * Math.pow(10, Math.ceil(Math.log(fraction) / Math.LN10)) / fraction;
  const power = Math.pow(10, Math.ceil(Math.log(fraction) / Math.LN2) + 1);
  result = Math.round(result * power) / power;
  return result;
}
function DOLLARFR(decimal_dollar, fraction) {
  decimal_dollar = parseNumber(decimal_dollar);
  fraction = parseNumber(fraction);
  if (anyIsError(decimal_dollar, fraction)) {
    return value;
  }
  if (fraction < 0) {
    return num;
  }
  if (fraction >= 0 && fraction < 1) {
    return div0;
  }
  fraction = parseInt(fraction, 10);
  let result = parseInt(decimal_dollar, 10);
  result += decimal_dollar % 1 * Math.pow(10, -Math.ceil(Math.log(fraction) / Math.LN10)) * fraction;
  return result;
}
function EFFECT(nominal_rate, npery) {
  nominal_rate = parseNumber(nominal_rate);
  npery = parseNumber(npery);
  if (anyIsError(nominal_rate, npery)) {
    return value;
  }
  if (nominal_rate <= 0 || npery < 1) {
    return num;
  }
  npery = parseInt(npery, 10);
  return Math.pow(1 + nominal_rate / npery, npery) - 1;
}
function FV(rate, nper, payment, value$1, type) {
  value$1 = value$1 || 0;
  type = type || 0;
  rate = parseNumber(rate);
  nper = parseNumber(nper);
  payment = parseNumber(payment);
  value$1 = parseNumber(value$1);
  type = parseNumber(type);
  if (anyIsError(rate, nper, payment, value$1, type)) {
    return value;
  }
  let result;
  if (rate === 0) {
    result = value$1 + payment * nper;
  } else {
    const term = Math.pow(1 + rate, nper);
    result = type === 1 ? value$1 * term + payment * (1 + rate) * (term - 1) / rate : value$1 * term + payment * (term - 1) / rate;
  }
  return -result;
}
function FVSCHEDULE(principal, schedule) {
  principal = parseNumber(principal);
  schedule = parseNumberArray(flatten(schedule));
  if (anyIsError(principal, schedule)) {
    return value;
  }
  const n = schedule.length;
  let future = principal;
  for (let i = 0;i < n; i++) {
    future *= 1 + schedule[i];
  }
  return future;
}
function IPMT(rate, per, nper, pv, fv, type) {
  fv = fv || 0;
  type = type || 0;
  rate = parseNumber(rate);
  per = parseNumber(per);
  nper = parseNumber(nper);
  pv = parseNumber(pv);
  fv = parseNumber(fv);
  type = parseNumber(type);
  if (anyIsError(rate, per, nper, pv, fv, type)) {
    return value;
  }
  const payment = PMT(rate, nper, pv, fv, type);
  let interest = per === 1 ? type === 1 ? 0 : -pv : type === 1 ? FV(rate, per - 2, payment, pv, 1) - payment : FV(rate, per - 1, payment, pv, 0);
  return interest * rate;
}
function IRR(values, guess) {
  guess = typeof guess === "number" ? guess : typeof guess === "undefined" ? 0.1 : parseNumber(guess);
  values = flatten(values).filter(isDefined);
  values = parseNumberArray(values);
  if (anyIsError(values, guess)) {
    return value;
  }
  const cashFlows = new Float64Array(values.length);
  let positive = false;
  let negative = false;
  for (let i = 0;i < values.length; i++) {
    cashFlows[i] = values[i];
    if (cashFlows[i] > 0)
      positive = true;
    if (cashFlows[i] < 0)
      negative = true;
  }
  if (!positive || !negative) {
    return num;
  }
  const npv = (rate) => {
    if (rate <= -1)
      rate = -0.999999999;
    let result = cashFlows[0];
    const r = 1 + rate;
    let factor = 1;
    for (let i = 1;i < cashFlows.length; i++) {
      factor *= r;
      result += cashFlows[i] / factor;
    }
    return result;
  };
  const npvCache = new Map;
  const cachedNpv = function(rate) {
    const roundedRate = Math.round(rate * 10000000000) / 10000000000;
    if (npvCache.has(roundedRate)) {
      return npvCache.get(roundedRate);
    }
    const result = npv(roundedRate);
    npvCache.set(roundedRate, result);
    return result;
  };
  const combinedMethod = function() {
    const epsMax = 0.0000000001;
    const maxIterations = 1000;
    let rate = guess;
    let prevRate = rate;
    let iteration = 0;
    while (iteration < maxIterations) {
      const currentNpv = cachedNpv(rate);
      if (Math.abs(currentNpv) < epsMax) {
        return rate;
      }
      if (iteration > 0 && Math.abs(rate - prevRate) < epsMax * 10) {
        break;
      }
      const delta = Math.max(0.0001, Math.abs(rate * 0.0001));
      const derivNpv = (cachedNpv(rate + delta) - currentNpv) / delta;
      if (Math.abs(derivNpv) < epsMax) {
        break;
      }
      prevRate = rate;
      const newtonStep = currentNpv / derivNpv;
      const maxStep = Math.max(0.1, Math.abs(rate) * 0.5);
      if (Math.abs(newtonStep) > maxStep) {
        rate -= Math.sign(newtonStep) * maxStep;
      } else {
        rate -= newtonStep;
      }
      if (rate <= -1)
        rate = -0.99999999;
      if (rate > 1000)
        rate = 1000;
      iteration++;
    }
    let npvAtRate = cachedNpv(rate);
    if (Math.abs(npvAtRate) < epsMax) {
      return rate;
    }
    let a, b;
    if (npvAtRate > 0) {
      a = rate;
      b = rate + 0.1;
      while (cachedNpv(b) > 0 && b < 1000) {
        b = b * 2 + 0.1;
      }
      if (b >= 1000)
        return rate;
    } else {
      b = rate;
      a = Math.max(-0.99999999, rate - 0.1);
      while (cachedNpv(a) < 0 && a > -0.99999999) {
        a = Math.max(-0.99999999, a - 0.1);
      }
      if (a <= -0.99999999)
        return rate;
    }
    let c;
    for (let i = 0;i < maxIterations; i++) {
      c = (a + b) / 2;
      const npvC = cachedNpv(c);
      if (Math.abs(npvC) < epsMax || Math.abs(b - a) < epsMax) {
        return c;
      }
      if (npvC * cachedNpv(a) < 0) {
        b = c;
      } else {
        a = c;
      }
    }
    return c;
  };
  return combinedMethod();
}
function ISPMT(rate, per, nper, pv) {
  rate = parseNumber(rate);
  per = parseNumber(per);
  nper = parseNumber(nper);
  pv = parseNumber(pv);
  if (anyIsError(rate, per, nper, pv)) {
    return value;
  }
  return pv * rate * (per / nper - 1);
}
function MIRR(values, finance_rate, reinvest_rate) {
  values = parseNumberArray(flatten(values));
  finance_rate = parseNumber(finance_rate);
  reinvest_rate = parseNumber(reinvest_rate);
  if (anyIsError(values, finance_rate, reinvest_rate)) {
    return value;
  }
  const n = values.length;
  const payments = [];
  const incomes = [];
  for (let i = 0;i < n; i++) {
    if (values[i] < 0) {
      payments.push(values[i]);
    } else {
      incomes.push(values[i]);
    }
  }
  const num2 = -NPV(reinvest_rate, incomes) * Math.pow(1 + reinvest_rate, n - 1);
  const den = NPV(finance_rate, payments) * (1 + finance_rate);
  return Math.pow(num2 / den, 1 / (n - 1)) - 1;
}
function NOMINAL(effect_rate, npery) {
  effect_rate = parseNumber(effect_rate);
  npery = parseNumber(npery);
  if (anyIsError(effect_rate, npery)) {
    return value;
  }
  if (effect_rate <= 0 || npery < 1) {
    return num;
  }
  npery = parseInt(npery, 10);
  return (Math.pow(effect_rate + 1, 1 / npery) - 1) * npery;
}
function NPER(rate, pmt, pv, fv, type) {
  type = type === undefined ? 0 : type;
  fv = fv === undefined ? 0 : fv;
  rate = parseNumber(rate);
  pmt = parseNumber(pmt);
  pv = parseNumber(pv);
  fv = parseNumber(fv);
  type = parseNumber(type);
  if (anyIsError(rate, pmt, pv, fv, type)) {
    return value;
  }
  if (rate === 0) {
    return -(pv + fv) / pmt;
  } else {
    const num2 = pmt * (1 + rate * type) - fv * rate;
    const den = pv * rate + pmt * (1 + rate * type);
    return Math.log(num2 / den) / Math.log(1 + rate);
  }
}
function NPV() {
  const args2 = parseNumberArray(flatten(arguments));
  if (args2 instanceof Error) {
    return args2;
  }
  const rate = args2[0];
  let value2 = 0;
  for (let j = 1;j < args2.length; j++) {
    value2 += args2[j] / Math.pow(1 + rate, j);
  }
  return value2;
}
function PDURATION(rate, pv, fv) {
  rate = parseNumber(rate);
  pv = parseNumber(pv);
  fv = parseNumber(fv);
  if (anyIsError(rate, pv, fv)) {
    return value;
  }
  if (rate <= 0) {
    return num;
  }
  return (Math.log(fv) - Math.log(pv)) / Math.log(1 + rate);
}
function PMT(rate, nper, pv, fv, type) {
  fv = fv || 0;
  type = type || 0;
  rate = parseNumber(rate);
  nper = parseNumber(nper);
  pv = parseNumber(pv);
  fv = parseNumber(fv);
  type = parseNumber(type);
  if (anyIsError(rate, nper, pv, fv, type)) {
    return value;
  }
  let result;
  if (rate === 0) {
    result = (pv + fv) / nper;
  } else {
    const term = Math.pow(1 + rate, nper);
    result = type === 1 ? (fv * rate / (term - 1) + pv * rate / (1 - 1 / term)) / (1 + rate) : fv * rate / (term - 1) + pv * rate / (1 - 1 / term);
  }
  return -result;
}
function PPMT(rate, per, nper, pv, fv, type) {
  fv = fv || 0;
  type = type || 0;
  rate = parseNumber(rate);
  nper = parseNumber(nper);
  pv = parseNumber(pv);
  fv = parseNumber(fv);
  type = parseNumber(type);
  if (anyIsError(rate, nper, pv, fv, type)) {
    return value;
  }
  return PMT(rate, nper, pv, fv, type) - IPMT(rate, per, nper, pv, fv, type);
}
function PRICEDISC(settlement, maturity, discount, redemption, basis2) {
  settlement = parseDate(settlement);
  maturity = parseDate(maturity);
  discount = parseNumber(discount);
  redemption = parseNumber(redemption);
  basis2 = parseNumber(basis2);
  basis2 = basis2 || 0;
  if (anyIsError(settlement, maturity, discount, redemption, basis2)) {
    return value;
  }
  if (discount <= 0 || redemption <= 0) {
    return num;
  }
  if (settlement >= maturity) {
    return value;
  }
  let basisVal, diff;
  switch (basis2) {
    case 0:
      basisVal = 360;
      diff = DAYS360(settlement, maturity, false);
      break;
    case 1:
      basisVal = 365;
      diff = DATEDIF(settlement, maturity, "D");
      break;
    case 2:
      basisVal = 360;
      diff = DATEDIF(settlement, maturity, "D");
      break;
    case 3:
      basisVal = 365;
      diff = DATEDIF(settlement, maturity, "D");
      break;
    case 4:
      basisVal = 360;
      diff = DAYS360(settlement, maturity, true);
      break;
    default:
      return num;
  }
  return redemption - discount * redemption * diff / basisVal;
}
function PV(rate, per, pmt, fv, type) {
  fv = fv || 0;
  type = type || 0;
  rate = parseNumber(rate);
  per = parseNumber(per);
  pmt = parseNumber(pmt);
  fv = parseNumber(fv);
  type = parseNumber(type);
  if (anyIsError(rate, per, pmt, fv, type)) {
    return value;
  }
  return rate === 0 ? -pmt * per - fv : ((1 - Math.pow(1 + rate, per)) / rate * pmt * (1 + rate * type) - fv) / Math.pow(1 + rate, per);
}
function RATE(nper, pmt, pv, fv, type, guess) {
  guess = guess === undefined ? 0.1 : guess;
  fv = fv === undefined ? 0 : fv;
  type = type === undefined ? 0 : type;
  nper = parseNumber(nper);
  pmt = parseNumber(pmt);
  pv = parseNumber(pv);
  fv = parseNumber(fv);
  type = parseNumber(type);
  guess = parseNumber(guess);
  if (anyIsError(nper, pmt, pv, fv, type, guess)) {
    return value;
  }
  const epsMax = 0.0000000001;
  const iterMax = 100;
  let rate = guess;
  type = type ? 1 : 0;
  for (let i = 0;i < iterMax; i++) {
    if (rate <= -1) {
      return num;
    }
    let y2, f;
    if (Math.abs(rate) < epsMax) {
      y2 = pv * (1 + nper * rate) + pmt * (1 + rate * type) * nper + fv;
    } else {
      f = Math.pow(1 + rate, nper);
      y2 = pv * f + pmt * (1 / rate + type) * (f - 1) + fv;
    }
    if (Math.abs(y2) < epsMax) {
      return rate;
    }
    let dy;
    if (Math.abs(rate) < epsMax) {
      dy = pv * nper + pmt * type * nper;
    } else {
      f = Math.pow(1 + rate, nper);
      const df = nper * Math.pow(1 + rate, nper - 1);
      dy = pv * df + pmt * (1 / rate + type) * df + pmt * (-1 / (rate * rate)) * (f - 1);
    }
    rate -= y2 / dy;
  }
  return rate;
}
function RRI(nper, pv, fv) {
  nper = parseNumber(nper);
  pv = parseNumber(pv);
  fv = parseNumber(fv);
  if (anyIsError(nper, pv, fv)) {
    return value;
  }
  if (nper === 0 || pv === 0) {
    return num;
  }
  return Math.pow(fv / pv, 1 / nper) - 1;
}
function SLN(cost, salvage, life) {
  cost = parseNumber(cost);
  salvage = parseNumber(salvage);
  life = parseNumber(life);
  if (anyIsError(cost, salvage, life)) {
    return value;
  }
  if (life === 0) {
    return num;
  }
  return (cost - salvage) / life;
}
function SYD(cost, salvage, life, per) {
  cost = parseNumber(cost);
  salvage = parseNumber(salvage);
  life = parseNumber(life);
  per = parseNumber(per);
  if (anyIsError(cost, salvage, life, per)) {
    return value;
  }
  if (life === 0) {
    return num;
  }
  if (per < 1 || per > life) {
    return num;
  }
  per = parseInt(per, 10);
  return (cost - salvage) * (life - per + 1) * 2 / (life * (life + 1));
}
function TBILLEQ(settlement, maturity, discount) {
  settlement = parseDate(settlement);
  maturity = parseDate(maturity);
  discount = parseNumber(discount);
  if (anyIsError(settlement, maturity, discount)) {
    return value;
  }
  if (discount <= 0) {
    return num;
  }
  if (settlement > maturity) {
    return num;
  }
  if (maturity - settlement > 365 * 24 * 60 * 60 * 1000) {
    return num;
  }
  return 365 * discount / (360 - discount * DAYS360(settlement, maturity, false));
}
function TBILLPRICE(settlement, maturity, discount) {
  settlement = parseDate(settlement);
  maturity = parseDate(maturity);
  discount = parseNumber(discount);
  if (anyIsError(settlement, maturity, discount)) {
    return value;
  }
  if (discount <= 0) {
    return num;
  }
  if (settlement > maturity) {
    return num;
  }
  if (maturity - settlement > 365 * 24 * 60 * 60 * 1000) {
    return num;
  }
  return 100 * (1 - discount * DAYS360(settlement, maturity, false) / 360);
}
function TBILLYIELD(settlement, maturity, pr) {
  settlement = parseDate(settlement);
  maturity = parseDate(maturity);
  pr = parseNumber(pr);
  if (anyIsError(settlement, maturity, pr)) {
    return value;
  }
  if (pr <= 0) {
    return num;
  }
  if (settlement > maturity) {
    return num;
  }
  if (maturity - settlement > 365 * 24 * 60 * 60 * 1000) {
    return num;
  }
  return (100 - pr) * 360 / (pr * DAYS360(settlement, maturity, false));
}
function XIRR(values, dates, guess) {
  values = parseNumberArray(flatten(values));
  dates = parseDateArray(flatten(dates));
  guess = parseNumber(guess);
  if (anyIsError(values, dates, guess)) {
    return value;
  }
  const irrResult = (values2, dates2, rate) => {
    const r = rate + 1;
    let result = values2[0];
    for (let i = 1;i < values2.length; i++) {
      result += values2[i] / Math.pow(r, DAYS(dates2[i], dates2[0]) / 365);
    }
    return result;
  };
  const irrResultDeriv = (values2, dates2, rate) => {
    const r = rate + 1;
    let result = 0;
    for (let i = 1;i < values2.length; i++) {
      const frac = DAYS(dates2[i], dates2[0]) / 365;
      result -= frac * values2[i] / Math.pow(r, frac + 1);
    }
    return result;
  };
  let positive = false;
  let negative = false;
  for (let i = 0;i < values.length; i++) {
    if (values[i] > 0) {
      positive = true;
    }
    if (values[i] < 0) {
      negative = true;
    }
  }
  if (!positive || !negative) {
    return num;
  }
  guess = guess || 0.1;
  let resultRate = guess;
  const epsMax = 0.0000000001;
  let newRate, epsRate, resultValue;
  let contLoop = true;
  do {
    resultValue = irrResult(values, dates, resultRate);
    newRate = resultRate - resultValue / irrResultDeriv(values, dates, resultRate);
    epsRate = Math.abs(newRate - resultRate);
    resultRate = newRate;
    contLoop = epsRate > epsMax && Math.abs(resultValue) > epsMax;
  } while (contLoop);
  return resultRate;
}
function XNPV(rate, values, dates) {
  rate = parseNumber(rate);
  values = parseNumberArray(flatten(values));
  dates = parseDateArray(flatten(dates));
  if (anyIsError(rate, values, dates)) {
    return value;
  }
  let result = 0;
  for (let i = 0;i < values.length; i++) {
    result += values[i] / Math.pow(1 + rate, DAYS(dates[i], dates[0]) / 365);
  }
  return result;
}
function AND() {
  const args2 = flatten(arguments);
  let result = value;
  for (let i = 0;i < args2.length; i++) {
    if (args2[i] instanceof Error) {
      return args2[i];
    }
    if (args2[i] === undefined || args2[i] === null || typeof args2[i] === "string") {
      continue;
    }
    if (result === value) {
      result = true;
    }
    if (!args2[i]) {
      result = false;
    }
  }
  return result;
}
function FALSE() {
  return false;
}
function IF(logical_test, value_if_true, value_if_false) {
  if (logical_test instanceof Error) {
    return logical_test;
  }
  value_if_true = arguments.length >= 2 ? value_if_true : true;
  if (value_if_true === undefined || value_if_true === null) {
    value_if_true = 0;
  }
  value_if_false = arguments.length === 3 ? value_if_false : false;
  if (value_if_false === undefined || value_if_false === null) {
    value_if_false = 0;
  }
  return logical_test ? value_if_true : value_if_false;
}
function IFS() {
  for (let i = 0;i < arguments.length / 2; i++) {
    if (arguments[i * 2]) {
      return arguments[i * 2 + 1];
    }
  }
  return na;
}
function NOT(logical) {
  if (typeof logical === "string") {
    return value;
  }
  if (logical instanceof Error) {
    return logical;
  }
  return !logical;
}
function OR() {
  const args2 = flatten(arguments);
  let result = value;
  for (let i = 0;i < args2.length; i++) {
    if (args2[i] instanceof Error) {
      return args2[i];
    }
    if (args2[i] === undefined || args2[i] === null || typeof args2[i] === "string") {
      continue;
    }
    if (result === value) {
      result = false;
    }
    if (args2[i]) {
      result = true;
    }
  }
  return result;
}
function TRUE() {
  return true;
}
function XOR() {
  const args2 = flatten(arguments);
  let result = value;
  for (let i = 0;i < args2.length; i++) {
    if (args2[i] instanceof Error) {
      return args2[i];
    }
    if (args2[i] === undefined || args2[i] === null || typeof args2[i] === "string") {
      continue;
    }
    if (result === value) {
      result = 0;
    }
    if (args2[i]) {
      result++;
    }
  }
  if (result === value) {
    return result;
  }
  return !!(Math.floor(Math.abs(result)) & 1);
}
function SWITCH() {
  let result;
  if (arguments.length > 0) {
    const targetValue = arguments[0];
    const argc = arguments.length - 1;
    const switchCount = Math.floor(argc / 2);
    let switchSatisfied = false;
    const hasDefaultClause = argc % 2 !== 0;
    const defaultClause = argc % 2 === 0 ? null : arguments[arguments.length - 1];
    if (switchCount) {
      for (let index = 0;index < switchCount; index++) {
        if (targetValue === arguments[index * 2 + 1]) {
          result = arguments[index * 2 + 2];
          switchSatisfied = true;
          break;
        }
      }
    }
    if (!switchSatisfied) {
      result = hasDefaultClause ? defaultClause : na;
    }
  } else {
    result = value;
  }
  return result;
}
var utils = { errors: errors4, symbols, date: date5 };

// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/statistical.js
var DIV_ZERO_ERROR = { kind: "Error", code: "#DIV/0!" };
var VALUE_ERROR = { kind: "Error", code: "#VALUE!" };
var DIV0_ERROR = { kind: "Error", code: "#DIV/0!" };
var NUM_ERROR_CODE = "#NUM!";
var NUM_ERROR = { kind: "Error", code: NUM_ERROR_CODE };
var NA_ERROR = { kind: "Error", code: "#N/A" };
var MAX_DEGREES_OF_FREEDOM = 10000000000;
var PROBABILITY_SUM_TOLERANCE = 0.000000000001;
function isErrorValue2(value2) {
  return typeof value2 === "object" && value2 !== null && value2.kind === "Error";
}
function toErrorValueFromJsError(error49) {
  const trimmed = error49.message?.trim();
  if (trimmed) {
    return { kind: "Error", code: trimmed };
  }
  return VALUE_ERROR;
}
function isNumError(value2) {
  if (isErrorValue2(value2)) {
    return value2.code === NUM_ERROR_CODE;
  }
  if (typeof value2 === "string") {
    return value2.trim().toUpperCase() === NUM_ERROR_CODE;
  }
  return false;
}
function findFirstArrayError(args2) {
  for (const arg of args2) {
    const next = extractErrorFromArg(arg);
    if (next) {
      return next;
    }
  }
  return null;
}
function extractErrorFromArg(arg) {
  if (arg === undefined) {
    return null;
  }
  if (Array.isArray(arg)) {
    for (const row2 of arg) {
      if (!row2) {
        continue;
      }
      for (const cell of row2) {
        if (cell === undefined) {
          continue;
        }
        const normalized = normalizeScalarError(cell);
        if (normalized) {
          return normalized;
        }
      }
    }
    return null;
  }
  return normalizeScalarError(arg);
}
function normalizeScalarError(value2) {
  if (isErrorValue2(value2)) {
    return value2;
  }
  if (value2 instanceof Error) {
    const code = value2.message?.trim();
    if (code && code.startsWith("#")) {
      return { kind: "Error", code };
    }
    return VALUE_ERROR;
  }
  return null;
}
function coerceNumberArg(value2) {
  if (value2 === undefined) {
    return VALUE_ERROR;
  }
  const scalar = extractScalarFromFunctionArg(value2);
  if (scalar === undefined) {
    return VALUE_ERROR;
  }
  const numeric = coerceLiteralNumberForStats(scalar);
  if (typeof numeric === "number") {
    return numeric;
  }
  if (numeric === null) {
    return VALUE_ERROR;
  }
  return numeric;
}
function coerceNonNegativeNumber(value2) {
  const numeric = coerceNumberArg(value2);
  if (typeof numeric !== "number") {
    return numeric;
  }
  if (numeric < 0) {
    return NUM_ERROR;
  }
  return numeric;
}
function coercePositiveNumber(value2) {
  const numeric = coerceNumberArg(value2);
  if (typeof numeric !== "number") {
    return numeric;
  }
  if (numeric <= 0) {
    return NUM_ERROR;
  }
  return numeric;
}
function coerceIntegerInRange(value2, constraints) {
  const numeric = coerceNumberArg(value2);
  if (typeof numeric !== "number") {
    return numeric;
  }
  const integer2 = Math.trunc(numeric);
  if (integer2 !== numeric) {
    return NUM_ERROR;
  }
  if (!constraints.allowNegative && !constraints.allowZero && integer2 <= 0) {
    return NUM_ERROR;
  }
  if (!constraints.allowNegative && constraints.allowZero && integer2 < 0) {
    return NUM_ERROR;
  }
  if (constraints.min !== undefined && integer2 < constraints.min) {
    return NUM_ERROR;
  }
  if (constraints.max !== undefined && integer2 > constraints.max) {
    return NUM_ERROR;
  }
  return integer2;
}
function coercePositiveInteger(value2, constraints) {
  return coerceIntegerInRange(value2, {
    min: constraints?.min ?? 1,
    max: constraints?.max,
    allowZero: false,
    allowNegative: false
  });
}
function coerceNonNegativeInteger(value2) {
  return coerceIntegerInRange(value2, {
    allowZero: true,
    allowNegative: false,
    min: 0
  });
}
function coerceProbability(value2, options) {
  const numeric = coerceNumberArg(value2);
  if (typeof numeric !== "number") {
    return numeric;
  }
  const lowerBoundOk = options?.inclusiveZero ? numeric >= 0 : numeric > 0;
  const upperBoundOk = options?.inclusiveOne ? numeric <= 1 : numeric < 1;
  if (!lowerBoundOk || !upperBoundOk) {
    return NUM_ERROR;
  }
  return numeric;
}
function coerceDegreesOfFreedom(value2) {
  return coercePositiveInteger(value2, { max: MAX_DEGREES_OF_FREEDOM });
}
function hasInsufficientRegressionData(knownYs, knownXs) {
  const pairs = extractNumericPairsForRegression(knownYs, knownXs);
  if (pairs.ys.length < 3 || pairs.xs.length < 3) {
    return true;
  }
  return !hasDistinctValues(pairs.xs);
}
function extractNumericPairsForRegression(knownYs, knownXs) {
  const dependentValues = flattenRegressionArg(knownYs);
  const independentValues = flattenRegressionArg(knownXs);
  const length2 = Math.min(dependentValues.length, independentValues.length);
  const ys = [];
  const xs = [];
  for (let idx = 0;idx < length2; idx += 1) {
    const yNumeric = coerceRegressionNumber(dependentValues[idx]);
    const xNumeric = coerceRegressionNumber(independentValues[idx]);
    if (yNumeric == null || xNumeric == null) {
      continue;
    }
    ys.push(yNumeric);
    xs.push(xNumeric);
  }
  return { ys, xs };
}
function flattenRegressionArg(arg) {
  if (Array.isArray(arg)) {
    const values = [];
    for (const row2 of arg) {
      if (!row2) {
        continue;
      }
      for (const cell of row2) {
        values.push(cell ?? null);
      }
    }
    return values;
  }
  if (arg !== undefined && isArrayValue(arg)) {
    const arrayArg = arg;
    const values = [];
    for (const row2 of arrayArg.values) {
      for (const cell of row2) {
        values.push(cell ?? null);
      }
    }
    return values;
  }
  if (arg === undefined) {
    return [];
  }
  return [arg];
}
function coerceRegressionNumber(value2) {
  if (value2 == null) {
    return null;
  }
  if (typeof value2 === "number") {
    return Number.isFinite(value2) ? value2 : null;
  }
  if (typeof value2 === "string") {
    const trimmed = value2.trim();
    if (trimmed === "") {
      return null;
    }
    const parsed = Number(trimmed);
    return Number.isFinite(parsed) ? parsed : null;
  }
  return null;
}
function hasDistinctValues(values) {
  if (values.length === 0) {
    return false;
  }
  const first = values[0];
  for (let idx = 1;idx < values.length; idx += 1) {
    if (values[idx] !== first) {
      return true;
    }
  }
  return false;
}
function callVariadic(fn, number1, number22, ...rest2) {
  const filteredArgs = [number1, number22, ...rest2].filter((arg) => arg !== undefined);
  return fn(...filteredArgs);
}
function collectStatisticalNumbers(args2) {
  const collected = [];
  for (const arg of args2) {
    if (arg === undefined) {
      continue;
    }
    if (Array.isArray(arg)) {
      const error49 = collectFromMatrix(arg, collected);
      if (error49) {
        return error49;
      }
      continue;
    }
    const scalarArg = arg;
    if (isArrayValue(scalarArg)) {
      const error49 = collectFromMatrix(scalarArg.values, collected);
      if (error49) {
        return error49;
      }
      continue;
    }
    const literal2 = coerceLiteralNumberForStats(scalarArg);
    if (literal2 === null) {
      continue;
    }
    if (typeof literal2 === "number") {
      collected.push(literal2);
      continue;
    }
    return literal2;
  }
  return collected;
}
function collectFromMatrix(matrix, collected) {
  for (const row2 of matrix) {
    if (!row2) {
      continue;
    }
    for (const cell of row2) {
      const coerced = coerceReferenceNumberForStats(cell);
      if (coerced === null) {
        continue;
      }
      if (typeof coerced === "number") {
        collected.push(coerced);
        continue;
      }
      return coerced;
    }
  }
  return null;
}
function coerceReferenceNumberForStats(value2) {
  if (value2 === undefined || value2 === null) {
    return null;
  }
  if (isErrorValue2(value2)) {
    return value2;
  }
  if (value2 instanceof Error) {
    return VALUE_ERROR;
  }
  if (typeof value2 === "number") {
    return Number.isFinite(value2) ? value2 : VALUE_ERROR;
  }
  if (typeof value2 === "string") {
    return value2.trim() === "" ? null : null;
  }
  if (typeof value2 === "boolean") {
    return null;
  }
  if (isArrayValue(value2)) {
    return VALUE_ERROR;
  }
  return VALUE_ERROR;
}
function coerceLiteralNumberForStats(value2) {
  if (value2 === undefined || value2 === null) {
    return 0;
  }
  if (isErrorValue2(value2)) {
    return value2;
  }
  if (value2 instanceof Error) {
    return VALUE_ERROR;
  }
  if (typeof value2 === "number") {
    return Number.isFinite(value2) ? value2 : VALUE_ERROR;
  }
  if (typeof value2 === "boolean") {
    return value2 ? 1 : 0;
  }
  if (typeof value2 === "string") {
    const trimmed = value2.trim();
    if (trimmed === "") {
      return 0;
    }
    const parsed = Number(trimmed);
    return Number.isFinite(parsed) ? parsed : VALUE_ERROR;
  }
  return VALUE_ERROR;
}
function COUNT2(value1, value2, ...rest2) {
  return callVariadic(COUNT, value1, value2, ...rest2);
}
function flattenFunctionArgs(args2) {
  const flattened = [];
  for (const arg of args2) {
    if (Array.isArray(arg)) {
      for (const row2 of arg) {
        if (!row2) {
          continue;
        }
        for (const cell of row2) {
          if (cell !== undefined) {
            flattened.push(cell ?? null);
          }
        }
      }
      continue;
    }
    flattened.push(arg ?? null);
  }
  return flattened;
}
function flattenFunctionArg(arg) {
  return flattenFunctionArgs([arg]);
}
function validateProbabilityRange(probRange) {
  const flattened = flattenFunctionArg(probRange);
  let sum2 = 0;
  for (const entry of flattened) {
    if (isErrorValue2(entry)) {
      return entry;
    }
    if (entry instanceof Error) {
      return toErrorValueFromJsError(entry);
    }
    const numeric = coerceLiteralNumberForStats(entry);
    if (typeof numeric !== "number") {
      if (numeric === null) {
        return VALUE_ERROR;
      }
      return numeric;
    }
    if (numeric < 0 || numeric > 1) {
      return NUM_ERROR;
    }
    sum2 += numeric;
  }
  if (!Number.isFinite(sum2)) {
    return NUM_ERROR;
  }
  return Math.abs(sum2 - 1) <= PROBABILITY_SUM_TOLERANCE ? null : NUM_ERROR;
}
function getFunctionArgShape(arg) {
  if (Array.isArray(arg)) {
    const rows = arg.length;
    const cols = arg.reduce((max4, row2) => Math.max(max4, row2?.length ?? 0), 0);
    if (rows === 0 || cols === 0) {
      return VALUE_ERROR;
    }
    for (const row2 of arg) {
      if ((row2?.length ?? 0) !== cols) {
        return VALUE_ERROR;
      }
    }
    return { rows, cols };
  }
  if (arg === undefined) {
    return VALUE_ERROR;
  }
  const scalar = arg;
  if (isArrayValue(scalar)) {
    if (scalar.rows < 1 || scalar.cols < 1) {
      return VALUE_ERROR;
    }
    return { rows: scalar.rows, cols: scalar.cols };
  }
  return { rows: 1, cols: 1 };
}
function validateRangeShapes(baseRange, candidateRanges) {
  const baseShape = getFunctionArgShape(baseRange);
  if (isErrorValue2(baseShape)) {
    return baseShape;
  }
  for (const candidate of candidateRanges) {
    if (candidate === undefined) {
      return VALUE_ERROR;
    }
    const shape2 = getFunctionArgShape(candidate);
    if (isErrorValue2(shape2)) {
      return shape2;
    }
    if (shape2.rows !== baseShape.rows || shape2.cols !== baseShape.cols) {
      return VALUE_ERROR;
    }
  }
  return null;
}
function ensureMatchingShapes(ranges) {
  if (ranges.length === 0) {
    return null;
  }
  const [first, ...rest2] = ranges;
  return validateRangeShapes(first, rest2);
}
function normalizePercentileArray(array3) {
  const flattened = flattenFunctionArg(array3);
  const values = [];
  for (const entry of flattened) {
    if (isErrorValue2(entry)) {
      return entry;
    }
    if (entry instanceof Error) {
      return VALUE_ERROR;
    }
    if (entry == null || entry === "") {
      continue;
    }
    if (typeof entry === "number") {
      if (Number.isFinite(entry)) {
        values.push(entry);
        continue;
      }
      return VALUE_ERROR;
    }
    if (typeof entry === "string") {
      const trimmed = entry.trim();
      if (trimmed === "") {
        continue;
      }
      const parsed = Number(trimmed);
      if (Number.isFinite(parsed)) {
        values.push(parsed);
      }
      continue;
    }
    return VALUE_ERROR;
  }
  return values;
}
function normalizeCriteriaValue(criteria) {
  if (Array.isArray(criteria)) {
    const flattened = flattenFunctionArgs([criteria]);
    return flattened.length > 0 ? flattened[0] ?? "" : "";
  }
  return criteria;
}
function matchesAverageIfCriteria(candidate, criteria) {
  if (isErrorValue2(candidate)) {
    return candidate;
  }
  if (candidate instanceof Error) {
    return VALUE_ERROR;
  }
  const normalizedCriteria = normalizeCriteriaValue(criteria);
  try {
    const matchCount = COUNTIF([[candidate]], normalizedCriteria);
    if (matchCount instanceof Error) {
      return VALUE_ERROR;
    }
    if (typeof matchCount === "number") {
      return matchCount > 0;
    }
    return VALUE_ERROR;
  } catch {
    return VALUE_ERROR;
  }
}
function coerceAverageIfValue(value2) {
  if (isErrorValue2(value2)) {
    return value2;
  }
  if (value2 instanceof Error) {
    return VALUE_ERROR;
  }
  if (value2 == null) {
    return null;
  }
  if (typeof value2 === "number") {
    return Number.isFinite(value2) ? value2 : null;
  }
  return null;
}
function evaluateAverageIf(range2, criteria, averageRange) {
  const rangeValues = flattenFunctionArg(range2);
  const valuesToAverage = averageRange ? flattenFunctionArg(averageRange) : rangeValues;
  const limit = Math.min(rangeValues.length, valuesToAverage.length);
  if (limit === 0) {
    return DIV_ZERO_ERROR;
  }
  let sum2 = 0;
  let matched = 0;
  for (let idx = 0;idx < limit; idx += 1) {
    const candidate = rangeValues[idx] ?? null;
    const matches = matchesAverageIfCriteria(candidate, criteria);
    if (matches === false) {
      continue;
    }
    if (matches !== true) {
      return matches;
    }
    const candidateValue = valuesToAverage[idx] ?? null;
    const numeric = coerceAverageIfValue(candidateValue);
    if (numeric === null) {
      continue;
    }
    if (isErrorValue2(numeric)) {
      return numeric;
    }
    sum2 += numeric;
    matched += 1;
  }
  if (matched === 0) {
    return DIV_ZERO_ERROR;
  }
  return sum2 / matched;
}
function AVERAGE2(number1, number22, ...rest2) {
  const argsList = [number1, number22, ...rest2].filter((arg) => arg !== undefined);
  const flattened = flattenFunctionArgs(argsList);
  let sum2 = 0;
  let matched = 0;
  for (const value2 of flattened) {
    if (isErrorValue2(value2)) {
      return value2;
    }
    if (value2 instanceof Error) {
      return toErrorValueFromJsError(value2);
    }
    if (typeof value2 === "number") {
      if (Number.isFinite(value2)) {
        sum2 += value2;
        matched += 1;
      }
      continue;
    }
    if (typeof value2 === "boolean") {
      continue;
    }
    if (typeof value2 === "string") {
      if (!value2.trim()) {
        continue;
      }
      continue;
    }
  }
  if (matched === 0) {
    const hasOnlyScalarInputs = argsList.every((arg) => !Array.isArray(arg));
    if (hasOnlyScalarInputs && flattened.length > 0 && flattened.every((value2) => value2 === "" || value2 === null)) {
      return 0;
    }
    return DIV_ZERO_ERROR;
  }
  return sum2 / matched;
}
function MIN2(number1, number22, ...rest2) {
  return callVariadic(MIN, number1, number22, ...rest2);
}
function MAX2(number1, number22, ...rest2) {
  return callVariadic(MAX, number1, number22, ...rest2);
}
function LINEST2(knownYs, knownXs, constParam, stats) {
  return LINEST(knownYs, knownXs, constParam, stats);
}
function TREND2(knownYs, knownXs, newXs, constParam) {
  return TREND(knownYs, knownXs, newXs, constParam);
}
function LOGEST2(knownYs, knownXs, constParam, stats) {
  return LOGEST(knownYs, knownXs, constParam, stats);
}
function GROWTH2(knownYs, knownXs, newXs, constParam) {
  return GROWTH(knownYs, knownXs, newXs, constParam);
}
function COUNTA2(value1, value2, ...rest2) {
  const args2 = [value1, value2, ...rest2].filter((arg) => arg !== undefined);
  const flattened = flattenFunctionArgs(args2);
  let count3 = 0;
  for (const entry of flattened) {
    if (entry === null) {
      continue;
    }
    count3 += 1;
  }
  return count3;
}
function MEDIAN2(number1, number22, ...rest2) {
  return callVariadic(MEDIAN, number1, number22, ...rest2);
}
function FREQUENCY2(dataArray, binsArray) {
  return FREQUENCY(dataArray, binsArray);
}
function AVEDEV2(number1, number22, ...rest2) {
  return callVariadic(AVEDEV, number1, number22, ...rest2);
}
function GAMMALN2(x2) {
  return GAMMALN(x2);
}
function FISHER2(x2) {
  return FISHER(x2);
}
function FISHERINV2(y2) {
  return FISHERINV(y2);
}
function STANDARDIZE2(x2, mean3, standardDev) {
  return STANDARDIZE(x2, mean3, standardDev);
}
function PERMUT2(numberParam, numberChosen) {
  return PERMUT(numberParam, numberChosen);
}
function CORREL2(array1, array22) {
  return CORREL(array1, array22);
}
function INTERCEPT2(knownYs, knownXs) {
  return INTERCEPT(knownYs, knownXs);
}
function PEARSON2(array1, array22) {
  return PEARSON(array1, array22);
}
function RSQ2(knownYs, knownXs) {
  const error49 = findFirstArrayError([knownYs, knownXs]);
  if (error49) {
    return error49;
  }
  const pairs = extractNumericPairsForRegression(knownYs, knownXs);
  if (pairs.ys.length < 2 || pairs.xs.length < 2 || !hasDistinctValues(pairs.ys) || !hasDistinctValues(pairs.xs)) {
    return DIV_ZERO_ERROR;
  }
  return RSQ(knownYs, knownXs);
}
function STEYX2(knownYs, knownXs) {
  const error49 = findFirstArrayError([knownYs, knownXs]);
  if (error49) {
    return error49;
  }
  if (hasInsufficientRegressionData(knownYs, knownXs)) {
    return DIV_ZERO_ERROR;
  }
  return STEYX(knownYs, knownXs);
}
function SLOPE2(knownYs, knownXs) {
  const error49 = findFirstArrayError([knownYs, knownXs]);
  if (error49) {
    return error49;
  }
  return SLOPE(knownYs, knownXs);
}
function PROB2(xRange, probRange, lowerLimit, upperLimit) {
  const validationError = validateProbabilityRange(probRange);
  if (validationError) {
    return validationError;
  }
  return PROB(xRange, probRange, lowerLimit, upperLimit);
}
function DEVSQ2(number1, number22, ...rest2) {
  return callVariadic(DEVSQ, number1, number22, ...rest2);
}
function GEOMEAN2(number1, number22, ...rest2) {
  return callVariadic(GEOMEAN, number1, number22, ...rest2);
}
function HARMEAN2(number1, number22, ...rest2) {
  return callVariadic(HARMEAN, number1, number22, ...rest2);
}
function KURT2(number1, number22, ...rest2) {
  return callVariadic(KURT, number1, number22, ...rest2);
}
function SKEW2(number1, number22, ...rest2) {
  const valuesOrError = collectStatisticalNumbers([number1, number22, ...rest2]);
  if (!Array.isArray(valuesOrError)) {
    return valuesOrError;
  }
  const values = valuesOrError;
  if (values.length < 3) {
    return DIV0_ERROR;
  }
  const mean3 = values.reduce((acc, value2) => acc + value2, 0) / values.length;
  let sumSquared = 0;
  let sumCubed = 0;
  for (const value2 of values) {
    const delta = value2 - mean3;
    sumSquared += delta * delta;
    sumCubed += delta * delta * delta;
  }
  if (sumSquared === 0) {
    return DIV0_ERROR;
  }
  const n = values.length;
  const sampleStdDev = Math.sqrt(sumSquared / (n - 1));
  if (sampleStdDev === 0) {
    return DIV0_ERROR;
  }
  const denominator = (n - 1) * (n - 2) * Math.pow(sampleStdDev, 3);
  if (denominator === 0) {
    return DIV0_ERROR;
  }
  const skew = n * sumCubed / denominator;
  return Number.isFinite(skew) ? skew : DIV0_ERROR;
}
function LARGE2(array3, k) {
  return LARGE(array3, k);
}
function SMALL2(array3, k) {
  return SMALL(array3, k);
}
function TRIMMEAN2(array3, percent) {
  return TRIMMEAN(array3, percent);
}
function COUNTIF2(range2, criteria) {
  const normalizedRange = normalizeCountifArg(range2);
  const normalizedCriteria = normalizeCountifArg(criteria);
  return COUNTIF(normalizedRange, normalizedCriteria);
}
function COUNTBLANK2(range2) {
  return COUNTBLANK(range2);
}
function AVERAGEA2(value1, value2, ...rest2) {
  const result = callVariadic(AVERAGEA, value1, value2, ...rest2);
  if (isNumError(result)) {
    return DIV_ZERO_ERROR;
  }
  return result;
}
function MAXA2(value1, value2, ...rest2) {
  return callVariadic(MAXA, value1, value2, ...rest2);
}
function MINA2(value1, value2, ...rest2) {
  return callVariadic(MINA, value1, value2, ...rest2);
}
function STDEVPA2(value1, value2, ...rest2) {
  return callVariadic(STDEVPA, value1, value2, ...rest2);
}
function VARPA2(value1, value2, ...rest2) {
  return callVariadic(VARPA, value1, value2, ...rest2);
}
function STDEVA2(value1, value2, ...rest2) {
  return callVariadic(STDEVA, value1, value2, ...rest2);
}
function VARA2(value1, value2, ...rest2) {
  return callVariadic(VARA, value1, value2, ...rest2);
}
function COUNTIFS2(criteriaRange, criteria, ...rest2) {
  const rangeArgs = [criteriaRange];
  for (let idx = 0;idx < rest2.length; idx += 2) {
    rangeArgs.push(rest2[idx]);
  }
  const shapeError = ensureMatchingShapes(rangeArgs);
  if (shapeError) {
    return shapeError;
  }
  const normalizedArgs = [
    normalizeCountifArg(criteriaRange),
    normalizeCountifArg(criteria)
  ];
  for (let idx = 0;idx < rest2.length; idx += 2) {
    const rangeArg = rest2[idx];
    const criterionArg = rest2[idx + 1];
    normalizedArgs.push(normalizeCountifArg(rangeArg));
    normalizedArgs.push(criterionArg === undefined ? undefined : normalizeCountifArg(criterionArg));
  }
  return COUNTIFS(normalizedArgs[0], normalizedArgs[1], ...normalizedArgs.slice(2));
}
function AVERAGEIF(range2, criteria, averageRange) {
  return evaluateAverageIf(range2, criteria, averageRange);
}
function AVERAGEIFS2(averageRange, criteriaRange, criteria, ...rest2) {
  const rangeArgs = [criteriaRange];
  for (let idx = 0;idx < rest2.length; idx += 2) {
    rangeArgs.push(rest2[idx]);
  }
  const shapeError = validateRangeShapes(averageRange, rangeArgs);
  if (shapeError) {
    return shapeError;
  }
  const count3 = COUNTIFS(criteriaRange, criteria, ...rest2);
  const countError = normalizeScalarError(count3);
  if (countError) {
    return countError;
  }
  if (typeof count3 === "number" && count3 === 0) {
    return DIV_ZERO_ERROR;
  }
  return AVERAGEIFS(averageRange, criteriaRange, criteria, ...rest2);
}
function BINOM_DIST(numberS, trials, probabilityS, cumulative) {
  return BINOM.DIST(numberS, trials, probabilityS, cumulative);
}
function BINOM_INV(trials, probabilityS, alpha) {
  return BINOM.INV(trials, probabilityS, alpha);
}
function CONFIDENCE_NORM(alpha, standardDev, size2) {
  return CONFIDENCE.NORM(alpha, standardDev, size2);
}
function CONFIDENCE_T(alpha, standardDev, size2) {
  return CONFIDENCE.T(alpha, standardDev, size2);
}
function CHISQ_TEST(actualRange, expectedRange) {
  return CHISQ.TEST(actualRange, expectedRange);
}
function F_TEST(array1, array22) {
  const shape1 = getFunctionArgShape(array1);
  if (isErrorValue2(shape1)) {
    return shape1;
  }
  const shape2 = getFunctionArgShape(array22);
  if (isErrorValue2(shape2)) {
    return shape2;
  }
  if (shape1.rows * shape1.cols !== shape2.rows * shape2.cols) {
    return NA_ERROR;
  }
  return F.TEST(array1, array22);
}
function COVARIANCE_P(array1, array22) {
  return COVARIANCE.P(array1, array22);
}
function COVARIANCE_S(array1, array22) {
  return COVARIANCE.S(array1, array22);
}
function EXPON_DIST(x2, lambda, cumulative) {
  return EXPON.DIST(x2, lambda, cumulative);
}
function GAMMA_DIST(x2, alpha, beta, cumulative) {
  const xValue = coerceNonNegativeNumber(x2);
  if (typeof xValue !== "number") {
    return xValue;
  }
  const alphaValue = coercePositiveNumber(alpha);
  if (typeof alphaValue !== "number") {
    return alphaValue;
  }
  const betaValue = coercePositiveNumber(beta);
  if (typeof betaValue !== "number") {
    return betaValue;
  }
  return GAMMA.DIST(xValue, alphaValue, betaValue, cumulative);
}
function GAMMA_INV(probability, alpha, beta) {
  const probabilityValue = coerceProbability(probability, {
    inclusiveZero: false,
    inclusiveOne: false
  });
  if (typeof probabilityValue !== "number") {
    return probabilityValue;
  }
  const alphaValue = coercePositiveNumber(alpha);
  if (typeof alphaValue !== "number") {
    return alphaValue;
  }
  const betaValue = coercePositiveNumber(beta);
  if (typeof betaValue !== "number") {
    return betaValue;
  }
  return GAMMA.INV(probabilityValue, alphaValue, betaValue);
}
function MODE_MULT(number1, number22, ...rest2) {
  return callVariadic(MODE.MULT, number1, number22, ...rest2);
}
function MODE_SNGL(number1, number22, ...rest2) {
  return callVariadic(MODE.SNGL, number1, number22, ...rest2);
}
function NORM_DIST(x2, mean3, standardDev, cumulative) {
  return NORM.DIST(x2, mean3, standardDev, cumulative);
}
function NORM_INV(probability, mean3, standardDev) {
  return NORM.INV(probability, mean3, standardDev);
}
function PERCENTILE_EXC(array3, k) {
  const normalized = normalizePercentileArray(array3);
  if (isErrorValue2(normalized)) {
    return normalized;
  }
  return PERCENTILE.EXC(normalized, k);
}
function PERCENTILE_INC(array3, k) {
  const normalized = normalizePercentileArray(array3);
  if (isErrorValue2(normalized)) {
    return normalized;
  }
  return PERCENTILE.INC(normalized, k);
}
function PERCENTRANK_EXC(array3, x2, significance) {
  const normalized = normalizePercentileArray(array3);
  if (isErrorValue2(normalized)) {
    return normalized;
  }
  if (normalized.length < 2) {
    return NUM_ERROR;
  }
  const xValue = coerceNumberArg(x2);
  if (typeof xValue !== "number") {
    return xValue;
  }
  const min3 = Math.min(...normalized);
  const max4 = Math.max(...normalized);
  if (!Number.isFinite(min3) || !Number.isFinite(max4) || min3 === max4) {
    return NUM_ERROR;
  }
  if (xValue <= min3 || xValue >= max4) {
    return NUM_ERROR;
  }
  return PERCENTRANK.EXC(normalized, xValue, significance);
}
function PERCENTRANK_INC(array3, x2, significance) {
  return PERCENTRANK.INC(array3, x2, significance);
}
function POISSON_DIST(x2, mean3, cumulative) {
  const events = coerceNonNegativeInteger(x2);
  if (typeof events !== "number") {
    return events;
  }
  const meanValue = coerceNonNegativeNumber(mean3);
  if (typeof meanValue !== "number") {
    return meanValue;
  }
  return POISSON.DIST(events, meanValue, cumulative);
}
function QUARTILE_EXC(array3, quart) {
  const normalized = normalizePercentileArray(array3);
  if (isErrorValue2(normalized)) {
    return normalized;
  }
  const quartile = coerceQuartileSelector(quart);
  if (typeof quartile !== "number") {
    return quartile;
  }
  if (quartile < 1 || quartile > 3) {
    return { kind: "Error", code: NUM_ERROR_CODE };
  }
  return PERCENTILE.EXC(normalized, quartile / 4);
}
function QUARTILE_INC(array3, quart) {
  const normalized = normalizePercentileArray(array3);
  if (isErrorValue2(normalized)) {
    return normalized;
  }
  const quartile = coerceQuartileSelector(quart);
  if (typeof quartile !== "number") {
    return quartile;
  }
  if (quartile < 0 || quartile > 4) {
    return { kind: "Error", code: NUM_ERROR_CODE };
  }
  return PERCENTILE.INC(normalized, quartile / 4);
}
function coerceQuartileSelector(value2) {
  const scalar = extractScalarFromFunctionArg(value2);
  if (scalar === undefined) {
    return VALUE_ERROR;
  }
  if (isErrorValue2(scalar)) {
    return scalar;
  }
  if (scalar instanceof Error) {
    return VALUE_ERROR;
  }
  if (scalar == null || scalar === "") {
    return VALUE_ERROR;
  }
  if (typeof scalar === "number") {
    return Number.isFinite(scalar) ? Math.trunc(scalar) : VALUE_ERROR;
  }
  if (typeof scalar === "boolean") {
    return scalar ? 1 : 0;
  }
  if (typeof scalar === "string") {
    const trimmed = scalar.trim();
    if (trimmed === "") {
      return VALUE_ERROR;
    }
    const parsed = Number(trimmed);
    return Number.isFinite(parsed) ? Math.trunc(parsed) : VALUE_ERROR;
  }
  return VALUE_ERROR;
}
function extractScalarFromFunctionArg(value2) {
  if (value2 === undefined) {
    return;
  }
  if (Array.isArray(value2)) {
    return value2[0]?.[0] ?? null;
  }
  const scalar = value2;
  if (isArrayValue(scalar)) {
    return scalar.values[0]?.[0] ?? null;
  }
  return scalar;
}
function _XLFN_QUARTILE_INC(array3, quart) {
  return QUARTILE_INC(array3, quart);
}
function RANK_AVG(numberParam, ref2, order) {
  return RANK.AVG(numberParam, ref2, order);
}
function RANK_EQ(numberParam, ref2, order) {
  return RANK.EQ(numberParam, ref2, order);
}
function STDEV_S(number1, number22, ...rest2) {
  return callVariadic(STDEV.S, number1, number22, ...rest2);
}
function _XLFN_STDEV_S(number1, number22, ...rest2) {
  return STDEV_S(number1, number22, ...rest2);
}
function STDEV_P(number1, number22, ...rest2) {
  return callVariadic(STDEV.P, number1, number22, ...rest2);
}
function _XLFN_STDEV_P(number1, number22, ...rest2) {
  return STDEV_P(number1, number22, ...rest2);
}
function T_DIST(x2, degFreedom, cumulative) {
  const xValue = coerceNumberArg(x2);
  if (typeof xValue !== "number") {
    return xValue;
  }
  const degrees = coerceDegreesOfFreedom(degFreedom);
  if (typeof degrees !== "number") {
    return degrees;
  }
  return T.DIST(xValue, degrees, cumulative);
}
function T_DIST_2T(x2, degFreedom) {
  const xValue = coerceNumberArg(x2);
  if (typeof xValue !== "number") {
    return xValue;
  }
  const degrees = coerceDegreesOfFreedom(degFreedom);
  if (typeof degrees !== "number") {
    return degrees;
  }
  return TDIST._2T(xValue, degrees);
}
function T_DIST_RT(x2, degFreedom) {
  const xValue = coerceNumberArg(x2);
  if (typeof xValue !== "number") {
    return xValue;
  }
  const degrees = coerceDegreesOfFreedom(degFreedom);
  if (typeof degrees !== "number") {
    return degrees;
  }
  return TDISTRT(xValue, degrees);
}
function T_INV(probability, degFreedom) {
  const probabilityValue = coerceProbability(probability, {
    inclusiveZero: false,
    inclusiveOne: false
  });
  if (typeof probabilityValue !== "number") {
    return probabilityValue;
  }
  const degrees = coerceDegreesOfFreedom(degFreedom);
  if (typeof degrees !== "number") {
    return degrees;
  }
  return T.INV(probabilityValue, degrees);
}
function T_INV_2T(probability, degFreedom) {
  const probabilityValue = coerceProbability(probability, {
    inclusiveZero: false,
    inclusiveOne: false
  });
  if (typeof probabilityValue !== "number") {
    return probabilityValue;
  }
  const degrees = coerceDegreesOfFreedom(degFreedom);
  if (typeof degrees !== "number") {
    return degrees;
  }
  const invTwoTail = TINV._2T;
  return invTwoTail(probabilityValue, degrees);
}
function VAR_S(number1, number22, ...rest2) {
  return callVariadic(VAR.S, number1, number22, ...rest2);
}
function VAR_P(number1, number22, ...rest2) {
  return callVariadic(VAR.P, number1, number22, ...rest2);
}
function WEIBULL_DIST(x2, alpha, beta, cumulative) {
  const xValue = coerceNonNegativeNumber(x2);
  if (typeof xValue !== "number") {
    return xValue;
  }
  const alphaValue = coercePositiveNumber(alpha);
  if (typeof alphaValue !== "number") {
    return alphaValue;
  }
  const betaValue = coercePositiveNumber(beta);
  if (typeof betaValue !== "number") {
    return betaValue;
  }
  return WEIBULL.DIST(xValue, alphaValue, betaValue, cumulative);
}
function BETA_DIST(x2, alpha, beta, cumulative, a, b) {
  return BETA.DIST(x2, alpha, beta, cumulative, a, b);
}
function BETA_INV(probability, alpha, beta, a, b) {
  return BETA.INV(probability, alpha, beta, a, b);
}
function CHISQ_DIST(x2, degFreedom, cumulative) {
  const xValue = coerceNonNegativeNumber(x2);
  if (typeof xValue !== "number") {
    return xValue;
  }
  const degrees = coerceDegreesOfFreedom(degFreedom);
  if (typeof degrees !== "number") {
    return degrees;
  }
  return CHISQ.DIST(xValue, degrees, cumulative);
}
function CHISQ_DIST_RT(x2, degFreedom) {
  const xValue = coerceNonNegativeNumber(x2);
  if (typeof xValue !== "number") {
    return xValue;
  }
  const degrees = coerceDegreesOfFreedom(degFreedom);
  if (typeof degrees !== "number") {
    return degrees;
  }
  return CHIDISTRT(xValue, degrees);
}
function CHISQ_INV(probability, degFreedom) {
  const probabilityValue = coerceProbability(probability);
  if (typeof probabilityValue !== "number") {
    return probabilityValue;
  }
  const degrees = coerceDegreesOfFreedom(degFreedom);
  if (typeof degrees !== "number") {
    return degrees;
  }
  return CHISQ.INV(probabilityValue, degrees);
}
function CHISQ_INV_RT(probability, degFreedom) {
  const probabilityValue = coerceProbability(probability);
  if (typeof probabilityValue !== "number") {
    return probabilityValue;
  }
  const degrees = coerceDegreesOfFreedom(degFreedom);
  if (typeof degrees !== "number") {
    return degrees;
  }
  return CHIINVRT(probabilityValue, degrees);
}
function F_DIST(x2, degFreedom1, degFreedom2, cumulative) {
  const xValue = coerceNonNegativeNumber(x2);
  if (typeof xValue !== "number") {
    return xValue;
  }
  const degrees1 = coerceDegreesOfFreedom(degFreedom1);
  if (typeof degrees1 !== "number") {
    return degrees1;
  }
  const degrees2 = coerceDegreesOfFreedom(degFreedom2);
  if (typeof degrees2 !== "number") {
    return degrees2;
  }
  return F.DIST(xValue, degrees1, degrees2, cumulative);
}
function F_DIST_RT(x2, degFreedom1, degFreedom2) {
  const xValue = coerceNonNegativeNumber(x2);
  if (typeof xValue !== "number") {
    return xValue;
  }
  const degrees1 = coerceDegreesOfFreedom(degFreedom1);
  if (typeof degrees1 !== "number") {
    return degrees1;
  }
  const degrees2 = coerceDegreesOfFreedom(degFreedom2);
  if (typeof degrees2 !== "number") {
    return degrees2;
  }
  return FDISTRT(xValue, degrees1, degrees2);
}
function F_INV(probability, degFreedom1, degFreedom2) {
  const probabilityValue = coerceProbability(probability, {
    inclusiveZero: false,
    inclusiveOne: false
  });
  if (typeof probabilityValue !== "number") {
    return probabilityValue;
  }
  const degrees1 = coerceDegreesOfFreedom(degFreedom1);
  if (typeof degrees1 !== "number") {
    return degrees1;
  }
  const degrees2 = coerceDegreesOfFreedom(degFreedom2);
  if (typeof degrees2 !== "number") {
    return degrees2;
  }
  return F.INV(probabilityValue, degrees1, degrees2);
}
function F_INV_RT(probability, degFreedom1, degFreedom2) {
  const probabilityValue = coerceProbability(probability, {
    inclusiveZero: false,
    inclusiveOne: false
  });
  if (typeof probabilityValue !== "number") {
    return probabilityValue;
  }
  const degrees1 = coerceDegreesOfFreedom(degFreedom1);
  if (typeof degrees1 !== "number") {
    return degrees1;
  }
  const degrees2 = coerceDegreesOfFreedom(degFreedom2);
  if (typeof degrees2 !== "number") {
    return degrees2;
  }
  return FINVRT(probabilityValue, degrees1, degrees2);
}
function HYPGEOM_DIST(sampleS, numberSample, populationS, numberPop, cumulative) {
  return HYPGEOM.DIST(sampleS, numberSample, populationS, numberPop, cumulative);
}
function LOGNORM_DIST(x2, mean3, standardDev, cumulative) {
  return LOGNORM.DIST(x2, mean3, standardDev, cumulative);
}
function LOGNORM_INV(probability, mean3, standardDev) {
  return LOGNORM.INV(probability, mean3, standardDev);
}
function NEGBINOM_DIST(numberF, numberS, probabilityS, cumulative) {
  return NEGBINOM.DIST(numberF, numberS, probabilityS, cumulative);
}
function NORM_S_DIST(z2, cumulative) {
  return NORM.S.DIST(z2, cumulative);
}
function NORM_S_INV(probability) {
  return NORM.S.INV(probability);
}
function T_TEST(array1, array22, tails, typeParam) {
  const tailsValue = coercePositiveInteger(tails, { min: 1, max: 2 });
  if (typeof tailsValue !== "number") {
    return tailsValue;
  }
  const typeValue = coercePositiveInteger(typeParam, { min: 1, max: 3 });
  if (typeof typeValue !== "number") {
    return typeValue;
  }
  return T.TEST(array1, array22, tailsValue, typeValue);
}
function Z_TEST(array3, x2, sigma) {
  return Z.TEST(array3, x2, sigma);
}
function GAMMALN_PRECISE(x2) {
  return GAMMALN.PRECISE(x2);
}
function PERMUTATIONA2(numberParam, numberChosen) {
  return PERMUTATIONA(numberParam, numberChosen);
}
function BINOM_DIST_RANGE(trials, probabilityS, numberS, numberS2) {
  return BINOM.DIST.RANGE(trials, probabilityS, numberS, numberS2);
}
function GAMMA2(x2) {
  return GAMMA(x2);
}
function SKEW_P(number1, number22, ...rest2) {
  const valuesOrError = collectStatisticalNumbers([number1, number22, ...rest2]);
  if (!Array.isArray(valuesOrError)) {
    return valuesOrError;
  }
  const values = valuesOrError;
  if (values.length === 0) {
    return DIV0_ERROR;
  }
  const mean3 = values.reduce((acc, value2) => acc + value2, 0) / values.length;
  let sumSquared = 0;
  let sumCubed = 0;
  for (const value2 of values) {
    const delta = value2 - mean3;
    sumSquared += delta * delta;
    sumCubed += delta * delta * delta;
  }
  if (sumSquared === 0) {
    return DIV0_ERROR;
  }
  const n = values.length;
  const m2 = sumSquared / n;
  if (m2 === 0) {
    return DIV0_ERROR;
  }
  const denominator = Math.pow(Math.sqrt(m2), 3);
  if (denominator === 0) {
    return DIV0_ERROR;
  }
  const skew = sumCubed / n / denominator;
  return Number.isFinite(skew) ? skew : DIV0_ERROR;
}
function GAUSS2(x2) {
  return GAUSS(x2);
}
function PHI3(x2) {
  return PHI2(x2);
}
function FORECAST_LINEAR(x2, knownYs, knownXs) {
  return FORECAST(x2, knownYs, knownXs);
}
function sanitizeNumericRangeArg(arg, options) {
  if (Array.isArray(arg)) {
    const sanitizedRows = arg.map((row2) => {
      if (!row2) {
        return [];
      }
      return row2.map((value2) => sanitizeNumericScalar(value2, options) ?? null);
    });
    return sanitizedRows;
  }
  if (arg === undefined) {
    return;
  }
  const scalarArg = arg;
  if (isArrayValue(scalarArg)) {
    const sanitizedValues = scalarArg.values.map((row2) => row2.map((cell) => sanitizeNumericScalar(cell, options)));
    return {
      ...scalarArg,
      values: sanitizedValues
    };
  }
  return sanitizeNumericScalar(scalarArg, options);
}
function sanitizeNumericScalar(value2, options) {
  if (value2 == null) {
    return value2;
  }
  if (typeof value2 === "string") {
    const trimmed = value2.trim();
    if (trimmed === "") {
      if (options?.blankNonNumeric) {
        return null;
      }
      return value2;
    }
    const numeric = Number(trimmed);
    if (Number.isFinite(numeric)) {
      return numeric;
    }
    if (options?.blankNonNumeric) {
      return null;
    }
  }
  return value2;
}
function normalizeCountifArg(arg) {
  if (Array.isArray(arg)) {
    const normalizedRows = arg.map((row2) => {
      if (!row2) {
        return [];
      }
      return row2.map((value2) => normalizeCountifScalar(value2) ?? null);
    });
    return normalizedRows;
  }
  if (arg === undefined) {
    return;
  }
  const scalarArg = arg;
  if (isArrayValue(scalarArg)) {
    const normalizedValues = scalarArg.values.map((row2) => row2.map((cell) => normalizeCountifScalar(cell)));
    return {
      ...scalarArg,
      values: normalizedValues
    };
  }
  return normalizeCountifScalar(scalarArg);
}
function normalizeCountifScalar(value2) {
  if (typeof value2 === "string") {
    return value2.toLowerCase();
  }
  return value2;
}
function MAXIFS2(maxRange, criteriaRange, criteria, ...rest2) {
  const rangeArgs = [criteriaRange];
  for (let idx = 0;idx < rest2.length; idx += 2) {
    rangeArgs.push(rest2[idx]);
  }
  const shapeError = validateRangeShapes(maxRange, rangeArgs);
  if (shapeError) {
    return shapeError;
  }
  const normalizedMaxRange = sanitizeNumericRangeArg(maxRange, {
    blankNonNumeric: true
  });
  const normalizedCriteriaRange = sanitizeNumericRangeArg(criteriaRange);
  const normalizedRest = [];
  for (let idx = 0;idx < rest2.length; idx += 2) {
    const rangeArg = rest2[idx];
    const criterionArg = rest2[idx + 1];
    if (rangeArg !== undefined) {
      normalizedRest.push(sanitizeNumericRangeArg(rangeArg));
    } else {
      normalizedRest.push(rangeArg);
    }
    if (criterionArg !== undefined) {
      normalizedRest.push(criterionArg);
    }
  }
  return MAXIFS(normalizedMaxRange, normalizedCriteriaRange, criteria, ...normalizedRest);
}
function MINIFS2(minRange, criteriaRange, criteria, ...rest2) {
  return MINIFS(minRange, criteriaRange, criteria, ...rest2);
}

// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/compatibility.js
function STDEV2(number1, number22, ...rest2) {
  return STDEV_S(number1, number22, ...rest2);
}
function VAR2(number1, number22, ...rest2) {
  return VAR_S(number1, number22, ...rest2);
}
function STDEVP2(number1, number22, ...rest2) {
  return STDEVP(number1, number22, ...rest2);
}
function VARP2(number1, number22, ...rest2) {
  return VARP(number1, number22, ...rest2);
}
function RANK2(numberParam, ref2, order) {
  return RANK_EQ(numberParam, ref2, order);
}
function BETADIST2(x2, alpha, beta, a, b) {
  return BETADIST(x2, alpha, beta, a, b);
}
function BETAINV2(probability, alpha, beta, a, b) {
  return BETAINV(probability, alpha, beta, a, b);
}
function BINOMDIST2(numberS, trials, probabilityS, cumulative) {
  return BINOMDIST(numberS, trials, probabilityS, cumulative);
}
function CHIDIST2(x2, degFreedom) {
  return CHIDIST(x2, degFreedom);
}
function CHIINV2(probability, degFreedom) {
  return CHIINV(probability, degFreedom);
}
function CONFIDENCE2(alpha, standardDev, size2) {
  throw new Error(`CONFIDENCE is not implemented. alpha=${String(alpha)}, standardDev=${String(standardDev)}, size=${String(size2)}`);
}
function CRITBINOM2(trials, probabilityS, alpha) {
  return CRITBINOM(trials, probabilityS, alpha);
}
function EXPONDIST2(x2, lambda, cumulative) {
  return EXPONDIST(x2, lambda, cumulative);
}
function FDIST2(x2, degFreedom1, degFreedom2) {
  return FDIST(x2, degFreedom1, degFreedom2);
}
function FINV2(probability, degFreedom1, degFreedom2) {
  return FINV(probability, degFreedom1, degFreedom2);
}
function FLOOR2(numberParam, significance) {
  return FLOOR(numberParam, significance);
}
function GAMMADIST2(x2, alpha, beta, cumulative) {
  return GAMMADIST(x2, alpha, beta, cumulative);
}
function GAMMAINV2(probability, alpha, beta) {
  return GAMMAINV(probability, alpha, beta);
}
function CEILING2(numberParam, significance) {
  return CEILING(numberParam, significance);
}
function HYPGEOMDIST2(sampleS, numberSample, populationS, numberPop) {
  return HYPGEOMDIST(sampleS, numberSample, populationS, numberPop, false);
}
function LOGNORMDIST2(x2, mean3, standardDev) {
  return LOGNORMDIST(x2, mean3, standardDev);
}
function LOGINV2(probability, mean3, standardDev) {
  return LOGINV(probability, mean3, standardDev);
}
function NEGBINOMDIST2(numberF, numberS, probabilityS) {
  return NEGBINOMDIST(numberF, numberS, probabilityS);
}
function NORMDIST2(x2, mean3, standardDev, cumulative) {
  return NORMDIST(x2, mean3, standardDev, cumulative);
}
function NORMSDIST2(z2) {
  return NORMSDIST(z2);
}
function NORMINV2(probability, mean3, standardDev) {
  return NORMINV(probability, mean3, standardDev);
}
function NORMSINV2(probability) {
  return NORMSINV(probability);
}
function POISSON2(x2, mean3, cumulative) {
  throw new Error(`POISSON is not implemented. x=${String(x2)}, mean=${String(mean3)}, cumulative=${String(cumulative)}`);
}
function TDIST2(x2, degFreedom, tails) {
  return TDIST(x2, degFreedom, tails);
}
function WEIBULL2(x2, alpha, beta, cumulative) {
  throw new Error(`WEIBULL is not implemented. x=${String(x2)}, alpha=${String(alpha)}, beta=${String(beta)}, cumulative=${String(cumulative)}`);
}
function CHITEST2(actualRange, expectedRange) {
  return CHITEST(actualRange, expectedRange);
}
function COVAR2(array1, array22) {
  return COVAR(array1, array22);
}
function FORECAST2(x2, knownYs, knownXs) {
  return FORECAST(x2, knownYs, knownXs);
}
function FTEST2(array1, array22) {
  return FTEST(array1, array22);
}
function TTEST2(array1, array22, tails, typeParam) {
  return TTEST(array1, array22, tails, typeParam);
}
function ZTEST2(array3, x2, sigma) {
  return ZTEST(array3, x2, sigma);
}
function QUARTILE2(array3, quart) {
  return QUARTILE_INC(array3, quart);
}
function PERCENTILE2(array3, k) {
  return PERCENTILE.INC(array3, k);
}
function PERCENTRANK2(array3, x2, significance) {
  return PERCENTRANK_INC(array3, x2, significance);
}
function MODE2(number1, number22, ...rest2) {
  throw new Error(`MODE is not implemented. number1=${String(number1)}, number2=${String(number22)}, rest.length=${rest2.length}`);
}
function TINV2(probability, degFreedom) {
  return TINV(probability, degFreedom);
}
function CONCATENATE2(text1, text2, ...rest2) {
  return CONCATENATE(text1, text2, ...rest2);
}
// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/cube.js
function CUBEVALUE(connection, memberExpression1, ...rest2) {
  throw new Error(`CUBEVALUE is not implemented. connection=${String(connection)}, memberExpression1=${String(memberExpression1)}, rest.length=${rest2.length}`);
}
function CUBEMEMBER(connection, memberExpression, caption) {
  throw new Error(`CUBEMEMBER is not implemented. connection=${String(connection)}, memberExpression=${String(memberExpression)}, caption=${String(caption)}`);
}
function CUBEMEMBERPROPERTY(connection, memberExpression, property) {
  throw new Error(`CUBEMEMBERPROPERTY is not implemented. connection=${String(connection)}, memberExpression=${String(memberExpression)}, property=${String(property)}`);
}
function CUBERANKEDMEMBER(connection, setExpression, rank, caption) {
  throw new Error(`CUBERANKEDMEMBER is not implemented. connection=${String(connection)}, setExpression=${String(setExpression)}, rank=${String(rank)}, caption=${String(caption)}`);
}
function CUBEKPIMEMBER(connection, kpiName, kpiProperty, caption) {
  throw new Error(`CUBEKPIMEMBER is not implemented. connection=${String(connection)}, kpiName=${String(kpiName)}, kpiProperty=${String(kpiProperty)}, caption=${String(caption)}`);
}
function CUBESET(connection, setExpression, caption, sortOrder, sortBy) {
  throw new Error(`CUBESET is not implemented. connection=${String(connection)}, setExpression=${String(setExpression)}, caption=${String(caption)}, sortOrder=${String(sortOrder)}, sortBy=${String(sortBy)}`);
}
function CUBESETCOUNT(setParam) {
  throw new Error(`CUBESETCOUNT is not implemented. setParam=${String(setParam)}`);
}
// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/database.js
var VALUE_ERROR2 = { kind: "Error", code: "#VALUE!" };
var EXCEL_EPOCH_MS2 = Date.UTC(1899, 11, 30);
var MS_PER_DAY2 = 24 * 60 * 60 * 1000;
function DCOUNT2(database, field, criteria) {
  return DCOUNT(normalizeDatabaseRangeArg(database), field, normalizeCriteriaRangeArg(criteria));
}
function DSUM(database, field, criteria) {
  const rows = coerceRowMajorRange(database);
  if (rows.length === 0) {
    return 0;
  }
  const headerRow = rows[0] ?? [];
  const headerMap = buildHeaderIndexMap(headerRow);
  const fieldIndex = resolveFieldIndex(field, headerRow, headerMap);
  if (fieldIndex == null) {
    return VALUE_ERROR2;
  }
  const criteriaSets = buildCriteriaSets(criteria, headerMap);
  if (criteriaSets === null) {
    return 0;
  }
  const dataRows = rows.slice(1);
  let sum2 = 0;
  for (const row2 of dataRows) {
    if (!row2) {
      continue;
    }
    if (!matchesCriteria(row2, criteriaSets)) {
      continue;
    }
    if (!row2[fieldIndex]) {
      continue;
    }
    const numericValue = coerceNumericValue(row2[fieldIndex]);
    if (numericValue == null) {
      continue;
    }
    sum2 += numericValue;
  }
  return sum2;
}
function DAVERAGE2(database, field, criteria) {
  return DAVERAGE(normalizeDatabaseRangeArg(database), field, normalizeCriteriaRangeArg(criteria));
}
function DMIN2(database, field, criteria) {
  return DMIN(normalizeDatabaseRangeArg(database), field, normalizeCriteriaRangeArg(criteria));
}
function DMAX2(database, field, criteria) {
  return DMAX(normalizeDatabaseRangeArg(database), field, normalizeCriteriaRangeArg(criteria));
}
function DSTDEV2(database, field, criteria) {
  return DSTDEV(normalizeDatabaseRangeArg(database), field, normalizeCriteriaRangeArg(criteria));
}
function DVAR2(database, field, criteria) {
  return DVAR(normalizeDatabaseRangeArg(database), field, normalizeCriteriaRangeArg(criteria));
}
function DPRODUCT2(database, field, criteria) {
  return DPRODUCT(normalizeDatabaseRangeArg(database), field, normalizeCriteriaRangeArg(criteria));
}
function DSTDEVP2(database, field, criteria) {
  return DSTDEVP(normalizeDatabaseRangeArg(database), field, normalizeCriteriaRangeArg(criteria));
}
function DVARP2(database, field, criteria) {
  return DVARP(normalizeDatabaseRangeArg(database), field, normalizeCriteriaRangeArg(criteria));
}
function DCOUNTA2(database, field, criteria) {
  return DCOUNTA(normalizeDatabaseRangeArg(database), field, normalizeCriteriaRangeArg(criteria));
}
function DGET2(database, field, criteria) {
  return DGET(normalizeDatabaseRangeArg(database), field, normalizeCriteriaRangeArg(criteria));
}
function normalizeDatabaseRangeArg(arg) {
  return normalizeTableLikeArg(arg);
}
function normalizeCriteriaRangeArg(arg) {
  return normalizeTableLikeArg(arg);
}
function normalizeTableLikeArg(arg) {
  if (Array.isArray(arg)) {
    return transposeRows(arg);
  }
  if (arg !== undefined && isArrayValue(arg)) {
    const arrayValue = arg;
    return transposeRows(arrayValue.values);
  }
  return arg;
}
function transposeRows(rows) {
  if (!rows || rows.length === 0) {
    return rows ?? [];
  }
  const columnCount = rows.reduce((max4, row2) => Math.max(max4, row2?.length ?? 0), 0);
  if (columnCount === 0) {
    return [];
  }
  const result = [];
  for (let columnIndex2 = 0;columnIndex2 < columnCount; columnIndex2 += 1) {
    const column2 = [];
    for (let rowIndex2 = 0;rowIndex2 < rows.length; rowIndex2 += 1) {
      const row2 = rows[rowIndex2];
      column2.push(row2?.[columnIndex2] ?? null);
    }
    result.push(column2);
  }
  return result;
}
function coerceRowMajorRange(arg) {
  if (Array.isArray(arg)) {
    return arg.map((row2) => row2 ? [...row2] : []);
  }
  if (arg !== undefined && isArrayValue(arg)) {
    const arrayValue = arg;
    return arrayValue.values.map((row2) => [...row2]);
  }
  return [];
}
function buildHeaderIndexMap(headers) {
  const map4 = new Map;
  headers.forEach((value2, index) => {
    const key = normalizeHeaderKey(value2);
    if (key && !map4.has(key)) {
      map4.set(key, index);
    }
  });
  return map4;
}
function normalizeHeaderKey(value2) {
  if (typeof value2 === "string" && value2.trim()) {
    return value2.trim().toUpperCase();
  }
  return null;
}
function resolveFieldIndex(field, headers, headerMap) {
  const scalarField = extractScalarValue(field);
  if (scalarField == null) {
    return null;
  }
  if (typeof scalarField === "number" && Number.isFinite(scalarField)) {
    const zeroBased = Math.trunc(scalarField) - 1;
    if (zeroBased < 0 || zeroBased >= headers.length) {
      return null;
    }
    return zeroBased;
  }
  const headerKey = normalizeHeaderKey(scalarField);
  if (!headerKey) {
    return null;
  }
  const index = headerMap.get(headerKey);
  return index ?? null;
}
function buildCriteriaSets(criteriaArg, headerMap) {
  const rows = coerceRowMajorRange(criteriaArg);
  if (rows.length === 0) {
    return [];
  }
  const headerRow = rows[0] ?? [];
  const headerKeys = headerRow.map((value2) => normalizeHeaderKey(value2));
  if (!headerKeys.some((key) => key && headerMap.has(key))) {
    return null;
  }
  const result = [];
  for (let rowIndex2 = 1;rowIndex2 < rows.length; rowIndex2 += 1) {
    const row2 = rows[rowIndex2] ?? [];
    const conditions = [];
    for (let colIndex = 0;colIndex < row2.length; colIndex += 1) {
      const headerKey = headerKeys[colIndex];
      if (!headerKey) {
        continue;
      }
      const columnIndex2 = headerMap.get(headerKey);
      if (columnIndex2 == null) {
        continue;
      }
      const value2 = row2[colIndex];
      if (value2 == undefined) {
        continue;
      }
      const predicate = buildCriterionPredicate(value2);
      if (!predicate) {
        continue;
      }
      conditions.push({ columnIndex: columnIndex2, test: predicate });
    }
    if (conditions.length > 0) {
      result.push(conditions);
    }
  }
  if (result.length === 0) {
    result.push([]);
  }
  return result;
}
function matchesCriteria(row2, criteriaSets) {
  if (criteriaSets.length === 0) {
    return true;
  }
  for (const conditions of criteriaSets) {
    let matches = true;
    for (const condition of conditions) {
      const value2 = row2[condition.columnIndex];
      if (value2 == undefined) {
        continue;
      }
      if (!condition.test(value2)) {
        matches = false;
        break;
      }
    }
    if (matches) {
      return true;
    }
  }
  return false;
}
function buildCriterionPredicate(condition) {
  if (condition == null) {
    return null;
  }
  if (typeof condition === "boolean") {
    return (value2) => Boolean(value2) === condition;
  }
  if (typeof condition === "number" && Number.isFinite(condition)) {
    return (value2) => compareNumbers(coerceNumericValue(value2), condition, "=");
  }
  if (condition instanceof Date) {
    const serial = dateToExcelSerial(condition);
    return (value2) => compareNumbers(coerceNumericValue(value2), serial, "=");
  }
  const text2 = normalizeCriterionText(String(condition));
  if (!text2) {
    return null;
  }
  const operatorMatch = text2.match(/^(<=|>=|<>|=|<|>)/);
  const operator = operatorMatch ? operatorMatch[0] : "=";
  const operandText = text2.slice(operator.length).trim();
  if ((operator === "=" || operator === "<>") && containsWildcards(operandText)) {
    const regex = wildcardToRegex(operandText);
    return (value2) => {
      const candidate = normalizeCriterionText(String(value2 ?? "")).toUpperCase();
      const isMatch = regex.test(candidate);
      return operator === "=" ? isMatch : !isMatch;
    };
  }
  const operandNumber = coerceNumberFromText(operandText);
  if (operandNumber != null) {
    return (value2) => compareNumbers(coerceNumericValue(value2), operandNumber, operator);
  }
  if (operator !== "=" && operator !== "<>") {
    return () => false;
  }
  const operandUpper = operandText.toUpperCase();
  return (value2) => compareStrings(normalizeCriterionText(String(value2 ?? "")).toUpperCase(), operandUpper, operator);
}
function extractScalarValue(arg) {
  if (Array.isArray(arg)) {
    return arg[0]?.[0];
  }
  if (arg !== undefined && isArrayValue(arg)) {
    const arrayValue = arg;
    return arrayValue.values[0]?.[0];
  }
  return arg;
}
function coerceNumericValue(value2) {
  if (typeof value2 === "number" && Number.isFinite(value2)) {
    return value2;
  }
  if (value2 instanceof Date) {
    return dateToExcelSerial(value2);
  }
  if (typeof value2 === "boolean") {
    return value2 ? 1 : 0;
  }
  if (typeof value2 === "string") {
    const trimmed = value2.trim();
    if (!trimmed) {
      return null;
    }
    const numeric = Number(trimmed);
    return Number.isFinite(numeric) ? numeric : null;
  }
  return null;
}
function coerceNumberFromText(text2) {
  if (!text2) {
    return null;
  }
  const numeric = Number(text2);
  if (Number.isFinite(numeric)) {
    return numeric;
  }
  const parsedDate = parseDateTextToTimestamp(text2);
  if (parsedDate != null) {
    return (parsedDate - EXCEL_EPOCH_MS2) / MS_PER_DAY2;
  }
  return null;
}
function parseDateTextToTimestamp(text2) {
  const cleaned = text2.replace(/[-.]/g, "/").trim();
  if (!cleaned) {
    return null;
  }
  const parts = cleaned.split("/");
  if (parts.length !== 3) {
    return null;
  }
  const [yearPart, monthPart, dayPart] = parts;
  const year = Number(yearPart);
  const month = Number(monthPart);
  const day = Number(dayPart);
  if (!Number.isFinite(year) || !Number.isFinite(month) || !Number.isFinite(day)) {
    return null;
  }
  const date6 = new Date(year, month - 1, day);
  if (Number.isNaN(date6.getTime())) {
    return null;
  }
  return date6.getTime();
}
function normalizeCriterionText(text2) {
  let result = "";
  for (const char of text2.trim()) {
    switch (char) {
      case "／":
        result += "/";
        break;
      case "－":
        result += "-";
        break;
      case "，":
        result += ",";
        break;
      default:
        result += char;
        break;
    }
  }
  return result.trim();
}
function containsWildcards(value2) {
  return value2.includes("*") || value2.includes("?");
}
function wildcardToRegex(pattern) {
  const escaped = pattern.toUpperCase().replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*").replace(/\\\?/g, ".");
  return new RegExp(`^${escaped}$`, "u");
}
function compareNumbers(left, right, operator) {
  if (left == null) {
    return operator === "<>" ? right !== 0 : false;
  }
  switch (operator) {
    case "<":
      return left < right;
    case "<=":
      return left <= right;
    case ">":
      return left > right;
    case ">=":
      return left >= right;
    case "<>":
      return left !== right;
    case "=":
    default:
      return left === right;
  }
}
function compareStrings(left, right, operator) {
  switch (operator) {
    case "<":
      return left < right;
    case "<=":
      return left <= right;
    case ">":
      return left > right;
    case ">=":
      return left >= right;
    case "<>":
      return left !== right;
    case "=":
    default:
      return left === right;
  }
}
function dateToExcelSerial(date6) {
  return (date6.getTime() - EXCEL_EPOCH_MS2) / MS_PER_DAY2;
}
// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/date-time.js
var EXCEL_EPOCH_MS3 = Date.UTC(1899, 11, 30);
var MS_PER_DAY3 = 24 * 60 * 60 * 1000;
function toExcelSerialFromDate(value2) {
  if (value2 instanceof Date) {
    return (value2.getTime() - EXCEL_EPOCH_MS3) / MS_PER_DAY3;
  }
  return value2;
}
function DATE2(year, month, day) {
  return DATE(year, month, day);
}
function TIME2(hour, minute, second) {
  return TIME(hour, minute, second);
}
function DAY2(serialNumber) {
  return DAY(serialNumber);
}
function MONTH2(serialNumber) {
  return MONTH(serialNumber);
}
function YEAR2(serialNumber) {
  return YEAR(serialNumber);
}
function WEEKDAY2(serialNumber, returnType) {
  return WEEKDAY(serialNumber, returnType);
}
function HOUR2(serialNumber) {
  return HOUR(serialNumber);
}
function MINUTE2(serialNumber) {
  return MINUTE(serialNumber);
}
function SECOND2(serialNumber) {
  return SECOND(serialNumber);
}
function NOW2() {
  return NOW();
}
function DATEVALUE2(dateText) {
  return toExcelSerialFromDate(DATEVALUE(dateText));
}
function TIMEVALUE2(timeText) {
  return TIMEVALUE(timeText);
}
function DAYS3602(startDate, endDate, method) {
  return DAYS360(startDate, endDate, method);
}
function TODAY2() {
  return TODAY();
}
function EDATE2(startDate, months) {
  return EDATE(startDate, months);
}
function EOMONTH2(startDate, months) {
  return EOMONTH(startDate, months);
}
function YEARFRAC2(startDate, endDate, basis2) {
  return YEARFRAC(startDate, endDate, basis2);
}
function WEEKNUM2(serialNumber, returnType) {
  return WEEKNUM(serialNumber, returnType);
}
function WORKDAY2(startDate, days, holidays) {
  return WORKDAY(startDate, days, holidays);
}
function NETWORKDAYS2(startDate, endDate, holidays) {
  return NETWORKDAYS(startDate, endDate, holidays);
}
function NETWORKDAYS_INTL(startDate, endDate, weekend, holidays) {
  return NETWORKDAYS.INTL(startDate, endDate, weekend, holidays);
}
function WORKDAY_INTL(startDate, days, weekend, holidays) {
  return WORKDAY.INTL(startDate, days, weekend, holidays);
}
function DAYS2(endDate, startDate) {
  return DAYS(endDate, startDate);
}
function ISOWEEKNUM2(date6) {
  return ISOWEEKNUM(date6);
}
// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/engineering.js
function HEX2BIN2(numberParam, places) {
  return HEX2BIN(numberParam, places);
}
function HEX2DEC2(numberParam) {
  return HEX2DEC(numberParam);
}
function HEX2OCT2(numberParam, places) {
  return HEX2OCT(numberParam, places);
}
function DEC2BIN2(numberParam, places) {
  return DEC2BIN(numberParam, places);
}
function DEC2HEX2(numberParam, places) {
  return DEC2HEX(numberParam, places);
}
function DEC2OCT2(numberParam, places) {
  return DEC2OCT(numberParam, places);
}
function OCT2BIN2(numberParam, places) {
  return OCT2BIN(numberParam, places);
}
function OCT2HEX2(numberParam, places) {
  return OCT2HEX(numberParam, places);
}
function OCT2DEC2(numberParam) {
  return OCT2DEC(numberParam);
}
function BIN2DEC2(numberParam) {
  return BIN2DEC(numberParam);
}
function BIN2OCT2(numberParam, places) {
  return BIN2OCT(numberParam, places);
}
function BIN2HEX2(numberParam, places) {
  return BIN2HEX(numberParam, places);
}
function IMSUB2(inumber1, inumber2) {
  return IMSUB(inumber1, inumber2);
}
function IMDIV2(inumber1, inumber2) {
  return IMDIV(inumber1, inumber2);
}
function IMPOWER2(inumber, numberParam) {
  return IMPOWER(inumber, numberParam);
}
function IMABS2(inumber) {
  return IMABS(inumber);
}
function IMSQRT2(inumber) {
  return IMSQRT(inumber);
}
function IMLN2(inumber) {
  return IMLN(inumber);
}
function IMLOG22(inumber) {
  return IMLOG2(inumber);
}
function IMLOG102(inumber) {
  return IMLOG10(inumber);
}
function IMSIN2(inumber) {
  return IMSIN(inumber);
}
function IMCOS2(inumber) {
  return IMCOS(inumber);
}
function IMEXP2(inumber) {
  return IMEXP(inumber);
}
function IMARGUMENT2(inumber) {
  return IMARGUMENT(inumber);
}
function IMCONJUGATE2(inumber) {
  return IMCONJUGATE(inumber);
}
function IMAGINARY2(inumber) {
  return IMAGINARY(inumber);
}
function IMREAL2(inumber) {
  return IMREAL(inumber);
}
function COMPLEX2(realNum, iNum, suffix) {
  return COMPLEX(realNum, iNum, suffix);
}
function IMSUM2(inumber1, inumber2, ...rest2) {
  return IMSUM(inumber1, inumber2, ...rest2);
}
function IMPRODUCT2(inumber1, inumber2, ...rest2) {
  return IMPRODUCT(inumber1, inumber2, ...rest2);
}
function DELTA2(number1, number22) {
  return DELTA(number1, number22);
}
function GESTEP2(numberParam, step) {
  return GESTEP(numberParam, step);
}
function ERF2(lowerLimit, upperLimit) {
  return ERF(lowerLimit, upperLimit);
}
function ERFC2(x2) {
  return ERFC(x2);
}
function BESSELJ2(x2, n) {
  return BESSELJ(x2, n);
}
function BESSELK2(x2, n) {
  return BESSELK(x2, n);
}
function BESSELY2(x2, n) {
  return BESSELY(x2, n);
}
function BESSELI2(x2, n) {
  return BESSELI(x2, n);
}
function CONVERT2(numberParam, fromUnit, toUnit) {
  return CONVERT(numberParam, fromUnit, toUnit);
}
function ERF_PRECISE(x2) {
  return ERF(x2);
}
function ERFC_PRECISE(x2) {
  return ERFC(x2);
}
function IMTAN2(inumber) {
  return IMTAN(inumber);
}
function IMCOT2(inumber) {
  return IMCOT(inumber);
}
function IMCSC2(inumber) {
  return IMCSC(inumber);
}
function IMCSCH2(inumber) {
  return IMCSCH(inumber);
}
function IMSEC2(inumber) {
  return IMSEC(inumber);
}
function IMSECH2(inumber) {
  return IMSECH(inumber);
}
function BITAND2(number1, number22) {
  return BITAND(number1, number22);
}
function BITOR2(number1, number22) {
  return BITOR(number1, number22);
}
function BITXOR2(number1, number22) {
  return BITXOR(number1, number22);
}
function BITLSHIFT2(numberParam, shiftAmount) {
  return BITLSHIFT(numberParam, shiftAmount);
}
function BITRSHIFT2(numberParam, shiftAmount) {
  return BITRSHIFT(numberParam, shiftAmount);
}
function IMSINH2(inumber) {
  return IMSINH(inumber);
}
function IMCOSH2(inumber) {
  return IMCOSH(inumber);
}
// node_modules/date-fns/constants.js
var daysInYear = 365.2425;
var maxTime = Math.pow(10, 8) * 24 * 60 * 60 * 1000;
var minTime = -maxTime;
var millisecondsInDay = 86400000;
var secondsInHour = 3600;
var secondsInDay = secondsInHour * 24;
var secondsInWeek = secondsInDay * 7;
var secondsInYear = secondsInDay * daysInYear;
var secondsInMonth = secondsInYear / 12;
var secondsInQuarter = secondsInMonth * 3;
var constructFromSymbol = Symbol.for("constructDateFrom");

// node_modules/date-fns/constructFrom.js
function constructFrom(date6, value2) {
  if (typeof date6 === "function")
    return date6(value2);
  if (date6 && typeof date6 === "object" && constructFromSymbol in date6)
    return date6[constructFromSymbol](value2);
  if (date6 instanceof Date)
    return new date6.constructor(value2);
  return new Date(value2);
}

// node_modules/date-fns/toDate.js
function toDate2(argument, context) {
  return constructFrom(context || argument, argument);
}

// node_modules/date-fns/addMonths.js
function addMonths(date6, amount, options) {
  const _date2 = toDate2(date6, options?.in);
  if (isNaN(amount))
    return constructFrom(options?.in || date6, NaN);
  if (!amount) {
    return _date2;
  }
  const dayOfMonth = _date2.getDate();
  const endOfDesiredMonth = constructFrom(options?.in || date6, _date2.getTime());
  endOfDesiredMonth.setMonth(_date2.getMonth() + amount + 1, 0);
  const daysInMonth = endOfDesiredMonth.getDate();
  if (dayOfMonth >= daysInMonth) {
    return endOfDesiredMonth;
  } else {
    _date2.setFullYear(endOfDesiredMonth.getFullYear(), endOfDesiredMonth.getMonth(), dayOfMonth);
    return _date2;
  }
}

// node_modules/date-fns/_lib/getTimezoneOffsetInMilliseconds.js
function getTimezoneOffsetInMilliseconds(date6) {
  const _date2 = toDate2(date6);
  const utcDate = new Date(Date.UTC(_date2.getFullYear(), _date2.getMonth(), _date2.getDate(), _date2.getHours(), _date2.getMinutes(), _date2.getSeconds(), _date2.getMilliseconds()));
  utcDate.setUTCFullYear(_date2.getFullYear());
  return +date6 - +utcDate;
}

// node_modules/date-fns/_lib/normalizeDates.js
function normalizeDates(context, ...dates) {
  const normalize3 = constructFrom.bind(null, context || dates.find((date6) => typeof date6 === "object"));
  return dates.map(normalize3);
}

// node_modules/date-fns/startOfDay.js
function startOfDay2(date6, options) {
  const _date2 = toDate2(date6, options?.in);
  _date2.setHours(0, 0, 0, 0);
  return _date2;
}

// node_modules/date-fns/differenceInCalendarDays.js
function differenceInCalendarDays(laterDate, earlierDate, options) {
  const [laterDate_, earlierDate_] = normalizeDates(options?.in, laterDate, earlierDate);
  const laterStartOfDay = startOfDay2(laterDate_);
  const earlierStartOfDay = startOfDay2(earlierDate_);
  const laterTimestamp = +laterStartOfDay - getTimezoneOffsetInMilliseconds(laterStartOfDay);
  const earlierTimestamp = +earlierStartOfDay - getTimezoneOffsetInMilliseconds(earlierStartOfDay);
  return Math.round((laterTimestamp - earlierTimestamp) / millisecondsInDay);
}

// node_modules/date-fns/compareAsc.js
function compareAsc(dateLeft, dateRight) {
  const diff = +toDate2(dateLeft) - +toDate2(dateRight);
  if (diff < 0)
    return -1;
  else if (diff > 0)
    return 1;
  return diff;
}

// node_modules/date-fns/differenceInCalendarMonths.js
function differenceInCalendarMonths(laterDate, earlierDate, options) {
  const [laterDate_, earlierDate_] = normalizeDates(options?.in, laterDate, earlierDate);
  const yearsDiff = laterDate_.getFullYear() - earlierDate_.getFullYear();
  const monthsDiff = laterDate_.getMonth() - earlierDate_.getMonth();
  return yearsDiff * 12 + monthsDiff;
}

// node_modules/date-fns/differenceInDays.js
function differenceInDays(laterDate, earlierDate, options) {
  const [laterDate_, earlierDate_] = normalizeDates(options?.in, laterDate, earlierDate);
  const sign2 = compareLocalAsc(laterDate_, earlierDate_);
  const difference = Math.abs(differenceInCalendarDays(laterDate_, earlierDate_));
  laterDate_.setDate(laterDate_.getDate() - sign2 * difference);
  const isLastDayNotFull = Number(compareLocalAsc(laterDate_, earlierDate_) === -sign2);
  const result = sign2 * (difference - isLastDayNotFull);
  return result === 0 ? 0 : result;
}
function compareLocalAsc(laterDate, earlierDate) {
  const diff = laterDate.getFullYear() - earlierDate.getFullYear() || laterDate.getMonth() - earlierDate.getMonth() || laterDate.getDate() - earlierDate.getDate() || laterDate.getHours() - earlierDate.getHours() || laterDate.getMinutes() - earlierDate.getMinutes() || laterDate.getSeconds() - earlierDate.getSeconds() || laterDate.getMilliseconds() - earlierDate.getMilliseconds();
  if (diff < 0)
    return -1;
  if (diff > 0)
    return 1;
  return diff;
}

// node_modules/date-fns/endOfDay.js
function endOfDay(date6, options) {
  const _date2 = toDate2(date6, options?.in);
  _date2.setHours(23, 59, 59, 999);
  return _date2;
}

// node_modules/date-fns/endOfMonth.js
function endOfMonth(date6, options) {
  const _date2 = toDate2(date6, options?.in);
  const month = _date2.getMonth();
  _date2.setFullYear(_date2.getFullYear(), month + 1, 0);
  _date2.setHours(23, 59, 59, 999);
  return _date2;
}

// node_modules/date-fns/isLastDayOfMonth.js
function isLastDayOfMonth(date6, options) {
  const _date2 = toDate2(date6, options?.in);
  return +endOfDay(_date2, options) === +endOfMonth(_date2, options);
}

// node_modules/date-fns/differenceInMonths.js
function differenceInMonths(laterDate, earlierDate, options) {
  const [laterDate_, workingLaterDate, earlierDate_] = normalizeDates(options?.in, laterDate, laterDate, earlierDate);
  const sign2 = compareAsc(workingLaterDate, earlierDate_);
  const difference = Math.abs(differenceInCalendarMonths(workingLaterDate, earlierDate_));
  if (difference < 1)
    return 0;
  if (workingLaterDate.getMonth() === 1 && workingLaterDate.getDate() > 27)
    workingLaterDate.setDate(30);
  workingLaterDate.setMonth(workingLaterDate.getMonth() - sign2 * difference);
  let isLastMonthNotFull = compareAsc(workingLaterDate, earlierDate_) === -sign2;
  if (isLastDayOfMonth(laterDate_) && difference === 1 && compareAsc(laterDate_, earlierDate_) === 1) {
    isLastMonthNotFull = false;
  }
  const result = sign2 * (difference - +isLastMonthNotFull);
  return result === 0 ? 0 : result;
}

// node_modules/date-fns/getDate.js
function getDate(date6, options) {
  return toDate2(date6, options?.in).getDate();
}

// node_modules/date-fns/getMonth.js
function getMonth(date6, options) {
  return toDate2(date6, options?.in).getMonth();
}

// node_modules/date-fns/getYear.js
function getYear(date6, options) {
  return toDate2(date6, options?.in).getFullYear();
}

// node_modules/date-fns/isAfter.js
function isAfter(date6, dateToCompare) {
  return +toDate2(date6) > +toDate2(dateToCompare);
}

// node_modules/date-fns/isBefore.js
function isBefore(date6, dateToCompare) {
  return +toDate2(date6) < +toDate2(dateToCompare);
}

// node_modules/date-fns/isEqual.js
function isEqual(leftDate, rightDate) {
  return +toDate2(leftDate) === +toDate2(rightDate);
}

// node_modules/date-fns/setYear.js
function setYear(date6, year, options) {
  const date_ = toDate2(date6, options?.in);
  if (isNaN(+date_))
    return constructFrom(options?.in || date6, NaN);
  date_.setFullYear(year);
  return date_;
}

// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/bond-calculator/newton.js
var DEFAULT_TOL = 0.0000000000001;
var DEFAULT_EPS = 0.00000000000001;
var DEFAULT_MAX_ITER = 100;
function newton(f, fp, initialGuess, tol = DEFAULT_TOL, eps = DEFAULT_EPS, maxIter = DEFAULT_MAX_ITER) {
  let current = initialGuess;
  for (let iter = 0;iter <= maxIter; iter += 1) {
    const y2 = f(current);
    const slope = fp(current);
    if (Math.abs(slope) < eps) {
      throw new Error(`Newton's method failed to converge because yp is smaller than eps (${eps})`);
    }
    const next = current - y2 / slope;
    if (Math.abs(current - next) <= tol * Math.abs(next)) {
      return next;
    }
    current = next;
  }
  return current;
}

// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/bond-calculator/utils.js
var clampTo30 = (value2) => Math.min(value2, 30);
var base30360 = (d1, m1, y1, d2, m2, y2) => (y2 - y1) * 360 + (m2 - m1) * 30 + d2 - d1;
var countDays30E360 = (d1, m1, y1, d2, m2, y2) => base30360(clampTo30(d1), m1, y1, clampTo30(d2), m2, y2);
var countDays30360 = (d1, m1, y1, d2, m2, y2) => base30360(clampTo30(d1), m1, y1, d1 >= 30 ? clampTo30(d2) : d2, m2, y2);
var startOfEndOfMonth = (date6) => startOfDay2(endOfMonth(date6));
var isEndOfMonth = (date6) => isEqual(endOfDay(date6), endOfMonth(date6));
var isFebruary = (date6) => getMonth(date6) === 1;
var isEndOfFebruary = (date6) => isEndOfMonth(date6) && isFebruary(date6);
var endOfFebruary = (year) => startOfEndOfMonth(new Date(year, 1));
var addPeriods = (date6, frequency, periods) => addMonths(date6, 12 / frequency * periods);
var changeYear = (date1, date22) => {
  if (isEndOfFebruary(date1)) {
    return endOfFebruary(getYear(date22));
  }
  return setYear(date1, getYear(date22));
};

// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/bond-calculator/coupon.js
var toDate3 = (value2) => {
  const result = value2 instanceof Date ? new Date(value2.getTime()) : new Date(value2);
  if (Number.isNaN(result.getTime())) {
    throw new Error("Invalid date provided to coupon helper");
  }
  return result;
};
var isBeforeOrEqual = (left, right) => isBefore(left, right) || isEqual(left, right);
var days = (previous, next, frequency, convention) => {
  const previousDate = toDate3(previous);
  const nextDate = toDate3(next);
  switch (convention) {
    case "ACTUAL/365":
      return 365 / frequency;
    case "ACTUAL/ACTUAL":
      return differenceInDays(nextDate, previousDate);
    case "30U/360":
    case "30E/360":
    case "30/360":
    case "ACTUAL/360":
    default:
      return 360 / frequency;
  }
};
var accrued = (date1, date22, convention) => {
  const firstDate = toDate3(date1);
  const secondDate = toDate3(date22);
  let d1 = getDate(firstDate);
  const m1 = getMonth(firstDate);
  const y1 = getYear(firstDate);
  let d2 = getDate(secondDate);
  const m2 = getMonth(secondDate);
  const y2 = getYear(secondDate);
  switch (convention) {
    case "30/360":
      return countDays30360(d1, m1, y1, d2, m2, y2);
    case "30E/360":
      return countDays30E360(d1, m1, y1, d2, m2, y2);
    case "ACTUAL/360":
    case "ACTUAL/365":
    case "ACTUAL/ACTUAL":
      return differenceInDays(secondDate, firstDate);
    case "30U/360":
    default:
      if (isEndOfFebruary(firstDate)) {
        d1 = 30;
      }
      if (isEndOfFebruary(firstDate) && isEndOfFebruary(secondDate)) {
        d2 = 30;
      }
      return countDays30360(d1, m1, y1, d2, m2, y2);
  }
};
var buildSchedule = (settlement, maturity, frequency) => {
  const settlementDate = toDate3(settlement);
  const maturityDate = toDate3(maturity);
  const count3 = Math.max(4, frequency);
  const base = changeYear(maturityDate, settlementDate);
  const shouldSnapToEndOfMonth = isEndOfMonth(maturityDate);
  const result = [];
  for (let offset = 1 - count3;offset < count3; offset += 1) {
    const candidate = addPeriods(base, frequency, offset);
    result.push(shouldSnapToEndOfMonth ? startOfEndOfMonth(candidate) : candidate);
  }
  return result;
};
var previous = (settlement, maturity, frequency) => {
  const settlementDate = toDate3(settlement);
  const schedule = buildSchedule(settlementDate, maturity, frequency);
  let previousCouponDate = schedule[0];
  for (const date6 of schedule) {
    if (isBeforeOrEqual(date6, settlementDate)) {
      previousCouponDate = date6;
    }
  }
  return previousCouponDate;
};
var next = (settlement, maturity, frequency) => {
  const settlementDate = toDate3(settlement);
  const schedule = buildSchedule(settlementDate, maturity, frequency);
  for (const date6 of schedule) {
    if (isAfter(date6, settlementDate)) {
      return date6;
    }
  }
  return schedule[schedule.length - 1];
};
var num2 = (settlement, maturity, frequency) => {
  const nextCoupon = next(settlement, maturity, frequency);
  const months = differenceInMonths(toDate3(maturity), nextCoupon);
  return Math.ceil(1 + frequency / 12 * months);
};

// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/bond-calculator/bond.js
var priceForMultiplePeriods = (rate, yieldRate, redemption, frequency, dsc, periodDays, couponCount, accruedDays) => {
  let sum2 = redemption / (1 + yieldRate / frequency) ** (couponCount - 1 + dsc / periodDays) - 100 * rate * accruedDays / (frequency * periodDays);
  for (let k = 1;k <= couponCount; k += 1) {
    sum2 += 100 * rate / frequency / (1 + yieldRate / frequency) ** (k - 1 + dsc / periodDays);
  }
  return sum2;
};
var derivativePrice = (rate, yieldRate, redemption, frequency, dsc, periodDays, couponCount) => {
  let sum2 = -redemption / frequency * (couponCount - 1 + dsc / periodDays) * (1 + yieldRate / frequency) ** -(couponCount + dsc / periodDays);
  for (let k = 1;k <= couponCount; k += 1) {
    sum2 -= (100 * rate) ** 2 / frequency ** 2 * (k - 1 + dsc / periodDays) * (1 + yieldRate / frequency) ** -(k + dsc / periodDays);
  }
  return sum2;
};
var calcPrice = (settlement, maturity, rate, yieldRate, redemption, frequency, convention) => {
  const previous2 = previous(settlement, maturity, frequency);
  const next2 = next(settlement, maturity, frequency);
  const periodDays = days(previous2, next2, frequency, convention);
  const accruedDays = accrued(previous2, settlement, convention);
  const dsc = periodDays - accruedDays;
  const couponCount = num2(settlement, maturity, frequency);
  if (couponCount === 1) {
    const T1 = 100 * rate / frequency + redemption;
    const T2 = yieldRate / frequency * (dsc / periodDays) + 1;
    const T3 = 100 * rate * accruedDays / (frequency * periodDays);
    return T1 / T2 - T3;
  }
  return priceForMultiplePeriods(rate, yieldRate, redemption, frequency, dsc, periodDays, couponCount, accruedDays);
};
var calcYield = (settlement, maturity, rate, price, redemption, frequency, convention) => {
  const previous2 = previous(settlement, maturity, frequency);
  const next2 = next(settlement, maturity, frequency);
  const accruedDays = accrued(previous2, settlement, convention);
  let periodDays = days(previous2, next2, frequency, convention);
  let dsc = periodDays - accruedDays;
  const couponCount = num2(settlement, maturity, frequency);
  if (couponCount === 1) {
    dsc = accrued(settlement, maturity, convention);
    if (convention.includes("ACTUAL")) {
      periodDays = differenceInDays(maturity, previous2);
    }
    return (redemption / 100 + rate / frequency - price / 100 - accruedDays / periodDays * (rate / frequency)) / (price / 100 + accruedDays / periodDays * (rate / frequency)) * frequency * (periodDays / dsc);
  }
  const f = (guess) => priceForMultiplePeriods(rate, guess, redemption, frequency, dsc, periodDays, couponCount, accruedDays) - price;
  const fp = (guess) => derivativePrice(rate, guess, redemption, frequency, dsc, periodDays, couponCount);
  return newton(f, fp, rate);
};

// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/bond-calculator/bond-calculator.js
var VALID_FREQUENCIES = new Set([1, 2, 4, 12]);
var VALID_CONVENTIONS = new Set([
  "30U/360",
  "ACTUAL/ACTUAL",
  "ACTUAL/360",
  "ACTUAL/365",
  "30E/360",
  "30/360"
]);
var cloneDate = (value2) => new Date(value2.getTime());
var toDate4 = (value2, field) => {
  if (value2 instanceof Date) {
    if (Number.isNaN(value2.getTime())) {
      throw new Error(`${field} must be a valid date`);
    }
    return cloneDate(value2);
  }
  if (typeof value2 === "string") {
    const result = new Date(value2);
    if (Number.isNaN(result.getTime())) {
      throw new Error(`${field} must be a valid date`);
    }
    return result;
  }
  throw new Error(`${field} must be provided`);
};
var validateBondInput = (bond) => {
  if (!bond) {
    throw new Error("A bond object is required");
  }
  const settlement = toDate4(bond.settlement, "settlement");
  const maturity = toDate4(bond.maturity, "maturity");
  if (settlement.getTime() > maturity.getTime()) {
    throw new Error("settlement must be on or before maturity");
  }
  if (typeof bond.rate !== "number" || bond.rate < 0 || bond.rate > 1) {
    throw new Error("rate must be a number between 0 and 1");
  }
  if (typeof bond.redemption !== "number" || Number.isNaN(bond.redemption) || bond.redemption <= 0) {
    throw new Error("redemption must be a positive number");
  }
  if (typeof bond.frequency !== "number" || !VALID_FREQUENCIES.has(bond.frequency)) {
    throw new Error(`frequency must be one of ${Array.from(VALID_FREQUENCIES).join(", ")}`);
  }
  if (typeof bond.convention !== "string") {
    throw new Error("convention must be a string");
  }
  if (!VALID_CONVENTIONS.has(bond.convention)) {
    throw new Error(`convention must be one of ${Array.from(VALID_CONVENTIONS).join(", ")}`);
  }
  return {
    settlement,
    maturity,
    rate: bond.rate,
    redemption: bond.redemption,
    frequency: bond.frequency,
    convention: bond.convention
  };
};
function bondCalculator(bond) {
  const normalized = validateBondInput(bond);
  const { settlement, maturity, rate, redemption, frequency, convention } = normalized;
  return {
    price: (yieldRate) => calcPrice(settlement, maturity, rate, yieldRate, redemption, frequency, convention),
    yield: (securityPrice) => calcYield(settlement, maturity, rate, securityPrice, redemption, frequency, convention)
  };
}

// node_modules/decimal.js/decimal.mjs
/*!
 *  decimal.js v10.6.0
 *  An arbitrary-precision Decimal type for JavaScript.
 *  https://github.com/MikeMcl/decimal.js
 *  Copyright (c) 2025 Michael Mclaughlin <M8ch88l@gmail.com>
 *  MIT Licence
 */
var EXP_LIMIT = 9000000000000000;
var MAX_DIGITS = 1e9;
var NUMERALS = "0123456789abcdef";
var LN10 = "2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058";
var PI2 = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789";
var DEFAULTS = {
  precision: 20,
  rounding: 4,
  modulo: 1,
  toExpNeg: -7,
  toExpPos: 21,
  minE: -EXP_LIMIT,
  maxE: EXP_LIMIT,
  crypto: false
};
var inexact;
var quadrant;
var external2 = true;
var decimalError = "[DecimalError] ";
var invalidArgument = decimalError + "Invalid argument: ";
var precisionLimitExceeded = decimalError + "Precision limit exceeded";
var cryptoUnavailable = decimalError + "crypto unavailable";
var tag = "[object Decimal]";
var mathfloor = Math.floor;
var mathpow = Math.pow;
var isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i;
var isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i;
var isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i;
var isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;
var BASE = 1e7;
var LOG_BASE = 7;
var MAX_SAFE_INTEGER2 = 9007199254740991;
var LN10_PRECISION = LN10.length - 1;
var PI_PRECISION = PI2.length - 1;
var P = { toStringTag: tag };
P.absoluteValue = P.abs = function() {
  var x2 = new this.constructor(this);
  if (x2.s < 0)
    x2.s = 1;
  return finalise(x2);
};
P.ceil = function() {
  return finalise(new this.constructor(this), this.e + 1, 2);
};
P.clampedTo = P.clamp = function(min3, max4) {
  var k, x2 = this, Ctor = x2.constructor;
  min3 = new Ctor(min3);
  max4 = new Ctor(max4);
  if (!min3.s || !max4.s)
    return new Ctor(NaN);
  if (min3.gt(max4))
    throw Error(invalidArgument + max4);
  k = x2.cmp(min3);
  return k < 0 ? min3 : x2.cmp(max4) > 0 ? max4 : new Ctor(x2);
};
P.comparedTo = P.cmp = function(y2) {
  var i, j, xdL, ydL, x2 = this, xd = x2.d, yd = (y2 = new x2.constructor(y2)).d, xs = x2.s, ys = y2.s;
  if (!xd || !yd) {
    return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;
  }
  if (!xd[0] || !yd[0])
    return xd[0] ? xs : yd[0] ? -ys : 0;
  if (xs !== ys)
    return xs;
  if (x2.e !== y2.e)
    return x2.e > y2.e ^ xs < 0 ? 1 : -1;
  xdL = xd.length;
  ydL = yd.length;
  for (i = 0, j = xdL < ydL ? xdL : ydL;i < j; ++i) {
    if (xd[i] !== yd[i])
      return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;
  }
  return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;
};
P.cosine = P.cos = function() {
  var pr, rm, x2 = this, Ctor = x2.constructor;
  if (!x2.d)
    return new Ctor(NaN);
  if (!x2.d[0])
    return new Ctor(1);
  pr = Ctor.precision;
  rm = Ctor.rounding;
  Ctor.precision = pr + Math.max(x2.e, x2.sd()) + LOG_BASE;
  Ctor.rounding = 1;
  x2 = cosine(Ctor, toLessThanHalfPi(Ctor, x2));
  Ctor.precision = pr;
  Ctor.rounding = rm;
  return finalise(quadrant == 2 || quadrant == 3 ? x2.neg() : x2, pr, rm, true);
};
P.cubeRoot = P.cbrt = function() {
  var e, m, n, r, rep, s, sd, t, t3, t3plusx, x2 = this, Ctor = x2.constructor;
  if (!x2.isFinite() || x2.isZero())
    return new Ctor(x2);
  external2 = false;
  s = x2.s * mathpow(x2.s * x2, 1 / 3);
  if (!s || Math.abs(s) == 1 / 0) {
    n = digitsToString(x2.d);
    e = x2.e;
    if (s = (e - n.length + 1) % 3)
      n += s == 1 || s == -2 ? "0" : "00";
    s = mathpow(n, 1 / 3);
    e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));
    if (s == 1 / 0) {
      n = "5e" + e;
    } else {
      n = s.toExponential();
      n = n.slice(0, n.indexOf("e") + 1) + e;
    }
    r = new Ctor(n);
    r.s = x2.s;
  } else {
    r = new Ctor(s.toString());
  }
  sd = (e = Ctor.precision) + 3;
  for (;; ) {
    t = r;
    t3 = t.times(t).times(t);
    t3plusx = t3.plus(x2);
    r = divide(t3plusx.plus(x2).times(t), t3plusx.plus(t3), sd + 2, 1);
    if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
      n = n.slice(sd - 3, sd + 1);
      if (n == "9999" || !rep && n == "4999") {
        if (!rep) {
          finalise(t, e + 1, 0);
          if (t.times(t).times(t).eq(x2)) {
            r = t;
            break;
          }
        }
        sd += 4;
        rep = 1;
      } else {
        if (!+n || !+n.slice(1) && n.charAt(0) == "5") {
          finalise(r, e + 1, 1);
          m = !r.times(r).times(r).eq(x2);
        }
        break;
      }
    }
  }
  external2 = true;
  return finalise(r, e, Ctor.rounding, m);
};
P.decimalPlaces = P.dp = function() {
  var w, d = this.d, n = NaN;
  if (d) {
    w = d.length - 1;
    n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;
    w = d[w];
    if (w)
      for (;w % 10 == 0; w /= 10)
        n--;
    if (n < 0)
      n = 0;
  }
  return n;
};
P.dividedBy = P.div = function(y2) {
  return divide(this, new this.constructor(y2));
};
P.dividedToIntegerBy = P.divToInt = function(y2) {
  var x2 = this, Ctor = x2.constructor;
  return finalise(divide(x2, new Ctor(y2), 0, 1, 1), Ctor.precision, Ctor.rounding);
};
P.equals = P.eq = function(y2) {
  return this.cmp(y2) === 0;
};
P.floor = function() {
  return finalise(new this.constructor(this), this.e + 1, 3);
};
P.greaterThan = P.gt = function(y2) {
  return this.cmp(y2) > 0;
};
P.greaterThanOrEqualTo = P.gte = function(y2) {
  var k = this.cmp(y2);
  return k == 1 || k === 0;
};
P.hyperbolicCosine = P.cosh = function() {
  var k, n, pr, rm, len, x2 = this, Ctor = x2.constructor, one2 = new Ctor(1);
  if (!x2.isFinite())
    return new Ctor(x2.s ? 1 / 0 : NaN);
  if (x2.isZero())
    return one2;
  pr = Ctor.precision;
  rm = Ctor.rounding;
  Ctor.precision = pr + Math.max(x2.e, x2.sd()) + 4;
  Ctor.rounding = 1;
  len = x2.d.length;
  if (len < 32) {
    k = Math.ceil(len / 3);
    n = (1 / tinyPow(4, k)).toString();
  } else {
    k = 16;
    n = "2.3283064365386962890625e-10";
  }
  x2 = taylorSeries(Ctor, 1, x2.times(n), new Ctor(1), true);
  var cosh2_x, i = k, d8 = new Ctor(8);
  for (;i--; ) {
    cosh2_x = x2.times(x2);
    x2 = one2.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));
  }
  return finalise(x2, Ctor.precision = pr, Ctor.rounding = rm, true);
};
P.hyperbolicSine = P.sinh = function() {
  var k, pr, rm, len, x2 = this, Ctor = x2.constructor;
  if (!x2.isFinite() || x2.isZero())
    return new Ctor(x2);
  pr = Ctor.precision;
  rm = Ctor.rounding;
  Ctor.precision = pr + Math.max(x2.e, x2.sd()) + 4;
  Ctor.rounding = 1;
  len = x2.d.length;
  if (len < 3) {
    x2 = taylorSeries(Ctor, 2, x2, x2, true);
  } else {
    k = 1.4 * Math.sqrt(len);
    k = k > 16 ? 16 : k | 0;
    x2 = x2.times(1 / tinyPow(5, k));
    x2 = taylorSeries(Ctor, 2, x2, x2, true);
    var sinh2_x, d5 = new Ctor(5), d16 = new Ctor(16), d20 = new Ctor(20);
    for (;k--; ) {
      sinh2_x = x2.times(x2);
      x2 = x2.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));
    }
  }
  Ctor.precision = pr;
  Ctor.rounding = rm;
  return finalise(x2, pr, rm, true);
};
P.hyperbolicTangent = P.tanh = function() {
  var pr, rm, x2 = this, Ctor = x2.constructor;
  if (!x2.isFinite())
    return new Ctor(x2.s);
  if (x2.isZero())
    return new Ctor(x2);
  pr = Ctor.precision;
  rm = Ctor.rounding;
  Ctor.precision = pr + 7;
  Ctor.rounding = 1;
  return divide(x2.sinh(), x2.cosh(), Ctor.precision = pr, Ctor.rounding = rm);
};
P.inverseCosine = P.acos = function() {
  var x2 = this, Ctor = x2.constructor, k = x2.abs().cmp(1), pr = Ctor.precision, rm = Ctor.rounding;
  if (k !== -1) {
    return k === 0 ? x2.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0) : new Ctor(NaN);
  }
  if (x2.isZero())
    return getPi(Ctor, pr + 4, rm).times(0.5);
  Ctor.precision = pr + 6;
  Ctor.rounding = 1;
  x2 = new Ctor(1).minus(x2).div(x2.plus(1)).sqrt().atan();
  Ctor.precision = pr;
  Ctor.rounding = rm;
  return x2.times(2);
};
P.inverseHyperbolicCosine = P.acosh = function() {
  var pr, rm, x2 = this, Ctor = x2.constructor;
  if (x2.lte(1))
    return new Ctor(x2.eq(1) ? 0 : NaN);
  if (!x2.isFinite())
    return new Ctor(x2);
  pr = Ctor.precision;
  rm = Ctor.rounding;
  Ctor.precision = pr + Math.max(Math.abs(x2.e), x2.sd()) + 4;
  Ctor.rounding = 1;
  external2 = false;
  x2 = x2.times(x2).minus(1).sqrt().plus(x2);
  external2 = true;
  Ctor.precision = pr;
  Ctor.rounding = rm;
  return x2.ln();
};
P.inverseHyperbolicSine = P.asinh = function() {
  var pr, rm, x2 = this, Ctor = x2.constructor;
  if (!x2.isFinite() || x2.isZero())
    return new Ctor(x2);
  pr = Ctor.precision;
  rm = Ctor.rounding;
  Ctor.precision = pr + 2 * Math.max(Math.abs(x2.e), x2.sd()) + 6;
  Ctor.rounding = 1;
  external2 = false;
  x2 = x2.times(x2).plus(1).sqrt().plus(x2);
  external2 = true;
  Ctor.precision = pr;
  Ctor.rounding = rm;
  return x2.ln();
};
P.inverseHyperbolicTangent = P.atanh = function() {
  var pr, rm, wpr, xsd, x2 = this, Ctor = x2.constructor;
  if (!x2.isFinite())
    return new Ctor(NaN);
  if (x2.e >= 0)
    return new Ctor(x2.abs().eq(1) ? x2.s / 0 : x2.isZero() ? x2 : NaN);
  pr = Ctor.precision;
  rm = Ctor.rounding;
  xsd = x2.sd();
  if (Math.max(xsd, pr) < 2 * -x2.e - 1)
    return finalise(new Ctor(x2), pr, rm, true);
  Ctor.precision = wpr = xsd - x2.e;
  x2 = divide(x2.plus(1), new Ctor(1).minus(x2), wpr + pr, 1);
  Ctor.precision = pr + 4;
  Ctor.rounding = 1;
  x2 = x2.ln();
  Ctor.precision = pr;
  Ctor.rounding = rm;
  return x2.times(0.5);
};
P.inverseSine = P.asin = function() {
  var halfPi2, k, pr, rm, x2 = this, Ctor = x2.constructor;
  if (x2.isZero())
    return new Ctor(x2);
  k = x2.abs().cmp(1);
  pr = Ctor.precision;
  rm = Ctor.rounding;
  if (k !== -1) {
    if (k === 0) {
      halfPi2 = getPi(Ctor, pr + 4, rm).times(0.5);
      halfPi2.s = x2.s;
      return halfPi2;
    }
    return new Ctor(NaN);
  }
  Ctor.precision = pr + 6;
  Ctor.rounding = 1;
  x2 = x2.div(new Ctor(1).minus(x2.times(x2)).sqrt().plus(1)).atan();
  Ctor.precision = pr;
  Ctor.rounding = rm;
  return x2.times(2);
};
P.inverseTangent = P.atan = function() {
  var i, j, k, n, px, t, r, wpr, x2, x3 = this, Ctor = x3.constructor, pr = Ctor.precision, rm = Ctor.rounding;
  if (!x3.isFinite()) {
    if (!x3.s)
      return new Ctor(NaN);
    if (pr + 4 <= PI_PRECISION) {
      r = getPi(Ctor, pr + 4, rm).times(0.5);
      r.s = x3.s;
      return r;
    }
  } else if (x3.isZero()) {
    return new Ctor(x3);
  } else if (x3.abs().eq(1) && pr + 4 <= PI_PRECISION) {
    r = getPi(Ctor, pr + 4, rm).times(0.25);
    r.s = x3.s;
    return r;
  }
  Ctor.precision = wpr = pr + 10;
  Ctor.rounding = 1;
  k = Math.min(28, wpr / LOG_BASE + 2 | 0);
  for (i = k;i; --i)
    x3 = x3.div(x3.times(x3).plus(1).sqrt().plus(1));
  external2 = false;
  j = Math.ceil(wpr / LOG_BASE);
  n = 1;
  x2 = x3.times(x3);
  r = new Ctor(x3);
  px = x3;
  for (;i !== -1; ) {
    px = px.times(x2);
    t = r.minus(px.div(n += 2));
    px = px.times(x2);
    r = t.plus(px.div(n += 2));
    if (r.d[j] !== undefined)
      for (i = j;r.d[i] === t.d[i] && i--; )
        ;
  }
  if (k)
    r = r.times(2 << k - 1);
  external2 = true;
  return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);
};
P.isFinite = function() {
  return !!this.d;
};
P.isInteger = P.isInt = function() {
  return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;
};
P.isNaN = function() {
  return !this.s;
};
P.isNegative = P.isNeg = function() {
  return this.s < 0;
};
P.isPositive = P.isPos = function() {
  return this.s > 0;
};
P.isZero = function() {
  return !!this.d && this.d[0] === 0;
};
P.lessThan = P.lt = function(y2) {
  return this.cmp(y2) < 0;
};
P.lessThanOrEqualTo = P.lte = function(y2) {
  return this.cmp(y2) < 1;
};
P.logarithm = P.log = function(base) {
  var isBase10, d, denominator, k, inf, num3, sd, r, arg = this, Ctor = arg.constructor, pr = Ctor.precision, rm = Ctor.rounding, guard = 5;
  if (base == null) {
    base = new Ctor(10);
    isBase10 = true;
  } else {
    base = new Ctor(base);
    d = base.d;
    if (base.s < 0 || !d || !d[0] || base.eq(1))
      return new Ctor(NaN);
    isBase10 = base.eq(10);
  }
  d = arg.d;
  if (arg.s < 0 || !d || !d[0] || arg.eq(1)) {
    return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0);
  }
  if (isBase10) {
    if (d.length > 1) {
      inf = true;
    } else {
      for (k = d[0];k % 10 === 0; )
        k /= 10;
      inf = k !== 1;
    }
  }
  external2 = false;
  sd = pr + guard;
  num3 = naturalLogarithm(arg, sd);
  denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
  r = divide(num3, denominator, sd, 1);
  if (checkRoundingDigits(r.d, k = pr, rm)) {
    do {
      sd += 10;
      num3 = naturalLogarithm(arg, sd);
      denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
      r = divide(num3, denominator, sd, 1);
      if (!inf) {
        if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 100000000000000) {
          r = finalise(r, pr + 1, 0);
        }
        break;
      }
    } while (checkRoundingDigits(r.d, k += 10, rm));
  }
  external2 = true;
  return finalise(r, pr, rm);
};
P.minus = P.sub = function(y2) {
  var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd, x2 = this, Ctor = x2.constructor;
  y2 = new Ctor(y2);
  if (!x2.d || !y2.d) {
    if (!x2.s || !y2.s)
      y2 = new Ctor(NaN);
    else if (x2.d)
      y2.s = -y2.s;
    else
      y2 = new Ctor(y2.d || x2.s !== y2.s ? x2 : NaN);
    return y2;
  }
  if (x2.s != y2.s) {
    y2.s = -y2.s;
    return x2.plus(y2);
  }
  xd = x2.d;
  yd = y2.d;
  pr = Ctor.precision;
  rm = Ctor.rounding;
  if (!xd[0] || !yd[0]) {
    if (yd[0])
      y2.s = -y2.s;
    else if (xd[0])
      y2 = new Ctor(x2);
    else
      return new Ctor(rm === 3 ? -0 : 0);
    return external2 ? finalise(y2, pr, rm) : y2;
  }
  e = mathfloor(y2.e / LOG_BASE);
  xe = mathfloor(x2.e / LOG_BASE);
  xd = xd.slice();
  k = xe - e;
  if (k) {
    xLTy = k < 0;
    if (xLTy) {
      d = xd;
      k = -k;
      len = yd.length;
    } else {
      d = yd;
      e = xe;
      len = xd.length;
    }
    i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;
    if (k > i) {
      k = i;
      d.length = 1;
    }
    d.reverse();
    for (i = k;i--; )
      d.push(0);
    d.reverse();
  } else {
    i = xd.length;
    len = yd.length;
    xLTy = i < len;
    if (xLTy)
      len = i;
    for (i = 0;i < len; i++) {
      if (xd[i] != yd[i]) {
        xLTy = xd[i] < yd[i];
        break;
      }
    }
    k = 0;
  }
  if (xLTy) {
    d = xd;
    xd = yd;
    yd = d;
    y2.s = -y2.s;
  }
  len = xd.length;
  for (i = yd.length - len;i > 0; --i)
    xd[len++] = 0;
  for (i = yd.length;i > k; ) {
    if (xd[--i] < yd[i]) {
      for (j = i;j && xd[--j] === 0; )
        xd[j] = BASE - 1;
      --xd[j];
      xd[i] += BASE;
    }
    xd[i] -= yd[i];
  }
  for (;xd[--len] === 0; )
    xd.pop();
  for (;xd[0] === 0; xd.shift())
    --e;
  if (!xd[0])
    return new Ctor(rm === 3 ? -0 : 0);
  y2.d = xd;
  y2.e = getBase10Exponent(xd, e);
  return external2 ? finalise(y2, pr, rm) : y2;
};
P.modulo = P.mod = function(y2) {
  var q, x2 = this, Ctor = x2.constructor;
  y2 = new Ctor(y2);
  if (!x2.d || !y2.s || y2.d && !y2.d[0])
    return new Ctor(NaN);
  if (!y2.d || x2.d && !x2.d[0]) {
    return finalise(new Ctor(x2), Ctor.precision, Ctor.rounding);
  }
  external2 = false;
  if (Ctor.modulo == 9) {
    q = divide(x2, y2.abs(), 0, 3, 1);
    q.s *= y2.s;
  } else {
    q = divide(x2, y2, 0, Ctor.modulo, 1);
  }
  q = q.times(y2);
  external2 = true;
  return x2.minus(q);
};
P.naturalExponential = P.exp = function() {
  return naturalExponential(this);
};
P.naturalLogarithm = P.ln = function() {
  return naturalLogarithm(this);
};
P.negated = P.neg = function() {
  var x2 = new this.constructor(this);
  x2.s = -x2.s;
  return finalise(x2);
};
P.plus = P.add = function(y2) {
  var carry, d, e, i, k, len, pr, rm, xd, yd, x2 = this, Ctor = x2.constructor;
  y2 = new Ctor(y2);
  if (!x2.d || !y2.d) {
    if (!x2.s || !y2.s)
      y2 = new Ctor(NaN);
    else if (!x2.d)
      y2 = new Ctor(y2.d || x2.s === y2.s ? x2 : NaN);
    return y2;
  }
  if (x2.s != y2.s) {
    y2.s = -y2.s;
    return x2.minus(y2);
  }
  xd = x2.d;
  yd = y2.d;
  pr = Ctor.precision;
  rm = Ctor.rounding;
  if (!xd[0] || !yd[0]) {
    if (!yd[0])
      y2 = new Ctor(x2);
    return external2 ? finalise(y2, pr, rm) : y2;
  }
  k = mathfloor(x2.e / LOG_BASE);
  e = mathfloor(y2.e / LOG_BASE);
  xd = xd.slice();
  i = k - e;
  if (i) {
    if (i < 0) {
      d = xd;
      i = -i;
      len = yd.length;
    } else {
      d = yd;
      e = k;
      len = xd.length;
    }
    k = Math.ceil(pr / LOG_BASE);
    len = k > len ? k + 1 : len + 1;
    if (i > len) {
      i = len;
      d.length = 1;
    }
    d.reverse();
    for (;i--; )
      d.push(0);
    d.reverse();
  }
  len = xd.length;
  i = yd.length;
  if (len - i < 0) {
    i = len;
    d = yd;
    yd = xd;
    xd = d;
  }
  for (carry = 0;i; ) {
    carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;
    xd[i] %= BASE;
  }
  if (carry) {
    xd.unshift(carry);
    ++e;
  }
  for (len = xd.length;xd[--len] == 0; )
    xd.pop();
  y2.d = xd;
  y2.e = getBase10Exponent(xd, e);
  return external2 ? finalise(y2, pr, rm) : y2;
};
P.precision = P.sd = function(z2) {
  var k, x2 = this;
  if (z2 !== undefined && z2 !== !!z2 && z2 !== 1 && z2 !== 0)
    throw Error(invalidArgument + z2);
  if (x2.d) {
    k = getPrecision(x2.d);
    if (z2 && x2.e + 1 > k)
      k = x2.e + 1;
  } else {
    k = NaN;
  }
  return k;
};
P.round = function() {
  var x2 = this, Ctor = x2.constructor;
  return finalise(new Ctor(x2), x2.e + 1, Ctor.rounding);
};
P.sine = P.sin = function() {
  var pr, rm, x2 = this, Ctor = x2.constructor;
  if (!x2.isFinite())
    return new Ctor(NaN);
  if (x2.isZero())
    return new Ctor(x2);
  pr = Ctor.precision;
  rm = Ctor.rounding;
  Ctor.precision = pr + Math.max(x2.e, x2.sd()) + LOG_BASE;
  Ctor.rounding = 1;
  x2 = sine(Ctor, toLessThanHalfPi(Ctor, x2));
  Ctor.precision = pr;
  Ctor.rounding = rm;
  return finalise(quadrant > 2 ? x2.neg() : x2, pr, rm, true);
};
P.squareRoot = P.sqrt = function() {
  var m, n, sd, r, rep, t, x2 = this, d = x2.d, e = x2.e, s = x2.s, Ctor = x2.constructor;
  if (s !== 1 || !d || !d[0]) {
    return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x2 : 1 / 0);
  }
  external2 = false;
  s = Math.sqrt(+x2);
  if (s == 0 || s == 1 / 0) {
    n = digitsToString(d);
    if ((n.length + e) % 2 == 0)
      n += "0";
    s = Math.sqrt(n);
    e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);
    if (s == 1 / 0) {
      n = "5e" + e;
    } else {
      n = s.toExponential();
      n = n.slice(0, n.indexOf("e") + 1) + e;
    }
    r = new Ctor(n);
  } else {
    r = new Ctor(s.toString());
  }
  sd = (e = Ctor.precision) + 3;
  for (;; ) {
    t = r;
    r = t.plus(divide(x2, t, sd + 2, 1)).times(0.5);
    if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
      n = n.slice(sd - 3, sd + 1);
      if (n == "9999" || !rep && n == "4999") {
        if (!rep) {
          finalise(t, e + 1, 0);
          if (t.times(t).eq(x2)) {
            r = t;
            break;
          }
        }
        sd += 4;
        rep = 1;
      } else {
        if (!+n || !+n.slice(1) && n.charAt(0) == "5") {
          finalise(r, e + 1, 1);
          m = !r.times(r).eq(x2);
        }
        break;
      }
    }
  }
  external2 = true;
  return finalise(r, e, Ctor.rounding, m);
};
P.tangent = P.tan = function() {
  var pr, rm, x2 = this, Ctor = x2.constructor;
  if (!x2.isFinite())
    return new Ctor(NaN);
  if (x2.isZero())
    return new Ctor(x2);
  pr = Ctor.precision;
  rm = Ctor.rounding;
  Ctor.precision = pr + 10;
  Ctor.rounding = 1;
  x2 = x2.sin();
  x2.s = 1;
  x2 = divide(x2, new Ctor(1).minus(x2.times(x2)).sqrt(), pr + 10, 0);
  Ctor.precision = pr;
  Ctor.rounding = rm;
  return finalise(quadrant == 2 || quadrant == 4 ? x2.neg() : x2, pr, rm, true);
};
P.times = P.mul = function(y2) {
  var carry, e, i, k, r, rL, t, xdL, ydL, x2 = this, Ctor = x2.constructor, xd = x2.d, yd = (y2 = new Ctor(y2)).d;
  y2.s *= x2.s;
  if (!xd || !xd[0] || !yd || !yd[0]) {
    return new Ctor(!y2.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd ? NaN : !xd || !yd ? y2.s / 0 : y2.s * 0);
  }
  e = mathfloor(x2.e / LOG_BASE) + mathfloor(y2.e / LOG_BASE);
  xdL = xd.length;
  ydL = yd.length;
  if (xdL < ydL) {
    r = xd;
    xd = yd;
    yd = r;
    rL = xdL;
    xdL = ydL;
    ydL = rL;
  }
  r = [];
  rL = xdL + ydL;
  for (i = rL;i--; )
    r.push(0);
  for (i = ydL;--i >= 0; ) {
    carry = 0;
    for (k = xdL + i;k > i; ) {
      t = r[k] + yd[i] * xd[k - i - 1] + carry;
      r[k--] = t % BASE | 0;
      carry = t / BASE | 0;
    }
    r[k] = (r[k] + carry) % BASE | 0;
  }
  for (;!r[--rL]; )
    r.pop();
  if (carry)
    ++e;
  else
    r.shift();
  y2.d = r;
  y2.e = getBase10Exponent(r, e);
  return external2 ? finalise(y2, Ctor.precision, Ctor.rounding) : y2;
};
P.toBinary = function(sd, rm) {
  return toStringBinary(this, 2, sd, rm);
};
P.toDecimalPlaces = P.toDP = function(dp, rm) {
  var x2 = this, Ctor = x2.constructor;
  x2 = new Ctor(x2);
  if (dp === undefined)
    return x2;
  checkInt32(dp, 0, MAX_DIGITS);
  if (rm === undefined)
    rm = Ctor.rounding;
  else
    checkInt32(rm, 0, 8);
  return finalise(x2, dp + x2.e + 1, rm);
};
P.toExponential = function(dp, rm) {
  var str, x2 = this, Ctor = x2.constructor;
  if (dp === undefined) {
    str = finiteToString(x2, true);
  } else {
    checkInt32(dp, 0, MAX_DIGITS);
    if (rm === undefined)
      rm = Ctor.rounding;
    else
      checkInt32(rm, 0, 8);
    x2 = finalise(new Ctor(x2), dp + 1, rm);
    str = finiteToString(x2, true, dp + 1);
  }
  return x2.isNeg() && !x2.isZero() ? "-" + str : str;
};
P.toFixed = function(dp, rm) {
  var str, y2, x2 = this, Ctor = x2.constructor;
  if (dp === undefined) {
    str = finiteToString(x2);
  } else {
    checkInt32(dp, 0, MAX_DIGITS);
    if (rm === undefined)
      rm = Ctor.rounding;
    else
      checkInt32(rm, 0, 8);
    y2 = finalise(new Ctor(x2), dp + x2.e + 1, rm);
    str = finiteToString(y2, false, dp + y2.e + 1);
  }
  return x2.isNeg() && !x2.isZero() ? "-" + str : str;
};
P.toFraction = function(maxD) {
  var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r, x2 = this, xd = x2.d, Ctor = x2.constructor;
  if (!xd)
    return new Ctor(x2);
  n1 = d0 = new Ctor(1);
  d1 = n0 = new Ctor(0);
  d = new Ctor(d1);
  e = d.e = getPrecision(xd) - x2.e - 1;
  k = e % LOG_BASE;
  d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k);
  if (maxD == null) {
    maxD = e > 0 ? d : n1;
  } else {
    n = new Ctor(maxD);
    if (!n.isInt() || n.lt(n1))
      throw Error(invalidArgument + n);
    maxD = n.gt(d) ? e > 0 ? d : n1 : n;
  }
  external2 = false;
  n = new Ctor(digitsToString(xd));
  pr = Ctor.precision;
  Ctor.precision = e = xd.length * LOG_BASE * 2;
  for (;; ) {
    q = divide(n, d, 0, 1, 1);
    d2 = d0.plus(q.times(d1));
    if (d2.cmp(maxD) == 1)
      break;
    d0 = d1;
    d1 = d2;
    d2 = n1;
    n1 = n0.plus(q.times(d2));
    n0 = d2;
    d2 = d;
    d = n.minus(q.times(d2));
    n = d2;
  }
  d2 = divide(maxD.minus(d0), d1, 0, 1, 1);
  n0 = n0.plus(d2.times(n1));
  d0 = d0.plus(d2.times(d1));
  n0.s = n1.s = x2.s;
  r = divide(n1, d1, e, 1).minus(x2).abs().cmp(divide(n0, d0, e, 1).minus(x2).abs()) < 1 ? [n1, d1] : [n0, d0];
  Ctor.precision = pr;
  external2 = true;
  return r;
};
P.toHexadecimal = P.toHex = function(sd, rm) {
  return toStringBinary(this, 16, sd, rm);
};
P.toNearest = function(y2, rm) {
  var x2 = this, Ctor = x2.constructor;
  x2 = new Ctor(x2);
  if (y2 == null) {
    if (!x2.d)
      return x2;
    y2 = new Ctor(1);
    rm = Ctor.rounding;
  } else {
    y2 = new Ctor(y2);
    if (rm === undefined) {
      rm = Ctor.rounding;
    } else {
      checkInt32(rm, 0, 8);
    }
    if (!x2.d)
      return y2.s ? x2 : y2;
    if (!y2.d) {
      if (y2.s)
        y2.s = x2.s;
      return y2;
    }
  }
  if (y2.d[0]) {
    external2 = false;
    x2 = divide(x2, y2, 0, rm, 1).times(y2);
    external2 = true;
    finalise(x2);
  } else {
    y2.s = x2.s;
    x2 = y2;
  }
  return x2;
};
P.toNumber = function() {
  return +this;
};
P.toOctal = function(sd, rm) {
  return toStringBinary(this, 8, sd, rm);
};
P.toPower = P.pow = function(y2) {
  var e, k, pr, r, rm, s, x2 = this, Ctor = x2.constructor, yn = +(y2 = new Ctor(y2));
  if (!x2.d || !y2.d || !x2.d[0] || !y2.d[0])
    return new Ctor(mathpow(+x2, yn));
  x2 = new Ctor(x2);
  if (x2.eq(1))
    return x2;
  pr = Ctor.precision;
  rm = Ctor.rounding;
  if (y2.eq(1))
    return finalise(x2, pr, rm);
  e = mathfloor(y2.e / LOG_BASE);
  if (e >= y2.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER2) {
    r = intPow(Ctor, x2, k, pr);
    return y2.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm);
  }
  s = x2.s;
  if (s < 0) {
    if (e < y2.d.length - 1)
      return new Ctor(NaN);
    if ((y2.d[e] & 1) == 0)
      s = 1;
    if (x2.e == 0 && x2.d[0] == 1 && x2.d.length == 1) {
      x2.s = s;
      return x2;
    }
  }
  k = mathpow(+x2, yn);
  e = k == 0 || !isFinite(k) ? mathfloor(yn * (Math.log("0." + digitsToString(x2.d)) / Math.LN10 + x2.e + 1)) : new Ctor(k + "").e;
  if (e > Ctor.maxE + 1 || e < Ctor.minE - 1)
    return new Ctor(e > 0 ? s / 0 : 0);
  external2 = false;
  Ctor.rounding = x2.s = 1;
  k = Math.min(12, (e + "").length);
  r = naturalExponential(y2.times(naturalLogarithm(x2, pr + k)), pr);
  if (r.d) {
    r = finalise(r, pr + 5, 1);
    if (checkRoundingDigits(r.d, pr, rm)) {
      e = pr + 10;
      r = finalise(naturalExponential(y2.times(naturalLogarithm(x2, e + k)), e), e + 5, 1);
      if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 100000000000000) {
        r = finalise(r, pr + 1, 0);
      }
    }
  }
  r.s = s;
  external2 = true;
  Ctor.rounding = rm;
  return finalise(r, pr, rm);
};
P.toPrecision = function(sd, rm) {
  var str, x2 = this, Ctor = x2.constructor;
  if (sd === undefined) {
    str = finiteToString(x2, x2.e <= Ctor.toExpNeg || x2.e >= Ctor.toExpPos);
  } else {
    checkInt32(sd, 1, MAX_DIGITS);
    if (rm === undefined)
      rm = Ctor.rounding;
    else
      checkInt32(rm, 0, 8);
    x2 = finalise(new Ctor(x2), sd, rm);
    str = finiteToString(x2, sd <= x2.e || x2.e <= Ctor.toExpNeg, sd);
  }
  return x2.isNeg() && !x2.isZero() ? "-" + str : str;
};
P.toSignificantDigits = P.toSD = function(sd, rm) {
  var x2 = this, Ctor = x2.constructor;
  if (sd === undefined) {
    sd = Ctor.precision;
    rm = Ctor.rounding;
  } else {
    checkInt32(sd, 1, MAX_DIGITS);
    if (rm === undefined)
      rm = Ctor.rounding;
    else
      checkInt32(rm, 0, 8);
  }
  return finalise(new Ctor(x2), sd, rm);
};
P.toString = function() {
  var x2 = this, Ctor = x2.constructor, str = finiteToString(x2, x2.e <= Ctor.toExpNeg || x2.e >= Ctor.toExpPos);
  return x2.isNeg() && !x2.isZero() ? "-" + str : str;
};
P.truncated = P.trunc = function() {
  return finalise(new this.constructor(this), this.e + 1, 1);
};
P.valueOf = P.toJSON = function() {
  var x2 = this, Ctor = x2.constructor, str = finiteToString(x2, x2.e <= Ctor.toExpNeg || x2.e >= Ctor.toExpPos);
  return x2.isNeg() ? "-" + str : str;
};
function digitsToString(d) {
  var i, k, ws, indexOfLastWord = d.length - 1, str = "", w = d[0];
  if (indexOfLastWord > 0) {
    str += w;
    for (i = 1;i < indexOfLastWord; i++) {
      ws = d[i] + "";
      k = LOG_BASE - ws.length;
      if (k)
        str += getZeroString(k);
      str += ws;
    }
    w = d[i];
    ws = w + "";
    k = LOG_BASE - ws.length;
    if (k)
      str += getZeroString(k);
  } else if (w === 0) {
    return "0";
  }
  for (;w % 10 === 0; )
    w /= 10;
  return str + w;
}
function checkInt32(i, min3, max4) {
  if (i !== ~~i || i < min3 || i > max4) {
    throw Error(invalidArgument + i);
  }
}
function checkRoundingDigits(d, i, rm, repeating) {
  var di, k, r, rd;
  for (k = d[0];k >= 10; k /= 10)
    --i;
  if (--i < 0) {
    i += LOG_BASE;
    di = 0;
  } else {
    di = Math.ceil((i + 1) / LOG_BASE);
    i %= LOG_BASE;
  }
  k = mathpow(10, LOG_BASE - i);
  rd = d[di] % k | 0;
  if (repeating == null) {
    if (i < 3) {
      if (i == 0)
        rd = rd / 100 | 0;
      else if (i == 1)
        rd = rd / 10 | 0;
      r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;
    } else {
      r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) && (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 || (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0;
    }
  } else {
    if (i < 4) {
      if (i == 0)
        rd = rd / 1000 | 0;
      else if (i == 1)
        rd = rd / 100 | 0;
      else if (i == 2)
        rd = rd / 10 | 0;
      r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999;
    } else {
      r = ((repeating || rm < 4) && rd + 1 == k || !repeating && rm > 3 && rd + 1 == k / 2) && (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1;
    }
  }
  return r;
}
function convertBase(str, baseIn, baseOut) {
  var j, arr = [0], arrL, i = 0, strL = str.length;
  for (;i < strL; ) {
    for (arrL = arr.length;arrL--; )
      arr[arrL] *= baseIn;
    arr[0] += NUMERALS.indexOf(str.charAt(i++));
    for (j = 0;j < arr.length; j++) {
      if (arr[j] > baseOut - 1) {
        if (arr[j + 1] === undefined)
          arr[j + 1] = 0;
        arr[j + 1] += arr[j] / baseOut | 0;
        arr[j] %= baseOut;
      }
    }
  }
  return arr.reverse();
}
function cosine(Ctor, x2) {
  var k, len, y2;
  if (x2.isZero())
    return x2;
  len = x2.d.length;
  if (len < 32) {
    k = Math.ceil(len / 3);
    y2 = (1 / tinyPow(4, k)).toString();
  } else {
    k = 16;
    y2 = "2.3283064365386962890625e-10";
  }
  Ctor.precision += k;
  x2 = taylorSeries(Ctor, 1, x2.times(y2), new Ctor(1));
  for (var i = k;i--; ) {
    var cos2x = x2.times(x2);
    x2 = cos2x.times(cos2x).minus(cos2x).times(8).plus(1);
  }
  Ctor.precision -= k;
  return x2;
}
var divide = function() {
  function multiplyInteger(x2, k, base) {
    var temp, carry = 0, i = x2.length;
    for (x2 = x2.slice();i--; ) {
      temp = x2[i] * k + carry;
      x2[i] = temp % base | 0;
      carry = temp / base | 0;
    }
    if (carry)
      x2.unshift(carry);
    return x2;
  }
  function compare(a, b, aL, bL) {
    var i, r;
    if (aL != bL) {
      r = aL > bL ? 1 : -1;
    } else {
      for (i = r = 0;i < aL; i++) {
        if (a[i] != b[i]) {
          r = a[i] > b[i] ? 1 : -1;
          break;
        }
      }
    }
    return r;
  }
  function subtract(a, b, aL, base) {
    var i = 0;
    for (;aL--; ) {
      a[aL] -= i;
      i = a[aL] < b[aL] ? 1 : 0;
      a[aL] = i * base + a[aL] - b[aL];
    }
    for (;!a[0] && a.length > 1; )
      a.shift();
  }
  return function(x2, y2, pr, rm, dp, base) {
    var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0, yL, yz, Ctor = x2.constructor, sign2 = x2.s == y2.s ? 1 : -1, xd = x2.d, yd = y2.d;
    if (!xd || !xd[0] || !yd || !yd[0]) {
      return new Ctor(!x2.s || !y2.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN : xd && xd[0] == 0 || !yd ? sign2 * 0 : sign2 / 0);
    }
    if (base) {
      logBase = 1;
      e = x2.e - y2.e;
    } else {
      base = BASE;
      logBase = LOG_BASE;
      e = mathfloor(x2.e / logBase) - mathfloor(y2.e / logBase);
    }
    yL = yd.length;
    xL = xd.length;
    q = new Ctor(sign2);
    qd = q.d = [];
    for (i = 0;yd[i] == (xd[i] || 0); i++)
      ;
    if (yd[i] > (xd[i] || 0))
      e--;
    if (pr == null) {
      sd = pr = Ctor.precision;
      rm = Ctor.rounding;
    } else if (dp) {
      sd = pr + (x2.e - y2.e) + 1;
    } else {
      sd = pr;
    }
    if (sd < 0) {
      qd.push(1);
      more = true;
    } else {
      sd = sd / logBase + 2 | 0;
      i = 0;
      if (yL == 1) {
        k = 0;
        yd = yd[0];
        sd++;
        for (;(i < xL || k) && sd--; i++) {
          t = k * base + (xd[i] || 0);
          qd[i] = t / yd | 0;
          k = t % yd | 0;
        }
        more = k || i < xL;
      } else {
        k = base / (yd[0] + 1) | 0;
        if (k > 1) {
          yd = multiplyInteger(yd, k, base);
          xd = multiplyInteger(xd, k, base);
          yL = yd.length;
          xL = xd.length;
        }
        xi = yL;
        rem = xd.slice(0, yL);
        remL = rem.length;
        for (;remL < yL; )
          rem[remL++] = 0;
        yz = yd.slice();
        yz.unshift(0);
        yd0 = yd[0];
        if (yd[1] >= base / 2)
          ++yd0;
        do {
          k = 0;
          cmp = compare(yd, rem, yL, remL);
          if (cmp < 0) {
            rem0 = rem[0];
            if (yL != remL)
              rem0 = rem0 * base + (rem[1] || 0);
            k = rem0 / yd0 | 0;
            if (k > 1) {
              if (k >= base)
                k = base - 1;
              prod = multiplyInteger(yd, k, base);
              prodL = prod.length;
              remL = rem.length;
              cmp = compare(prod, rem, prodL, remL);
              if (cmp == 1) {
                k--;
                subtract(prod, yL < prodL ? yz : yd, prodL, base);
              }
            } else {
              if (k == 0)
                cmp = k = 1;
              prod = yd.slice();
            }
            prodL = prod.length;
            if (prodL < remL)
              prod.unshift(0);
            subtract(rem, prod, remL, base);
            if (cmp == -1) {
              remL = rem.length;
              cmp = compare(yd, rem, yL, remL);
              if (cmp < 1) {
                k++;
                subtract(rem, yL < remL ? yz : yd, remL, base);
              }
            }
            remL = rem.length;
          } else if (cmp === 0) {
            k++;
            rem = [0];
          }
          qd[i++] = k;
          if (cmp && rem[0]) {
            rem[remL++] = xd[xi] || 0;
          } else {
            rem = [xd[xi]];
            remL = 1;
          }
        } while ((xi++ < xL || rem[0] !== undefined) && sd--);
        more = rem[0] !== undefined;
      }
      if (!qd[0])
        qd.shift();
    }
    if (logBase == 1) {
      q.e = e;
      inexact = more;
    } else {
      for (i = 1, k = qd[0];k >= 10; k /= 10)
        i++;
      q.e = i + e * logBase - 1;
      finalise(q, dp ? pr + q.e + 1 : pr, rm, more);
    }
    return q;
  };
}();
function finalise(x2, sd, rm, isTruncated) {
  var digits, i, j, k, rd, roundUp, w, xd, xdi, Ctor = x2.constructor;
  out:
    if (sd != null) {
      xd = x2.d;
      if (!xd)
        return x2;
      for (digits = 1, k = xd[0];k >= 10; k /= 10)
        digits++;
      i = sd - digits;
      if (i < 0) {
        i += LOG_BASE;
        j = sd;
        w = xd[xdi = 0];
        rd = w / mathpow(10, digits - j - 1) % 10 | 0;
      } else {
        xdi = Math.ceil((i + 1) / LOG_BASE);
        k = xd.length;
        if (xdi >= k) {
          if (isTruncated) {
            for (;k++ <= xdi; )
              xd.push(0);
            w = rd = 0;
            digits = 1;
            i %= LOG_BASE;
            j = i - LOG_BASE + 1;
          } else {
            break out;
          }
        } else {
          w = k = xd[xdi];
          for (digits = 1;k >= 10; k /= 10)
            digits++;
          i %= LOG_BASE;
          j = i - LOG_BASE + digits;
          rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0;
        }
      }
      isTruncated = isTruncated || sd < 0 || xd[xdi + 1] !== undefined || (j < 0 ? w : w % mathpow(10, digits - j - 1));
      roundUp = rm < 4 ? (rd || isTruncated) && (rm == 0 || rm == (x2.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 && (i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10 & 1 || rm == (x2.s < 0 ? 8 : 7));
      if (sd < 1 || !xd[0]) {
        xd.length = 0;
        if (roundUp) {
          sd -= x2.e + 1;
          xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);
          x2.e = -sd || 0;
        } else {
          xd[0] = x2.e = 0;
        }
        return x2;
      }
      if (i == 0) {
        xd.length = xdi;
        k = 1;
        xdi--;
      } else {
        xd.length = xdi + 1;
        k = mathpow(10, LOG_BASE - i);
        xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0;
      }
      if (roundUp) {
        for (;; ) {
          if (xdi == 0) {
            for (i = 1, j = xd[0];j >= 10; j /= 10)
              i++;
            j = xd[0] += k;
            for (k = 1;j >= 10; j /= 10)
              k++;
            if (i != k) {
              x2.e++;
              if (xd[0] == BASE)
                xd[0] = 1;
            }
            break;
          } else {
            xd[xdi] += k;
            if (xd[xdi] != BASE)
              break;
            xd[xdi--] = 0;
            k = 1;
          }
        }
      }
      for (i = xd.length;xd[--i] === 0; )
        xd.pop();
    }
  if (external2) {
    if (x2.e > Ctor.maxE) {
      x2.d = null;
      x2.e = NaN;
    } else if (x2.e < Ctor.minE) {
      x2.e = 0;
      x2.d = [0];
    }
  }
  return x2;
}
function finiteToString(x2, isExp, sd) {
  if (!x2.isFinite())
    return nonFiniteToString(x2);
  var k, e = x2.e, str = digitsToString(x2.d), len = str.length;
  if (isExp) {
    if (sd && (k = sd - len) > 0) {
      str = str.charAt(0) + "." + str.slice(1) + getZeroString(k);
    } else if (len > 1) {
      str = str.charAt(0) + "." + str.slice(1);
    }
    str = str + (x2.e < 0 ? "e" : "e+") + x2.e;
  } else if (e < 0) {
    str = "0." + getZeroString(-e - 1) + str;
    if (sd && (k = sd - len) > 0)
      str += getZeroString(k);
  } else if (e >= len) {
    str += getZeroString(e + 1 - len);
    if (sd && (k = sd - e - 1) > 0)
      str = str + "." + getZeroString(k);
  } else {
    if ((k = e + 1) < len)
      str = str.slice(0, k) + "." + str.slice(k);
    if (sd && (k = sd - len) > 0) {
      if (e + 1 === len)
        str += ".";
      str += getZeroString(k);
    }
  }
  return str;
}
function getBase10Exponent(digits, e) {
  var w = digits[0];
  for (e *= LOG_BASE;w >= 10; w /= 10)
    e++;
  return e;
}
function getLn10(Ctor, sd, pr) {
  if (sd > LN10_PRECISION) {
    external2 = true;
    if (pr)
      Ctor.precision = pr;
    throw Error(precisionLimitExceeded);
  }
  return finalise(new Ctor(LN10), sd, 1, true);
}
function getPi(Ctor, sd, rm) {
  if (sd > PI_PRECISION)
    throw Error(precisionLimitExceeded);
  return finalise(new Ctor(PI2), sd, rm, true);
}
function getPrecision(digits) {
  var w = digits.length - 1, len = w * LOG_BASE + 1;
  w = digits[w];
  if (w) {
    for (;w % 10 == 0; w /= 10)
      len--;
    for (w = digits[0];w >= 10; w /= 10)
      len++;
  }
  return len;
}
function getZeroString(k) {
  var zs = "";
  for (;k--; )
    zs += "0";
  return zs;
}
function intPow(Ctor, x2, n, pr) {
  var isTruncated, r = new Ctor(1), k = Math.ceil(pr / LOG_BASE + 4);
  external2 = false;
  for (;; ) {
    if (n % 2) {
      r = r.times(x2);
      if (truncate(r.d, k))
        isTruncated = true;
    }
    n = mathfloor(n / 2);
    if (n === 0) {
      n = r.d.length - 1;
      if (isTruncated && r.d[n] === 0)
        ++r.d[n];
      break;
    }
    x2 = x2.times(x2);
    truncate(x2.d, k);
  }
  external2 = true;
  return r;
}
function isOdd(n) {
  return n.d[n.d.length - 1] & 1;
}
function maxOrMin(Ctor, args2, n) {
  var k, y2, x2 = new Ctor(args2[0]), i = 0;
  for (;++i < args2.length; ) {
    y2 = new Ctor(args2[i]);
    if (!y2.s) {
      x2 = y2;
      break;
    }
    k = x2.cmp(y2);
    if (k === n || k === 0 && x2.s === n) {
      x2 = y2;
    }
  }
  return x2;
}
function naturalExponential(x2, sd) {
  var denominator, guard, j, pow2, sum2, t, wpr, rep = 0, i = 0, k = 0, Ctor = x2.constructor, rm = Ctor.rounding, pr = Ctor.precision;
  if (!x2.d || !x2.d[0] || x2.e > 17) {
    return new Ctor(x2.d ? !x2.d[0] ? 1 : x2.s < 0 ? 0 : 1 / 0 : x2.s ? x2.s < 0 ? 0 : x2 : 0 / 0);
  }
  if (sd == null) {
    external2 = false;
    wpr = pr;
  } else {
    wpr = sd;
  }
  t = new Ctor(0.03125);
  while (x2.e > -2) {
    x2 = x2.times(t);
    k += 5;
  }
  guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;
  wpr += guard;
  denominator = pow2 = sum2 = new Ctor(1);
  Ctor.precision = wpr;
  for (;; ) {
    pow2 = finalise(pow2.times(x2), wpr, 1);
    denominator = denominator.times(++i);
    t = sum2.plus(divide(pow2, denominator, wpr, 1));
    if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum2.d).slice(0, wpr)) {
      j = k;
      while (j--)
        sum2 = finalise(sum2.times(sum2), wpr, 1);
      if (sd == null) {
        if (rep < 3 && checkRoundingDigits(sum2.d, wpr - guard, rm, rep)) {
          Ctor.precision = wpr += 10;
          denominator = pow2 = t = new Ctor(1);
          i = 0;
          rep++;
        } else {
          return finalise(sum2, Ctor.precision = pr, rm, external2 = true);
        }
      } else {
        Ctor.precision = pr;
        return sum2;
      }
    }
    sum2 = t;
  }
}
function naturalLogarithm(y2, sd) {
  var c, c0, denominator, e, numerator, rep, sum2, t, wpr, x1, x2, n = 1, guard = 10, x3 = y2, xd = x3.d, Ctor = x3.constructor, rm = Ctor.rounding, pr = Ctor.precision;
  if (x3.s < 0 || !xd || !xd[0] || !x3.e && xd[0] == 1 && xd.length == 1) {
    return new Ctor(xd && !xd[0] ? -1 / 0 : x3.s != 1 ? NaN : xd ? 0 : x3);
  }
  if (sd == null) {
    external2 = false;
    wpr = pr;
  } else {
    wpr = sd;
  }
  Ctor.precision = wpr += guard;
  c = digitsToString(xd);
  c0 = c.charAt(0);
  if (Math.abs(e = x3.e) < 1500000000000000) {
    while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {
      x3 = x3.times(y2);
      c = digitsToString(x3.d);
      c0 = c.charAt(0);
      n++;
    }
    e = x3.e;
    if (c0 > 1) {
      x3 = new Ctor("0." + c);
      e++;
    } else {
      x3 = new Ctor(c0 + "." + c.slice(1));
    }
  } else {
    t = getLn10(Ctor, wpr + 2, pr).times(e + "");
    x3 = naturalLogarithm(new Ctor(c0 + "." + c.slice(1)), wpr - guard).plus(t);
    Ctor.precision = pr;
    return sd == null ? finalise(x3, pr, rm, external2 = true) : x3;
  }
  x1 = x3;
  sum2 = numerator = x3 = divide(x3.minus(1), x3.plus(1), wpr, 1);
  x2 = finalise(x3.times(x3), wpr, 1);
  denominator = 3;
  for (;; ) {
    numerator = finalise(numerator.times(x2), wpr, 1);
    t = sum2.plus(divide(numerator, new Ctor(denominator), wpr, 1));
    if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum2.d).slice(0, wpr)) {
      sum2 = sum2.times(2);
      if (e !== 0)
        sum2 = sum2.plus(getLn10(Ctor, wpr + 2, pr).times(e + ""));
      sum2 = divide(sum2, new Ctor(n), wpr, 1);
      if (sd == null) {
        if (checkRoundingDigits(sum2.d, wpr - guard, rm, rep)) {
          Ctor.precision = wpr += guard;
          t = numerator = x3 = divide(x1.minus(1), x1.plus(1), wpr, 1);
          x2 = finalise(x3.times(x3), wpr, 1);
          denominator = rep = 1;
        } else {
          return finalise(sum2, Ctor.precision = pr, rm, external2 = true);
        }
      } else {
        Ctor.precision = pr;
        return sum2;
      }
    }
    sum2 = t;
    denominator += 2;
  }
}
function nonFiniteToString(x2) {
  return String(x2.s * x2.s / 0);
}
function parseDecimal(x2, str) {
  var e, i, len;
  if ((e = str.indexOf(".")) > -1)
    str = str.replace(".", "");
  if ((i = str.search(/e/i)) > 0) {
    if (e < 0)
      e = i;
    e += +str.slice(i + 1);
    str = str.substring(0, i);
  } else if (e < 0) {
    e = str.length;
  }
  for (i = 0;str.charCodeAt(i) === 48; i++)
    ;
  for (len = str.length;str.charCodeAt(len - 1) === 48; --len)
    ;
  str = str.slice(i, len);
  if (str) {
    len -= i;
    x2.e = e = e - i - 1;
    x2.d = [];
    i = (e + 1) % LOG_BASE;
    if (e < 0)
      i += LOG_BASE;
    if (i < len) {
      if (i)
        x2.d.push(+str.slice(0, i));
      for (len -= LOG_BASE;i < len; )
        x2.d.push(+str.slice(i, i += LOG_BASE));
      str = str.slice(i);
      i = LOG_BASE - str.length;
    } else {
      i -= len;
    }
    for (;i--; )
      str += "0";
    x2.d.push(+str);
    if (external2) {
      if (x2.e > x2.constructor.maxE) {
        x2.d = null;
        x2.e = NaN;
      } else if (x2.e < x2.constructor.minE) {
        x2.e = 0;
        x2.d = [0];
      }
    }
  } else {
    x2.e = 0;
    x2.d = [0];
  }
  return x2;
}
function parseOther(x2, str) {
  var base, Ctor, divisor, i, isFloat, len, p, xd, xe;
  if (str.indexOf("_") > -1) {
    str = str.replace(/(\d)_(?=\d)/g, "$1");
    if (isDecimal.test(str))
      return parseDecimal(x2, str);
  } else if (str === "Infinity" || str === "NaN") {
    if (!+str)
      x2.s = NaN;
    x2.e = NaN;
    x2.d = null;
    return x2;
  }
  if (isHex.test(str)) {
    base = 16;
    str = str.toLowerCase();
  } else if (isBinary.test(str)) {
    base = 2;
  } else if (isOctal.test(str)) {
    base = 8;
  } else {
    throw Error(invalidArgument + str);
  }
  i = str.search(/p/i);
  if (i > 0) {
    p = +str.slice(i + 1);
    str = str.substring(2, i);
  } else {
    str = str.slice(2);
  }
  i = str.indexOf(".");
  isFloat = i >= 0;
  Ctor = x2.constructor;
  if (isFloat) {
    str = str.replace(".", "");
    len = str.length;
    i = len - i;
    divisor = intPow(Ctor, new Ctor(base), i, i * 2);
  }
  xd = convertBase(str, base, BASE);
  xe = xd.length - 1;
  for (i = xe;xd[i] === 0; --i)
    xd.pop();
  if (i < 0)
    return new Ctor(x2.s * 0);
  x2.e = getBase10Exponent(xd, xe);
  x2.d = xd;
  external2 = false;
  if (isFloat)
    x2 = divide(x2, divisor, len * 4);
  if (p)
    x2 = x2.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p));
  external2 = true;
  return x2;
}
function sine(Ctor, x2) {
  var k, len = x2.d.length;
  if (len < 3) {
    return x2.isZero() ? x2 : taylorSeries(Ctor, 2, x2, x2);
  }
  k = 1.4 * Math.sqrt(len);
  k = k > 16 ? 16 : k | 0;
  x2 = x2.times(1 / tinyPow(5, k));
  x2 = taylorSeries(Ctor, 2, x2, x2);
  var sin2_x, d5 = new Ctor(5), d16 = new Ctor(16), d20 = new Ctor(20);
  for (;k--; ) {
    sin2_x = x2.times(x2);
    x2 = x2.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20))));
  }
  return x2;
}
function taylorSeries(Ctor, n, x2, y2, isHyperbolic) {
  var j, t, u, x22, i = 1, pr = Ctor.precision, k = Math.ceil(pr / LOG_BASE);
  external2 = false;
  x22 = x2.times(x2);
  u = new Ctor(y2);
  for (;; ) {
    t = divide(u.times(x22), new Ctor(n++ * n++), pr, 1);
    u = isHyperbolic ? y2.plus(t) : y2.minus(t);
    y2 = divide(t.times(x22), new Ctor(n++ * n++), pr, 1);
    t = u.plus(y2);
    if (t.d[k] !== undefined) {
      for (j = k;t.d[j] === u.d[j] && j--; )
        ;
      if (j == -1)
        break;
    }
    j = u;
    u = y2;
    y2 = t;
    t = j;
    i++;
  }
  external2 = true;
  t.d.length = k + 1;
  return t;
}
function tinyPow(b, e) {
  var n = b;
  while (--e)
    n *= b;
  return n;
}
function toLessThanHalfPi(Ctor, x2) {
  var t, isNeg = x2.s < 0, pi3 = getPi(Ctor, Ctor.precision, 1), halfPi2 = pi3.times(0.5);
  x2 = x2.abs();
  if (x2.lte(halfPi2)) {
    quadrant = isNeg ? 4 : 1;
    return x2;
  }
  t = x2.divToInt(pi3);
  if (t.isZero()) {
    quadrant = isNeg ? 3 : 2;
  } else {
    x2 = x2.minus(t.times(pi3));
    if (x2.lte(halfPi2)) {
      quadrant = isOdd(t) ? isNeg ? 2 : 3 : isNeg ? 4 : 1;
      return x2;
    }
    quadrant = isOdd(t) ? isNeg ? 1 : 4 : isNeg ? 3 : 2;
  }
  return x2.minus(pi3).abs();
}
function toStringBinary(x2, baseOut, sd, rm) {
  var base, e, i, k, len, roundUp, str, xd, y2, Ctor = x2.constructor, isExp = sd !== undefined;
  if (isExp) {
    checkInt32(sd, 1, MAX_DIGITS);
    if (rm === undefined)
      rm = Ctor.rounding;
    else
      checkInt32(rm, 0, 8);
  } else {
    sd = Ctor.precision;
    rm = Ctor.rounding;
  }
  if (!x2.isFinite()) {
    str = nonFiniteToString(x2);
  } else {
    str = finiteToString(x2);
    i = str.indexOf(".");
    if (isExp) {
      base = 2;
      if (baseOut == 16) {
        sd = sd * 4 - 3;
      } else if (baseOut == 8) {
        sd = sd * 3 - 2;
      }
    } else {
      base = baseOut;
    }
    if (i >= 0) {
      str = str.replace(".", "");
      y2 = new Ctor(1);
      y2.e = str.length - i;
      y2.d = convertBase(finiteToString(y2), 10, base);
      y2.e = y2.d.length;
    }
    xd = convertBase(str, 10, base);
    e = len = xd.length;
    for (;xd[--len] == 0; )
      xd.pop();
    if (!xd[0]) {
      str = isExp ? "0p+0" : "0";
    } else {
      if (i < 0) {
        e--;
      } else {
        x2 = new Ctor(x2);
        x2.d = xd;
        x2.e = e;
        x2 = divide(x2, y2, sd, rm, 0, base);
        xd = x2.d;
        e = x2.e;
        roundUp = inexact;
      }
      i = xd[sd];
      k = base / 2;
      roundUp = roundUp || xd[sd + 1] !== undefined;
      roundUp = rm < 4 ? (i !== undefined || roundUp) && (rm === 0 || rm === (x2.s < 0 ? 3 : 2)) : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 || rm === (x2.s < 0 ? 8 : 7));
      xd.length = sd;
      if (roundUp) {
        for (;++xd[--sd] > base - 1; ) {
          xd[sd] = 0;
          if (!sd) {
            ++e;
            xd.unshift(1);
          }
        }
      }
      for (len = xd.length;!xd[len - 1]; --len)
        ;
      for (i = 0, str = "";i < len; i++)
        str += NUMERALS.charAt(xd[i]);
      if (isExp) {
        if (len > 1) {
          if (baseOut == 16 || baseOut == 8) {
            i = baseOut == 16 ? 4 : 3;
            for (--len;len % i; len++)
              str += "0";
            xd = convertBase(str, base, baseOut);
            for (len = xd.length;!xd[len - 1]; --len)
              ;
            for (i = 1, str = "1.";i < len; i++)
              str += NUMERALS.charAt(xd[i]);
          } else {
            str = str.charAt(0) + "." + str.slice(1);
          }
        }
        str = str + (e < 0 ? "p" : "p+") + e;
      } else if (e < 0) {
        for (;++e; )
          str = "0" + str;
        str = "0." + str;
      } else {
        if (++e > len)
          for (e -= len;e--; )
            str += "0";
        else if (e < len)
          str = str.slice(0, e) + "." + str.slice(e);
      }
    }
    str = (baseOut == 16 ? "0x" : baseOut == 2 ? "0b" : baseOut == 8 ? "0o" : "") + str;
  }
  return x2.s < 0 ? "-" + str : str;
}
function truncate(arr, len) {
  if (arr.length > len) {
    arr.length = len;
    return true;
  }
}
function abs3(x2) {
  return new this(x2).abs();
}
function acos2(x2) {
  return new this(x2).acos();
}
function acosh(x2) {
  return new this(x2).acosh();
}
function add(x2, y2) {
  return new this(x2).plus(y2);
}
function asin2(x2) {
  return new this(x2).asin();
}
function asinh(x2) {
  return new this(x2).asinh();
}
function atan(x2) {
  return new this(x2).atan();
}
function atanh(x2) {
  return new this(x2).atanh();
}
function atan22(y2, x2) {
  y2 = new this(y2);
  x2 = new this(x2);
  var r, pr = this.precision, rm = this.rounding, wpr = pr + 4;
  if (!y2.s || !x2.s) {
    r = new this(NaN);
  } else if (!y2.d && !x2.d) {
    r = getPi(this, wpr, 1).times(x2.s > 0 ? 0.25 : 0.75);
    r.s = y2.s;
  } else if (!x2.d || y2.isZero()) {
    r = x2.s < 0 ? getPi(this, pr, rm) : new this(0);
    r.s = y2.s;
  } else if (!y2.d || x2.isZero()) {
    r = getPi(this, wpr, 1).times(0.5);
    r.s = y2.s;
  } else if (x2.s < 0) {
    this.precision = wpr;
    this.rounding = 1;
    r = this.atan(divide(y2, x2, wpr, 1));
    x2 = getPi(this, wpr, 1);
    this.precision = pr;
    this.rounding = rm;
    r = y2.s < 0 ? r.minus(x2) : r.plus(x2);
  } else {
    r = this.atan(divide(y2, x2, wpr, 1));
  }
  return r;
}
function cbrt(x2) {
  return new this(x2).cbrt();
}
function ceil(x2) {
  return finalise(x2 = new this(x2), x2.e + 1, 2);
}
function clamp8(x2, min3, max4) {
  return new this(x2).clamp(min3, max4);
}
function config2(obj) {
  if (!obj || typeof obj !== "object")
    throw Error(decimalError + "Object expected");
  var i, p, v, useDefaults = obj.defaults === true, ps = [
    "precision",
    1,
    MAX_DIGITS,
    "rounding",
    0,
    8,
    "toExpNeg",
    -EXP_LIMIT,
    0,
    "toExpPos",
    0,
    EXP_LIMIT,
    "maxE",
    0,
    EXP_LIMIT,
    "minE",
    -EXP_LIMIT,
    0,
    "modulo",
    0,
    9
  ];
  for (i = 0;i < ps.length; i += 3) {
    if (p = ps[i], useDefaults)
      this[p] = DEFAULTS[p];
    if ((v = obj[p]) !== undefined) {
      if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2])
        this[p] = v;
      else
        throw Error(invalidArgument + p + ": " + v);
    }
  }
  if (p = "crypto", useDefaults)
    this[p] = DEFAULTS[p];
  if ((v = obj[p]) !== undefined) {
    if (v === true || v === false || v === 0 || v === 1) {
      if (v) {
        if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
          this[p] = true;
        } else {
          throw Error(cryptoUnavailable);
        }
      } else {
        this[p] = false;
      }
    } else {
      throw Error(invalidArgument + p + ": " + v);
    }
  }
  return this;
}
function cos2(x2) {
  return new this(x2).cos();
}
function cosh(x2) {
  return new this(x2).cosh();
}
function clone2(obj) {
  var i, p, ps;
  function Decimal(v) {
    var e, i2, t, x2 = this;
    if (!(x2 instanceof Decimal))
      return new Decimal(v);
    x2.constructor = Decimal;
    if (isDecimalInstance(v)) {
      x2.s = v.s;
      if (external2) {
        if (!v.d || v.e > Decimal.maxE) {
          x2.e = NaN;
          x2.d = null;
        } else if (v.e < Decimal.minE) {
          x2.e = 0;
          x2.d = [0];
        } else {
          x2.e = v.e;
          x2.d = v.d.slice();
        }
      } else {
        x2.e = v.e;
        x2.d = v.d ? v.d.slice() : v.d;
      }
      return;
    }
    t = typeof v;
    if (t === "number") {
      if (v === 0) {
        x2.s = 1 / v < 0 ? -1 : 1;
        x2.e = 0;
        x2.d = [0];
        return;
      }
      if (v < 0) {
        v = -v;
        x2.s = -1;
      } else {
        x2.s = 1;
      }
      if (v === ~~v && v < 1e7) {
        for (e = 0, i2 = v;i2 >= 10; i2 /= 10)
          e++;
        if (external2) {
          if (e > Decimal.maxE) {
            x2.e = NaN;
            x2.d = null;
          } else if (e < Decimal.minE) {
            x2.e = 0;
            x2.d = [0];
          } else {
            x2.e = e;
            x2.d = [v];
          }
        } else {
          x2.e = e;
          x2.d = [v];
        }
        return;
      }
      if (v * 0 !== 0) {
        if (!v)
          x2.s = NaN;
        x2.e = NaN;
        x2.d = null;
        return;
      }
      return parseDecimal(x2, v.toString());
    }
    if (t === "string") {
      if ((i2 = v.charCodeAt(0)) === 45) {
        v = v.slice(1);
        x2.s = -1;
      } else {
        if (i2 === 43)
          v = v.slice(1);
        x2.s = 1;
      }
      return isDecimal.test(v) ? parseDecimal(x2, v) : parseOther(x2, v);
    }
    if (t === "bigint") {
      if (v < 0) {
        v = -v;
        x2.s = -1;
      } else {
        x2.s = 1;
      }
      return parseDecimal(x2, v.toString());
    }
    throw Error(invalidArgument + v);
  }
  Decimal.prototype = P;
  Decimal.ROUND_UP = 0;
  Decimal.ROUND_DOWN = 1;
  Decimal.ROUND_CEIL = 2;
  Decimal.ROUND_FLOOR = 3;
  Decimal.ROUND_HALF_UP = 4;
  Decimal.ROUND_HALF_DOWN = 5;
  Decimal.ROUND_HALF_EVEN = 6;
  Decimal.ROUND_HALF_CEIL = 7;
  Decimal.ROUND_HALF_FLOOR = 8;
  Decimal.EUCLID = 9;
  Decimal.config = Decimal.set = config2;
  Decimal.clone = clone2;
  Decimal.isDecimal = isDecimalInstance;
  Decimal.abs = abs3;
  Decimal.acos = acos2;
  Decimal.acosh = acosh;
  Decimal.add = add;
  Decimal.asin = asin2;
  Decimal.asinh = asinh;
  Decimal.atan = atan;
  Decimal.atanh = atanh;
  Decimal.atan2 = atan22;
  Decimal.cbrt = cbrt;
  Decimal.ceil = ceil;
  Decimal.clamp = clamp8;
  Decimal.cos = cos2;
  Decimal.cosh = cosh;
  Decimal.div = div;
  Decimal.exp = exp;
  Decimal.floor = floor2;
  Decimal.hypot = hypot;
  Decimal.ln = ln;
  Decimal.log = log;
  Decimal.log10 = log10;
  Decimal.log2 = log2;
  Decimal.max = max4;
  Decimal.min = min3;
  Decimal.mod = mod;
  Decimal.mul = mul;
  Decimal.pow = pow2;
  Decimal.random = random;
  Decimal.round = round;
  Decimal.sign = sign2;
  Decimal.sin = sin2;
  Decimal.sinh = sinh;
  Decimal.sqrt = sqrt3;
  Decimal.sub = sub;
  Decimal.sum = sum2;
  Decimal.tan = tan;
  Decimal.tanh = tanh;
  Decimal.trunc = trunc;
  if (obj === undefined)
    obj = {};
  if (obj) {
    if (obj.defaults !== true) {
      ps = ["precision", "rounding", "toExpNeg", "toExpPos", "maxE", "minE", "modulo", "crypto"];
      for (i = 0;i < ps.length; )
        if (!obj.hasOwnProperty(p = ps[i++]))
          obj[p] = this[p];
    }
  }
  Decimal.config(obj);
  return Decimal;
}
function div(x2, y2) {
  return new this(x2).div(y2);
}
function exp(x2) {
  return new this(x2).exp();
}
function floor2(x2) {
  return finalise(x2 = new this(x2), x2.e + 1, 3);
}
function hypot() {
  var i, n, t = new this(0);
  external2 = false;
  for (i = 0;i < arguments.length; ) {
    n = new this(arguments[i++]);
    if (!n.d) {
      if (n.s) {
        external2 = true;
        return new this(1 / 0);
      }
      t = n;
    } else if (t.d) {
      t = t.plus(n.times(n));
    }
  }
  external2 = true;
  return t.sqrt();
}
function isDecimalInstance(obj) {
  return obj instanceof Decimal || obj && obj.toStringTag === tag || false;
}
function ln(x2) {
  return new this(x2).ln();
}
function log(x2, y2) {
  return new this(x2).log(y2);
}
function log2(x2) {
  return new this(x2).log(2);
}
function log10(x2) {
  return new this(x2).log(10);
}
function max4() {
  return maxOrMin(this, arguments, -1);
}
function min3() {
  return maxOrMin(this, arguments, 1);
}
function mod(x2, y2) {
  return new this(x2).mod(y2);
}
function mul(x2, y2) {
  return new this(x2).mul(y2);
}
function pow2(x2, y2) {
  return new this(x2).pow(y2);
}
function random(sd) {
  var d, e, k, n, i = 0, r = new this(1), rd = [];
  if (sd === undefined)
    sd = this.precision;
  else
    checkInt32(sd, 1, MAX_DIGITS);
  k = Math.ceil(sd / LOG_BASE);
  if (!this.crypto) {
    for (;i < k; )
      rd[i++] = Math.random() * 1e7 | 0;
  } else if (crypto.getRandomValues) {
    d = crypto.getRandomValues(new Uint32Array(k));
    for (;i < k; ) {
      n = d[i];
      if (n >= 4290000000) {
        d[i] = crypto.getRandomValues(new Uint32Array(1))[0];
      } else {
        rd[i++] = n % 1e7;
      }
    }
  } else if (crypto.randomBytes) {
    d = crypto.randomBytes(k *= 4);
    for (;i < k; ) {
      n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 127) << 24);
      if (n >= 2140000000) {
        crypto.randomBytes(4).copy(d, i);
      } else {
        rd.push(n % 1e7);
        i += 4;
      }
    }
    i = k / 4;
  } else {
    throw Error(cryptoUnavailable);
  }
  k = rd[--i];
  sd %= LOG_BASE;
  if (k && sd) {
    n = mathpow(10, LOG_BASE - sd);
    rd[i] = (k / n | 0) * n;
  }
  for (;rd[i] === 0; i--)
    rd.pop();
  if (i < 0) {
    e = 0;
    rd = [0];
  } else {
    e = -1;
    for (;rd[0] === 0; e -= LOG_BASE)
      rd.shift();
    for (k = 1, n = rd[0];n >= 10; n /= 10)
      k++;
    if (k < LOG_BASE)
      e -= LOG_BASE - k;
  }
  r.e = e;
  r.d = rd;
  return r;
}
function round(x2) {
  return finalise(x2 = new this(x2), x2.e + 1, this.rounding);
}
function sign2(x2) {
  x2 = new this(x2);
  return x2.d ? x2.d[0] ? x2.s : 0 * x2.s : x2.s || NaN;
}
function sin2(x2) {
  return new this(x2).sin();
}
function sinh(x2) {
  return new this(x2).sinh();
}
function sqrt3(x2) {
  return new this(x2).sqrt();
}
function sub(x2, y2) {
  return new this(x2).sub(y2);
}
function sum2() {
  var i = 0, args2 = arguments, x2 = new this(args2[i]);
  external2 = false;
  for (;x2.s && ++i < args2.length; )
    x2 = x2.plus(args2[i]);
  external2 = true;
  return finalise(x2, this.precision, this.rounding);
}
function tan(x2) {
  return new this(x2).tan();
}
function tanh(x2) {
  return new this(x2).tanh();
}
function trunc(x2) {
  return finalise(x2 = new this(x2), x2.e + 1, 1);
}
P[Symbol.for("nodejs.util.inspect.custom")] = P.toString;
P[Symbol.toStringTag] = "Decimal";
var Decimal = P.constructor = clone2(DEFAULTS);
LN10 = new Decimal(LN10);
PI2 = new Decimal(PI2);
var decimal_default = Decimal;

// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/financial.js
decimal_default.set({ precision: 50, rounding: decimal_default.ROUND_HALF_EVEN });
var VALUE_ERROR3 = { kind: "Error", code: "#VALUE!" };
var NUM_ERROR2 = { kind: "Error", code: "#NUM!" };
var EXCEL_EPOCH_MS4 = Date.UTC(1899, 11, 30);
var MS_PER_DAY4 = 24 * 60 * 60 * 1000;
var DEFAULT_CONVENTION = "30U/360";
var BASIS_TO_CONVENTION = {
  0: "30U/360",
  1: "ACTUAL/ACTUAL",
  2: "ACTUAL/360",
  3: "ACTUAL/365",
  4: "30E/360"
};
var createBondCalculator = bondCalculator;
function NPV2(rate, value1, value2, ...rest2) {
  return NPV(rate, value1, value2, ...rest2);
}
function PV2(rate, nper, pmt, fv, typeParam) {
  return PV(rate, nper, pmt, fv, typeParam);
}
function FV2(rate, nper, pmt, pv, typeParam) {
  return FV(rate, nper, pmt, pv, typeParam);
}
function NPER2(rate, pmt, pv, fv, typeParam) {
  return NPER(rate, pmt, pv, fv, typeParam);
}
function PMT2(rate, nper, pv, fv, typeParam) {
  const rateResult = coerceNumberArg2(rate);
  if (typeof rateResult !== "number") {
    return rateResult;
  }
  const nperResult = coerceNumberArg2(nper);
  if (typeof nperResult !== "number") {
    return nperResult;
  }
  const pvResult = coerceNumberArg2(pv);
  if (typeof pvResult !== "number") {
    return pvResult;
  }
  const fvResult = fv === undefined ? 0 : coerceNumberArg2(fv);
  if (typeof fvResult !== "number") {
    return fvResult;
  }
  const typeResult = typeParam === undefined ? 0 : coerceNumberArg2(typeParam);
  if (typeof typeResult !== "number") {
    return typeResult;
  }
  return precisePMT(rateResult, nperResult, pvResult, fvResult, typeResult);
}
function RATE2(nper, pmt, pv, fv, typeParam, guess) {
  return RATE(nper, pmt, pv, fv, typeParam, guess);
}
function MIRR2(values, financeRate, reinvestRate) {
  return MIRR(values, financeRate, reinvestRate);
}
function IRR2(values, guess) {
  return IRR(values, guess);
}
function SLN2(cost, salvage, life) {
  return SLN(cost, salvage, life);
}
function SYD2(cost, salvage, life, per) {
  return SYD(cost, salvage, life, per);
}
function DDB2(cost, salvage, life, period, factor) {
  return DDB(cost, salvage, life, period, factor);
}
function IPMT2(rate, per, nper, pv, fv, typeParam) {
  return IPMT(rate, per, nper, pv, fv, typeParam);
}
function PPMT2(rate, per, nper, pv, fv, typeParam) {
  return PPMT(rate, per, nper, pv, fv, typeParam);
}
function VDB(cost, salvage, life, startPeriod, endPeriod, factor, noSwitch) {
  throw new Error(`VDB is not implemented. cost=${String(cost)}, salvage=${String(salvage)}, life=${String(life)}, startPeriod=${String(startPeriod)}, endPeriod=${String(endPeriod)}, factor=${String(factor)}, noSwitch=${String(noSwitch)}`);
}
function DB2(cost, salvage, life, period, month) {
  return DB(cost, salvage, life, period, month);
}
function ISPMT2(rate, per, nper, pv) {
  return ISPMT(rate, per, nper, pv);
}
function XIRR2(values, dates, guess) {
  return XIRR(values, dates, guess);
}
function XNPV2(rate, values, dates) {
  return XNPV(rate, values, dates);
}
function PRICEMAT(settlement, maturity, issue2, rate, yld, basis2) {
  const timeline = buildIssueTimelineInput(settlement, maturity, issue2, basis2);
  if (isErrorValue3(timeline)) {
    return timeline;
  }
  const rateResult = coerceNumberArg2(rate);
  if (typeof rateResult !== "number") {
    return rateResult;
  }
  const yieldResult = coerceNumberArg2(yld);
  if (typeof yieldResult !== "number") {
    return yieldResult;
  }
  if (rateResult < 0 || yieldResult < 0) {
    return NUM_ERROR2;
  }
  const settlementToMaturity = dayCountBetween(timeline.settlement, timeline.maturity, timeline.convention);
  const issueToMaturity = dayCountBetween(timeline.issue, timeline.maturity, timeline.convention);
  if (settlementToMaturity <= 0 || issueToMaturity <= 0) {
    return NUM_ERROR2;
  }
  const settlementBasis = yearLengthFromBasis(timeline.convention, timeline.settlement);
  const issueBasis = yearLengthFromBasis(timeline.convention, timeline.issue);
  const maturityValue = 100 + rateResult * 100 * issueToMaturity / issueBasis;
  const discountFactor = 1 + yieldResult * settlementToMaturity / settlementBasis;
  if (discountFactor <= 0) {
    return NUM_ERROR2;
  }
  const price = maturityValue / discountFactor;
  return Number.isFinite(price) ? price : NUM_ERROR2;
}
function YIELDMAT(settlement, maturity, issue2, rate, pr, basis2) {
  const timeline = buildIssueTimelineInput(settlement, maturity, issue2, basis2);
  if (isErrorValue3(timeline)) {
    return timeline;
  }
  const rateResult = coerceNumberArg2(rate);
  if (typeof rateResult !== "number") {
    return rateResult;
  }
  const priceResult = coerceNumberArg2(pr);
  if (typeof priceResult !== "number") {
    return priceResult;
  }
  if (priceResult <= 0 || rateResult < 0) {
    return NUM_ERROR2;
  }
  const settlementToMaturity = dayCountBetween(timeline.settlement, timeline.maturity, timeline.convention);
  const issueToMaturity = dayCountBetween(timeline.issue, timeline.maturity, timeline.convention);
  if (settlementToMaturity <= 0 || issueToMaturity <= 0) {
    return NUM_ERROR2;
  }
  const settlementBasis = yearLengthFromBasis(timeline.convention, timeline.settlement);
  const issueBasis = yearLengthFromBasis(timeline.convention, timeline.issue);
  const maturityValue = 100 + rateResult * 100 * issueToMaturity / issueBasis;
  if (maturityValue <= 0) {
    return NUM_ERROR2;
  }
  const ratio = maturityValue / priceResult;
  if (ratio <= 0) {
    return NUM_ERROR2;
  }
  const yieldValue = (ratio - 1) * (settlementBasis / settlementToMaturity);
  return Number.isFinite(yieldValue) ? yieldValue : NUM_ERROR2;
}
function INTRATE(settlement, maturity, investment, redemption, basis2) {
  throw new Error(`INTRATE is not implemented. settlement=${String(settlement)}, maturity=${String(maturity)}, investment=${String(investment)}, redemption=${String(redemption)}, basis=${String(basis2)}`);
}
function RECEIVED(settlement, maturity, investment, discount, basis2) {
  const timeline = buildDateRangeInput(settlement, maturity, basis2);
  if (isErrorValue3(timeline)) {
    return timeline;
  }
  const investmentResult = coerceNumberArg2(investment);
  if (typeof investmentResult !== "number") {
    return investmentResult;
  }
  const discountResult = coerceNumberArg2(discount);
  if (typeof discountResult !== "number") {
    return discountResult;
  }
  if (investmentResult <= 0 || discountResult < 0) {
    return NUM_ERROR2;
  }
  const dayCount = dayCountBetween(timeline.settlement, timeline.maturity, timeline.convention);
  if (dayCount <= 0) {
    return NUM_ERROR2;
  }
  const basisDays = yearLengthFromBasis(timeline.convention, timeline.settlement);
  const discountFraction = discountResult * dayCount / basisDays;
  if (discountFraction >= 1) {
    return NUM_ERROR2;
  }
  const redemption = investmentResult / (1 - discountFraction);
  return Number.isFinite(redemption) ? redemption : NUM_ERROR2;
}
function DISC2(settlement, maturity, pr, redemption, basis2) {
  return DISC(settlement, maturity, pr, redemption, basis2);
}
function PRICEDISC2(settlement, maturity, discount, redemption, basis2) {
  return PRICEDISC(settlement, maturity, discount, redemption, basis2);
}
function YIELDDISC(settlement, maturity, pr, redemption, basis2) {
  const timeline = buildDateRangeInput(settlement, maturity, basis2);
  if (isErrorValue3(timeline)) {
    return timeline;
  }
  const priceResult = coerceNumberArg2(pr);
  if (typeof priceResult !== "number") {
    return priceResult;
  }
  const redemptionResult = coerceNumberArg2(redemption);
  if (typeof redemptionResult !== "number") {
    return redemptionResult;
  }
  if (priceResult <= 0 || redemptionResult <= 0) {
    return NUM_ERROR2;
  }
  const dayCount = dayCountBetween(timeline.settlement, timeline.maturity, timeline.convention);
  if (dayCount <= 0) {
    return NUM_ERROR2;
  }
  const basisDays = yearLengthFromBasis(timeline.convention, timeline.settlement);
  const yieldValue = (redemptionResult - priceResult) / priceResult * (basisDays / dayCount);
  return Number.isFinite(yieldValue) ? yieldValue : NUM_ERROR2;
}
function TBILLEQ2(settlement, maturity, discount) {
  return TBILLEQ(settlement, maturity, discount);
}
function TBILLPRICE2(settlement, maturity, discount) {
  return TBILLPRICE(settlement, maturity, discount);
}
function TBILLYIELD2(settlement, maturity, pr) {
  return TBILLYIELD(settlement, maturity, pr);
}
function PRICE(settlement, maturity, rate, yld, redemption, frequency, basis2) {
  const bondInput = buildBondCalculatorInput(settlement, maturity, rate, redemption, frequency, basis2);
  if (isErrorValue3(bondInput)) {
    return bondInput;
  }
  const yieldResult = coerceNumberArg2(yld);
  if (typeof yieldResult !== "number") {
    return yieldResult;
  }
  try {
    const calculator = createBondCalculator(bondInput);
    const priceValue = calculator.price(yieldResult);
    return Number.isFinite(priceValue) ? priceValue : NUM_ERROR2;
  } catch (error49) {
    return convertBondError(error49);
  }
}
function YIELD(settlement, maturity, rate, pr, redemption, frequency, basis2) {
  const bondInput = buildBondCalculatorInput(settlement, maturity, rate, redemption, frequency, basis2);
  if (isErrorValue3(bondInput)) {
    return bondInput;
  }
  const priceResult = coerceNumberArg2(pr);
  if (typeof priceResult !== "number") {
    return priceResult;
  }
  if (priceResult <= 0) {
    return NUM_ERROR2;
  }
  try {
    const calculator = createBondCalculator(bondInput);
    const yieldValue = calculator.yield(priceResult);
    return Number.isFinite(yieldValue) ? yieldValue : NUM_ERROR2;
  } catch (error49) {
    return convertBondError(error49);
  }
}
function DOLLARDE2(fractionalDollar, fraction) {
  return DOLLARDE(fractionalDollar, fraction);
}
function DOLLARFR2(decimalDollar, fraction) {
  return DOLLARFR(decimalDollar, fraction);
}
function NOMINAL2(effectRate, npery) {
  return NOMINAL(effectRate, npery);
}
function EFFECT2(nominalRate, npery) {
  return EFFECT(nominalRate, npery);
}
function CUMPRINC2(rate, nper, pv, startPeriod, endPeriod, typeParam) {
  return CUMPRINC(rate, nper, pv, startPeriod, endPeriod, typeParam);
}
function CUMIPMT2(rate, nper, pv, startPeriod, endPeriod, typeParam) {
  return CUMIPMT(rate, nper, pv, startPeriod, endPeriod, typeParam);
}
function COUPDAYBS(settlement, maturity, frequency, basis2) {
  const schedule = buildCouponSchedule(settlement, maturity, frequency, basis2);
  if (isErrorValue3(schedule)) {
    return schedule;
  }
  return schedule.accruedDays;
}
function COUPDAYS2(settlement, maturity, frequency, basis2) {
  return COUPDAYS(settlement, maturity, frequency, basis2);
}
function COUPDAYSNC(settlement, maturity, frequency, basis2) {
  const schedule = buildCouponSchedule(settlement, maturity, frequency, basis2);
  if (isErrorValue3(schedule)) {
    return schedule;
  }
  return schedule.periodDays - schedule.accruedDays;
}
function COUPNCD(settlement, maturity, frequency, basis2) {
  const schedule = buildCouponSchedule(settlement, maturity, frequency, basis2);
  if (isErrorValue3(schedule)) {
    return schedule;
  }
  return dateToExcelSerial2(schedule.nextCoupon);
}
function COUPNUM(settlement, maturity, frequency, basis2) {
  const input = buildCouponInput(settlement, maturity, frequency, basis2);
  if (isErrorValue3(input)) {
    return input;
  }
  const count3 = num2(input.settlement, input.maturity, input.frequency);
  return Number.isFinite(count3) ? count3 : NUM_ERROR2;
}
function COUPPCD(settlement, maturity, frequency, basis2) {
  const schedule = buildCouponSchedule(settlement, maturity, frequency, basis2);
  if (isErrorValue3(schedule)) {
    return schedule;
  }
  return dateToExcelSerial2(schedule.previousCoupon);
}
function DURATION(settlement, maturity, coupon, yld, frequency, basis2) {
  throw new Error(`DURATION is not implemented. settlement=${String(settlement)}, maturity=${String(maturity)}, coupon=${String(coupon)}, yld=${String(yld)}, frequency=${String(frequency)}, basis=${String(basis2)}`);
}
function MDURATION(settlement, maturity, coupon, yld, frequency, basis2) {
  throw new Error(`MDURATION is not implemented. settlement=${String(settlement)}, maturity=${String(maturity)}, coupon=${String(coupon)}, yld=${String(yld)}, frequency=${String(frequency)}, basis=${String(basis2)}`);
}
function ODDLPRICE(settlement, maturity, lastInterest, rate, yld, redemption, frequency, basis2) {
  throw new Error(`ODDLPRICE is not implemented. settlement=${String(settlement)}, maturity=${String(maturity)}, lastInterest=${String(lastInterest)}, rate=${String(rate)}, yld=${String(yld)}, redemption=${String(redemption)}, frequency=${String(frequency)}, basis=${String(basis2)}`);
}
function ODDLYIELD(settlement, maturity, lastInterest, rate, pr, redemption, frequency, basis2) {
  throw new Error(`ODDLYIELD is not implemented. settlement=${String(settlement)}, maturity=${String(maturity)}, lastInterest=${String(lastInterest)}, rate=${String(rate)}, pr=${String(pr)}, redemption=${String(redemption)}, frequency=${String(frequency)}, basis=${String(basis2)}`);
}
function ODDFPRICE(settlement, maturity, issue2, firstCoupon, rate, yld, redemption, frequency, basis2) {
  throw new Error(`ODDFPRICE is not implemented. settlement=${String(settlement)}, maturity=${String(maturity)}, issue=${String(issue2)}, firstCoupon=${String(firstCoupon)}, rate=${String(rate)}, yld=${String(yld)}, redemption=${String(redemption)}, frequency=${String(frequency)}, basis=${String(basis2)}`);
}
function ODDFYIELD(settlement, maturity, issue2, firstCoupon, rate, pr, redemption, frequency, basis2) {
  throw new Error(`ODDFYIELD is not implemented. settlement=${String(settlement)}, maturity=${String(maturity)}, issue=${String(issue2)}, firstCoupon=${String(firstCoupon)}, rate=${String(rate)}, pr=${String(pr)}, redemption=${String(redemption)}, frequency=${String(frequency)}, basis=${String(basis2)}`);
}
function AMORLINC(cost, datePurchased, firstPeriod, salvage, period, rate, basis2) {
  throw new Error(`AMORLINC is not implemented. cost=${String(cost)}, datePurchased=${String(datePurchased)}, firstPeriod=${String(firstPeriod)}, salvage=${String(salvage)}, period=${String(period)}, rate=${String(rate)}, basis=${String(basis2)}`);
}
function ACCRINT2(issue2, firstInterest, settlement, rate, par, frequency, basis2, _calcMethod) {
  return ACCRINT(issue2, firstInterest, settlement, rate, par, frequency, basis2);
}
function ACCRINTM(issue2, settlement, rate, par, basis2) {
  throw new Error(`ACCRINTM is not implemented. issue=${String(issue2)}, settlement=${String(settlement)}, rate=${String(rate)}, par=${String(par)}, basis=${String(basis2)}`);
}
function FVSCHEDULE2(principal, schedule) {
  return FVSCHEDULE(principal, schedule);
}
function PDURATION2(rate, pv, fv) {
  return PDURATION(rate, pv, fv);
}
function RRI2(nper, pv, fv) {
  return RRI(nper, pv, fv);
}
function STOCKHISTORY(stock, startDate, endDate, interval, headers, properties1, ...rest2) {
  throw new Error(`STOCKHISTORY is not implemented. stock=${String(stock)}, startDate=${String(startDate)}, endDate=${String(endDate)}, interval=${String(interval)}, headers=${String(headers)}, properties1=${String(properties1)}, rest.length=${rest2.length}`);
}
function precisePMT(rate, nper, pv, fv, typeParam) {
  const rateDec = new decimal_default(rate);
  const nperDec = new decimal_default(nper);
  const pvDec = new decimal_default(pv);
  const fvDec = new decimal_default(fv);
  const typeDec = new decimal_default(typeParam);
  const one2 = new decimal_default(1);
  if (rateDec.isZero()) {
    return pvDec.neg().minus(fvDec).div(nperDec).toNumber();
  }
  const compound = one2.add(rateDec).pow(nperDec);
  const numerator = rateDec.mul(fvDec.add(compound.mul(pvDec)));
  const denominator = compound.sub(one2);
  const payment = numerator.div(one2.add(rateDec.mul(typeDec))).div(denominator).neg();
  return payment.toNumber();
}
function buildBondCalculatorInput(settlement, maturity, rate, redemption, frequency, basis2) {
  const settlementResult = coerceDateArg(settlement);
  if (isErrorValue3(settlementResult)) {
    return settlementResult;
  }
  const maturityResult = coerceDateArg(maturity);
  if (isErrorValue3(maturityResult)) {
    return maturityResult;
  }
  const rateResult = coerceNumberArg2(rate);
  if (typeof rateResult !== "number") {
    return rateResult;
  }
  const redemptionResult = coerceNumberArg2(redemption);
  if (typeof redemptionResult !== "number") {
    return redemptionResult;
  }
  if (redemptionResult <= 0) {
    return NUM_ERROR2;
  }
  const frequencyResult = coerceFrequencyArg(frequency);
  if (isErrorValue3(frequencyResult)) {
    return frequencyResult;
  }
  const conventionResult = coerceBasisArg(basis2);
  if (isErrorValue3(conventionResult)) {
    return conventionResult;
  }
  if (settlementResult.getTime() >= maturityResult.getTime()) {
    return NUM_ERROR2;
  }
  return {
    settlement: settlementResult,
    maturity: maturityResult,
    rate: rateResult,
    redemption: redemptionResult,
    frequency: frequencyResult,
    convention: conventionResult
  };
}
function buildDateRangeInput(settlement, maturity, basis2) {
  const settlementResult = coerceDateArg(settlement);
  if (isErrorValue3(settlementResult)) {
    return settlementResult;
  }
  const maturityResult = coerceDateArg(maturity);
  if (isErrorValue3(maturityResult)) {
    return maturityResult;
  }
  if (settlementResult.getTime() >= maturityResult.getTime()) {
    return NUM_ERROR2;
  }
  const conventionResult = coerceBasisArg(basis2);
  if (isErrorValue3(conventionResult)) {
    return conventionResult;
  }
  return {
    settlement: settlementResult,
    maturity: maturityResult,
    convention: conventionResult
  };
}
function buildCouponInput(settlement, maturity, frequency, basis2) {
  const range2 = buildDateRangeInput(settlement, maturity, basis2);
  if (isErrorValue3(range2)) {
    return range2;
  }
  const frequencyResult = coerceFrequencyArg(frequency);
  if (isErrorValue3(frequencyResult)) {
    return frequencyResult;
  }
  return {
    ...range2,
    frequency: frequencyResult
  };
}
function buildCouponSchedule(settlement, maturity, frequency, basis2) {
  const input = buildCouponInput(settlement, maturity, frequency, basis2);
  if (isErrorValue3(input)) {
    return input;
  }
  const previousCoupon = previous(input.settlement, input.maturity, input.frequency);
  const nextCoupon = next(input.settlement, input.maturity, input.frequency);
  const periodDays = days(previousCoupon, nextCoupon, input.frequency, input.convention);
  const accruedDays = accrued(previousCoupon, input.settlement, input.convention);
  if (periodDays <= 0 || accruedDays < 0) {
    return NUM_ERROR2;
  }
  return {
    ...input,
    previousCoupon,
    nextCoupon,
    periodDays,
    accruedDays
  };
}
function buildIssueTimelineInput(settlement, maturity, issue2, basis2) {
  const range2 = buildDateRangeInput(settlement, maturity, basis2);
  if (isErrorValue3(range2)) {
    return range2;
  }
  const issueResult = coerceDateArg(issue2);
  if (isErrorValue3(issueResult)) {
    return issueResult;
  }
  if (issueResult.getTime() >= range2.settlement.getTime()) {
    return NUM_ERROR2;
  }
  return {
    ...range2,
    issue: issueResult
  };
}
function coerceNumberArg2(arg) {
  const scalar = extractScalar(arg);
  if (isErrorValue3(scalar)) {
    return scalar;
  }
  return normalizeNumber(scalar);
}
function coerceDateArg(arg) {
  const scalar = extractScalar(arg);
  if (isErrorValue3(scalar)) {
    return scalar;
  }
  if (scalar === "" || scalar === null) {
    return VALUE_ERROR3;
  }
  if (typeof scalar === "number") {
    const date6 = excelSerialToDate(scalar);
    return date6 ?? VALUE_ERROR3;
  }
  if (typeof scalar === "string") {
    const parsed = parseDateLiteral(scalar);
    return parsed ?? VALUE_ERROR3;
  }
  return VALUE_ERROR3;
}
function coerceBasisArg(arg) {
  if (arg === undefined) {
    return DEFAULT_CONVENTION;
  }
  const scalar = extractScalar(arg);
  if (isErrorValue3(scalar)) {
    return scalar;
  }
  if (scalar === "" || scalar === null) {
    return DEFAULT_CONVENTION;
  }
  if (typeof scalar === "boolean") {
    return scalar ? BASIS_TO_CONVENTION[1] ?? NUM_ERROR2 : DEFAULT_CONVENTION;
  }
  if (typeof scalar === "number") {
    return BASIS_TO_CONVENTION[Math.trunc(scalar)] ?? NUM_ERROR2;
  }
  if (typeof scalar === "string") {
    const parsed = Number(scalar);
    if (!Number.isFinite(parsed)) {
      return VALUE_ERROR3;
    }
    return BASIS_TO_CONVENTION[Math.trunc(parsed)] ?? NUM_ERROR2;
  }
  return VALUE_ERROR3;
}
function coerceFrequencyArg(arg) {
  const numeric = coerceNumberArg2(arg);
  if (typeof numeric !== "number") {
    return numeric;
  }
  if (!Number.isInteger(numeric)) {
    return NUM_ERROR2;
  }
  if (numeric !== 1 && numeric !== 2 && numeric !== 4) {
    return NUM_ERROR2;
  }
  return numeric;
}
function dayCountBetween(start, end, convention) {
  return accrued(start, end, convention);
}
function yearLengthFromBasis(convention, referenceDate) {
  switch (convention) {
    case "ACTUAL/ACTUAL":
      return isLeapYear2(referenceDate.getUTCFullYear()) ? 366 : 365;
    case "ACTUAL/365":
      return 365;
    case "ACTUAL/360":
    case "30U/360":
    case "30E/360":
    case "30/360":
    default:
      return 360;
  }
}
function extractScalar(arg) {
  if (arg === undefined) {
    return VALUE_ERROR3;
  }
  if (Array.isArray(arg)) {
    for (const row2 of arg) {
      if (!row2) {
        continue;
      }
      for (const cell of row2) {
        if (cell !== undefined) {
          return normalizeScalar(cell ?? "");
        }
      }
    }
    return "";
  }
  return normalizeScalar(arg);
}
function normalizeScalar(value2) {
  if (isErrorValue3(value2)) {
    return value2;
  }
  if (value2 instanceof Error) {
    return VALUE_ERROR3;
  }
  if (isLambdaValue2(value2)) {
    return VALUE_ERROR3;
  }
  return value2;
}
function normalizeNumber(value2) {
  if (value2 === "" || value2 === null) {
    return VALUE_ERROR3;
  }
  if (typeof value2 === "number") {
    return Number.isFinite(value2) ? value2 : VALUE_ERROR3;
  }
  if (typeof value2 === "boolean") {
    return value2 ? 1 : 0;
  }
  if (typeof value2 === "string") {
    const parsed = Number(value2);
    return Number.isFinite(parsed) ? parsed : VALUE_ERROR3;
  }
  return VALUE_ERROR3;
}
function dateToExcelSerial2(date6) {
  return (date6.getTime() - EXCEL_EPOCH_MS4) / MS_PER_DAY4;
}
function excelSerialToDate(serial) {
  if (!Number.isFinite(serial)) {
    return null;
  }
  const millis = EXCEL_EPOCH_MS4 + serial * MS_PER_DAY4;
  return new Date(millis);
}
function parseDateLiteral(value2) {
  const trimmed = value2.trim();
  if (!trimmed) {
    return null;
  }
  const timestamp = Date.parse(trimmed);
  return Number.isNaN(timestamp) ? null : new Date(timestamp);
}
function isLeapYear2(year) {
  if (year % 4 !== 0) {
    return false;
  }
  if (year % 100 !== 0) {
    return true;
  }
  return year % 400 === 0;
}
function convertBondError(_) {
  return NUM_ERROR2;
}
function isErrorValue3(value2) {
  return typeof value2 === "object" && value2 !== null && value2.kind === "Error";
}
function isLambdaValue2(value2) {
  return typeof value2 === "object" && value2 !== null && value2.kind === "Lambda";
}
// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/information.js
function ISNA2(value2) {
  return ISNA(value2);
}
function ISERROR2(value2) {
  return ISERROR(value2);
}
function NA2() {
  return NA();
}
function TYPE2(value2) {
  const scalar = resolveScalarValue(value2);
  if (scalar === null) {
    return 1;
  }
  return TYPE(scalar);
}
function ISREF(value2) {
  throw new Error(`ISREF is not implemented. value=${String(value2)}`);
}
function ISERR2(value2) {
  return ISERR(value2);
}
function ISTEXT2(value2) {
  return ISTEXT(value2);
}
function ISNUMBER2(value2) {
  return ISNUMBER(value2);
}
function ISBLANK(value2) {
  return resolveScalarValue(value2) == null;
}
function N2(value2) {
  return N(value2);
}
function ISNONTEXT2(value2) {
  return ISNONTEXT(value2);
}
function ISLOGICAL2(value2) {
  return ISLOGICAL(value2);
}
function ERROR_TYPE(errorVal) {
  return ERROR.TYPE(errorVal);
}
function ISEVEN2(numberParam) {
  return ISEVEN(numberParam);
}
function ISODD2(numberParam) {
  return ISODD(numberParam);
}
function SHEET(value2) {
  throw new Error(`SHEET is not implemented. value=${String(value2)}`);
}
function SHEETS(reference) {
  throw new Error(`SHEETS is not implemented. reference=${String(reference)}`);
}
function ISFORMULA(reference) {
  throw new Error(`ISFORMULA is not implemented. reference=${String(reference)}`);
}
function ISOMITTED(argument) {
  throw new Error(`ISOMITTED is not implemented. argument=${String(argument)}`);
}
function resolveScalarValue(value2) {
  if (Array.isArray(value2)) {
    for (const row2 of value2) {
      if (!row2 || row2.length === 0) {
        continue;
      }
      return row2[0] ?? null;
    }
    return null;
  }
  return value2 ?? null;
}
// node_modules/@oai/granola/dist/models/spreadsheet/engine/function-context.js
var contextStack = [];
function pushEvaluationContext(ctx) {
  contextStack.push(ctx);
}
function popEvaluationContext(ctx) {
  if (contextStack.length === 0) {
    return;
  }
  const popped = contextStack.pop();
  if (popped && popped !== ctx) {
    contextStack.length = 0;
  }
}
function withEvaluationContext(ctx, fn) {
  pushEvaluationContext(ctx);
  try {
    return fn();
  } finally {
    popEvaluationContext(ctx);
  }
}
function getActiveEvaluationContext() {
  if (contextStack.length === 0) {
    return null;
  }
  return contextStack[contextStack.length - 1] ?? null;
}

// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/logical.js
function IF2(logicalTest, valueIfTrue, valueIfFalse) {
  return IF(logicalTest, valueIfTrue, valueIfFalse);
}
function TRUE2() {
  return TRUE();
}
function FALSE2() {
  return FALSE();
}
function AND2(logical1, logical2, ...rest2) {
  return AND(logical1, logical2, ...rest2);
}
function OR2(logical1, logical2, ...rest2) {
  return OR(logical1, logical2, ...rest2);
}
function NOT2(logical) {
  return NOT(logical);
}
function IFERROR(value2, valueIfError) {
  if (value2 === undefined || valueIfError === undefined) {
    return VALUE_ERROR4;
  }
  const scalarValue = coerceScalarArgument(value2);
  const errorCode = getErrorCode(scalarValue);
  if (errorCode) {
    return coerceScalarArgument(valueIfError) ?? null;
  }
  return scalarValue ?? null;
}
function XOR2(logical1, logical2, ...rest2) {
  return XOR(logical1, logical2, ...rest2);
}
function IFNA(value2, valueIfNa) {
  if (value2 === undefined || valueIfNa === undefined) {
    return VALUE_ERROR4;
  }
  const scalarValue = coerceScalarArgument(value2);
  const errorCode = getErrorCode(scalarValue);
  if (errorCode === "#N/A") {
    return coerceScalarArgument(valueIfNa) ?? null;
  }
  return scalarValue ?? null;
}
function IFS2(logicalTest, valueIfTrue, ...rest2) {
  const result = IFS(logicalTest, valueIfTrue, ...rest2);
  return unwrapSingleCell(result) ?? result;
}
function _XLFN_IFS(logicalTest, valueIfTrue, ...rest2) {
  return IFS2(logicalTest, valueIfTrue, ...rest2);
}
function SWITCH2(expression2, value1, result1, defaultOrValue2, result2, ...rest2) {
  return SWITCH(expression2, value1, result1, defaultOrValue2, result2, ...rest2);
}
function coerceScalarArgument(value2) {
  if (Array.isArray(value2)) {
    return value2[0]?.[0];
  }
  if (isArrayValue(value2)) {
    const arrayValue = value2;
    return arrayValue.values[0]?.[0] ?? null;
  }
  return value2;
}
function getErrorCode(value2) {
  if (value2 instanceof Error) {
    return value2.message || "#VALUE!";
  }
  if (isErrorValue4(value2)) {
    return value2.code;
  }
  return null;
}
function unwrapSingleCell(value2) {
  if (!Array.isArray(value2) || value2.length !== 1) {
    return;
  }
  const [row2] = value2;
  if (!Array.isArray(row2) || row2.length !== 1) {
    return;
  }
  return row2[0] ?? null;
}
function LET(name1, nameValue1, calculationOrName2, nameValue2, ...rest2) {
  throw new Error(`LET is not implemented. name1=${String(name1)}, nameValue1=${String(nameValue1)}, calculationOrName2=${String(calculationOrName2)}, nameValue2=${String(nameValue2)}, rest.length=${rest2.length}`);
}
function LAMBDA(parameterOrCalculation, ...rest2) {
  throw new Error(`LAMBDA is not implemented. parameterOrCalculation=${String(parameterOrCalculation)}, rest.length=${rest2.length}`);
}
function MAKEARRAY(rows, columns, functionParam) {
  throw new Error(`MAKEARRAY is not implemented. rows=${String(rows)}, columns=${String(columns)}, functionParam=${String(functionParam)}`);
}
function MAP(array3, lambdaOrArray2, ...rest2) {
  throw new Error(`MAP is not implemented. array=${String(array3)}, lambdaOrArray2=${String(lambdaOrArray2)}, rest.length=${rest2.length}`);
}
function REDUCE(initialValue, array3, functionParam) {
  throw new Error(`REDUCE is not implemented. initialValue=${String(initialValue)}, array=${String(array3)}, functionParam=${String(functionParam)}`);
}
function SCAN(initialValue, array3, functionParam) {
  throw new Error(`SCAN is not implemented. initialValue=${String(initialValue)}, array=${String(array3)}, functionParam=${String(functionParam)}`);
}
function BYROW(array3, functionParam) {
  const source = normalizeGridArgument(array3);
  if (isErrorValue4(source)) {
    return source;
  }
  const lambda = getLambdaFromArg(functionParam);
  if (isErrorValue4(lambda)) {
    return lambda;
  }
  const ctx = getActiveEvaluationContext();
  if (!ctx) {
    return VALUE_ERROR4;
  }
  if (source.length === 0) {
    return makeArrayValue([]);
  }
  const rows = [];
  for (const rowValues of source) {
    const lambdaInput = [rowValues];
    const result = lambda.invoke([lambdaInput], ctx);
    const scalar = coerceLambdaResult(result);
    if (isErrorValue4(scalar)) {
      return scalar;
    }
    rows.push([scalar]);
  }
  return makeArrayValue(rows);
}
function BYCOL(array3, functionParam) {
  const source = normalizeGridArgument(array3);
  if (isErrorValue4(source)) {
    return source;
  }
  const lambda = getLambdaFromArg(functionParam);
  if (isErrorValue4(lambda)) {
    return lambda;
  }
  const ctx = getActiveEvaluationContext();
  if (!ctx) {
    return VALUE_ERROR4;
  }
  if (source.length === 0) {
    return makeArrayValue([[]]);
  }
  const columnCount = source.reduce((max5, row2) => Math.max(max5, row2.length), 0);
  if (columnCount === 0) {
    return makeArrayValue([[]]);
  }
  const results = [];
  for (let col = 0;col < columnCount; col += 1) {
    const columnValues = source.map((row2) => col < row2.length ? row2[col] : null);
    const lambdaInput = columnValues.map((value2) => [value2]);
    const result = lambda.invoke([lambdaInput], ctx);
    const scalar = coerceLambdaResult(result);
    if (isErrorValue4(scalar)) {
      return scalar;
    }
    results.push(scalar);
  }
  return makeArrayValue([results]);
}
var VALUE_ERROR4 = { kind: "Error", code: "#VALUE!" };
function normalizeGridArgument(arg) {
  if (arg === undefined) {
    return VALUE_ERROR4;
  }
  if (Array.isArray(arg)) {
    return arg.map((row2) => (row2 ?? []).map((cell) => coerceScalarValue(cell ?? null)));
  }
  if (isArrayValue(arg)) {
    return cloneArrayValue(arg);
  }
  return [[coerceScalarValue(arg)]];
}
function cloneArrayValue(value2) {
  return value2.values.map((row2) => row2.map((cell) => coerceScalarValue(cell)));
}
function coerceScalarValue(value2) {
  if (value2 === undefined) {
    return null;
  }
  if (isArrayValue(value2)) {
    return VALUE_ERROR4;
  }
  if (isLambdaValue3(value2)) {
    return VALUE_ERROR4;
  }
  return value2;
}
function getLambdaFromArg(arg) {
  if (arg === undefined) {
    return VALUE_ERROR4;
  }
  const scalar = extractLambdaScalar(arg);
  if (scalar === undefined) {
    return VALUE_ERROR4;
  }
  if (isErrorValue4(scalar)) {
    return scalar;
  }
  if (isLambdaValue3(scalar)) {
    return scalar;
  }
  return VALUE_ERROR4;
}
function extractLambdaScalar(arg) {
  if (Array.isArray(arg)) {
    const firstRow = arg[0];
    if (!Array.isArray(firstRow) || firstRow.length === 0) {
      return;
    }
    return firstRow[0] ?? null;
  }
  if (isArrayValue(arg)) {
    const arrayValue = arg;
    return arrayValue.values[0]?.[0] ?? null;
  }
  if (arg === undefined) {
    return null;
  }
  return arg;
}
function coerceLambdaResult(result) {
  if (isErrorValue4(result)) {
    return result;
  }
  if (isArrayValue(result)) {
    if (result.rows === 0 || result.cols === 0) {
      return null;
    }
    if (result.rows !== 1 || result.cols !== 1) {
      return VALUE_ERROR4;
    }
    return coerceScalarValue(result.values[0]?.[0]);
  }
  return coerceScalarValue(result);
}
function isLambdaValue3(value2) {
  return typeof value2 === "object" && value2 !== null && value2.kind === "Lambda";
}
function isErrorValue4(value2) {
  return typeof value2 === "object" && value2 !== null && value2.kind === "Error";
}
// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/lookup-reference.js
var DEBUG_HLOOKUP_ERROR_COUNT = 0;
var DEBUG_CHOOSE_ERROR_COUNT = 0;
var VALUE_ERROR5 = { kind: "Error", code: "#VALUE!" };
var NA_ERROR2 = { kind: "Error", code: "#N/A" };
var CALC_ERROR = { kind: "Error", code: "#CALC!" };
var NUMBER_COMPARISON_EPSILON2 = 0.000000001;
function ROW2(reference) {
  const projected = resolveIndexFromMetadata(reference, (addr) => addr.row);
  if (projected !== null) {
    return projected;
  }
  return ROW(reference);
}
function COLUMN2(reference) {
  const projected = resolveIndexFromMetadata(reference, (addr) => addr.col + 1);
  if (projected !== null) {
    return projected;
  }
  return COLUMN(reference);
}
function LOOKUP2(lookupValue, lookupVector, resultVectorLookupValue, array3) {
  return LOOKUP(lookupValue, lookupVector, resultVectorLookupValue, array3);
}
function INDEX2(array3, rowNum, columnNumReference, rowNum2, columnNum, areaNum) {
  return INDEX(array3, rowNum, columnNumReference, rowNum2, columnNum, areaNum);
}
function MATCH2(lookupValue, lookupArray, matchType) {
  const normalizedLookup = normalizeLookupValue(lookupValue);
  if (matchType === undefined) {
    const exactResult = MATCH(normalizedLookup, lookupArray, 0);
    if (!isFormulajsNaError(exactResult)) {
      return exactResult;
    }
  }
  return MATCH(normalizedLookup, lookupArray, matchType);
}
function AREAS(reference) {
  throw new Error(`AREAS is not implemented. reference=${String(reference)}`);
}
function ROWS2(array3) {
  return ROWS(array3);
}
function COLUMNS2(array3) {
  return COLUMNS(array3);
}
function OFFSET(reference, rows, cols, height, width) {
  throw new Error(`OFFSET is not implemented. reference=${String(reference)}, rows=${String(rows)}, cols=${String(cols)}, height=${String(height)}, width=${String(width)}`);
}
function TRANSPOSE2(array3) {
  return TRANSPOSE(array3);
}
function UNIQUE2(array3, byCol, exactlyOnce) {
  const matrix = coerceArrayToMatrix(array3);
  if (!matrix) {
    return { kind: "Error", code: "#VALUE!" };
  }
  const byColumns = coerceBooleanFlag(byCol);
  const requireSingleOccurrence = coerceBooleanFlag(exactlyOnce);
  const result = byColumns ? uniqueColumns(matrix, requireSingleOccurrence) : uniqueRows(matrix, requireSingleOccurrence);
  if (result.length === 0) {
    return makeArrayValue([[null]]);
  }
  return makeArrayValue(result);
}
function CHOOSE2(indexNum, value1, value2, ...rest2) {
  const normalizedIndex = normalizeLookupValue(indexNum);
  const result = CHOOSE(normalizedIndex, value1, value2, ...rest2);
  const singleCell = extractSingleCellValue(result);
  if (singleCell !== undefined) {
    return singleCell;
  }
  if (result instanceof Error && DEBUG_CHOOSE_ERROR_COUNT < 5) {
    DEBUG_CHOOSE_ERROR_COUNT += 1;
  }
  return result;
}
function HLOOKUP2(lookupValue, tableArray, rowIndexNum, rangeLookup) {
  const result = HLOOKUP(normalizeLookupValue(lookupValue), tableArray, rowIndexNum, rangeLookup);
  if (result instanceof Error && DEBUG_HLOOKUP_ERROR_COUNT < 5) {
    DEBUG_HLOOKUP_ERROR_COUNT += 1;
  }
  return result;
}
function VLOOKUP2(lookupValue, tableArray, colIndexNum, rangeLookup) {
  const normalizedLookupValue = normalizeLookupValue(lookupValue);
  const exactMatch = isExactLookup(rangeLookup);
  const coercedTable = coerceTableArray(tableArray);
  const lookupForMatch = exactMatch && typeof normalizedLookupValue === "string" ? normalizedLookupValue.toLowerCase() : normalizedLookupValue;
  const tableForMatch = exactMatch ? normalizeVlookupTable(coercedTable) : coercedTable;
  return VLOOKUP(lookupForMatch, tableForMatch, colIndexNum, rangeLookup);
}
function normalizeLookupValue(value2) {
  if (Array.isArray(value2)) {
    return normalizeLookupScalar(value2[0]?.[0]);
  }
  return normalizeLookupScalar(value2);
}
function normalizeLookupScalar(value2) {
  if (value2 === undefined || value2 === null) {
    return value2;
  }
  if (typeof value2 !== "string") {
    return value2;
  }
  if (value2 === "") {
    return 0;
  }
  const trimmed = value2.trim();
  if (trimmed === "") {
    return value2;
  }
  const numeric = Number(value2);
  return Number.isNaN(numeric) ? value2 : numeric;
}
function coerceTableArray(arg) {
  if (Array.isArray(arg) || arg === undefined) {
    return arg;
  }
  const scalar = arg;
  if (isArrayValue(scalar)) {
    const arrayArg = scalar;
    return arrayArg.values.map((row2) => [...row2]);
  }
  return arg;
}
function isExactLookup(rangeLookup) {
  if (rangeLookup === undefined) {
    return false;
  }
  const scalar = Array.isArray(rangeLookup) ? extractSingleCellValue(rangeLookup) : rangeLookup;
  if (scalar === undefined || scalar === null) {
    return false;
  }
  if (typeof scalar === "boolean") {
    return scalar === false;
  }
  if (typeof scalar === "number") {
    if (!Number.isFinite(scalar)) {
      return false;
    }
    return scalar === 0;
  }
  if (typeof scalar === "string") {
    const normalized = scalar.trim().toLowerCase();
    if (normalized === "false" || normalized === "0") {
      return true;
    }
    return false;
  }
  return false;
}
function normalizeVlookupTable(table2) {
  if (Array.isArray(table2)) {
    return table2.map((row2) => normalizeVlookupRow(row2));
  }
  return table2;
}
function normalizeVlookupRow(row2) {
  if (!row2 || row2.length === 0) {
    return [];
  }
  const normalized = row2.map((cell) => cell ?? null);
  const normalizedFirst = normalizeLookupCaseScalar(row2[0]);
  normalized[0] = normalizedFirst ?? null;
  return normalized;
}
function normalizeLookupCaseScalar(value2) {
  if (typeof value2 === "string") {
    return value2.toLowerCase();
  }
  return value2;
}
function extractSingleCellValue(value2) {
  if (!Array.isArray(value2)) {
    return;
  }
  if (value2.length !== 1) {
    return;
  }
  const [row2] = value2;
  if (!Array.isArray(row2) || row2.length !== 1) {
    return;
  }
  return row2[0] ?? null;
}
function isFormulajsNaError(value2) {
  return value2 instanceof Error && value2.message === "#N/A";
}
function coerceArrayToMatrix(arg) {
  if (Array.isArray(arg)) {
    return arg.map((row2) => row2 ? [...row2] : []);
  }
  if (arg === undefined) {
    return null;
  }
  const scalar = arg;
  if (isArrayValue(scalar)) {
    return scalar.values.map((row2) => [...row2]);
  }
  return [[scalar]];
}
function coerceBooleanFlag(arg) {
  if (arg === undefined) {
    return false;
  }
  const scalar = Array.isArray(arg) ? arg[0]?.[0] : arg;
  if (scalar === undefined || scalar === null) {
    return false;
  }
  if (typeof scalar === "boolean") {
    return scalar;
  }
  if (typeof scalar === "number") {
    return scalar !== 0;
  }
  if (typeof scalar === "string") {
    const normalized = scalar.trim().toLowerCase();
    if (normalized === "true") {
      return true;
    }
    if (normalized === "false") {
      return false;
    }
    const parsed = Number(scalar);
    return Number.isFinite(parsed) ? parsed !== 0 : normalized === "y";
  }
  return false;
}
function uniqueRows(matrix, exactlyOnce) {
  const counts = new Map;
  const order = [];
  for (const row2 of matrix) {
    const normalized = [...row2];
    const key = serializeScalarArray(normalized);
    const existing = counts.get(key);
    if (existing) {
      existing.count += 1;
    } else {
      counts.set(key, { row: normalized, count: 1 });
      order.push(key);
    }
  }
  const result = [];
  for (const key of order) {
    const entry = counts.get(key);
    if (!entry) {
      continue;
    }
    if (exactlyOnce) {
      if (entry.count === 1) {
        result.push(entry.row);
      }
    } else {
      result.push(entry.row);
    }
  }
  if (result.length === 0 && matrix.length > 0) {
    return [[null]];
  }
  return result;
}
function uniqueColumns(matrix, exactlyOnce) {
  const columnCount = matrix.reduce((max5, row2) => Math.max(max5, row2.length), 0);
  if (columnCount === 0) {
    return [];
  }
  const counts = new Map;
  const order = [];
  for (let colIdx = 0;colIdx < columnCount; colIdx += 1) {
    const columnValues = [];
    for (let rowIdx = 0;rowIdx < matrix.length; rowIdx += 1) {
      columnValues.push(matrix[rowIdx]?.[colIdx] ?? null);
    }
    const key = serializeScalarArray(columnValues);
    const existing = counts.get(key);
    if (existing) {
      existing.count += 1;
    } else {
      counts.set(key, { column: columnValues, count: 1 });
      order.push(key);
    }
  }
  const uniqueColumnsList = [];
  for (const key of order) {
    const entry = counts.get(key);
    if (!entry) {
      continue;
    }
    if (exactlyOnce) {
      if (entry.count === 1) {
        uniqueColumnsList.push(entry.column);
      }
    } else {
      uniqueColumnsList.push(entry.column);
    }
  }
  if (uniqueColumnsList.length === 0) {
    return [[null]];
  }
  const rows = matrix.length;
  const result = [];
  for (let rowIdx = 0;rowIdx < rows; rowIdx += 1) {
    const row2 = [];
    for (const column2 of uniqueColumnsList) {
      row2.push(column2[rowIdx] ?? null);
    }
    result.push(row2);
  }
  return result;
}
function serializeScalarArray(values) {
  return values.map((value2) => serializeScalarValue(value2)).join("|#|");
}
function serializeScalarValue(value2) {
  if (value2 === null || value2 === undefined) {
    return "null";
  }
  if (typeof value2 === "number") {
    if (!Number.isFinite(value2)) {
      return `number:${value2}`;
    }
    return `number:${value2.toPrecision(15)}`;
  }
  if (typeof value2 === "string") {
    return `string:${value2}`;
  }
  if (typeof value2 === "boolean") {
    return `boolean:${value2 ? "true" : "false"}`;
  }
  if (value2 instanceof Date) {
    return `date:${value2.toISOString()}`;
  }
  if (isErrorValue(value2)) {
    return `error:${value2.code}`;
  }
  return JSON.stringify(value2);
}
function INDIRECT(refText, a1) {
  throw new Error(`INDIRECT is not implemented. refText=${String(refText)}, a1=${String(a1)}`);
}
function ADDRESS(rowNum, columnNum, absNum, a1, sheetText) {
  const parsedRow = parseAddressCoordinate(rowNum);
  if (isErrorValue(parsedRow)) {
    return parsedRow;
  }
  const parsedColumn = parseAddressCoordinate(columnNum);
  if (isErrorValue(parsedColumn)) {
    return parsedColumn;
  }
  const absSetting = parseAddressAbsNum(absNum);
  if (isErrorValue(absSetting)) {
    return absSetting;
  }
  let useA1Style = true;
  if (a1 !== undefined) {
    const styleFlag = parseBooleanFlag(a1);
    if (isErrorValue(styleFlag)) {
      return styleFlag;
    }
    useA1Style = styleFlag;
  }
  const sheetPrefixResult = formatSheetPrefix(sheetText);
  if (isErrorValue(sheetPrefixResult)) {
    return sheetPrefixResult;
  }
  const sheetPrefix = sheetPrefixResult;
  const zeroBasedColumn = parsedColumn - 1;
  if (zeroBasedColumn < 0) {
    return VALUE_ERROR5;
  }
  const columnLabelText = columnLabel(zeroBasedColumn);
  const columnAbsolute = absSetting === 1 || absSetting === 3;
  const rowAbsolute = absSetting === 1 || absSetting === 2;
  if (useA1Style) {
    const colToken2 = columnAbsolute ? `$${columnLabelText}` : columnLabelText;
    const rowToken2 = rowAbsolute ? `$${parsedRow}` : String(parsedRow);
    return `${sheetPrefix}${colToken2}${rowToken2}`;
  }
  const rowToken = rowAbsolute ? `R${parsedRow}` : `R[${parsedRow}]`;
  const colToken = columnAbsolute ? `C${parsedColumn}` : `C[${parsedColumn}]`;
  return `${sheetPrefix}${rowToken}${colToken}`;
}
function GETPIVOTDATA(dataField, pivotTable, field, item, ...rest2) {
  throw new Error(`GETPIVOTDATA is not implemented. dataField=${String(dataField)}, pivotTable=${String(pivotTable)}, field=${String(field)}, item=${String(item)}, rest.length=${rest2.length}`);
}
function HYPERLINK(linkLocation, friendlyName) {
  throw new Error(`HYPERLINK is not implemented. linkLocation=${String(linkLocation)}, friendlyName=${String(friendlyName)}`);
}
function FORMULATEXT(reference) {
  throw new Error(`FORMULATEXT is not implemented. reference=${String(reference)}`);
}
function FIELDVALUE(value2, fieldName) {
  throw new Error(`FIELDVALUE is not implemented. value=${String(value2)}, fieldName=${String(fieldName)}`);
}
function FILTER(array3, include, ifEmpty) {
  const source = normalizeGridArgument2(array3);
  const includeVector = flattenGridArgument(include);
  if (includeVector === null) {
    return { kind: "Error", code: "#VALUE!" };
  }
  const results = [];
  for (let row2 = 0;row2 < source.length; row2 += 1) {
    const gate = includeVector.length > 1 ? includeVector[row2] ?? includeVector[includeVector.length - 1] : includeVector[0] ?? 0;
    const decision = coerceIncludeDecision(gate ?? null);
    if (isErrorValue(decision)) {
      return decision;
    }
    if (decision) {
      const rowValues = source[row2] ?? [];
      results.push([...rowValues]);
    }
  }
  if (results.length === 0) {
    if (ifEmpty !== undefined) {
      return toScalarValue(ifEmpty);
    }
    return { kind: "Error", code: "#CALC!" };
  }
  return makeArrayValue(results);
}
function normalizeGridArgument2(arg) {
  if (arg === undefined) {
    return [];
  }
  if (isArrayValue(arg)) {
    return cloneArrayValue2(arg);
  }
  if (Array.isArray(arg)) {
    return arg;
  }
  return [[coerceScalarValue2(arg)]];
}
function flattenGridArgument(arg) {
  if (arg === undefined) {
    return [];
  }
  if (isArrayValue(arg)) {
    const flattened = [];
    for (const row2 of arg.values) {
      for (const cell of row2) {
        flattened.push(coerceScalarValue2(cell));
      }
    }
    return flattened;
  }
  if (Array.isArray(arg)) {
    const flattened = [];
    for (const row2 of arg) {
      if (Array.isArray(row2)) {
        for (const cell of row2) {
          flattened.push(cell ?? null);
        }
      } else {
        flattened.push(row2 ?? null);
      }
    }
    return flattened;
  }
  return [arg ?? null];
}
function coerceIncludeDecision(value2) {
  if (isErrorValue(value2)) {
    return value2;
  }
  if (value2 === null) {
    return false;
  }
  if (typeof value2 === "boolean") {
    return value2;
  }
  if (typeof value2 === "number") {
    return value2 !== 0 && !Number.isNaN(value2);
  }
  if (typeof value2 === "string") {
    const trimmed = value2.trim();
    if (trimmed === "") {
      return false;
    }
    const numeric = Number(trimmed);
    if (!Number.isNaN(numeric)) {
      return numeric !== 0;
    }
    return true;
  }
  if (value2 instanceof Error) {
    return { kind: "Error", code: value2.message ?? "#VALUE!" };
  }
  return false;
}
function toScalarValue(arg) {
  if (Array.isArray(arg)) {
    return arg[0]?.[0] ?? null;
  }
  return arg ?? null;
}
function compareSortValues(left, right) {
  if (isErrorValue(left)) {
    return isErrorValue(right) ? 0 : -1;
  }
  if (isErrorValue(right)) {
    return 1;
  }
  const leftBlank = isBlankSortValue(left);
  const rightBlank = isBlankSortValue(right);
  if (leftBlank || rightBlank) {
    if (leftBlank && rightBlank) {
      return 0;
    }
    return leftBlank ? 1 : -1;
  }
  const leftNum = coerceSortNumber(left);
  const rightNum = coerceSortNumber(right);
  if (leftNum !== null && rightNum !== null) {
    if (leftNum < rightNum)
      return -1;
    if (leftNum > rightNum)
      return 1;
    return 0;
  }
  const leftText = coerceSortText(left);
  const rightText = coerceSortText(right);
  return leftText.localeCompare(rightText);
}
function normalizeSingleVector(arg) {
  const grid2 = normalizeGridArgument2(arg);
  if (grid2.length === 0) {
    return [];
  }
  if (grid2.length === 1) {
    return grid2[0]?.map(coerceScalarValue2) ?? [];
  }
  const isColumn = grid2.every((row2) => row2.length <= 1);
  if (!isColumn) {
    return VALUE_ERROR5;
  }
  return grid2.map((row2) => coerceScalarValue2(row2[0]));
}
function coerceSortNumber(value2) {
  if (value2 === null || value2 === undefined) {
    return null;
  }
  if (typeof value2 === "number") {
    return value2;
  }
  if (typeof value2 === "boolean") {
    return value2 ? 1 : 0;
  }
  if (typeof value2 === "string") {
    const trimmed = value2.trim();
    if (trimmed === "") {
      return null;
    }
    const num3 = Number(trimmed);
    return Number.isNaN(num3) ? null : num3;
  }
  return null;
}
function isBlankSortValue(value2) {
  if (value2 === null || value2 === undefined) {
    return true;
  }
  if (typeof value2 === "string") {
    return value2.trim() === "";
  }
  return false;
}
function coerceSortText(value2) {
  if (value2 === null || value2 === undefined) {
    return "";
  }
  if (typeof value2 === "string") {
    return value2;
  }
  if (typeof value2 === "boolean") {
    return value2 ? "TRUE" : "FALSE";
  }
  if (typeof value2 === "number") {
    return String(value2);
  }
  if (isErrorValue(value2)) {
    return value2.code;
  }
  return String(value2);
}
function textComparison(left, right) {
  const leftText = coerceSortText(left).toUpperCase();
  const rightText = coerceSortText(right).toUpperCase();
  if (leftText === rightText) {
    return 0;
  }
  return leftText < rightText ? -1 : 1;
}
function extractLookupVector(arg) {
  const grid2 = normalizeGridArgument2(arg);
  if (grid2.length === 0) {
    return VALUE_ERROR5;
  }
  if (grid2.length === 1) {
    const [row2 = []] = grid2;
    const values2 = row2.map((cell) => coerceLookupCandidate(cell));
    return { orientation: "row", values: values2 };
  }
  const isColumn = grid2.every((row2) => row2.length <= 1);
  if (!isColumn) {
    return VALUE_ERROR5;
  }
  const values = grid2.map((row2) => coerceLookupCandidate(row2[0]));
  return { orientation: "column", values };
}
function buildSortByPlan(rowCount, columnCount, firstByArray, firstSortOrder, rest2) {
  const instructions = [];
  const firstInstruction = buildSortInstruction(firstByArray, firstSortOrder, rowCount, columnCount);
  if (isErrorValue(firstInstruction)) {
    return firstInstruction;
  }
  instructions.push(firstInstruction);
  const orientation = firstInstruction.orientation;
  for (let idx = 0;idx < rest2.length; idx += 2) {
    const candidateByArray = rest2[idx];
    if (candidateByArray === undefined) {
      return VALUE_ERROR5;
    }
    const candidateOrder = rest2[idx + 1];
    const nextInstruction = buildSortInstruction(candidateByArray, candidateOrder, rowCount, columnCount);
    if (isErrorValue(nextInstruction)) {
      return nextInstruction;
    }
    if (nextInstruction.orientation !== orientation) {
      return VALUE_ERROR5;
    }
    instructions.push(nextInstruction);
  }
  return { orientation, instructions };
}
function buildSortInstruction(byArray, sortOrder, rowCount, columnCount) {
  const vector = extractLookupVector(byArray);
  if (isErrorValue(vector)) {
    return vector;
  }
  if (vector.orientation === "column") {
    if (vector.values.length !== rowCount) {
      return VALUE_ERROR5;
    }
  } else if (vector.values.length !== columnCount) {
    return VALUE_ERROR5;
  }
  const direction = parseSortDirection(sortOrder);
  if (isErrorValue(direction)) {
    return direction;
  }
  return {
    orientation: vector.orientation,
    values: vector.values,
    direction
  };
}
function parseSortDirection(arg) {
  if (arg === undefined) {
    return 1;
  }
  const scalar = coerceScalarValue2(extractScalarFromArg(arg));
  if (isErrorValue(scalar)) {
    return scalar;
  }
  const numeric = Number(scalar);
  if (Number.isNaN(numeric)) {
    return 1;
  }
  return numeric < 0 ? -1 : 1;
}
function getMaxColumnCount(grid2) {
  return grid2.reduce((max5, row2) => Math.max(max5, row2.length), 0);
}
function parseDropCount(arg, limit) {
  if (arg === undefined) {
    return 0;
  }
  if (limit <= 0) {
    return VALUE_ERROR5;
  }
  const scalar = coerceScalarValue2(extractScalarFromArg(arg));
  if (isErrorValue(scalar)) {
    return scalar;
  }
  const numeric = Number(scalar);
  if (!Number.isFinite(numeric)) {
    return VALUE_ERROR5;
  }
  const integerCount = Math.trunc(numeric);
  if (Math.abs(integerCount) > limit) {
    return VALUE_ERROR5;
  }
  return integerCount;
}
function parseTakeCount(arg, limit) {
  if (limit <= 0) {
    return VALUE_ERROR5;
  }
  const scalar = coerceScalarValue2(extractScalarFromArg(arg));
  if (isErrorValue(scalar)) {
    return scalar;
  }
  const numeric = Number(scalar);
  if (!Number.isFinite(numeric)) {
    return VALUE_ERROR5;
  }
  const integerCount = Math.trunc(numeric);
  if (integerCount === 0) {
    return VALUE_ERROR5;
  }
  if (Math.abs(integerCount) > limit) {
    return VALUE_ERROR5;
  }
  return integerCount;
}
function buildTakeIndexes(count3, size2) {
  if (size2 <= 0) {
    return VALUE_ERROR5;
  }
  const windowSize = Math.abs(count3);
  if (windowSize > size2) {
    return VALUE_ERROR5;
  }
  const indexes = [];
  if (count3 > 0) {
    for (let idx = 0;idx < windowSize; idx += 1) {
      indexes.push(idx);
    }
    return indexes;
  }
  for (let idx = size2 - windowSize;idx < size2; idx += 1) {
    indexes.push(idx);
  }
  return indexes;
}
function buildDropIndexes(count3, size2) {
  if (size2 <= 0) {
    return VALUE_ERROR5;
  }
  const drop = Math.abs(count3);
  if (drop >= size2) {
    return count3 === 0 ? buildAscendingIndexes(size2) : CALC_ERROR;
  }
  const start = count3 >= 0 ? drop : 0;
  const endExclusive = count3 >= 0 ? size2 : size2 - drop;
  const indexes = [];
  for (let idx = start;idx < endExclusive; idx += 1) {
    indexes.push(idx);
  }
  return indexes;
}
function parseChooseIndex(arg, size2) {
  const scalar = coerceScalarValue2(extractScalarFromArg(arg));
  if (isErrorValue(scalar)) {
    return scalar;
  }
  const numeric = Number(scalar);
  if (!Number.isFinite(numeric)) {
    return VALUE_ERROR5;
  }
  const integer2 = Math.trunc(numeric);
  if (integer2 === 0) {
    return VALUE_ERROR5;
  }
  const zeroBased = integer2 > 0 ? integer2 - 1 : size2 + integer2;
  if (zeroBased < 0 || zeroBased >= size2) {
    return VALUE_ERROR5;
  }
  return zeroBased;
}
function parseExpandDimension(arg, currentSize) {
  if (arg === undefined) {
    return currentSize;
  }
  const scalar = coerceScalarValue2(extractScalarFromArg(arg));
  if (isErrorValue(scalar)) {
    return scalar;
  }
  if (scalar === null) {
    return currentSize;
  }
  const numeric = Number(scalar);
  if (!Number.isFinite(numeric)) {
    return VALUE_ERROR5;
  }
  const target = Math.trunc(numeric);
  if (target < currentSize || target < 0) {
    return VALUE_ERROR5;
  }
  return target;
}
function parseWrapCount(arg) {
  const scalar = coerceScalarValue2(extractScalarFromArg(arg));
  if (isErrorValue(scalar)) {
    return scalar;
  }
  const numeric = Number(scalar);
  if (!Number.isFinite(numeric)) {
    return VALUE_ERROR5;
  }
  const count3 = Math.trunc(numeric);
  if (count3 <= 0) {
    return VALUE_ERROR5;
  }
  return count3;
}
function parseIgnorePredicate(arg) {
  if (arg === undefined) {
    return () => false;
  }
  const scalar = coerceScalarValue2(extractScalarFromArg(arg));
  if (isErrorValue(scalar)) {
    return scalar;
  }
  if (typeof scalar === "string") {
    switch (scalar.trim().toUpperCase()) {
      case "NUMBERS":
        return (value2) => typeof value2 === "number";
      case "TEXT":
        return (value2) => typeof value2 === "string";
      case "LOGICAL":
        return (value2) => typeof value2 === "boolean";
      case "BLANKS":
        return (value2) => value2 === null || value2 === "";
      case "ERRORS":
        return (value2) => isErrorValue(value2);
      default:
        break;
    }
  }
  if (typeof scalar === "number") {
    return () => scalar === 0;
  }
  if (typeof scalar === "boolean") {
    return () => scalar;
  }
  return () => false;
}
function parseBooleanFlag(arg) {
  if (arg === undefined) {
    return false;
  }
  const scalar = coerceScalarValue2(extractScalarFromArg(arg));
  if (isErrorValue(scalar)) {
    return scalar;
  }
  if (typeof scalar === "boolean") {
    return scalar;
  }
  if (typeof scalar === "number") {
    return scalar !== 0;
  }
  if (typeof scalar === "string") {
    const normalized = scalar.trim().toUpperCase();
    if (normalized === "TRUE") {
      return true;
    }
    if (normalized === "FALSE") {
      return false;
    }
    const numeric = Number(scalar);
    if (!Number.isNaN(numeric)) {
      return numeric !== 0;
    }
  }
  if (scalar === null) {
    return false;
  }
  return VALUE_ERROR5;
}
function parseAddressCoordinate(arg) {
  const scalar = coerceScalarValue2(extractScalarFromArg(arg));
  if (isErrorValue(scalar)) {
    return scalar;
  }
  if (scalar === null) {
    return VALUE_ERROR5;
  }
  let numeric;
  if (typeof scalar === "number") {
    numeric = scalar;
  } else if (typeof scalar === "string") {
    const trimmed = scalar.trim();
    if (!trimmed) {
      return VALUE_ERROR5;
    }
    numeric = Number(trimmed);
  } else if (typeof scalar === "boolean") {
    numeric = scalar ? 1 : 0;
  } else {
    return VALUE_ERROR5;
  }
  if (!Number.isFinite(numeric)) {
    return VALUE_ERROR5;
  }
  const truncated = Math.trunc(numeric);
  if (truncated < 1) {
    return VALUE_ERROR5;
  }
  return truncated;
}
function parseAddressAbsNum(arg) {
  if (arg === undefined) {
    return 1;
  }
  const scalar = coerceScalarValue2(extractScalarFromArg(arg));
  if (isErrorValue(scalar)) {
    return scalar;
  }
  if (scalar === null) {
    return VALUE_ERROR5;
  }
  let numeric;
  if (typeof scalar === "number") {
    numeric = scalar;
  } else if (typeof scalar === "string") {
    const trimmed = scalar.trim();
    if (!trimmed) {
      return VALUE_ERROR5;
    }
    numeric = Number(trimmed);
  } else if (typeof scalar === "boolean") {
    numeric = scalar ? 1 : 0;
  } else {
    return VALUE_ERROR5;
  }
  if (!Number.isFinite(numeric)) {
    return VALUE_ERROR5;
  }
  const truncated = Math.trunc(numeric);
  if (truncated < 1 || truncated > 4) {
    return VALUE_ERROR5;
  }
  return truncated;
}
function formatSheetPrefix(arg) {
  if (arg === undefined) {
    return "";
  }
  const scalar = coerceScalarValue2(extractScalarFromArg(arg));
  if (isErrorValue(scalar)) {
    return scalar;
  }
  if (scalar === null) {
    return "";
  }
  const text2 = String(scalar);
  if (!text2) {
    return "";
  }
  const escaped = text2.replace(/'/g, "''");
  if (/[^A-Za-z0-9_]/.test(text2)) {
    return `'${escaped}'!`;
  }
  return `${escaped}!`;
}
function resolveIndexFromMetadata(reference, projector) {
  const projectFromActiveCell = () => {
    const ctx = getActiveEvaluationContext();
    const activeAddress = ctx?.activeCellAddress;
    if (!activeAddress) {
      return null;
    }
    return projector(activeAddress);
  };
  if (reference === undefined) {
    return projectFromActiveCell();
  }
  const matrix = normalizeReferenceMatrix(reference);
  if (!matrix) {
    return projectFromActiveCell();
  }
  const metadata = getRangeMetadata(matrix);
  if (!metadata) {
    return projectFromActiveCell();
  }
  const rows = metadata.map((metaRow) => (metaRow ?? []).map((addr) => {
    if (!addr) {
      return VALUE_ERROR5;
    }
    return projector(addr);
  }));
  if (rows.length === 1 && rows[0]?.length === 1) {
    return rows[0][0] ?? VALUE_ERROR5;
  }
  return makeArrayValue(rows);
}
function normalizeReferenceMatrix(reference) {
  if (Array.isArray(reference)) {
    return reference;
  }
  if (reference === undefined) {
    return null;
  }
  const scalarArg = reference;
  if (isArrayValue(scalarArg)) {
    const source = scalarArg.values;
    const cloned = source.map((row2) => row2 ? [...row2] : []);
    copyRangeMetadata(source, cloned);
    return cloned;
  }
  return [[scalarArg]];
}
function compareSortedIndexes(left, right, instructions) {
  for (const instruction of instructions) {
    const leftValue = instruction.values[left] ?? null;
    const rightValue = instruction.values[right] ?? null;
    const comparison = compareSortValues(leftValue, rightValue);
    if (comparison !== 0) {
      return comparison * instruction.direction;
    }
  }
  return 0;
}
function parseXlookupMatchMode(arg) {
  if (arg === undefined) {
    return 0;
  }
  const scalar = coerceScalarValue2(extractScalarFromArg(arg));
  if (isErrorValue(scalar)) {
    return scalar;
  }
  if (typeof scalar === "number" && (scalar === 0 || scalar === 2)) {
    return scalar;
  }
  if (typeof scalar === "string") {
    const numeric = Number(scalar);
    if (!Number.isNaN(numeric) && (numeric === 0 || numeric === 2)) {
      return numeric;
    }
  }
  return VALUE_ERROR5;
}
function parseSearchMode(arg) {
  if (arg === undefined) {
    return 1;
  }
  const scalar = coerceScalarValue2(extractScalarFromArg(arg));
  if (isErrorValue(scalar)) {
    return scalar;
  }
  if (typeof scalar === "number" && (scalar === 1 || scalar === -1)) {
    return scalar;
  }
  if (typeof scalar === "string") {
    const numeric = Number(scalar);
    if (!Number.isNaN(numeric) && (numeric === 1 || numeric === -1)) {
      return numeric;
    }
  }
  return VALUE_ERROR5;
}
function buildAscendingIndexes(length2) {
  return Array.from({ length: length2 }, (_value, index) => index);
}
function buildDescendingIndexes(length2) {
  const indexes = [];
  for (let idx = length2 - 1;idx >= 0; idx -= 1) {
    indexes.push(idx);
  }
  return indexes;
}
function matchCandidate(target, candidate, mode) {
  if (isErrorValue(target)) {
    return target;
  }
  if (isErrorValue(candidate)) {
    return false;
  }
  if (mode === 2) {
    const pattern = coerceSortText(target);
    const subject = coerceSortText(candidate);
    return wildcardMatch(subject, pattern);
  }
  const diff = numericComparison(target, candidate);
  if (diff === null) {
    return textComparison(target, candidate) === 0;
  }
  return diff === 0;
}
function numericComparison(left, right) {
  const leftNum = coerceToNumber(left);
  const rightNum = coerceToNumber(right);
  if (leftNum === null || rightNum === null) {
    return null;
  }
  const delta = leftNum - rightNum;
  if (Math.abs(delta) <= NUMBER_COMPARISON_EPSILON2) {
    return 0;
  }
  return delta < 0 ? -1 : 1;
}
function coerceToNumber(value2) {
  if (typeof value2 === "number") {
    return value2;
  }
  if (typeof value2 === "boolean") {
    return value2 ? 1 : 0;
  }
  if (typeof value2 === "string") {
    const trimmed = value2.trim();
    if (trimmed === "") {
      return 0;
    }
    const parsed = Number(trimmed);
    return Number.isNaN(parsed) ? null : parsed;
  }
  if (value2 === null || value2 === undefined) {
    return 0;
  }
  return null;
}
function wildcardMatch(text2, pattern) {
  const regex = buildWildcardRegex(pattern);
  return regex.test(text2);
}
function buildWildcardRegex(pattern) {
  let result = "";
  for (let idx = 0;idx < pattern.length; idx += 1) {
    const char = pattern[idx];
    if (char === "~" && idx + 1 < pattern.length) {
      result += escapeRegExp(pattern[idx + 1]);
      idx += 1;
      continue;
    }
    if (char === "*") {
      result += ".*";
      continue;
    }
    if (char === "?") {
      result += ".";
      continue;
    }
    result += escapeRegExp(char);
  }
  return new RegExp(`^${result}$`, "i");
}
function escapeRegExp(value2) {
  return value2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function buildXlookupResult(grid2, orientation, index) {
  if (orientation === "column") {
    const row2 = grid2[index] ?? [];
    const normalizedRow = row2.map((cell) => coerceScalarValue2(cell));
    return normalizedRow.length <= 1 ? normalizedRow[0] ?? null : makeArrayValue([normalizedRow]);
  }
  const columnValues = grid2.map((row2) => row2.length > index ? coerceScalarValue2(row2[index]) : null);
  return columnValues.length <= 1 ? columnValues[0] ?? null : makeArrayValue(columnValues.map((value2) => [value2 ?? null]));
}
function buildIfNotFoundValue(arg) {
  if (arg === undefined) {
    return NA_ERROR2;
  }
  if (isArrayValue(arg)) {
    return makeArrayValue(cloneArrayValue2(arg));
  }
  if (Array.isArray(arg)) {
    return makeArrayValue(arg.map((row2) => row2.map((cell) => coerceScalarValue2(cell))));
  }
  return arg ?? null;
}
function cloneArrayValue2(value2) {
  return value2.values.map((row2) => row2.map((cell) => coerceScalarValue2(cell)));
}
function extractScalarFromArg(arg) {
  if (Array.isArray(arg)) {
    const firstRow = arg[0];
    if (Array.isArray(firstRow)) {
      return coerceScalarValue2(firstRow[0]);
    }
    return coerceScalarValue2(firstRow ?? null);
  }
  if (isArrayValue(arg)) {
    const arrayValue = arg;
    return coerceScalarValue2(arrayValue.values[0]?.[0]);
  }
  return coerceScalarValue2(arg);
}
function coerceScalarValue2(value2) {
  if (value2 === undefined) {
    return null;
  }
  if (value2 instanceof Error) {
    return { kind: "Error", code: value2.message ?? "#VALUE!" };
  }
  if (isArrayValue(value2)) {
    return VALUE_ERROR5;
  }
  if (isLambdaValue4(value2)) {
    return VALUE_ERROR5;
  }
  return value2 ?? null;
}
function coerceLookupCandidate(value2) {
  const scalar = coerceScalarValue2(value2);
  if (typeof scalar !== "string") {
    return scalar;
  }
  const normalized = scalar.replace(/\u00A0/g, " ").trim();
  if (normalized === "") {
    return "";
  }
  if (normalized.endsWith("%")) {
    const numericPortion = normalized.slice(0, -1);
    const parsedPercent = Number(numericPortion);
    if (!Number.isNaN(parsedPercent)) {
      return parsedPercent / 100;
    }
  }
  const numeric = Number(normalized);
  if (!Number.isNaN(numeric)) {
    return numeric;
  }
  return scalar;
}
function isLambdaValue4(value2) {
  return typeof value2 === "object" && value2 !== null && value2.kind === "Lambda";
}
function SORT(array3, sortIndex, sortOrder, byCol) {
  const source = normalizeGridArgument2(array3);
  if (source.length === 0) {
    return makeArrayValue([]);
  }
  const sortIndexValue = sortIndex ? Number(toScalarValue(sortIndex)) : 1;
  const targetIndex = Number.isFinite(sortIndexValue) ? Math.max(1, sortIndexValue) - 1 : 0;
  const sortOrderValue = sortOrder ? Number(toScalarValue(sortOrder)) : 1;
  const direction = sortOrderValue < 0 ? -1 : 1;
  const byColumn = byCol ? Boolean(toScalarValue(byCol)) : false;
  if (byColumn) {
    return { kind: "Error", code: "#VALUE!" };
  }
  const sorted = [...source].sort((left, right) => {
    const leftValue = left[targetIndex] ?? null;
    const rightValue = right[targetIndex] ?? null;
    return compareSortValues(leftValue, rightValue) * direction;
  });
  return makeArrayValue(sorted);
}
function XMATCH(lookupValue, lookupArray, matchMode, searchMode) {
  const candidates = normalizeSingleVector(lookupArray);
  if (isErrorValue(candidates)) {
    return candidates;
  }
  const target = coerceScalarValue2(extractScalarFromArg(lookupValue));
  if (isErrorValue(target)) {
    return target;
  }
  const parsedMatchMode = parseXlookupMatchMode(matchMode);
  if (isErrorValue(parsedMatchMode)) {
    return parsedMatchMode;
  }
  const parsedSearchMode = parseSearchMode(searchMode);
  if (isErrorValue(parsedSearchMode)) {
    return parsedSearchMode;
  }
  const indexes = parsedSearchMode === -1 ? buildDescendingIndexes(candidates.length) : buildAscendingIndexes(candidates.length);
  for (const idx of indexes) {
    const candidate = candidates[idx];
    const comparison = matchCandidate(target, candidate, parsedMatchMode);
    if (isErrorValue(comparison)) {
      return comparison;
    }
    if (comparison) {
      return idx + 1;
    }
  }
  return NA_ERROR2;
}
function XLOOKUP(lookupValue, lookupArray, returnArray, ifNotFound, matchMode, searchMode) {
  const lookupVector = extractLookupVector(lookupArray);
  if (isErrorValue(lookupVector)) {
    return lookupVector;
  }
  if (lookupVector.values.length === 0) {
    return VALUE_ERROR5;
  }
  const normalizedReturnGrid = normalizeGridArgument2(returnArray);
  if (normalizedReturnGrid.length === 0) {
    return VALUE_ERROR5;
  }
  const normalizedLookupValue = normalizeLookupValue(lookupValue);
  const targetValue = coerceScalarValue2(extractScalarFromArg(normalizedLookupValue));
  if (isErrorValue(targetValue)) {
    return targetValue;
  }
  const parsedMatchMode = parseXlookupMatchMode(matchMode);
  if (isErrorValue(parsedMatchMode)) {
    return parsedMatchMode;
  }
  const parsedSearchMode = parseSearchMode(searchMode);
  if (isErrorValue(parsedSearchMode)) {
    return parsedSearchMode;
  }
  const indexes = parsedSearchMode === -1 ? buildDescendingIndexes(lookupVector.values.length) : buildAscendingIndexes(lookupVector.values.length);
  for (const idx of indexes) {
    const candidate = coerceScalarValue2(lookupVector.values[idx]);
    const matchResult = matchCandidate(targetValue, candidate, parsedMatchMode);
    if (isErrorValue(matchResult)) {
      return matchResult;
    }
    if (matchResult) {
      return buildXlookupResult(normalizedReturnGrid, lookupVector.orientation, idx);
    }
  }
  return buildIfNotFoundValue(ifNotFound);
}
function SORTBY(array3, byArray, sortOrder, ...rest2) {
  const source = normalizeGridArgument2(array3);
  if (source.length === 0) {
    return makeArrayValue([]);
  }
  if (byArray === undefined) {
    return VALUE_ERROR5;
  }
  const columnCount = getMaxColumnCount(source);
  const plan = buildSortByPlan(source.length, columnCount, byArray, sortOrder, rest2);
  if (isErrorValue(plan)) {
    return plan;
  }
  if (plan.orientation === "column") {
    const rowIndexes = buildAscendingIndexes(source.length);
    rowIndexes.sort((left, right) => compareSortedIndexes(left, right, plan.instructions));
    const sortedRows = rowIndexes.map((rowIndex2) => {
      const row2 = source[rowIndex2] ?? [];
      return row2.map((cell) => coerceScalarValue2(cell));
    });
    return makeArrayValue(sortedRows);
  }
  const columnIndexes = buildAscendingIndexes(columnCount);
  columnIndexes.sort((left, right) => compareSortedIndexes(left, right, plan.instructions));
  const sortedColumns = source.map((row2) => columnIndexes.map((columnIndex2) => coerceScalarValue2(row2[columnIndex2] ?? null)));
  return makeArrayValue(sortedColumns);
}
function WRAPROWS(vector, wrapCount, padWith) {
  const values = flattenGridArgument(vector);
  if (values === null) {
    return VALUE_ERROR5;
  }
  const width = parseWrapCount(wrapCount);
  if (isErrorValue(width)) {
    return width;
  }
  const padValue = padWith === undefined ? NA_ERROR2 : coerceScalarValue2(extractScalarFromArg(padWith));
  if (padWith !== undefined && isErrorValue(padValue)) {
    return padValue;
  }
  if (width === 0) {
    return VALUE_ERROR5;
  }
  if (values.length === 0) {
    return makeArrayValue([]);
  }
  const rowCount = Math.ceil(values.length / width);
  const result = [];
  let index = 0;
  for (let row2 = 0;row2 < rowCount; row2 += 1) {
    const rowValues = [];
    for (let col = 0;col < width; col += 1) {
      if (index < values.length) {
        rowValues.push(coerceScalarValue2(values[index]));
        index += 1;
      } else {
        rowValues.push(padValue);
      }
    }
    result.push(rowValues);
  }
  return makeArrayValue(result);
}
function VSTACK(array1, array22, ...rest2) {
  const inputs = [array1, array22, ...rest2].filter((arg) => arg !== undefined);
  if (inputs.length === 0) {
    return VALUE_ERROR5;
  }
  const grids = inputs.map((arg) => normalizeGridArgument2(arg));
  const maxCols = grids.reduce((max5, grid2) => Math.max(max5, getMaxColumnCount(grid2)), 0);
  const stacked = [];
  for (const grid2 of grids) {
    for (const row2 of grid2) {
      const normalizedRow = [];
      for (let col = 0;col < maxCols; col += 1) {
        normalizedRow.push(coerceScalarValue2(row2[col] ?? null));
      }
      stacked.push(normalizedRow);
    }
  }
  return makeArrayValue(stacked);
}
function HSTACK(array1, array22, ...rest2) {
  const inputs = [array1, array22, ...rest2].filter((arg) => arg !== undefined);
  if (inputs.length === 0) {
    return VALUE_ERROR5;
  }
  const grids = inputs.map((arg) => normalizeGridArgument2(arg));
  const maxRows = grids.reduce((max5, grid2) => Math.max(max5, grid2.length), 0);
  if (maxRows === 0) {
    return makeArrayValue([]);
  }
  const stacked = Array.from({ length: maxRows }, () => []);
  for (const grid2 of grids) {
    const columnCount = getMaxColumnCount(grid2);
    for (let row2 = 0;row2 < maxRows; row2 += 1) {
      const sourceRow = row2 < grid2.length ? grid2[row2] : [];
      const targetRow = stacked[row2];
      for (let col = 0;col < columnCount; col += 1) {
        targetRow.push(coerceScalarValue2(sourceRow[col] ?? null));
      }
    }
  }
  return makeArrayValue(stacked);
}
function CHOOSEROWS(array3, rowNum1, rowNum2, ...rest2) {
  const source = normalizeGridArgument2(array3);
  if (source.length === 0) {
    return VALUE_ERROR5;
  }
  const selectors = [rowNum1, rowNum2, ...rest2].filter((selector) => selector !== undefined);
  if (selectors.length === 0) {
    return VALUE_ERROR5;
  }
  const selectedRows = [];
  for (const selector of selectors) {
    const rowIndex2 = parseChooseIndex(selector, source.length);
    if (isErrorValue(rowIndex2)) {
      return rowIndex2;
    }
    const row2 = source[rowIndex2] ?? [];
    selectedRows.push(row2.map((cell) => coerceScalarValue2(cell)));
  }
  return makeArrayValue(selectedRows);
}
function CHOOSECOLS(array3, colNum1, colNum2, ...rest2) {
  const source = normalizeGridArgument2(array3);
  if (source.length === 0) {
    return VALUE_ERROR5;
  }
  const columnCount = getMaxColumnCount(source);
  if (columnCount === 0) {
    return VALUE_ERROR5;
  }
  const selectors = [colNum1, colNum2, ...rest2].filter((selector) => selector !== undefined);
  if (selectors.length === 0) {
    return VALUE_ERROR5;
  }
  const selectedColumns = [];
  for (const selector of selectors) {
    const columnIndex2 = parseChooseIndex(selector, columnCount);
    if (isErrorValue(columnIndex2)) {
      return columnIndex2;
    }
    selectedColumns.push(columnIndex2);
  }
  const result = source.map((row2) => selectedColumns.map((columnIndex2) => coerceScalarValue2(row2[columnIndex2] ?? null)));
  return makeArrayValue(result);
}
function TOCOL(array3, ignore, scanByColumn) {
  const source = normalizeGridArgument2(array3);
  if (source.length === 0) {
    return makeArrayValue([]);
  }
  const predicate = parseIgnorePredicate(ignore);
  if (isErrorValue(predicate)) {
    return predicate;
  }
  const scanByColumnFlag = parseBooleanFlag(scanByColumn);
  if (isErrorValue(scanByColumnFlag)) {
    return scanByColumnFlag;
  }
  const values = [];
  const rows = source.length;
  const cols = getMaxColumnCount(source);
  if (scanByColumnFlag) {
    for (let col = 0;col < cols; col += 1) {
      for (let row2 = 0;row2 < rows; row2 += 1) {
        const value2 = coerceScalarValue2(source[row2]?.[col]);
        if (predicate(value2)) {
          continue;
        }
        values.push(value2);
      }
    }
  } else {
    for (const row2 of source) {
      for (const cell of row2) {
        const value2 = coerceScalarValue2(cell);
        if (predicate(value2)) {
          continue;
        }
        values.push(value2);
      }
    }
  }
  const column2 = values.map((value2) => [value2]);
  return makeArrayValue(column2);
}
function TOROW(array3, ignore, scanByColumn) {
  const source = normalizeGridArgument2(array3);
  if (source.length === 0) {
    return makeArrayValue([[]]);
  }
  const predicate = parseIgnorePredicate(ignore);
  if (isErrorValue(predicate)) {
    return predicate;
  }
  const scanByColumnFlag = parseBooleanFlag(scanByColumn);
  if (isErrorValue(scanByColumnFlag)) {
    return scanByColumnFlag;
  }
  const rows = source.length;
  const cols = getMaxColumnCount(source);
  const values = [];
  if (scanByColumnFlag) {
    for (let col = 0;col < cols; col += 1) {
      for (let row2 = 0;row2 < rows; row2 += 1) {
        const value2 = coerceScalarValue2(source[row2]?.[col]);
        if (predicate(value2)) {
          continue;
        }
        values.push(value2);
      }
    }
  } else {
    for (const row2 of source) {
      for (const cell of row2) {
        const value2 = coerceScalarValue2(cell);
        if (predicate(value2)) {
          continue;
        }
        values.push(value2);
      }
    }
  }
  return makeArrayValue([values]);
}
function WRAPCOLS(vector, wrapCount, padWith) {
  const values = flattenGridArgument(vector);
  if (values === null) {
    return VALUE_ERROR5;
  }
  const height = parseWrapCount(wrapCount);
  if (isErrorValue(height)) {
    return height;
  }
  if (height === 0) {
    return VALUE_ERROR5;
  }
  const padValue = padWith === undefined ? NA_ERROR2 : coerceScalarValue2(extractScalarFromArg(padWith));
  if (padWith !== undefined && isErrorValue(padValue)) {
    return padValue;
  }
  if (values.length === 0) {
    return makeArrayValue(Array.from({ length: height }, () => []));
  }
  const columnCount = Math.ceil(values.length / height);
  const result = Array.from({ length: height }, () => Array(columnCount).fill(padValue));
  for (let index = 0;index < values.length; index += 1) {
    const row2 = index % height;
    const col = Math.floor(index / height);
    result[row2][col] = coerceScalarValue2(values[index]);
  }
  return makeArrayValue(result);
}
function EXPAND(array3, rows, columns, padWith) {
  const source = normalizeGridArgument2(array3);
  const currentRows = source.length;
  const currentCols = getMaxColumnCount(source);
  const targetRows = parseExpandDimension(rows, currentRows);
  if (isErrorValue(targetRows)) {
    return targetRows;
  }
  const targetCols = parseExpandDimension(columns, currentCols);
  if (isErrorValue(targetCols)) {
    return targetCols;
  }
  if (targetRows === currentRows && targetCols === currentCols) {
    return makeArrayValue(source.map((row2) => row2.map((cell) => coerceScalarValue2(cell))));
  }
  const padValue = padWith === undefined ? NA_ERROR2 : coerceScalarValue2(extractScalarFromArg(padWith));
  if (padWith !== undefined && isErrorValue(padValue)) {
    return padValue;
  }
  const result = [];
  for (let row2 = 0;row2 < targetRows; row2 += 1) {
    const sourceRow = row2 < currentRows ? source[row2] ?? [] : [];
    const expandedRow = [];
    for (let col = 0;col < targetCols; col += 1) {
      if (sourceRow && col < sourceRow.length) {
        expandedRow.push(coerceScalarValue2(sourceRow[col]));
      } else {
        expandedRow.push(padValue);
      }
    }
    result.push(expandedRow);
  }
  return makeArrayValue(result);
}
function TAKE(array3, rows, columns) {
  const source = normalizeGridArgument2(array3);
  const rowCount = source.length;
  if (rowCount === 0) {
    return VALUE_ERROR5;
  }
  const parsedRowCount = parseTakeCount(rows, rowCount);
  if (isErrorValue(parsedRowCount)) {
    return parsedRowCount;
  }
  const rowIndexesResult = buildTakeIndexes(parsedRowCount, rowCount);
  if (isErrorValue(rowIndexesResult)) {
    return rowIndexesResult;
  }
  const rowIndexes = rowIndexesResult;
  const columnCount = getMaxColumnCount(source);
  let columnIndexes = null;
  if (columns !== undefined) {
    if (columnCount === 0) {
      return VALUE_ERROR5;
    }
    const parsedColumnCount = parseTakeCount(columns, columnCount);
    if (isErrorValue(parsedColumnCount)) {
      return parsedColumnCount;
    }
    const columnIndexesResult = buildTakeIndexes(parsedColumnCount, columnCount);
    if (isErrorValue(columnIndexesResult)) {
      return columnIndexesResult;
    }
    columnIndexes = columnIndexesResult;
  }
  const results = rowIndexes.map((rowIndex2) => {
    const row2 = source[rowIndex2] ?? [];
    if (columnIndexes === null) {
      return row2.map((cell) => coerceScalarValue2(cell));
    }
    return columnIndexes.map((columnIndex2) => coerceScalarValue2(row2[columnIndex2] ?? null));
  });
  return makeArrayValue(results);
}
function DROP(array3, rows, columns) {
  const source = normalizeGridArgument2(array3);
  const rowCount = source.length;
  if (rowCount === 0) {
    return VALUE_ERROR5;
  }
  const parsedRowDrop = parseDropCount(rows, rowCount);
  if (isErrorValue(parsedRowDrop)) {
    return parsedRowDrop;
  }
  const remainingRowIndexes = buildDropIndexes(parsedRowDrop, rowCount);
  if (isErrorValue(remainingRowIndexes)) {
    return remainingRowIndexes;
  }
  const columnCount = getMaxColumnCount(source);
  let columnIndexes = null;
  if (columns !== undefined) {
    if (columnCount === 0) {
      return VALUE_ERROR5;
    }
    const parsedColumnDrop = parseDropCount(columns, columnCount);
    if (isErrorValue(parsedColumnDrop)) {
      return parsedColumnDrop;
    }
    const remainingColumnIndexes = buildDropIndexes(parsedColumnDrop, columnCount);
    if (isErrorValue(remainingColumnIndexes)) {
      return remainingColumnIndexes;
    }
    columnIndexes = remainingColumnIndexes;
  }
  if (remainingRowIndexes.length === 0) {
    return CALC_ERROR;
  }
  const results = remainingRowIndexes.map((rowIndex2) => {
    const row2 = source[rowIndex2] ?? [];
    if (columnIndexes === null) {
      return row2.map((cell) => coerceScalarValue2(cell));
    }
    return columnIndexes.map((columnIndex2) => coerceScalarValue2(row2[columnIndex2] ?? null));
  });
  const hasColumns = columnIndexes === null ? getMaxColumnCount(results) > 0 : columnIndexes.length > 0;
  if (!hasColumns) {
    return CALC_ERROR;
  }
  return makeArrayValue(results);
}
function PY(useCtrlEnterToCommitPythonCodeCreatesPythonFormulas) {
  throw new Error(`PY is not implemented. useCtrlEnterToCommitPythonCodeCreatesPythonFormulas=${String(useCtrlEnterToCommitPythonCodeCreatesPythonFormulas)}`);
}
function IMAGE(source, altText, sizing, height, width) {
  throw new Error(`IMAGE is not implemented. source=${String(source)}, altText=${String(altText)}, sizing=${String(sizing)}, height=${String(height)}, width=${String(width)}`);
}
function GROUPBY(rowFields, values, functionParam, fieldHeaders, totalDepth, sortOrder, filterArray, fieldRelationship) {
  throw new Error(`GROUPBY is not implemented. rowFields=${String(rowFields)}, values=${String(values)}, functionParam=${String(functionParam)}, fieldHeaders=${String(fieldHeaders)}, totalDepth=${String(totalDepth)}, sortOrder=${String(sortOrder)}, filterArray=${String(filterArray)}, fieldRelationship=${String(fieldRelationship)}`);
}
function PIVOTBY(rowFields, colFields, values, functionParam, fieldHeaders, rowTotalDepth, rowSortOrder, colTotalDepth, colSortOrder, filterArray, relativeTo) {
  throw new Error(`PIVOTBY is not implemented. rowFields=${String(rowFields)}, colFields=${String(colFields)}, values=${String(values)}, functionParam=${String(functionParam)}, fieldHeaders=${String(fieldHeaders)}, rowTotalDepth=${String(rowTotalDepth)}, rowSortOrder=${String(rowSortOrder)}, colTotalDepth=${String(colTotalDepth)}, colSortOrder=${String(colSortOrder)}, filterArray=${String(filterArray)}, relativeTo=${String(relativeTo)}`);
}
function TRIMRANGE(range2, rowTrimMode, colTrimMode) {
  throw new Error(`TRIMRANGE is not implemented. range=${String(range2)}, rowTrimMode=${String(rowTrimMode)}, colTrimMode=${String(colTrimMode)}`);
}
// node_modules/@oai/granola/dist/models/spreadsheet/engine/aggregate-utils.js
var AGGREGATE_KINDS = new Set(["SUBTOTAL", "AGGREGATE"]);
function sanitizeAggregationArgs(args2, ctx, policy) {
  if (!policy.ignoreNestedAggregates && !policy.ignoreErrors) {
    return args2;
  }
  return args2.map((arg) => sanitizeArg(arg, ctx, policy));
}
function sanitizeArg(arg, ctx, policy) {
  if (Array.isArray(arg)) {
    return sanitizeMatrix(arg, ctx, policy);
  }
  if (isArrayValue(arg)) {
    return sanitizeMatrix(arg.values.map((row2) => [...row2]), ctx, policy);
  }
  return arg;
}
function sanitizeMatrix(matrix, ctx, policy) {
  const metadata = ctx ? getRangeMetadata(matrix) : null;
  let mutated = false;
  const sanitized = matrix.map((row2, rowIdx) => {
    if (!row2) {
      return row2;
    }
    const metadataRow = metadata?.[rowIdx];
    let rowCopy;
    for (let colIdx = 0;colIdx < row2.length; colIdx += 1) {
      const cell = row2[colIdx];
      if (policy.ignoreErrors && (isErrorScalar(cell) || cell instanceof Error)) {
        if (!rowCopy) {
          rowCopy = [...row2];
        }
        rowCopy[colIdx] = null;
        mutated = true;
        continue;
      }
      if (policy.ignoreNestedAggregates && ctx?.getCellFormulaType && metadataRow) {
        const addr = metadataRow[colIdx];
        if (!addr) {
          continue;
        }
        const kind = ctx.getCellFormulaType(addr);
        if (kind && AGGREGATE_KINDS.has(kind)) {
          if (!rowCopy) {
            rowCopy = [...row2];
          }
          rowCopy[colIdx] = null;
          mutated = true;
        }
      }
    }
    return rowCopy ?? row2;
  });
  return mutated ? sanitized : matrix;
}
function isErrorScalar(value2) {
  return typeof value2 === "object" && value2 !== null && value2.kind === "Error";
}

// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/math-trig.js
var VALUE_ERROR6 = { kind: "Error", code: "#VALUE!" };
var DIV0_ERROR2 = { kind: "Error", code: "#DIV/0!" };
var NUM_ERROR3 = { kind: "Error", code: "#NUM!" };
function isErrorValue5(value2) {
  return typeof value2 === "object" && value2 !== null && value2.kind === "Error";
}
function normalizeErrorObject(error49) {
  const message = error49.message?.trim();
  if (message && message.startsWith("#")) {
    return { kind: "Error", code: message };
  }
  return VALUE_ERROR6;
}
function alignSumRangeToCriteria(rangeArg, sumRangeArg) {
  if (sumRangeArg === undefined) {
    return;
  }
  const rangeMatrix = functionArgToMatrix(rangeArg);
  const sumMatrix = functionArgToMatrix(sumRangeArg);
  if (!rangeMatrix || !sumMatrix) {
    return sumRangeArg;
  }
  const targetRows = rangeMatrix.length;
  if (targetRows === 0) {
    return sumRangeArg;
  }
  const targetCols = rangeMatrix.reduce((max5, row2) => Math.max(max5, row2?.length ?? 0), 0);
  if (targetCols === 0) {
    return sumRangeArg;
  }
  const trimmed = [];
  for (let rowIdx = 0;rowIdx < targetRows; rowIdx += 1) {
    const sourceRow = sumMatrix[rowIdx] ?? [];
    const normalizedRow = [];
    for (let colIdx = 0;colIdx < targetCols; colIdx += 1) {
      normalizedRow[colIdx] = colIdx < sourceRow.length ? sourceRow[colIdx] ?? null : null;
    }
    trimmed[rowIdx] = normalizedRow;
  }
  return trimmed;
}
function functionArgToMatrix(arg) {
  if (Array.isArray(arg)) {
    return arg.map((row2) => row2 ? [...row2] : []);
  }
  if (arg === undefined) {
    return null;
  }
  const scalar = arg;
  if (isArrayValue(scalar)) {
    return scalar.values.map((row2) => [...row2]);
  }
  return [[scalar]];
}
function sumRangeValues(values) {
  let total = 0;
  for (const row2 of values) {
    if (!row2) {
      continue;
    }
    for (const cell of row2) {
      const coerced = coerceReferenceNumberForSum(cell);
      if (coerced === null) {
        continue;
      }
      if (typeof coerced === "number") {
        total += coerced;
        continue;
      }
      return coerced;
    }
  }
  return total;
}
function coerceReferenceNumberForSum(value2) {
  if (isErrorValue5(value2)) {
    return value2;
  }
  if (value2 instanceof Error) {
    return normalizeErrorObject(value2);
  }
  if (value2 === null) {
    return 0;
  }
  if (typeof value2 === "number") {
    return value2;
  }
  if (typeof value2 === "string") {
    if (value2 === "") {
      return 0;
    }
    return null;
  }
  if (typeof value2 === "boolean") {
    return null;
  }
  return VALUE_ERROR6;
}
function coerceLiteralNumberForSum(value2) {
  if (isErrorValue5(value2)) {
    return value2;
  }
  if (value2 instanceof Error) {
    return normalizeErrorObject(value2);
  }
  if (value2 === null) {
    return 0;
  }
  if (typeof value2 === "number") {
    return value2;
  }
  if (typeof value2 === "boolean") {
    return value2 ? 1 : 0;
  }
  if (typeof value2 === "string") {
    if (value2 === "") {
      return 0;
    }
    const numeric = Number(value2);
    if (Number.isNaN(numeric)) {
      return VALUE_ERROR6;
    }
    return numeric;
  }
  return VALUE_ERROR6;
}
function sumArguments(args2) {
  let total = 0;
  for (const arg of args2) {
    if (arg === undefined) {
      continue;
    }
    if (Array.isArray(arg)) {
      const rangeResult = sumRangeValues(arg);
      if (typeof rangeResult === "number") {
        total += rangeResult;
        continue;
      }
      return rangeResult;
    }
    if (isArrayValue(arg)) {
      const rangeResult = sumRangeValues(arg.values);
      if (typeof rangeResult === "number") {
        total += rangeResult;
        continue;
      }
      return rangeResult;
    }
    const literalResult = coerceLiteralNumberForSum(arg);
    if (literalResult === null) {
      continue;
    }
    if (typeof literalResult === "number") {
      total += literalResult;
      continue;
    }
    return literalResult;
  }
  return total;
}
var EXCEL_PRECISION_DIGITS = 15;
function roundToExcelPrecision(value2) {
  if (!Number.isFinite(value2)) {
    return value2;
  }
  const rounded = Number(value2.toPrecision(EXCEL_PRECISION_DIGITS));
  return Object.is(rounded, -0) ? 0 : rounded;
}
function extractScalarFromArg2(arg) {
  if (arg === undefined) {
    return;
  }
  if (Array.isArray(arg)) {
    const firstRow = arg[0];
    return firstRow ? firstRow[0] ?? null : null;
  }
  return arg;
}
function coerceScalarToNumber(value2, treatBlankAsZero = true) {
  if (value2 === undefined) {
    return VALUE_ERROR6;
  }
  if (isErrorValue5(value2)) {
    return value2;
  }
  if (value2 instanceof Error) {
    return normalizeErrorObject(value2);
  }
  if (value2 === null) {
    return treatBlankAsZero ? 0 : VALUE_ERROR6;
  }
  if (typeof value2 === "number") {
    if (!Number.isFinite(value2)) {
      return NUM_ERROR3;
    }
    return value2;
  }
  if (typeof value2 === "boolean") {
    return value2 ? 1 : 0;
  }
  if (typeof value2 === "string") {
    const trimmed = value2.trim();
    if (trimmed === "") {
      return treatBlankAsZero ? 0 : VALUE_ERROR6;
    }
    const parsed = Number(trimmed);
    return Number.isFinite(parsed) ? parsed : VALUE_ERROR6;
  }
  if (isArrayValue(value2)) {
    const first = value2.values[0]?.[0];
    return coerceScalarToNumber(first, treatBlankAsZero);
  }
  return VALUE_ERROR6;
}
function coerceCountArgument(arg, fallback) {
  if (arg === undefined) {
    return fallback;
  }
  const scalar = extractScalarFromArg2(arg);
  if (scalar === undefined) {
    return fallback;
  }
  const numeric = coerceScalarToNumber(scalar);
  if (typeof numeric !== "number") {
    return numeric;
  }
  const truncated = Math.trunc(numeric);
  if (truncated < 1) {
    return VALUE_ERROR6;
  }
  return truncated;
}
function coerceNumericArgument(arg, fallback) {
  if (arg === undefined) {
    return fallback;
  }
  const scalar = extractScalarFromArg2(arg);
  if (scalar === undefined) {
    return fallback;
  }
  const numeric = coerceScalarToNumber(scalar);
  if (typeof numeric !== "number") {
    return numeric;
  }
  return numeric;
}
function coerceBooleanArgument(arg, fallback) {
  if (arg === undefined) {
    return fallback;
  }
  const scalar = extractScalarFromArg2(arg);
  if (scalar === undefined) {
    return fallback;
  }
  if (isErrorValue5(scalar)) {
    return scalar;
  }
  if (scalar instanceof Error) {
    return normalizeErrorObject(scalar);
  }
  if (scalar === null) {
    return false;
  }
  if (typeof scalar === "boolean") {
    return scalar;
  }
  if (typeof scalar === "number") {
    if (!Number.isFinite(scalar)) {
      return NUM_ERROR3;
    }
    return scalar !== 0;
  }
  if (typeof scalar === "string") {
    const trimmed = scalar.trim().toLowerCase();
    if (trimmed === "") {
      return false;
    }
    if (trimmed === "true") {
      return true;
    }
    if (trimmed === "false") {
      return false;
    }
    const numeric = Number(trimmed);
    if (Number.isFinite(numeric)) {
      return numeric !== 0;
    }
    return VALUE_ERROR6;
  }
  return VALUE_ERROR6;
}
function createCriteriaEvaluator(criteria) {
  const scalar = extractScalarFromArg2(criteria);
  if (scalar === undefined) {
    return () => false;
  }
  if (isErrorValue5(scalar)) {
    return scalar;
  }
  if (scalar instanceof Error) {
    return normalizeErrorObject(scalar);
  }
  if (typeof scalar === "string") {
    const trimmed = scalar.trim();
    const comparison = parseCriteriaString(trimmed);
    if (comparison) {
      return buildComparisonEvaluator(comparison);
    }
    const normalized = trimmed.toUpperCase();
    return (value2) => valueToUppercaseString(value2) === normalized;
  }
  if (typeof scalar === "number") {
    return buildComparisonEvaluator({
      operator: "=",
      operand: { kind: "number", value: scalar }
    });
  }
  if (typeof scalar === "boolean") {
    return buildComparisonEvaluator({
      operator: "=",
      operand: { kind: "number", value: scalar ? 1 : 0 }
    });
  }
  if (scalar === null) {
    return buildComparisonEvaluator({
      operator: "=",
      operand: { kind: "blank" }
    });
  }
  if (isArrayValue(scalar)) {
    const first = scalar.values[0]?.[0];
    return createCriteriaEvaluator([[first ?? null]]);
  }
  return (value2) => value2 === scalar;
}
function buildComparisonEvaluator(comparison) {
  return (value2) => {
    switch (comparison.operand.kind) {
      case "number": {
        const numeric = coerceScalarToNumber(value2);
        if (typeof numeric !== "number") {
          return false;
        }
        return compareNumbers2(numeric, comparison.operand.value, comparison.operator);
      }
      case "string": {
        const candidate = valueToUppercaseString(value2);
        if (candidate === null) {
          return false;
        }
        if (comparison.operator === "=") {
          return candidate === comparison.operand.value;
        }
        if (comparison.operator === "<>") {
          return candidate !== comparison.operand.value;
        }
        return false;
      }
      case "blank": {
        const blank = isBlankCell(value2);
        if (comparison.operator === "=") {
          return blank;
        }
        if (comparison.operator === "<>") {
          return !blank;
        }
        return false;
      }
      default:
        return false;
    }
  };
}
function compareNumbers2(left, right, operator) {
  switch (operator) {
    case "=":
      return left === right;
    case "<>":
      return left !== right;
    case ">":
      return left > right;
    case "<":
      return left < right;
    case ">=":
      return left >= right;
    case "<=":
      return left <= right;
    default:
      return false;
  }
}
function parseCriteriaString(input) {
  if (!input) {
    return {
      operator: "=",
      operand: { kind: "blank" }
    };
  }
  const match = input.match(/^(<=|>=|<>|=|<|>)(.*)$/);
  if (match) {
    const operator = match[1];
    const operandText = match[2] ?? "";
    if (!operandText) {
      return {
        operator,
        operand: { kind: "blank" }
      };
    }
    const numeric2 = Number(operandText);
    if (!Number.isNaN(numeric2)) {
      return {
        operator,
        operand: { kind: "number", value: numeric2 }
      };
    }
    return {
      operator,
      operand: { kind: "string", value: operandText.trim().toUpperCase() }
    };
  }
  const numeric = Number(input);
  if (!Number.isNaN(numeric)) {
    return {
      operator: "=",
      operand: { kind: "number", value: numeric }
    };
  }
  return {
    operator: "=",
    operand: { kind: "string", value: input.trim().toUpperCase() }
  };
}
function valueToUppercaseString(value2) {
  if (value2 === undefined || value2 === null) {
    return "";
  }
  if (isErrorValue5(value2)) {
    return null;
  }
  if (value2 instanceof Error) {
    return null;
  }
  if (typeof value2 === "string") {
    return value2.trim().toUpperCase();
  }
  if (typeof value2 === "number") {
    if (!Number.isFinite(value2)) {
      return null;
    }
    return String(value2).toUpperCase();
  }
  if (typeof value2 === "boolean") {
    return value2 ? "TRUE" : "FALSE";
  }
  return String(value2).toUpperCase();
}
function isBlankCell(value2) {
  if (value2 === undefined || value2 === null) {
    return true;
  }
  if (typeof value2 === "string") {
    return value2.trim() === "";
  }
  return false;
}
function SUM2(number1, number22, ...rest2) {
  return sumArguments([number1, number22, ...rest2]);
}
function SIN2(numberParam) {
  return SIN(numberParam);
}
function COS2(numberParam) {
  return COS(numberParam);
}
function TAN2(numberParam) {
  return TAN(numberParam);
}
function ATAN3(numberParam) {
  return ATAN(numberParam);
}
function PI3() {
  return PI();
}
function SQRT2(numberParam) {
  return SQRT(numberParam);
}
function EXP2(numberParam) {
  return EXP(numberParam);
}
function LN2(numberParam) {
  return LN(numberParam);
}
function LOG102(numberParam) {
  const result = LOG10(numberParam);
  if (typeof result === "number") {
    return roundToExcelPrecision(result);
  }
  return result;
}
function ABS2(numberParam) {
  return ABS(numberParam);
}
function INT2(numberParam) {
  return INT(numberParam);
}
function SIGN2(numberParam) {
  return SIGN(numberParam);
}
function ROUND2(numberParam, numDigits) {
  return ROUND(numberParam, numDigits);
}
function MOD2(numberParam, divisor) {
  return MOD(numberParam, divisor);
}
function RAND2() {
  return RAND();
}
function ATAN22(xNum, yNum) {
  if (typeof xNum === "number" && typeof yNum === "number" && xNum === 0 && yNum === 0) {
    return DIV0_ERROR2;
  }
  return ATAN2(xNum, yNum);
}
function ASIN2(numberParam) {
  return ASIN(numberParam);
}
function ACOS2(numberParam) {
  return ACOS(numberParam);
}
function LOG2(numberParam, base) {
  return LOG(numberParam, base);
}
function MDETERM(array3) {
  const matrix = functionArgToMatrix(array3);
  if (!matrix || matrix.length === 0) {
    return VALUE_ERROR6;
  }
  const rowCount = matrix.length;
  const columnCount = matrix[0]?.length ?? 0;
  if (rowCount === 0 || columnCount === 0) {
    return VALUE_ERROR6;
  }
  if (rowCount !== columnCount) {
    return VALUE_ERROR6;
  }
  const numeric = coerceSquareNumericMatrix(matrix, rowCount);
  if (isErrorValue5(numeric)) {
    return numeric;
  }
  return computeDeterminant(numeric);
}
function MINVERSE(array3) {
  const matrix = functionArgToMatrix(array3);
  if (!matrix || matrix.length === 0) {
    return VALUE_ERROR6;
  }
  const rowCount = matrix.length;
  const columnCount = matrix[0]?.length ?? 0;
  if (rowCount === 0 || columnCount === 0) {
    return VALUE_ERROR6;
  }
  if (rowCount !== columnCount) {
    return VALUE_ERROR6;
  }
  const numeric = coerceSquareNumericMatrix(matrix, rowCount);
  if (isErrorValue5(numeric)) {
    return numeric;
  }
  const inverse = computeInverse(numeric);
  if (isErrorValue5(inverse)) {
    return inverse;
  }
  const rounded = inverse.map((row2) => row2.map((value2) => roundToExcelPrecision(value2)));
  return makeArrayValue(rounded);
}
function coerceSquareNumericMatrix(values, dimension) {
  const numeric = [];
  for (let r = 0;r < dimension; r += 1) {
    const row2 = values[r];
    if (!row2 || row2.length !== dimension) {
      return VALUE_ERROR6;
    }
    const outRow = [];
    for (let c = 0;c < dimension; c += 1) {
      const coerced = coerceScalarToNumber(row2[c] ?? null);
      if (typeof coerced !== "number") {
        return coerced;
      }
      outRow.push(coerced);
    }
    numeric.push(outRow);
  }
  return numeric;
}
function computeDeterminant(matrix) {
  const dimension = matrix.length;
  if (dimension === 0) {
    return VALUE_ERROR6;
  }
  const working = matrix.map((row2) => [...row2]);
  let sign3 = 1;
  for (let pivotCol = 0;pivotCol < dimension; pivotCol += 1) {
    let pivotRow = pivotCol;
    let best = Math.abs(working[pivotRow]?.[pivotCol] ?? 0);
    for (let candidate = pivotCol + 1;candidate < dimension; candidate += 1) {
      const value2 = Math.abs(working[candidate]?.[pivotCol] ?? 0);
      if (value2 > best) {
        best = value2;
        pivotRow = candidate;
      }
    }
    const pivot = working[pivotRow]?.[pivotCol] ?? 0;
    if (pivot === 0) {
      return 0;
    }
    if (pivotRow !== pivotCol) {
      const tmp = working[pivotCol];
      working[pivotCol] = working[pivotRow];
      working[pivotRow] = tmp;
      sign3 *= -1;
    }
    const pivotValue = working[pivotCol]?.[pivotCol] ?? 0;
    if (pivotValue === 0) {
      return 0;
    }
    for (let row2 = pivotCol + 1;row2 < dimension; row2 += 1) {
      const factor = (working[row2]?.[pivotCol] ?? 0) / pivotValue;
      if (!Number.isFinite(factor)) {
        return NUM_ERROR3;
      }
      for (let col = pivotCol;col < dimension; col += 1) {
        const current = working[row2]?.[col] ?? 0;
        const subtract = factor * (working[pivotCol]?.[col] ?? 0);
        const updated = current - subtract;
        if (!Number.isFinite(updated)) {
          return NUM_ERROR3;
        }
        working[row2][col] = updated;
      }
    }
  }
  let determinant = sign3;
  for (let i = 0;i < dimension; i += 1) {
    determinant *= working[i]?.[i] ?? 0;
    if (!Number.isFinite(determinant)) {
      return NUM_ERROR3;
    }
  }
  return roundToExcelPrecision(determinant);
}
function computeInverse(matrix) {
  const dimension = matrix.length;
  if (dimension === 0) {
    return VALUE_ERROR6;
  }
  const augmented = [];
  for (let r = 0;r < dimension; r += 1) {
    const row2 = matrix[r];
    if (!row2 || row2.length !== dimension) {
      return VALUE_ERROR6;
    }
    const identity4 = [];
    for (let c = 0;c < dimension; c += 1) {
      identity4.push(r === c ? 1 : 0);
    }
    augmented.push([...row2, ...identity4]);
  }
  for (let pivotCol = 0;pivotCol < dimension; pivotCol += 1) {
    let pivotRow = pivotCol;
    let best = Math.abs(augmented[pivotRow]?.[pivotCol] ?? 0);
    for (let candidate = pivotCol + 1;candidate < dimension; candidate += 1) {
      const value2 = Math.abs(augmented[candidate]?.[pivotCol] ?? 0);
      if (value2 > best) {
        best = value2;
        pivotRow = candidate;
      }
    }
    const pivot = augmented[pivotRow]?.[pivotCol] ?? 0;
    if (pivot === 0) {
      return NUM_ERROR3;
    }
    if (pivotRow !== pivotCol) {
      const tmp = augmented[pivotCol];
      augmented[pivotCol] = augmented[pivotRow];
      augmented[pivotRow] = tmp;
    }
    const pivotValue = augmented[pivotCol]?.[pivotCol] ?? 0;
    if (pivotValue === 0) {
      return NUM_ERROR3;
    }
    const width = dimension * 2;
    for (let col = 0;col < width; col += 1) {
      const updated = (augmented[pivotCol]?.[col] ?? 0) / pivotValue;
      if (!Number.isFinite(updated)) {
        return NUM_ERROR3;
      }
      augmented[pivotCol][col] = updated;
    }
    for (let row2 = 0;row2 < dimension; row2 += 1) {
      if (row2 === pivotCol) {
        continue;
      }
      const factor = augmented[row2]?.[pivotCol] ?? 0;
      if (factor === 0) {
        continue;
      }
      for (let col = 0;col < width; col += 1) {
        const current = augmented[row2]?.[col] ?? 0;
        const subtract = factor * (augmented[pivotCol]?.[col] ?? 0);
        const updated = current - subtract;
        if (!Number.isFinite(updated)) {
          return NUM_ERROR3;
        }
        augmented[row2][col] = updated;
      }
    }
  }
  const inverse = [];
  for (let r = 0;r < dimension; r += 1) {
    inverse.push(augmented[r].slice(dimension));
  }
  return inverse;
}
function MMULT2(array1, array22) {
  const result = MMULT(array1, array22);
  if (Array.isArray(result)) {
    return makeArrayValue(result);
  }
  return result;
}
function PRODUCT2(number1, number22, ...rest2) {
  return PRODUCT(number1, number22, ...rest2);
}
function FACT2(numberParam) {
  if (typeof numberParam === "number" && numberParam < 0) {
    return NUM_ERROR3;
  }
  return FACT(numberParam);
}
function TRUNC2(numberParam, numDigits) {
  return TRUNC(numberParam, numDigits);
}
function ROUNDUP2(numberParam, numDigits) {
  return ROUNDUP(numberParam, numDigits);
}
function ROUNDDOWN2(numberParam, numDigits) {
  return ROUNDDOWN(numberParam, numDigits);
}
function SUMPRODUCT(array1, ...rest2) {
  const normalizedArgs = [array1, ...rest2].filter((arg) => arg !== undefined);
  if (normalizedArgs.length === 0) {
    return 0;
  }
  const matrices = normalizedArgs.map((arg) => functionArgToMatrix(arg) ?? []);
  const infos = matrices.map(describeMatrix);
  for (const info of infos) {
    if (!info.valid) {
      return VALUE_ERROR6;
    }
  }
  let targetRows = 1;
  let targetCols = 1;
  let hasNonScalar = false;
  for (const info of infos) {
    if (info.rows === 0 || info.cols === 0) {
      return 0;
    }
    if (info.isScalar) {
      continue;
    }
    if (!hasNonScalar) {
      targetRows = info.rows;
      targetCols = info.cols;
      hasNonScalar = true;
      continue;
    }
    if (info.rows !== targetRows || info.cols !== targetCols) {
      return VALUE_ERROR6;
    }
  }
  if (!hasNonScalar) {
    targetRows = 1;
    targetCols = 1;
  }
  let total = 0;
  for (let row2 = 0;row2 < targetRows; row2 += 1) {
    for (let col = 0;col < targetCols; col += 1) {
      let product = 1;
      for (let idx = 0;idx < infos.length; idx += 1) {
        const info = infos[idx];
        const matrix = matrices[idx];
        const cell = info.isScalar && matrix[0] ? matrix[0][0] : matrix[row2]?.[col] ?? null;
        const numeric = coerceSumproductValue(cell);
        if (typeof numeric !== "number") {
          return numeric;
        }
        product *= numeric;
      }
      total += product;
    }
  }
  return total;
}
function describeMatrix(matrix) {
  const rows = matrix.length;
  if (rows === 0) {
    return { rows: 0, cols: 0, isScalar: false, valid: true };
  }
  const cols = matrix[0]?.length ?? 0;
  for (let r = 1;r < rows; r += 1) {
    const length2 = matrix[r]?.length ?? 0;
    if (length2 !== cols) {
      return {
        rows,
        cols: Math.max(cols, length2),
        isScalar: false,
        valid: false
      };
    }
  }
  const isScalar = rows === 1 && cols === 1;
  return { rows, cols, isScalar, valid: true };
}
function coerceSumproductValue(value2) {
  if (value2 === undefined) {
    return 0;
  }
  if (isErrorValue5(value2)) {
    return value2;
  }
  if (value2 instanceof Error) {
    return normalizeErrorObject(value2);
  }
  if (value2 === null) {
    return 0;
  }
  if (typeof value2 === "number") {
    if (!Number.isFinite(value2)) {
      return NUM_ERROR3;
    }
    return value2;
  }
  if (typeof value2 === "boolean") {
    return value2 ? 1 : 0;
  }
  if (typeof value2 === "string") {
    const trimmed = value2.trim();
    if (trimmed === "") {
      return 0;
    }
    const parsed = Number(trimmed);
    return Number.isFinite(parsed) ? parsed : 0;
  }
  if (isArrayValue(value2)) {
    return VALUE_ERROR6;
  }
  return VALUE_ERROR6;
}
function SINH2(numberParam) {
  return SINH(numberParam);
}
function COSH2(numberParam) {
  return COSH(numberParam);
}
function TANH2(numberParam) {
  return TANH(numberParam);
}
function ASINH2(numberParam) {
  return ASINH(numberParam);
}
function ACOSH2(numberParam) {
  return ACOSH(numberParam);
}
function ATANH2(numberParam) {
  return ATANH(numberParam);
}
function COMBIN2(numberParam, numberChosen) {
  return COMBIN(numberParam, numberChosen);
}
function EVEN2(numberParam) {
  return EVEN(numberParam);
}
function ODD2(numberParam) {
  return ODD(numberParam);
}
function SUMXMY22(arrayX, arrayY) {
  return SUMXMY2(arrayX, arrayY);
}
function SUMX2MY22(arrayX, arrayY) {
  return SUMX2MY2(arrayX, arrayY);
}
function SUMX2PY22(arrayX, arrayY) {
  return SUMX2PY2(arrayX, arrayY);
}
function SUMSQ(number1, number22, ...rest2) {
  const args2 = [number1, number22, ...rest2];
  let total = 0;
  for (const arg of args2) {
    if (arg === undefined) {
      continue;
    }
    if (Array.isArray(arg)) {
      const rangeResult = sumSquaresRangeValues(arg);
      if (typeof rangeResult === "number") {
        total += rangeResult;
        continue;
      }
      return rangeResult;
    }
    if (isArrayValue(arg)) {
      const arrayResult = sumSquaresRangeValues(arg.values);
      if (typeof arrayResult === "number") {
        total += arrayResult;
        continue;
      }
      return arrayResult;
    }
    const literalResult = coerceLiteralNumberForSum(arg);
    if (literalResult === null) {
      continue;
    }
    if (typeof literalResult === "number") {
      total += literalResult * literalResult;
      continue;
    }
    return literalResult;
  }
  return total;
}
function sumSquaresRangeValues(values) {
  let total = 0;
  for (const row2 of values) {
    if (!row2) {
      continue;
    }
    for (const cell of row2) {
      const coerced = coerceReferenceNumberForSum(cell);
      if (coerced === null) {
        continue;
      }
      if (typeof coerced === "number") {
        total += coerced * coerced;
        continue;
      }
      return coerced;
    }
  }
  return total;
}
function POWER2(numberParam, power) {
  return POWER(numberParam, power);
}
function RADIANS2(angle) {
  return RADIANS(angle);
}
function DEGREES2(angle) {
  return DEGREES(angle);
}
function SUBTOTAL2(functionNum, ref1, ...rest2) {
  const ctx = getActiveEvaluationContext();
  const refs = [ref1, ...rest2];
  const sanitized = ctx !== null ? sanitizeAggregationArgs(refs, ctx, { ignoreNestedAggregates: true }) : refs;
  const [first, ...others] = sanitized;
  return SUBTOTAL(functionNum, first, ...others);
}
function SUMIF(range2, criteria, sumRange) {
  const criteriaMatrix = functionArgToMatrix(range2);
  const evaluatorResult = createCriteriaEvaluator(criteria);
  if (isErrorValue5(evaluatorResult)) {
    return evaluatorResult;
  }
  const evaluator = evaluatorResult;
  if (!criteriaMatrix) {
    const scalar = extractScalarFromArg2(range2);
    const matches = evaluator(scalar);
    if (!matches) {
      return 0;
    }
    const sumValue = sumRange === undefined ? scalar : extractScalarFromArg2(sumRange);
    const numeric = coerceScalarToNumber(sumValue);
    return numeric;
  }
  const alignedSumRange = sumRange === undefined ? criteriaMatrix : functionArgToMatrix(alignSumRangeToCriteria(range2, sumRange) ?? sumRange);
  if (!alignedSumRange) {
    return VALUE_ERROR6;
  }
  let total = 0;
  for (let rowIdx = 0;rowIdx < criteriaMatrix.length; rowIdx += 1) {
    const criteriaRow = criteriaMatrix[rowIdx] ?? [];
    const sumRow = alignedSumRange[rowIdx] ?? [];
    for (let colIdx = 0;colIdx < criteriaRow.length; colIdx += 1) {
      const cell = criteriaRow[colIdx];
      if (!evaluator(cell)) {
        continue;
      }
      const sumValue = sumRow[colIdx] ?? null;
      const numeric = coerceScalarToNumber(sumValue);
      if (typeof numeric === "number") {
        total += numeric;
      } else if (isErrorValue5(numeric)) {
        return numeric;
      }
    }
  }
  return total;
}
function ROMAN2(numberParam, form) {
  const numeric = coerceScalarToNumber(extractScalarFromArg2(numberParam));
  if (typeof numeric !== "number") {
    return numeric;
  }
  const truncated = Math.trunc(numeric);
  if (truncated < 1 || truncated > 3999) {
    return VALUE_ERROR6;
  }
  return ROMAN(truncated, form);
}
function SERIESSUM2(x2, n, m, coefficients) {
  return SERIESSUM(x2, n, m, coefficients);
}
function FACTDOUBLE(numberParam) {
  const numeric = coerceScalarToNumber(extractScalarFromArg2(numberParam));
  if (typeof numeric !== "number") {
    return numeric;
  }
  const truncated = Math.trunc(numeric);
  if (truncated < 0) {
    return NUM_ERROR3;
  }
  let total = 1;
  for (let current = truncated;current > 1; current -= 2) {
    total *= current;
    if (!Number.isFinite(total)) {
      return NUM_ERROR3;
    }
  }
  return total;
}
function SQRTPI2(numberParam) {
  return SQRTPI(numberParam);
}
function QUOTIENT(numerator, denominator) {
  const numeratorValue = coerceScalarToNumber(extractScalarFromArg2(numerator));
  if (typeof numeratorValue !== "number") {
    return numeratorValue;
  }
  const denominatorValue = coerceScalarToNumber(extractScalarFromArg2(denominator));
  if (typeof denominatorValue !== "number") {
    return denominatorValue;
  }
  if (denominatorValue === 0) {
    return DIV0_ERROR2;
  }
  const result = Math.trunc(numeratorValue / denominatorValue);
  return Number.isFinite(result) ? result : NUM_ERROR3;
}
function MROUND2(numberParam, multiple) {
  return MROUND(numberParam, multiple);
}
function RANDBETWEEN(bottom, top) {
  const bottomValue = coerceScalarToNumber(extractScalarFromArg2(bottom));
  if (typeof bottomValue !== "number") {
    return bottomValue;
  }
  const topValue = coerceScalarToNumber(extractScalarFromArg2(top));
  if (typeof topValue !== "number") {
    return topValue;
  }
  if (!Number.isFinite(bottomValue) || !Number.isFinite(topValue)) {
    return VALUE_ERROR6;
  }
  const minInt = Math.ceil(bottomValue);
  const maxInt = Math.floor(topValue);
  if (minInt > maxInt) {
    return NUM_ERROR3;
  }
  const span = maxInt - minInt + 1;
  if (span <= 0) {
    return NUM_ERROR3;
  }
  return Math.floor(Math.random() * span) + minInt;
}
function GCD2(number1, number22, ...rest2) {
  return GCD(number1, number22, ...rest2);
}
function MULTINOMIAL2(number1, number22, ...rest2) {
  const args2 = [number1];
  if (number22 !== undefined) {
    args2.push(number22);
  }
  for (const arg of rest2) {
    if (arg !== undefined) {
      args2.push(arg);
    }
  }
  for (const arg of args2) {
    const numeric = coerceScalarToNumber(extractScalarFromArg2(arg));
    if (typeof numeric !== "number") {
      return numeric;
    }
    if (Math.trunc(numeric) < 0) {
      return NUM_ERROR3;
    }
  }
  return MULTINOMIAL(number1, number22, ...rest2);
}
function LCM2(number1, number22, ...rest2) {
  return LCM(number1, number22, ...rest2);
}
function SUMIFS2(sumRange, criteriaRange, criteria, ...rest2) {
  const sumShape = getFunctionArgShape2(sumRange);
  if (isErrorValue5(sumShape)) {
    return sumShape;
  }
  const firstCriteriaShape = getFunctionArgShape2(criteriaRange);
  if (isErrorValue5(firstCriteriaShape)) {
    return firstCriteriaShape;
  }
  if (sumShape.rows !== firstCriteriaShape.rows || sumShape.cols !== firstCriteriaShape.cols) {
    return VALUE_ERROR6;
  }
  for (let i = 0;i < rest2.length; i += 1) {
    const arg = rest2[i];
    if (arg === undefined) {
      continue;
    }
    const isRangeArgument = i % 2 === 0;
    if (!isRangeArgument) {
      continue;
    }
    const shape2 = getFunctionArgShape2(arg);
    if (isErrorValue5(shape2)) {
      return shape2;
    }
    if (shape2.rows !== sumShape.rows || shape2.cols !== sumShape.cols) {
      return VALUE_ERROR6;
    }
  }
  return SUMIFS(sumRange, criteriaRange, criteria, ...rest2);
}
function getFunctionArgShape2(arg) {
  if (Array.isArray(arg)) {
    const rows = arg.length;
    const cols = arg.reduce((max5, row2) => Math.max(max5, row2?.length ?? 0), 0);
    if (rows === 0 || cols === 0) {
      return VALUE_ERROR6;
    }
    for (const row2 of arg) {
      if ((row2?.length ?? 0) !== cols) {
        return VALUE_ERROR6;
      }
    }
    return { rows, cols };
  }
  if (arg === undefined) {
    return VALUE_ERROR6;
  }
  const scalar = arg;
  if (isArrayValue(scalar)) {
    if (scalar.rows < 1 || scalar.cols < 1) {
      return VALUE_ERROR6;
    }
    return { rows: scalar.rows, cols: scalar.cols };
  }
  return { rows: 1, cols: 1 };
}
var AGGREGATE_IGNORE_NESTED_OPTIONS = new Set([0, 5, 6, 7]);
var AGGREGATE_IGNORE_ERROR_OPTIONS = new Set([2, 3, 6, 7]);
function AGGREGATE2(functionNum, options, ref1, ...rest2) {
  const optionNumber = coerceAggregateNumber(options);
  if (typeof optionNumber !== "number") {
    return optionNumber;
  }
  const refs = [ref1, ...rest2];
  const shouldIgnoreNested = AGGREGATE_IGNORE_NESTED_OPTIONS.has(Math.trunc(optionNumber));
  const shouldIgnoreErrors = AGGREGATE_IGNORE_ERROR_OPTIONS.has(Math.trunc(optionNumber));
  const ctx = shouldIgnoreNested || shouldIgnoreErrors ? getActiveEvaluationContext() : null;
  const sanitized = ctx && (shouldIgnoreNested || shouldIgnoreErrors) ? sanitizeAggregationArgs(refs, ctx, {
    ignoreNestedAggregates: shouldIgnoreNested,
    ignoreErrors: shouldIgnoreErrors
  }) : shouldIgnoreErrors ? sanitizeAggregationArgs(refs, null, { ignoreErrors: true }) : refs;
  const [first, ...others] = sanitized;
  return AGGREGATE(functionNum, options, first, ...others);
}
function coerceAggregateNumber(arg) {
  const scalar = extractAggregateScalar(arg);
  if (isErrorValue5(scalar)) {
    return scalar;
  }
  if (scalar instanceof Error) {
    return normalizeErrorObject(scalar);
  }
  if (scalar == null) {
    return 0;
  }
  if (typeof scalar === "number") {
    return scalar;
  }
  if (typeof scalar === "boolean") {
    return scalar ? 1 : 0;
  }
  if (typeof scalar === "string") {
    const trimmed = scalar.trim();
    if (trimmed === "") {
      return 0;
    }
    const parsed = Number(trimmed);
    return Number.isFinite(parsed) ? parsed : VALUE_ERROR6;
  }
  return VALUE_ERROR6;
}
function extractAggregateScalar(arg) {
  if (Array.isArray(arg)) {
    const firstRow = arg[0];
    if (firstRow && firstRow.length > 0) {
      return firstRow[0] ?? null;
    }
    return null;
  }
  if (isArrayValue(arg)) {
    const array3 = arg;
    return array3.values[0]?.[0] ?? null;
  }
  return arg ?? null;
}
function ACOT2(numberParam) {
  const result = ACOT(numberParam);
  if (typeof result === "number") {
    if (result <= 0) {
      return result + Math.PI;
    }
    return result;
  }
  return result;
}
function ACOTH2(numberParam) {
  return ACOTH(numberParam);
}
function COT2(numberParam) {
  return COT(numberParam);
}
function COTH2(numberParam) {
  return COTH(numberParam);
}
function CSC2(numberParam) {
  return CSC(numberParam);
}
function CSCH2(numberParam) {
  return CSCH(numberParam);
}
function SEC2(numberParam) {
  return SEC(numberParam);
}
function SECH2(numberParam) {
  return SECH(numberParam);
}
function COMBINA2(numberParam, numberChosen) {
  return COMBINA(numberParam, numberChosen);
}
function BASE2(numberParam, radix, minLength) {
  const numberValue = coerceScalarToNumber(extractScalarFromArg2(numberParam));
  if (typeof numberValue !== "number") {
    return numberValue;
  }
  const radixValue = coerceScalarToNumber(extractScalarFromArg2(radix));
  if (typeof radixValue !== "number") {
    return radixValue;
  }
  const numeric = Math.trunc(numberValue);
  const base = Math.trunc(radixValue);
  if (numeric < 0) {
    return NUM_ERROR3;
  }
  if (base < 2 || base > 36) {
    return NUM_ERROR3;
  }
  const minLengthValue = minLength === undefined ? undefined : coerceScalarToNumber(extractScalarFromArg2(minLength));
  if (minLengthValue !== undefined && typeof minLengthValue !== "number") {
    return minLengthValue;
  }
  const minLengthDigits = minLengthValue === undefined ? 0 : Math.trunc(minLengthValue);
  if (minLengthDigits < 0) {
    return NUM_ERROR3;
  }
  let result = numeric.toString(base).toUpperCase();
  if (minLengthDigits > result.length) {
    result = result.padStart(minLengthDigits, "0");
  }
  return result;
}
function DECIMAL2(numberParam, radix) {
  return DECIMAL(numberParam, radix);
}
function MUNIT2(dimension) {
  return MUNIT(dimension);
}
function ARABIC2(text2) {
  return ARABIC(text2);
}
function CEILING_MATH(numberParam, significance, mode) {
  return CEILING.MATH(numberParam, significance, mode);
}
function CEILING_PRECISE(numberParam, significance) {
  return CEILING.PRECISE(numberParam, significance);
}
function FLOOR_MATH(numberParam, significance, mode) {
  return FLOOR.MATH(numberParam, significance, mode);
}
function FLOOR_PRECISE(numberParam, significance) {
  return FLOOR.PRECISE(numberParam, significance);
}
function ISO_CEILING(numberParam, significance) {
  const numberValue = coerceScalarToNumber(extractScalarFromArg2(numberParam));
  if (typeof numberValue !== "number") {
    return numberValue;
  }
  const significanceValue = significance === undefined ? 1 : coerceScalarToNumber(extractScalarFromArg2(significance));
  if (typeof significanceValue !== "number") {
    return significanceValue;
  }
  if (significanceValue === 0) {
    return 0;
  }
  const absSignificance = Math.abs(significanceValue);
  if (absSignificance === 0) {
    return 0;
  }
  const quotient = numberValue / absSignificance;
  const rounded = Math.ceil(quotient) * absSignificance;
  return roundToExcelPrecision(rounded);
}
function RANDARRAY(rows, columns, min4, max5, integer2) {
  const rowCount = coerceCountArgument(rows, 1);
  if (typeof rowCount !== "number") {
    return rowCount;
  }
  const columnCount = coerceCountArgument(columns, 1);
  if (typeof columnCount !== "number") {
    return columnCount;
  }
  const minValue = coerceNumericArgument(min4, 0);
  if (typeof minValue !== "number") {
    return minValue;
  }
  const maxValue = coerceNumericArgument(max5, 1);
  if (typeof maxValue !== "number") {
    return maxValue;
  }
  const integerFlag = coerceBooleanArgument(integer2, false);
  if (typeof integerFlag !== "boolean") {
    return integerFlag;
  }
  if (rowCount < 1 || columnCount < 1) {
    return VALUE_ERROR6;
  }
  if (!Number.isFinite(minValue) || !Number.isFinite(maxValue)) {
    return VALUE_ERROR6;
  }
  if (minValue > maxValue) {
    return NUM_ERROR3;
  }
  const rowsData = [];
  const useIntegers = integerFlag === true;
  const minInt = Math.ceil(minValue);
  const maxInt = Math.floor(maxValue);
  if (useIntegers && minInt > maxInt) {
    return NUM_ERROR3;
  }
  for (let r = 0;r < rowCount; r += 1) {
    const rowValues = [];
    for (let c = 0;c < columnCount; c += 1) {
      if (useIntegers) {
        const span2 = maxInt - minInt + 1;
        const value3 = Math.floor(Math.random() * span2) + minInt;
        rowValues.push(value3);
        continue;
      }
      const random2 = Math.random();
      const span = maxValue - minValue;
      const value2 = span === 0 ? minValue : random2 * span + minValue;
      rowValues.push(roundToExcelPrecision(value2));
    }
    rowsData.push(rowValues);
  }
  return makeArrayValue(rowsData);
}
function SEQUENCE(rows, columns, start, step) {
  if (rows === undefined) {
    return VALUE_ERROR6;
  }
  const rowCount = coerceCountArgument(rows, 1);
  if (typeof rowCount !== "number") {
    return rowCount;
  }
  const columnCount = coerceCountArgument(columns, 1);
  if (typeof columnCount !== "number") {
    return columnCount;
  }
  const startValue = coerceNumericArgument(start, 1);
  if (typeof startValue !== "number") {
    return startValue;
  }
  const stepValue = coerceNumericArgument(step, 1);
  if (typeof stepValue !== "number") {
    return stepValue;
  }
  const rowsData = [];
  for (let r = 0;r < rowCount; r += 1) {
    const rowValues = [];
    for (let c = 0;c < columnCount; c += 1) {
      const index = r * columnCount + c;
      const value2 = startValue + stepValue * index;
      if (!Number.isFinite(value2)) {
        return NUM_ERROR3;
      }
      rowValues.push(roundToExcelPrecision(value2));
    }
    rowsData.push(rowValues);
  }
  return makeArrayValue(rowsData);
}
function PERCENTOF(dataSubset, dataAll) {
  throw new Error(`PERCENTOF is not implemented. dataSubset=${String(dataSubset)}, dataAll=${String(dataAll)}`);
}
// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/text.js
var VALUE_ERROR7 = { kind: "Error", code: "#VALUE!" };
var NA_ERROR3 = { kind: "Error", code: "#N/A" };
function DOLLAR2(numberParam, decimals) {
  return DOLLAR(numberParam, decimals);
}
function FIXED2(numberParam, decimals, noCommas) {
  return FIXED(numberParam, decimals, noCommas);
}
function REPT2(text2, numberTimes) {
  return REPT(text2, numberTimes);
}
function MID2(text2, startNum, numChars) {
  return MID(text2, startNum, numChars);
}
function LEN2(text2) {
  return LEN(text2);
}
function VALUE2(text2) {
  if (Array.isArray(text2)) {
    if (text2.length === 0) {
      return { kind: "Error", code: "#VALUE!" };
    }
    const firstRow = text2[0];
    const firstValue = firstRow && firstRow.length > 0 ? firstRow[0] : null;
    return VALUE2(firstValue ?? null);
  }
  if (text2 === null) {
    return 0;
  }
  if (typeof text2 === "string") {
    if (text2 === "") {
      return 0;
    }
    if (text2.trim() === "") {
      return { kind: "Error", code: "#VALUE!" };
    }
  }
  return VALUE(text2);
}
function TEXT2(value2, formatText2) {
  return TEXT(value2, formatText2);
}
function SEARCH2(findText, withinText, startNum) {
  return SEARCH(findText, withinText, startNum);
}
function CHAR2(numberParam) {
  return CHAR(numberParam);
}
function LOWER2(text2) {
  return LOWER(text2);
}
function UPPER2(text2) {
  return UPPER(text2);
}
function PROPER2(text2) {
  return PROPER(text2);
}
function LEFT2(text2, numChars) {
  return LEFT(text2, numChars);
}
function RIGHT2(text2, numChars) {
  return RIGHT(text2, numChars);
}
function EXACT2(text1, text2) {
  return EXACT(text1, text2);
}
function TRIM2(text2) {
  return TRIM(text2);
}
function REPLACE2(oldText, startNum, numChars, newText) {
  return REPLACE(oldText, startNum, numChars, newText);
}
function SUBSTITUTE2(text2, oldText, newText, instanceNum) {
  return SUBSTITUTE(text2, oldText, newText, instanceNum);
}
function CODE2(text2) {
  return CODE(text2);
}
function FIND2(findText, withinText, startNum) {
  return FIND(findText, withinText, startNum);
}
function T2(value2) {
  return T(value2);
}
function CLEAN2(text2) {
  return CLEAN(text2);
}
function BAHTTEXT(numberParam) {
  throw new Error(`BAHTTEXT is not implemented. numberParam=${String(numberParam)}`);
}
function UNICHAR2(numberParam) {
  return UNICHAR(numberParam);
}
function UNICODE2(text2) {
  return UNICODE(text2);
}
function NUMBERVALUE2(text2, decimalSeparator, groupSeparator) {
  return NUMBERVALUE(text2, decimalSeparator, groupSeparator);
}
function TEXTJOIN2(delimiter, ignoreEmpty, text1, ...rest2) {
  return TEXTJOIN(delimiter, ignoreEmpty, text1, ...rest2);
}
function CONCAT2(text1, ...rest2) {
  return CONCAT(text1, ...rest2);
}
function TEXTBEFORE(text2, delimiter, instanceNum, matchMode, matchEnd, ifNotFound) {
  if (text2 === undefined || delimiter === undefined) {
    return VALUE_ERROR7;
  }
  const textValue = coerceTextInput(text2);
  if (typeof textValue !== "string") {
    return textValue;
  }
  const delimiterValue = coerceDelimiterInput(delimiter);
  if (typeof delimiterValue !== "string") {
    return delimiterValue;
  }
  if (delimiterValue === "") {
    return VALUE_ERROR7;
  }
  const instanceValue = coerceInstanceNumber(instanceNum);
  if (typeof instanceValue !== "number") {
    return instanceValue;
  }
  const matchModeValue = coerceMatchMode(matchMode);
  if (typeof matchModeValue !== "number") {
    return matchModeValue;
  }
  const matchEndValue = coerceBooleanFlag2(matchEnd, false);
  if (typeof matchEndValue !== "boolean") {
    return matchEndValue;
  }
  const matches = findDelimiterMatches(textValue, delimiterValue, matchModeValue === 1);
  const target = selectDelimiterMatch(matches, instanceValue, matchEndValue, textValue.length);
  if (!target) {
    return resolveIfNotFoundValue(ifNotFound);
  }
  return textValue.slice(0, target.index);
}
function TEXTAFTER(text2, delimiter, instanceNum, matchMode, matchEnd, ifNotFound) {
  if (text2 === undefined || delimiter === undefined) {
    return VALUE_ERROR7;
  }
  const textValue = coerceTextInput(text2);
  if (typeof textValue !== "string") {
    return textValue;
  }
  const delimiterValue = coerceDelimiterInput(delimiter);
  if (typeof delimiterValue !== "string") {
    return delimiterValue;
  }
  if (delimiterValue === "") {
    return VALUE_ERROR7;
  }
  const instanceValue = coerceInstanceNumber(instanceNum);
  if (typeof instanceValue !== "number") {
    return instanceValue;
  }
  const matchModeValue = coerceMatchMode(matchMode);
  if (typeof matchModeValue !== "number") {
    return matchModeValue;
  }
  const matchEndValue = coerceBooleanFlag2(matchEnd, false);
  if (typeof matchEndValue !== "boolean") {
    return matchEndValue;
  }
  const matches = findDelimiterMatches(textValue, delimiterValue, matchModeValue === 1);
  const target = selectDelimiterMatch(matches, instanceValue, matchEndValue, textValue.length);
  if (!target) {
    return resolveIfNotFoundValue(ifNotFound);
  }
  return textValue.slice(target.index + target.length);
}
function TEXTSPLIT(text2, colDelimiter, rowDelimiter, ignoreEmpty, matchMode, padWith) {
  const textValue = coerceTextInput(text2);
  if (typeof textValue !== "string") {
    return textValue;
  }
  const columnDelimiterResult = normalizeDelimiterArgument(colDelimiter);
  if (!Array.isArray(columnDelimiterResult)) {
    return columnDelimiterResult;
  }
  const filteredColumnDelimiters = columnDelimiterResult.filter((entry) => entry !== "");
  if (filteredColumnDelimiters.length === 0) {
    return VALUE_ERROR7;
  }
  const rowDelimiterResult = rowDelimiter === undefined ? [] : normalizeDelimiterArgument(rowDelimiter);
  if (!Array.isArray(rowDelimiterResult)) {
    return rowDelimiterResult;
  }
  const filteredRowDelimiters = rowDelimiterResult.filter((entry) => entry !== "");
  const ignoreEmptyResult = coerceBooleanFlag2(ignoreEmpty, true);
  if (typeof ignoreEmptyResult !== "boolean") {
    return ignoreEmptyResult;
  }
  const matchModeResult = coerceMatchMode(matchMode);
  if (typeof matchModeResult !== "number") {
    return matchModeResult;
  }
  const padWithResult = coercePadWith(padWith);
  if (typeof padWithResult !== "string") {
    return padWithResult;
  }
  const caseInsensitive = matchModeResult === 1;
  const rowChunksRaw = filteredRowDelimiters.length > 0 ? splitWithDelimiters(textValue, filteredRowDelimiters, caseInsensitive) : [textValue];
  const rowChunks = filteredRowDelimiters.length > 0 && ignoreEmptyResult ? rowChunksRaw.filter((chunk) => chunk !== "") : rowChunksRaw;
  if (rowChunks.length === 0) {
    return makeArrayValue([[]]);
  }
  const processedRows = [];
  let maxColumns = 0;
  for (const chunk of rowChunks) {
    const columns = splitWithDelimiters(chunk, filteredColumnDelimiters, caseInsensitive);
    const normalizedColumns = ignoreEmptyResult ? columns.filter((value2) => value2 !== "") : columns;
    if (normalizedColumns.length > maxColumns) {
      maxColumns = normalizedColumns.length;
    }
    processedRows.push(normalizedColumns);
  }
  if (maxColumns === 0) {
    return makeArrayValue([[]]);
  }
  const rows = processedRows.map((row2) => {
    const next2 = row2.map((value2) => value2);
    while (next2.length < maxColumns) {
      next2.push(padWithResult);
    }
    return next2;
  });
  return makeArrayValue(rows);
}
function VALUETOTEXT(value2, format2) {
  return formatValueArgument(value2, format2);
}
function ARRAYTOTEXT(array3, format2) {
  return formatValueArgument(array3, format2);
}
function TRANSLATE(text2, sourceLanguage, targetLanguage) {
  throw new Error(`TRANSLATE is not implemented. text=${String(text2)}, sourceLanguage=${String(sourceLanguage)}, targetLanguage=${String(targetLanguage)}`);
}
function DETECTLANGUAGE(text2) {
  throw new Error(`DETECTLANGUAGE is not implemented. text=${String(text2)}`);
}
function REGEXTEST(text2, pattern, caseSensitivity) {
  if (text2 === undefined || pattern === undefined) {
    return VALUE_ERROR7;
  }
  const textValue = coerceTextInput(text2);
  if (typeof textValue !== "string") {
    return textValue;
  }
  const patternValue = coerceTextInput(pattern);
  if (typeof patternValue !== "string") {
    return patternValue;
  }
  const caseMode = coerceRegexCaseMode(caseSensitivity);
  if (typeof caseMode !== "number") {
    return caseMode;
  }
  const regex = buildRegex(patternValue, caseMode === 1, false);
  if (!regex) {
    return VALUE_ERROR7;
  }
  return regex.test(textValue);
}
function REGEXREPLACE(text2, pattern, replacement, occurrence, caseSensitivity) {
  if (text2 === undefined || pattern === undefined || replacement === undefined) {
    return VALUE_ERROR7;
  }
  const textValue = coerceTextInput(text2);
  if (typeof textValue !== "string") {
    return textValue;
  }
  const patternValue = coerceTextInput(pattern);
  if (typeof patternValue !== "string") {
    return patternValue;
  }
  const replacementValue = coerceTextInput(replacement);
  if (typeof replacementValue !== "string") {
    return replacementValue;
  }
  const caseMode = coerceRegexCaseMode(caseSensitivity);
  if (typeof caseMode !== "number") {
    return caseMode;
  }
  const occurrenceValue = coerceRegexOccurrence(occurrence);
  if (typeof occurrenceValue !== "number") {
    return occurrenceValue;
  }
  const globalRegex = buildRegex(patternValue, caseMode === 1, true);
  if (!globalRegex) {
    return VALUE_ERROR7;
  }
  const matches = collectRegexMatches(textValue, globalRegex);
  if (matches.length === 0) {
    return textValue;
  }
  if (occurrenceValue === 0) {
    return replaceMatchesFromCollection(textValue, matches, () => true, replacementValue);
  }
  const targetIndex = occurrenceValue > 0 ? occurrenceValue - 1 : matches.length + occurrenceValue;
  if (targetIndex < 0 || targetIndex >= matches.length) {
    return textValue;
  }
  return replaceMatchesFromCollection(textValue, matches, (index) => index === targetIndex, replacementValue);
}
function REGEXEXTRACT(text2, pattern, returnMode, caseSensitivity) {
  if (text2 === undefined || pattern === undefined) {
    return VALUE_ERROR7;
  }
  const textValue = coerceTextInput(text2);
  if (typeof textValue !== "string") {
    return textValue;
  }
  const patternValue = coerceTextInput(pattern);
  if (typeof patternValue !== "string") {
    return patternValue;
  }
  const modeValue = coerceRegexReturnMode(returnMode);
  if (typeof modeValue !== "number") {
    return modeValue;
  }
  const caseMode = coerceRegexCaseMode(caseSensitivity);
  if (typeof caseMode !== "number") {
    return caseMode;
  }
  const regex = buildRegex(patternValue, caseMode === 1, true);
  if (!regex) {
    return VALUE_ERROR7;
  }
  const matches = collectRegexMatches(textValue, regex);
  if (matches.length === 0) {
    return NA_ERROR3;
  }
  if (modeValue === 0) {
    return matches[0][0];
  }
  const extracted = matches.map((match) => match[0] ?? "");
  if (modeValue === 1) {
    return makeArrayValue(extracted.map((entry) => [entry]));
  }
  return makeArrayValue([extracted]);
}
function coerceTextInput(arg) {
  const scalar = extractScalar2(arg);
  if (isErrorValue6(scalar)) {
    return scalar;
  }
  return scalarToString(scalar);
}
function normalizeDelimiterArgument(arg) {
  if (Array.isArray(arg)) {
    const values = [];
    for (const row2 of arg) {
      if (!row2) {
        continue;
      }
      for (const cell of row2) {
        if (cell === undefined) {
          continue;
        }
        const normalized = normalizeScalar2(cell ?? "");
        if (isErrorValue6(normalized)) {
          return normalized;
        }
        const asText2 = scalarToString(normalized);
        if (typeof asText2 !== "string") {
          return asText2;
        }
        values.push(asText2);
      }
    }
    return values;
  }
  const scalar = normalizeScalar2(arg);
  if (isErrorValue6(scalar)) {
    return scalar;
  }
  const asText = scalarToString(scalar);
  return typeof asText === "string" ? [asText] : asText;
}
function coerceBooleanFlag2(arg, fallback) {
  if (arg === undefined) {
    return fallback;
  }
  const scalar = extractScalar2(arg);
  if (isErrorValue6(scalar)) {
    return scalar;
  }
  if (scalar === null || scalar === "") {
    return false;
  }
  if (typeof scalar === "boolean") {
    return scalar;
  }
  if (typeof scalar === "number") {
    if (!Number.isFinite(scalar)) {
      return VALUE_ERROR7;
    }
    return scalar !== 0;
  }
  if (typeof scalar === "string") {
    const normalized = scalar.trim().toUpperCase();
    if (normalized === "TRUE" || normalized === "1") {
      return true;
    }
    if (normalized === "FALSE" || normalized === "0") {
      return false;
    }
  }
  return VALUE_ERROR7;
}
function coerceMatchMode(arg) {
  if (arg === undefined) {
    return 0;
  }
  const scalar = extractScalar2(arg);
  if (isErrorValue6(scalar)) {
    return scalar;
  }
  if (scalar === null || scalar === "") {
    return 0;
  }
  if (typeof scalar === "boolean") {
    return scalar ? 1 : 0;
  }
  if (typeof scalar === "number") {
    if (scalar === 0 || scalar === 1) {
      return scalar;
    }
    return VALUE_ERROR7;
  }
  if (typeof scalar === "string") {
    const parsed = Number(scalar);
    if (parsed === 0 || parsed === 1) {
      return parsed;
    }
  }
  return VALUE_ERROR7;
}
function coercePadWith(arg) {
  if (arg === undefined) {
    return "";
  }
  const scalar = extractScalar2(arg);
  if (isErrorValue6(scalar)) {
    return scalar;
  }
  return scalarToString(scalar);
}
function splitWithDelimiters(text2, delimiters, ignoreCase) {
  if (delimiters.length === 0) {
    return [text2];
  }
  const pattern = delimiters.map(escapeRegExp2).join("|");
  if (!pattern) {
    return [text2];
  }
  const flags = ignoreCase ? "gi" : "g";
  const regex = new RegExp(pattern, flags);
  return text2.split(regex);
}
function escapeRegExp2(value2) {
  return value2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function extractScalar2(arg) {
  if (Array.isArray(arg)) {
    for (const row2 of arg) {
      if (!row2) {
        continue;
      }
      for (const cell of row2) {
        if (cell !== undefined) {
          return normalizeScalar2(cell ?? "");
        }
      }
    }
    return "";
  }
  return normalizeScalar2(arg);
}
function normalizeScalar2(value2) {
  if (value2 instanceof Error) {
    return VALUE_ERROR7;
  }
  if (isLambdaValue5(value2)) {
    return VALUE_ERROR7;
  }
  return value2;
}
function scalarToString(value2) {
  if (isErrorValue6(value2)) {
    return value2;
  }
  if (value2 === null) {
    return "";
  }
  return String(value2);
}
function isErrorValue6(value2) {
  return typeof value2 === "object" && value2 !== null && value2.kind === "Error";
}
function isLambdaValue5(value2) {
  return typeof value2 === "object" && value2 !== null && value2.kind === "Lambda";
}
function coerceDelimiterInput(arg) {
  const scalar = extractScalar2(arg);
  if (isErrorValue6(scalar)) {
    return scalar;
  }
  const text2 = scalarToString(scalar);
  return typeof text2 === "string" ? text2 : text2;
}
function coerceInstanceNumber(arg) {
  if (arg === undefined) {
    return 1;
  }
  const scalar = extractScalar2(arg);
  if (isErrorValue6(scalar)) {
    return scalar;
  }
  if (scalar === null || scalar === "") {
    return 1;
  }
  if (typeof scalar === "boolean") {
    return scalar ? 1 : VALUE_ERROR7;
  }
  const numeric = Number(scalar);
  if (!Number.isFinite(numeric) || !Number.isInteger(numeric) || numeric === 0) {
    return VALUE_ERROR7;
  }
  return numeric;
}
function resolveIfNotFoundValue(arg) {
  if (arg === undefined) {
    return NA_ERROR3;
  }
  return extractScalar2(arg);
}
function findDelimiterMatches(text2, delimiter, ignoreCase) {
  if (delimiter === "") {
    return [];
  }
  const haystack = ignoreCase ? text2.toLowerCase() : text2;
  const needle = ignoreCase ? delimiter.toLowerCase() : delimiter;
  const matches = [];
  let index = 0;
  while (index <= haystack.length - needle.length) {
    const nextIndex = haystack.indexOf(needle, index);
    if (nextIndex === -1) {
      break;
    }
    matches.push({ index: nextIndex, length: delimiter.length });
    index = nextIndex + needle.length;
    if (needle.length === 0) {
      index += 1;
    }
  }
  return matches;
}
function selectDelimiterMatch(matches, instanceNum, matchEnd, textLength) {
  let pool = matches;
  if (matchEnd && (matches.length === 0 || Math.abs(instanceNum) > matches.length)) {
    pool = [...matches, { index: textLength, length: 0 }];
  }
  if (pool.length === 0) {
    return null;
  }
  if (instanceNum > 0) {
    const idx2 = instanceNum - 1;
    return pool[idx2] ?? null;
  }
  const idx = pool.length + instanceNum;
  if (idx < 0 || idx >= pool.length) {
    return null;
  }
  return pool[idx] ?? null;
}
function formatValueArgument(value2, format2) {
  if (value2 === undefined) {
    return VALUE_ERROR7;
  }
  const formatMode = coerceFormatMode(format2);
  if (typeof formatMode !== "number") {
    return formatMode;
  }
  const normalized = normalizeValueArgument(value2);
  if (normalized.kind === "Error") {
    return normalized;
  }
  if (normalized.kind === "scalar") {
    return formatScalarValue(normalized.value, formatMode === 1);
  }
  return formatMode === 0 ? formatConciseGrid(normalized.grid) : formatStrictGrid(normalized.grid);
}
function coerceFormatMode(arg) {
  if (arg === undefined) {
    return 0;
  }
  const scalar = extractScalar2(arg);
  if (isErrorValue6(scalar)) {
    return scalar;
  }
  if (scalar === null || scalar === "") {
    return 0;
  }
  if (typeof scalar === "boolean") {
    return scalar ? 1 : 0;
  }
  const numeric = Number(scalar);
  if (numeric === 0 || numeric === 1) {
    return numeric;
  }
  return VALUE_ERROR7;
}
function normalizeValueArgument(value2) {
  if (Array.isArray(value2)) {
    return {
      kind: "grid",
      grid: value2.map((row2) => normalizeRow(row2))
    };
  }
  const scalar = normalizeScalar2(value2);
  if (isArrayValue(scalar)) {
    const rows = scalar.values.map((row2) => row2.map((cell) => normalizeScalar2(cell ?? null)));
    return { kind: "grid", grid: rows };
  }
  return { kind: "scalar", value: scalar };
}
function normalizeRow(row2) {
  if (!row2) {
    return [];
  }
  return row2.map((cell) => normalizeScalar2(cell ?? null));
}
function formatScalarValue(value2, strict) {
  if (isErrorValue6(value2)) {
    return value2.code;
  }
  if (isArrayValue(value2)) {
    return VALUE_ERROR7;
  }
  if (value2 === null) {
    return "";
  }
  if (typeof value2 === "string") {
    return strict ? `"${value2.replace(/"/g, '""')}"` : value2;
  }
  if (typeof value2 === "boolean") {
    return value2 ? "TRUE" : "FALSE";
  }
  return String(value2);
}
function formatConciseGrid(grid2) {
  if (grid2.length === 0) {
    return "";
  }
  const pieces = [];
  for (const row2 of grid2) {
    const source = row2 ?? [];
    for (const cell of source) {
      const formatted = formatScalarValue(cell ?? null, false);
      if (isErrorValue6(formatted)) {
        return formatted;
      }
      pieces.push(formatted);
    }
  }
  return pieces.join(", ");
}
function formatStrictGrid(grid2) {
  if (grid2.length === 0) {
    return "{}";
  }
  const rows = [];
  for (const row2 of grid2) {
    const source = row2 ?? [];
    const formattedRow = [];
    for (const cell of source) {
      const formatted = formatScalarValue(cell ?? null, true);
      if (isErrorValue6(formatted)) {
        return formatted;
      }
      formattedRow.push(formatted);
    }
    rows.push(formattedRow.join(","));
  }
  return `{${rows.join(";")}}`;
}
function coerceRegexCaseMode(arg) {
  if (arg === undefined) {
    return 0;
  }
  const scalar = extractScalar2(arg);
  if (isErrorValue6(scalar)) {
    return scalar;
  }
  if (scalar === null || scalar === "") {
    return 0;
  }
  if (typeof scalar === "boolean") {
    return scalar ? 1 : 0;
  }
  const numeric = Number(scalar);
  if (numeric === 0 || numeric === 1) {
    return numeric;
  }
  return VALUE_ERROR7;
}
function coerceRegexReturnMode(arg) {
  if (arg === undefined) {
    return 0;
  }
  const scalar = extractScalar2(arg);
  if (isErrorValue6(scalar)) {
    return scalar;
  }
  if (scalar === null || scalar === "") {
    return 0;
  }
  if (typeof scalar === "boolean") {
    return scalar ? 1 : 0;
  }
  const numeric = Number(scalar);
  if (numeric === 0 || numeric === 1 || numeric === 2) {
    return numeric;
  }
  return VALUE_ERROR7;
}
function coerceRegexOccurrence(arg) {
  if (arg === undefined) {
    return 1;
  }
  const scalar = extractScalar2(arg);
  if (isErrorValue6(scalar)) {
    return scalar;
  }
  if (scalar === null || scalar === "") {
    return 1;
  }
  if (typeof scalar === "boolean") {
    return scalar ? 1 : 0;
  }
  const numeric = Number(scalar);
  if (!Number.isFinite(numeric) || !Number.isInteger(numeric)) {
    return VALUE_ERROR7;
  }
  return numeric;
}
function buildRegex(pattern, ignoreCase, global2) {
  let flags = "";
  if (global2) {
    flags += "g";
  }
  if (ignoreCase) {
    flags += "i";
  }
  try {
    return new RegExp(pattern, flags);
  } catch {
    return null;
  }
}
function collectRegexMatches(text2, regex) {
  const matches = [];
  let next2;
  while ((next2 = regex.exec(text2)) !== null) {
    matches.push(next2);
    if (next2[0] === "") {
      if (regex.lastIndex >= text2.length) {
        break;
      }
      regex.lastIndex += 1;
    }
  }
  return matches;
}
function replaceMatchesFromCollection(text2, matches, predicate, template) {
  if (matches.length === 0) {
    return text2;
  }
  let cursor = 0;
  let output = "";
  for (let idx = 0;idx < matches.length; idx += 1) {
    const match = matches[idx];
    const matchText = match[0] ?? "";
    const startIndex = match.index ?? 0;
    const endIndex = startIndex + matchText.length;
    output += text2.slice(cursor, startIndex);
    if (predicate(idx)) {
      const groups = match.slice(1).map((entry) => entry ?? "");
      output += applyReplacementTemplate(template, matchText, groups);
    } else {
      output += matchText;
    }
    cursor = endIndex;
  }
  output += text2.slice(cursor);
  return output;
}
function applyReplacementTemplate(template, matchText, captureGroups) {
  let result = "";
  for (let idx = 0;idx < template.length; idx += 1) {
    const char = template[idx];
    if (char === "$") {
      const nextChar = template[idx + 1];
      if (nextChar === "$") {
        result += "$";
        idx += 1;
        continue;
      }
      let digits = "";
      let lookahead = idx + 1;
      while (lookahead < template.length && /[0-9]/.test(template[lookahead])) {
        digits += template[lookahead];
        lookahead += 1;
      }
      if (digits) {
        const index = Number(digits);
        if (index === 0) {
          result += matchText;
        } else if (index > 0 && index <= captureGroups.length) {
          result += captureGroups[index - 1] ?? "";
        }
        idx = lookahead - 1;
        continue;
      }
    }
    result += char;
  }
  return result;
}
// node_modules/@oai/granola/dist/models/spreadsheet/engine/formulas/index.js
var FORMULAS_REGISTRY = {
  STDEV: STDEV2,
  VAR: VAR2,
  STDEVP: STDEVP2,
  VARP: VARP2,
  RANK: RANK2,
  BETADIST: BETADIST2,
  BETAINV: BETAINV2,
  BINOMDIST: BINOMDIST2,
  CHIDIST: CHIDIST2,
  CHIINV: CHIINV2,
  CONFIDENCE: CONFIDENCE2,
  CRITBINOM: CRITBINOM2,
  EXPONDIST: EXPONDIST2,
  FDIST: FDIST2,
  FINV: FINV2,
  FLOOR: FLOOR2,
  GAMMADIST: GAMMADIST2,
  GAMMAINV: GAMMAINV2,
  CEILING: CEILING2,
  HYPGEOMDIST: HYPGEOMDIST2,
  LOGNORMDIST: LOGNORMDIST2,
  LOGINV: LOGINV2,
  NEGBINOMDIST: NEGBINOMDIST2,
  NORMDIST: NORMDIST2,
  NORMSDIST: NORMSDIST2,
  NORMINV: NORMINV2,
  NORMSINV: NORMSINV2,
  POISSON: POISSON2,
  TDIST: TDIST2,
  WEIBULL: WEIBULL2,
  CHITEST: CHITEST2,
  COVAR: COVAR2,
  FORECAST: FORECAST2,
  FTEST: FTEST2,
  TTEST: TTEST2,
  ZTEST: ZTEST2,
  QUARTILE: QUARTILE2,
  PERCENTILE: PERCENTILE2,
  PERCENTRANK: PERCENTRANK2,
  MODE: MODE2,
  TINV: TINV2,
  CONCATENATE: CONCATENATE2,
  CUBEVALUE,
  CUBEMEMBER,
  CUBEMEMBERPROPERTY,
  CUBERANKEDMEMBER,
  CUBEKPIMEMBER,
  CUBESET,
  CUBESETCOUNT,
  DCOUNT: DCOUNT2,
  DSUM,
  DAVERAGE: DAVERAGE2,
  DMIN: DMIN2,
  DMAX: DMAX2,
  DSTDEV: DSTDEV2,
  DVAR: DVAR2,
  DPRODUCT: DPRODUCT2,
  DSTDEVP: DSTDEVP2,
  DVARP: DVARP2,
  DCOUNTA: DCOUNTA2,
  DGET: DGET2,
  DATE: DATE2,
  TIME: TIME2,
  DAY: DAY2,
  MONTH: MONTH2,
  YEAR: YEAR2,
  WEEKDAY: WEEKDAY2,
  HOUR: HOUR2,
  MINUTE: MINUTE2,
  SECOND: SECOND2,
  NOW: NOW2,
  DATEVALUE: DATEVALUE2,
  TIMEVALUE: TIMEVALUE2,
  DAYS360: DAYS3602,
  TODAY: TODAY2,
  EDATE: EDATE2,
  EOMONTH: EOMONTH2,
  YEARFRAC: YEARFRAC2,
  WEEKNUM: WEEKNUM2,
  WORKDAY: WORKDAY2,
  NETWORKDAYS: NETWORKDAYS2,
  NETWORKDAYS_INTL,
  WORKDAY_INTL,
  DAYS: DAYS2,
  ISOWEEKNUM: ISOWEEKNUM2,
  HEX2BIN: HEX2BIN2,
  HEX2DEC: HEX2DEC2,
  HEX2OCT: HEX2OCT2,
  DEC2BIN: DEC2BIN2,
  DEC2HEX: DEC2HEX2,
  DEC2OCT: DEC2OCT2,
  OCT2BIN: OCT2BIN2,
  OCT2HEX: OCT2HEX2,
  OCT2DEC: OCT2DEC2,
  BIN2DEC: BIN2DEC2,
  BIN2OCT: BIN2OCT2,
  BIN2HEX: BIN2HEX2,
  IMSUB: IMSUB2,
  IMDIV: IMDIV2,
  IMPOWER: IMPOWER2,
  IMABS: IMABS2,
  IMSQRT: IMSQRT2,
  IMLN: IMLN2,
  IMLOG2: IMLOG22,
  IMLOG10: IMLOG102,
  IMSIN: IMSIN2,
  IMCOS: IMCOS2,
  IMEXP: IMEXP2,
  IMARGUMENT: IMARGUMENT2,
  IMCONJUGATE: IMCONJUGATE2,
  IMAGINARY: IMAGINARY2,
  IMREAL: IMREAL2,
  COMPLEX: COMPLEX2,
  IMSUM: IMSUM2,
  IMPRODUCT: IMPRODUCT2,
  DELTA: DELTA2,
  GESTEP: GESTEP2,
  ERF: ERF2,
  ERFC: ERFC2,
  BESSELJ: BESSELJ2,
  BESSELK: BESSELK2,
  BESSELY: BESSELY2,
  BESSELI: BESSELI2,
  CONVERT: CONVERT2,
  ERF_PRECISE,
  ERFC_PRECISE,
  IMTAN: IMTAN2,
  IMCOT: IMCOT2,
  IMCSC: IMCSC2,
  IMCSCH: IMCSCH2,
  IMSEC: IMSEC2,
  IMSECH: IMSECH2,
  BITAND: BITAND2,
  BITOR: BITOR2,
  BITXOR: BITXOR2,
  BITLSHIFT: BITLSHIFT2,
  BITRSHIFT: BITRSHIFT2,
  IMSINH: IMSINH2,
  IMCOSH: IMCOSH2,
  NPV: NPV2,
  PV: PV2,
  FV: FV2,
  NPER: NPER2,
  PMT: PMT2,
  RATE: RATE2,
  MIRR: MIRR2,
  IRR: IRR2,
  SLN: SLN2,
  SYD: SYD2,
  DDB: DDB2,
  IPMT: IPMT2,
  PPMT: PPMT2,
  VDB,
  DB: DB2,
  ISPMT: ISPMT2,
  XIRR: XIRR2,
  XNPV: XNPV2,
  PRICEMAT,
  YIELDMAT,
  INTRATE,
  RECEIVED,
  DISC: DISC2,
  PRICEDISC: PRICEDISC2,
  YIELDDISC,
  TBILLEQ: TBILLEQ2,
  TBILLPRICE: TBILLPRICE2,
  TBILLYIELD: TBILLYIELD2,
  PRICE,
  YIELD,
  DOLLARDE: DOLLARDE2,
  DOLLARFR: DOLLARFR2,
  NOMINAL: NOMINAL2,
  EFFECT: EFFECT2,
  CUMPRINC: CUMPRINC2,
  CUMIPMT: CUMIPMT2,
  COUPDAYBS,
  COUPDAYS: COUPDAYS2,
  COUPDAYSNC,
  COUPNCD,
  COUPNUM,
  COUPPCD,
  DURATION,
  MDURATION,
  ODDLPRICE,
  ODDLYIELD,
  ODDFPRICE,
  ODDFYIELD,
  AMORLINC,
  ACCRINT: ACCRINT2,
  ACCRINTM,
  FVSCHEDULE: FVSCHEDULE2,
  PDURATION: PDURATION2,
  RRI: RRI2,
  STOCKHISTORY,
  ISNA: ISNA2,
  ISERROR: ISERROR2,
  NA: NA2,
  TYPE: TYPE2,
  ISREF,
  ISERR: ISERR2,
  ISTEXT: ISTEXT2,
  ISNUMBER: ISNUMBER2,
  ISBLANK,
  N: N2,
  ISNONTEXT: ISNONTEXT2,
  ISLOGICAL: ISLOGICAL2,
  ERROR_TYPE,
  ISEVEN: ISEVEN2,
  ISODD: ISODD2,
  SHEET,
  SHEETS,
  ISFORMULA,
  ISOMITTED,
  IF: IF2,
  TRUE: TRUE2,
  FALSE: FALSE2,
  AND: AND2,
  OR: OR2,
  NOT: NOT2,
  IFERROR,
  XOR: XOR2,
  IFNA,
  IFS: IFS2,
  _XLFN_IFS,
  SWITCH: SWITCH2,
  LET,
  LAMBDA,
  MAKEARRAY,
  MAP,
  REDUCE,
  SCAN,
  BYROW,
  BYCOL,
  ROW: ROW2,
  COLUMN: COLUMN2,
  LOOKUP: LOOKUP2,
  INDEX: INDEX2,
  MATCH: MATCH2,
  AREAS,
  ROWS: ROWS2,
  COLUMNS: COLUMNS2,
  OFFSET,
  TRANSPOSE: TRANSPOSE2,
  CHOOSE: CHOOSE2,
  HLOOKUP: HLOOKUP2,
  VLOOKUP: VLOOKUP2,
  INDIRECT,
  ADDRESS,
  GETPIVOTDATA,
  HYPERLINK,
  FORMULATEXT,
  FIELDVALUE,
  FILTER,
  SORT,
  UNIQUE: UNIQUE2,
  XMATCH,
  XLOOKUP,
  SORTBY,
  WRAPROWS,
  VSTACK,
  HSTACK,
  CHOOSEROWS,
  CHOOSECOLS,
  TOCOL,
  TOROW,
  WRAPCOLS,
  EXPAND,
  TAKE,
  DROP,
  PY,
  IMAGE,
  GROUPBY,
  PIVOTBY,
  TRIMRANGE,
  SUM: SUM2,
  SIN: SIN2,
  COS: COS2,
  TAN: TAN2,
  ATAN: ATAN3,
  PI: PI3,
  SQRT: SQRT2,
  EXP: EXP2,
  LN: LN2,
  LOG10: LOG102,
  ABS: ABS2,
  INT: INT2,
  SIGN: SIGN2,
  ROUND: ROUND2,
  MOD: MOD2,
  RAND: RAND2,
  ATAN2: ATAN22,
  ASIN: ASIN2,
  ACOS: ACOS2,
  LOG: LOG2,
  MDETERM,
  MINVERSE,
  MMULT: MMULT2,
  PRODUCT: PRODUCT2,
  FACT: FACT2,
  TRUNC: TRUNC2,
  ROUNDUP: ROUNDUP2,
  ROUNDDOWN: ROUNDDOWN2,
  SUMPRODUCT,
  SINH: SINH2,
  COSH: COSH2,
  TANH: TANH2,
  ASINH: ASINH2,
  ACOSH: ACOSH2,
  ATANH: ATANH2,
  COMBIN: COMBIN2,
  EVEN: EVEN2,
  ODD: ODD2,
  SUMXMY2: SUMXMY22,
  SUMX2MY2: SUMX2MY22,
  SUMX2PY2: SUMX2PY22,
  SUMSQ,
  POWER: POWER2,
  RADIANS: RADIANS2,
  DEGREES: DEGREES2,
  SUBTOTAL: SUBTOTAL2,
  SUMIF,
  ROMAN: ROMAN2,
  SERIESSUM: SERIESSUM2,
  FACTDOUBLE,
  SQRTPI: SQRTPI2,
  QUOTIENT,
  MROUND: MROUND2,
  RANDBETWEEN,
  GCD: GCD2,
  MULTINOMIAL: MULTINOMIAL2,
  LCM: LCM2,
  SUMIFS: SUMIFS2,
  AGGREGATE: AGGREGATE2,
  ACOT: ACOT2,
  ACOTH: ACOTH2,
  COT: COT2,
  COTH: COTH2,
  CSC: CSC2,
  CSCH: CSCH2,
  SEC: SEC2,
  SECH: SECH2,
  COMBINA: COMBINA2,
  BASE: BASE2,
  DECIMAL: DECIMAL2,
  MUNIT: MUNIT2,
  ARABIC: ARABIC2,
  CEILING_MATH,
  CEILING_PRECISE,
  FLOOR_MATH,
  FLOOR_PRECISE,
  RANDARRAY,
  SEQUENCE,
  PERCENTOF,
  ISO_CEILING,
  COUNT: COUNT2,
  AVERAGE: AVERAGE2,
  MIN: MIN2,
  MAX: MAX2,
  LINEST: LINEST2,
  TREND: TREND2,
  LOGEST: LOGEST2,
  GROWTH: GROWTH2,
  COUNTA: COUNTA2,
  MEDIAN: MEDIAN2,
  FREQUENCY: FREQUENCY2,
  AVEDEV: AVEDEV2,
  GAMMALN: GAMMALN2,
  FISHER: FISHER2,
  FISHERINV: FISHERINV2,
  STANDARDIZE: STANDARDIZE2,
  PERMUT: PERMUT2,
  CORREL: CORREL2,
  INTERCEPT: INTERCEPT2,
  PEARSON: PEARSON2,
  RSQ: RSQ2,
  STEYX: STEYX2,
  SLOPE: SLOPE2,
  PROB: PROB2,
  DEVSQ: DEVSQ2,
  GEOMEAN: GEOMEAN2,
  HARMEAN: HARMEAN2,
  KURT: KURT2,
  SKEW: SKEW2,
  LARGE: LARGE2,
  SMALL: SMALL2,
  TRIMMEAN: TRIMMEAN2,
  COUNTIF: COUNTIF2,
  COUNTBLANK: COUNTBLANK2,
  AVERAGEA: AVERAGEA2,
  MAXA: MAXA2,
  MINA: MINA2,
  STDEVPA: STDEVPA2,
  VARPA: VARPA2,
  STDEVA: STDEVA2,
  VARA: VARA2,
  COUNTIFS: COUNTIFS2,
  AVERAGEIF,
  AVERAGEIFS: AVERAGEIFS2,
  BINOM_DIST,
  BINOM_INV,
  CONFIDENCE_NORM,
  CONFIDENCE_T,
  CHISQ_TEST,
  F_TEST,
  COVARIANCE_P,
  COVARIANCE_S,
  EXPON_DIST,
  GAMMA_DIST,
  GAMMA_INV,
  MODE_MULT,
  MODE_SNGL,
  NORM_DIST,
  NORM_INV,
  PERCENTILE_EXC,
  PERCENTILE_INC,
  _XLFN_PERCENTILE_INC: PERCENTILE_INC,
  PERCENTRANK_EXC,
  PERCENTRANK_INC,
  POISSON_DIST,
  QUARTILE_EXC,
  _XLFN_QUARTILE_EXC: QUARTILE_EXC,
  QUARTILE_INC,
  _XLFN_QUARTILE_INC,
  RANK_AVG,
  RANK_EQ,
  STDEV_S,
  _XLFN_STDEV_S,
  STDEV_P,
  _XLFN_STDEV_P,
  T_DIST,
  T_DIST_2T,
  T_DIST_RT,
  T_INV,
  T_INV_2T,
  VAR_S,
  VAR_P,
  WEIBULL_DIST,
  BETA_DIST,
  BETA_INV,
  CHISQ_DIST,
  CHISQ_DIST_RT,
  CHISQ_INV,
  CHISQ_INV_RT,
  F_DIST,
  F_DIST_RT,
  F_INV,
  F_INV_RT,
  HYPGEOM_DIST,
  LOGNORM_DIST,
  LOGNORM_INV,
  NEGBINOM_DIST,
  NORM_S_DIST,
  NORM_S_INV,
  T_TEST,
  Z_TEST,
  GAMMALN_PRECISE,
  PERMUTATIONA: PERMUTATIONA2,
  BINOM_DIST_RANGE,
  GAMMA: GAMMA2,
  SKEW_P,
  GAUSS: GAUSS2,
  PHI: PHI3,
  FORECAST_LINEAR,
  _XLFN_FORECAST_LINEAR: FORECAST_LINEAR,
  MAXIFS: MAXIFS2,
  MINIFS: MINIFS2,
  DOLLAR: DOLLAR2,
  FIXED: FIXED2,
  REPT: REPT2,
  MID: MID2,
  LEN: LEN2,
  VALUE: VALUE2,
  TEXT: TEXT2,
  SEARCH: SEARCH2,
  CHAR: CHAR2,
  LOWER: LOWER2,
  UPPER: UPPER2,
  PROPER: PROPER2,
  LEFT: LEFT2,
  RIGHT: RIGHT2,
  EXACT: EXACT2,
  TRIM: TRIM2,
  REPLACE: REPLACE2,
  SUBSTITUTE: SUBSTITUTE2,
  CODE: CODE2,
  FIND: FIND2,
  T: T2,
  CLEAN: CLEAN2,
  BAHTTEXT,
  UNICHAR: UNICHAR2,
  UNICODE: UNICODE2,
  NUMBERVALUE: NUMBERVALUE2,
  TEXTJOIN: TEXTJOIN2,
  CONCAT: CONCAT2,
  TEXTBEFORE,
  TEXTAFTER,
  TEXTSPLIT,
  VALUETOTEXT,
  ARRAYTOTEXT,
  TRANSLATE,
  DETECTLANGUAGE,
  REGEXTEST,
  REGEXREPLACE,
  REGEXEXTRACT,
  _XLFN_XLOOKUP: XLOOKUP,
  _XLFN__XLWS_FILTER: FILTER,
  _XLFN__XLWS_SORT: SORT,
  _XLFN__XLWS_SORTBY: SORTBY,
  _XLFN__XLWS_TAKE: TAKE,
  _XLFN__XLWS_DROP: DROP,
  _XLFN__XLWS_CHOOSEROWS: CHOOSEROWS,
  _XLFN__XLWS_CHOOSECOLS: CHOOSECOLS,
  _XLFN__XLWS_VSTACK: VSTACK,
  _XLFN__XLWS_HSTACK: HSTACK,
  _XLFN__XLWS_TOCOL: TOCOL,
  _XLFN__XLWS_TOROW: TOROW,
  _XLFN__XLWS_EXPAND: EXPAND,
  _XLFN__XLWS_WRAPROWS: WRAPROWS,
  _XLFN__XLWS_WRAPCOLS: WRAPCOLS,
  _XLFN__XLWS_BYROW: BYROW,
  _XLFN__XLWS_BYCOL: BYCOL,
  _XLFN_TEXTSPLIT: TEXTSPLIT,
  _XLFN_DAYS: DAYS2,
  _XLFN_MAXIFS: MAXIFS2,
  _XLFN_CONCAT: CONCAT2,
  _XLFN_TEXTJOIN: TEXTJOIN2,
  _XLFN_UNIQUE: UNIQUE2,
  _XLFN_CEILING_PRECISE: CEILING_PRECISE,
  _XLFN_FLOOR_PRECISE: FLOOR_PRECISE,
  _XLFN_ISO_CEILING: ISO_CEILING
};
var FORMULAJS_ERRORS = utils?.errors ?? {};
function getFormulajsErrors() {
  return FORMULAJS_ERRORS;
}
function resolveFormulaFromRegistry(name2) {
  if (!name2) {
    return;
  }
  const normalized = name2.toUpperCase();
  const direct = FORMULAS_REGISTRY[normalized];
  if (direct) {
    return direct;
  }
  if (!normalized.includes(".")) {
    return;
  }
  const sanitized = normalized.replace(/\./g, "_");
  return FORMULAS_REGISTRY[sanitized];
}

// node_modules/@oai/granola/dist/models/spreadsheet/engine/function-registry.js
var FORMULAJS_ERRORS2 = getFormulajsErrors();
var ERROR_CODE_TO_FORMULAJS = new Map;
var FORMULAJS_ERROR_TO_CODE = new Map;
var KNOWN_ERRORS = [
  ["#NULL!", FORMULAJS_ERRORS2["nil"]],
  ["#DIV/0!", FORMULAJS_ERRORS2["div0"]],
  ["#VALUE!", FORMULAJS_ERRORS2["value"]],
  ["#REF!", FORMULAJS_ERRORS2["ref"]],
  ["#NAME?", FORMULAJS_ERRORS2["name"]],
  ["#NUM!", FORMULAJS_ERRORS2["num"]],
  ["#N/A", FORMULAJS_ERRORS2["na"]],
  ["#ERROR!", FORMULAJS_ERRORS2["error"]],
  ["#GETTING_DATA", FORMULAJS_ERRORS2["data"]]
];
for (const [code, err] of KNOWN_ERRORS) {
  if (err) {
    ERROR_CODE_TO_FORMULAJS.set(code, err);
    FORMULAJS_ERROR_TO_CODE.set(err, code);
  }
}
var DEFAULT_ERROR = { kind: "Error", code: "#VALUE!" };
var NUM_ERROR4 = { kind: "Error", code: "#NUM!" };
var NOT_IMPLEMENTED_ERROR = { kind: "Error", code: "#NAME?" };
var EXCEL_EPOCH_MS5 = Date.UTC(1899, 11, 30);
var MS_PER_DAY5 = 24 * 60 * 60 * 1000;
var PAIRED_RANGE_FUNCTIONS = {
  SLOPE: { dependentIndex: 0, independentIndex: 1 },
  INTERCEPT: { dependentIndex: 0, independentIndex: 1 },
  CORREL: { dependentIndex: 0, independentIndex: 1 },
  PEARSON: { dependentIndex: 0, independentIndex: 1 },
  RSQ: { dependentIndex: 0, independentIndex: 1 },
  STEYX: { dependentIndex: 0, independentIndex: 1 }
};
var RAW_ARGUMENT_FUNCTIONS = new Set([
  "COUNTA",
  "ISBLANK",
  "TYPE",
  "SUM",
  "UNIQUE",
  "BYROW",
  "_XLFN.BYROW",
  "BYCOL",
  "_XLFN.BYCOL",
  "COLUMN",
  "_XLFN.COLUMN",
  "ROW",
  "_XLFN.ROW",
  "COLUMNS",
  "_XLFN.COLUMNS",
  "ROWS",
  "_XLFN.ROWS",
  "AREAS",
  "_XLFN.AREAS"
]);
var TEXT_PRESERVING_FUNCTIONS = new Set([
  "ISTEXT",
  "_XLFN.ISTEXT",
  "ISNONTEXT",
  "_XLFN.ISNONTEXT",
  "ISNUMBER",
  "_XLFN.ISNUMBER",
  "ISLOGICAL",
  "_XLFN.ISLOGICAL",
  "ISERR",
  "_XLFN.ISERR",
  "ISERROR",
  "_XLFN.ISERROR",
  "ISNA",
  "_XLFN.ISNA",
  "DAVERAGE",
  "DCOUNT",
  "DCOUNTA",
  "DGET",
  "DMAX",
  "DMIN",
  "DPRODUCT",
  "DSTDEV",
  "DSTDEVP",
  "DSUM",
  "DVAR",
  "DVARP"
]);
function requiredArg(args2, index) {
  const value2 = args2[index];
  if (value2 === undefined) {
    return {
      __requiredArgError: true,
      error: { kind: "Error", code: "#VALUE!" }
    };
  }
  return value2;
}
function isRequiredArgError(value2) {
  return typeof value2 === "object" && value2 !== null && value2.__requiredArgError === true;
}
function optionalArg(args2, index, parse6, fallback) {
  const value2 = args2[index];
  return value2 === undefined ? fallback : parse6(value2);
}
function callSpreadsheetFunction(name2, args2) {
  const normalizedName = name2.toUpperCase();
  const canonicalName = canonicalizeFunctionName(normalizedName);
  const pairedConfig = PAIRED_RANGE_FUNCTIONS[canonicalName];
  let normalizedArgs = pairedConfig ? sanitizePairedRangeArgs(args2, pairedConfig) : args2;
  if (canonicalName === "AVERAGE") {
    normalizedArgs = sanitizeAverageArgs(normalizedArgs);
  }
  if (canonicalName === "AVERAGEIF") {
    normalizedArgs = sanitizeAverageIfArgs(normalizedArgs);
  }
  if (canonicalName === "AVERAGEIFS") {
    normalizedArgs = sanitizeAverageIfsArgs(normalizedArgs);
  }
  if (canonicalName === "MEDIAN") {
    normalizedArgs = sanitizeMedianArgs(normalizedArgs);
  }
  if (canonicalName === "SUMIF") {
    normalizedArgs = sanitizeSumIfArgs(normalizedArgs);
  }
  if (canonicalName === "SUMIFS") {
    normalizedArgs = sanitizeSumIfsArgs(normalizedArgs);
  }
  if (canonicalName === "NORMSDIST") {
    return evaluateStandardNormal(normalizedArgs, false);
  }
  if (canonicalName === "NORM.S.DIST") {
    return evaluateStandardNormal(normalizedArgs, true);
  }
  if (canonicalName === "TEXT") {
    return evaluateTextFunction(normalizedArgs);
  }
  if (canonicalName === "ROUND") {
    return evaluateRoundFunction(normalizedArgs);
  }
  if (canonicalName === "RATE") {
    const rateResult = evaluateRateSpecialCase(normalizedArgs);
    if (rateResult != null) {
      return rateResult;
    }
  }
  const fn = resolveFunction(canonicalName);
  if (!fn) {
    return NOT_IMPLEMENTED_ERROR;
  }
  try {
    const skipConversion = RAW_ARGUMENT_FUNCTIONS.has(canonicalName);
    const preserveText = TEXT_PRESERVING_FUNCTIONS.has(canonicalName);
    const convertedArgs = skipConversion ? normalizedArgs : normalizedArgs.map((arg) => convertArgumentForFormulajs(arg, preserveText));
    const result = fn(...convertedArgs);
    if (isArrayResult(result)) {
      return result;
    }
    if (Array.isArray(result)) {
      return convertResultFromFormulajs(result);
    }
    const final = convertResultFromFormulajs(result);
    return final;
  } catch (err) {
    return convertThrownError(err);
  }
}
function resolveFunction(name2) {
  return resolveFormulaFromRegistry(name2);
}
function convertArgumentForFormulajs(value2, preserveText) {
  if (value2 === undefined) {
    return;
  }
  if (isArrayFunctionArg(value2)) {
    return value2.values.map((row2) => row2.map((cell) => convertScalarValueForFormulajs(cell, preserveText)));
  }
  if (Array.isArray(value2)) {
    const singleCell = extractSingleCellFromGrid(value2);
    if (singleCell !== undefined) {
      return convertScalarValueForFormulajs(singleCell, preserveText);
    }
    const converted = value2.map((row2) => row2.map((cell) => convertScalarValueForFormulajs(cell, preserveText)));
    copyRangeMetadata(value2, converted);
    return converted;
  }
  if (isScalarFunctionArg(value2)) {
    return convertScalarValueForFormulajs(value2, preserveText);
  }
  return;
}
function convertScalarValueForFormulajs(value2, preserveText) {
  if (isErrorValue7(value2)) {
    return ERROR_CODE_TO_FORMULAJS.get(value2.code) ?? new Error(value2.code);
  }
  if (isLambdaValue6(value2)) {
    return new Error("#VALUE!");
  }
  if (typeof value2 === "string" && !preserveText) {
    const trimmed = value2.trim();
    if (trimmed === "" && value2 !== "") {
      return value2;
    }
    if (trimmed !== "") {
      const parsed = Number(trimmed);
      if (Number.isFinite(parsed)) {
        return parsed;
      }
    }
  }
  return value2;
}
function extractSingleCellFromGrid(grid2) {
  if (grid2.length !== 1) {
    return;
  }
  const [row2] = grid2;
  if (!row2 || row2.length !== 1) {
    return;
  }
  return row2[0] ?? null;
}
function convertResultFromFormulajs(result) {
  if (Array.isArray(result)) {
    const normalizedRows = result.map((row2) => Array.isArray(row2) ? row2.map(convertScalarResultFromFormulajs) : [convertScalarResultFromFormulajs(row2)]);
    return makeArrayValue(normalizedRows);
  }
  return convertScalarResultFromFormulajs(result);
}
function convertScalarResultFromFormulajs(result) {
  if (isErrorValue7(result)) {
    return result;
  }
  if (isFormulajsError(result)) {
    return {
      kind: "Error",
      code: FORMULAJS_ERROR_TO_CODE.get(result) ?? result.message ?? DEFAULT_ERROR.code
    };
  }
  if (result instanceof Date) {
    return excelSerialFromDate(result);
  }
  const primitive = result;
  if (primitive === null || primitive === undefined) {
    return "";
  }
  if (typeof primitive === "number" || typeof primitive === "string" || typeof primitive === "boolean") {
    if (typeof primitive === "number" && !Number.isFinite(primitive)) {
      return NUM_ERROR4;
    }
    return primitive;
  }
  return DEFAULT_ERROR;
}
function excelSerialFromDate(date6) {
  const year = date6.getFullYear();
  const month = date6.getMonth();
  const day = date6.getDate();
  const utcTimestamp = Date.UTC(year, month, day);
  return (utcTimestamp - EXCEL_EPOCH_MS5) / MS_PER_DAY5;
}
function evaluateTextFunction(args2) {
  if (args2.length < 2) {
    return { kind: "Error", code: "#VALUE!" };
  }
  const valueResult = requiredArg(args2, 0);
  if (isRequiredArgError(valueResult)) {
    return valueResult.error;
  }
  const formatResult = requiredArg(args2, 1);
  if (isRequiredArgError(formatResult)) {
    return formatResult.error;
  }
  const valueArg = coerceScalarArg(valueResult);
  if (isErrorValue7(valueArg)) {
    return valueArg;
  }
  const formatArg = coerceScalarArg(formatResult);
  if (isErrorValue7(formatArg)) {
    return formatArg;
  }
  if (typeof formatArg !== "string") {
    return { kind: "Error", code: "#VALUE!" };
  }
  let formattedInput;
  if (valueArg instanceof Date) {
    formattedInput = excelSerialFromDate(valueArg);
  } else if (typeof valueArg === "string") {
    const numericValue = Number(valueArg);
    formattedInput = Number.isFinite(numericValue) ? numericValue : valueArg;
  } else {
    formattedInput = valueArg;
  }
  try {
    const formatted = SSF6.format(formatArg, formattedInput);
    return formatted;
  } catch {
    return { kind: "Error", code: "#VALUE!" };
  }
}
function evaluateRoundFunction(args2) {
  if (args2.length === 0) {
    return { kind: "Error", code: "#VALUE!" };
  }
  const numberArg = requiredArg(args2, 0);
  if (isRequiredArgError(numberArg)) {
    return numberArg.error;
  }
  const numberValue = coerceNumberArg3(numberArg);
  if (!Number.isFinite(numberValue)) {
    return { kind: "Error", code: "#VALUE!" };
  }
  const digitsValue = optionalArg(args2, 1, coerceNumberArg3, 0);
  if (!Number.isFinite(digitsValue)) {
    return { kind: "Error", code: "#VALUE!" };
  }
  const digitsInt = Math.trunc(digitsValue);
  const rounded = roundToDigits(numberValue, digitsInt);
  if (!Number.isFinite(rounded)) {
    return { kind: "Error", code: "#NUM!" };
  }
  return Object.is(rounded, -0) ? 0 : rounded;
}
function roundToDigits(value2, digits) {
  if (!Number.isFinite(value2) || !Number.isFinite(digits)) {
    return NaN;
  }
  if (digits === 0) {
    return Math.round(value2);
  }
  const clamped = Math.min(Math.abs(digits), 15);
  const factor = Math.pow(10, clamped);
  if (!Number.isFinite(factor)) {
    return value2;
  }
  if (digits > 0) {
    return Math.round(value2 * factor) / factor;
  }
  const divisor = factor;
  return Math.round(value2 / divisor) * divisor;
}
function coerceScalarArg(arg) {
  if (arg === undefined) {
    return "";
  }
  if (Array.isArray(arg)) {
    const firstRow = arg[0];
    if (firstRow && firstRow.length > 0) {
      return firstRow[0];
    }
    return "";
  }
  if (isLambdaValue6(arg)) {
    return { kind: "Error", code: "#VALUE!" };
  }
  return arg;
}
function evaluateStandardNormal(args2, allowCumulativeFlag) {
  const inputArg = requiredArg(args2, 0);
  if (isRequiredArgError(inputArg)) {
    return inputArg.error;
  }
  const input = coerceNumberArg3(inputArg);
  if (!Number.isFinite(input)) {
    return { kind: "Error", code: "#VALUE!" };
  }
  const cumulative = allowCumulativeFlag ? optionalArg(args2, 1, (value2) => Boolean(coerceScalarArg(value2)), true) : true;
  const normdist = resolveFunction("NORMDIST");
  if (!normdist) {
    return { kind: "Error", code: "#NAME?" };
  }
  return normdist(input, 0, 1, cumulative);
}
function coerceNumberArg3(arg) {
  const scalar = coerceScalarArg(arg);
  if (typeof scalar === "number") {
    return scalar;
  }
  if (typeof scalar === "string") {
    const parsed = Number(scalar);
    return Number.isFinite(parsed) ? parsed : NaN;
  }
  if (typeof scalar === "boolean") {
    return scalar ? 1 : 0;
  }
  return NaN;
}
function convertThrownError(err) {
  if (isFormulajsError(err)) {
    return {
      kind: "Error",
      code: FORMULAJS_ERROR_TO_CODE.get(err) ?? err.message ?? DEFAULT_ERROR.code
    };
  }
  if (err instanceof Error && err.message) {
    return { kind: "Error", code: err.message };
  }
  return DEFAULT_ERROR;
}
function isErrorValue7(value2) {
  return typeof value2 === "object" && value2 !== null && "kind" in value2 && value2.kind === "Error";
}
function isLambdaValue6(value2) {
  return typeof value2 === "object" && value2 !== null && "kind" in value2 && value2.kind === "Lambda";
}
function isFormulajsError(value2) {
  if (!(value2 instanceof Error)) {
    return false;
  }
  return FORMULAJS_ERROR_TO_CODE.has(value2);
}
function sanitizeMedianArgs(args2) {
  const filtered = [];
  for (const arg of args2) {
    if (Array.isArray(arg)) {
      const cleanedRows = arg.map((row2) => row2.map((value2) => typeof value2 === "string" ? sanitizeAverageScalar(value2) : value2).filter((value2) => !isBlankValue(value2))).filter((row2) => row2.length > 0);
      if (cleanedRows.length > 0) {
        filtered.push(cleanedRows);
      }
      continue;
    }
    const normalized = typeof arg === "string" ? sanitizeAverageScalar(arg) : arg;
    if (!isBlankValue(normalized)) {
      filtered.push(normalized);
    }
  }
  return filtered;
}
function sanitizeSumIfArgs(args2) {
  if (args2.length === 0) {
    return args2;
  }
  if (args2.length === 1) {
    const onlyArg = args2[0];
    return onlyArg === undefined ? args2 : [coerceNumericArg(onlyArg)];
  }
  const range2 = args2[0];
  const criteria = args2[1];
  if (range2 === undefined || criteria === undefined) {
    return args2;
  }
  const sumRange = args2[2] ?? range2;
  const normalizedRange = coerceNumericArg(range2);
  const normalizedSumRange = coerceSumRangeArg(sumRange);
  return [normalizedRange, criteria, normalizedSumRange];
}
function sanitizeSumIfsArgs(args2) {
  if (args2.length < 3) {
    return args2;
  }
  const sumRange = args2[0];
  const criteriaRange = args2[1];
  const criteria = args2[2];
  if (sumRange === undefined || criteriaRange === undefined || criteria === undefined) {
    return args2;
  }
  const normalized = [
    coerceSumRangeArg(sumRange),
    coerceNumericArg(criteriaRange),
    criteria
  ];
  for (let i = 3;i < args2.length; i += 1) {
    const current = args2[i];
    if (current === undefined) {
      continue;
    }
    const isRangeArgument = (i - 3) % 2 === 0;
    normalized.push(isRangeArgument ? coerceNumericArg(current) : current);
  }
  return normalized;
}
function coerceNumericArg(arg) {
  if (Array.isArray(arg)) {
    return arg.map((row2) => row2.map(coerceNumericScalar));
  }
  if (arg === undefined) {
    return;
  }
  return coerceNumericScalar(arg);
}
function coerceNumericScalar(value2) {
  if (typeof value2 === "string") {
    const trimmed = value2.trim();
    if (trimmed) {
      const parsed = Number(trimmed);
      if (Number.isFinite(parsed)) {
        return parsed;
      }
    }
  }
  return value2;
}
function coerceSumRangeArg(arg) {
  if (Array.isArray(arg)) {
    return arg.map((row2) => row2.map(coerceSummableScalar));
  }
  if (arg === undefined) {
    return;
  }
  return coerceSummableScalar(arg);
}
function coerceSummableScalar(value2) {
  if (value2 !== null && value2 !== undefined && isErrorValue7(value2)) {
    return value2;
  }
  if (value2 instanceof Error) {
    return value2;
  }
  if (value2 == null) {
    return 0;
  }
  if (typeof value2 === "string") {
    const trimmed = value2.trim();
    if (!trimmed) {
      return 0;
    }
    const parsed = Number(trimmed);
    return Number.isFinite(parsed) ? parsed : 0;
  }
  if (typeof value2 === "boolean") {
    return value2 ? 1 : 0;
  }
  return value2;
}
function sanitizeAverageArgs(args2) {
  return args2.map((arg) => sanitizeAverageArg(arg));
}
function sanitizeAverageIfArgs(args2) {
  if (args2.length === 0) {
    return args2;
  }
  const targetIndex = args2[2] === undefined ? 0 : 2;
  const target = args2[targetIndex];
  if (target === undefined) {
    return args2;
  }
  const sanitized = [...args2];
  sanitized[targetIndex] = sanitizeAverageArg(target);
  return sanitized;
}
function sanitizeAverageIfsArgs(args2) {
  if (args2.length === 0 || args2[0] === undefined) {
    return args2;
  }
  const sanitized = [...args2];
  sanitized[0] = sanitizeAverageArg(args2[0]);
  return sanitized;
}
function sanitizeAverageArg(arg) {
  if (Array.isArray(arg)) {
    return arg.map((row2) => row2.map(sanitizeAverageScalar));
  }
  if (arg === undefined) {
    return;
  }
  return sanitizeAverageScalar(arg);
}
function sanitizeAverageScalar(value2) {
  if (value2 === null) {
    return "";
  }
  if (typeof value2 !== "string") {
    return value2;
  }
  if (value2.includes(" ")) {
    return "";
  }
  const trimmed = value2.trim();
  if (trimmed === "") {
    return "";
  }
  const parsed = Number(trimmed);
  return Number.isFinite(parsed) ? parsed : "";
}
function isBlankValue(value2) {
  if (Array.isArray(value2)) {
    return value2.length === 0;
  }
  if (value2 == null) {
    return true;
  }
  return typeof value2 === "string" && value2.trim() === "";
}
function sanitizePairedRangeArgs(args2, config3) {
  if (args2.length <= config3.dependentIndex || args2.length <= config3.independentIndex) {
    return args2;
  }
  const dependentArg = args2[config3.dependentIndex];
  const independentArg = args2[config3.independentIndex];
  if (dependentArg === undefined || independentArg === undefined) {
    return args2;
  }
  if (rangeContainsError(dependentArg) || rangeContainsError(independentArg)) {
    return args2;
  }
  const filtered = collectNumericPairs(dependentArg, independentArg);
  if (filtered.pairedLength !== filtered.dependentInputLength || filtered.pairedLength !== filtered.independentInputLength) {
    return args2;
  }
  if (filtered.dependent.length === filtered.pairedLength && !filtered.mutated) {
    return args2;
  }
  const sanitized = [...args2];
  sanitized[config3.dependentIndex] = filtered.dependent;
  sanitized[config3.independentIndex] = filtered.independent;
  return sanitized;
}
function rangeContainsError(arg) {
  if (Array.isArray(arg)) {
    for (const row2 of arg) {
      for (const value2 of row2) {
        if (isErrorValue7(value2)) {
          return true;
        }
      }
    }
    return false;
  }
  if (arg === undefined) {
    return false;
  }
  return isErrorValue7(arg);
}
function collectNumericPairs(dependent, independent) {
  const dependentValues = flattenFunctionArg2(dependent);
  const independentValues = flattenFunctionArg2(independent);
  const length2 = Math.min(dependentValues.length, independentValues.length);
  const filteredDependent = [];
  const filteredIndependent = [];
  let mutated = false;
  for (let idx = 0;idx < length2; idx += 1) {
    const dep = dependentValues[idx];
    const indep = independentValues[idx];
    if (dep === undefined || indep === undefined) {
      mutated = true;
      continue;
    }
    if (!isNumericScalar(dep) || !isNumericScalar(indep)) {
      mutated = true;
      continue;
    }
    const depNumeric = typeof dep === "number" ? dep : Number(dep);
    const indepNumeric = typeof indep === "number" ? indep : Number(indep);
    if (typeof dep !== "number" || typeof indep !== "number") {
      mutated = true;
    }
    filteredDependent.push([depNumeric]);
    filteredIndependent.push([indepNumeric]);
  }
  return {
    dependent: filteredDependent,
    independent: filteredIndependent,
    pairedLength: length2,
    dependentInputLength: dependentValues.length,
    independentInputLength: independentValues.length,
    mutated
  };
}
function flattenFunctionArg2(arg) {
  if (Array.isArray(arg)) {
    const values = [];
    for (const row2 of arg) {
      for (const value2 of row2) {
        values.push(value2);
      }
    }
    return values;
  }
  if (arg === undefined) {
    return [];
  }
  return [arg];
}
function isArrayResult(value2) {
  return isArrayValue(value2);
}
function isScalarFunctionArg(value2) {
  return value2 !== undefined && !Array.isArray(value2);
}
function isArrayFunctionArg(value2) {
  return isScalarFunctionArg(value2) && isArrayValue(value2);
}
function canonicalizeFunctionName(name2) {
  return name2.replace(/^_XLFN\._XLWS\./i, "").replace(/^_XLFN\./i, "").replace(/^_XLWS\./i, "").replace(/^_XLPM\./i, "");
}
function isNumericScalar(value2) {
  if (typeof value2 === "number") {
    return Number.isFinite(value2);
  }
  if (typeof value2 === "string") {
    if (value2.trim() === "") {
      return false;
    }
    const parsed = Number(value2);
    return Number.isFinite(parsed);
  }
  return false;
}
function evaluateRateSpecialCase(args2) {
  if (args2.length < 3) {
    return null;
  }
  const nperArg = requiredArg(args2, 0);
  const pmtArg = requiredArg(args2, 1);
  const pvArg = requiredArg(args2, 2);
  if (isRequiredArgError(nperArg) || isRequiredArgError(pmtArg) || isRequiredArgError(pvArg)) {
    return null;
  }
  const nper = coerceNumberArg3(nperArg);
  const pmt = coerceNumberArg3(pmtArg);
  const pv = coerceNumberArg3(pvArg);
  const fv = optionalArg(args2, 3, coerceNumberArg3, 0);
  if (!Number.isFinite(nper) || !Number.isFinite(pmt) || !Number.isFinite(pv) || !Number.isFinite(fv)) {
    return null;
  }
  if (nper <= 0) {
    return null;
  }
  if (pmt !== 0) {
    return null;
  }
  if (pv === 0) {
    return null;
  }
  const ratio = -fv / pv;
  if (ratio < 0) {
    return null;
  }
  const magnitude = Math.pow(ratio, 1 / nper);
  if (!Number.isFinite(magnitude)) {
    return null;
  }
  const computed = magnitude - 1;
  if (!Number.isFinite(computed)) {
    return null;
  }
  return computed;
}

// node_modules/@oai/granola/dist/models/spreadsheet/workbook-range-reference-analysis.js
function toStructuredReferenceRuntimeOptions(options) {
  return {
    fallbackSheet: options.fallbackSheet ?? "",
    activeCellAddress: options.activeCellAddress
  };
}

class WorkbookRangeReferenceAnalysis {
  #adapter;
  constructor(adapter) {
    this.#adapter = adapter;
  }
  getColumnIndex(ref2, options = {}) {
    switch (ref2.kind) {
      case "Cell":
        return ref2.addr.col;
      case "Range":
        return Math.min(ref2.start.col, ref2.end.col);
      case "WholeColumn":
        return ref2.col;
      case "ColumnRange":
        return Math.min(ref2.startCol, ref2.endCol);
      case "Spill":
        return this.getColumnIndex(ref2.base, options);
      case "Structured": {
        const resolved = this.#adapter.structuredReferences.resolveArea(ref2.reference, toStructuredReferenceRuntimeOptions(options));
        if (resolved.kind === "Error") {
          return null;
        }
        return resolved.area.startCol;
      }
      case "Named": {
        const fallbackSheet = options.fallbackSheet ?? "";
        const addresses = this.#adapter.expandRange(ref2, ref2.sheet?.sheetName ?? fallbackSheet, options.activeCellAddress);
        return addresses[0]?.col ?? null;
      }
      default:
        return null;
    }
  }
  getSheetName(ref2, options = {}) {
    switch (ref2.kind) {
      case "Cell":
        return ref2.addr.sheet?.sheetName ?? options.fallbackSheet ?? null;
      case "Range":
        return ref2.start.sheet?.sheetName ?? ref2.end.sheet?.sheetName ?? options.fallbackSheet ?? null;
      case "WholeColumn":
      case "ColumnRange":
      case "WholeRow":
        return ref2.sheet?.sheetName ?? options.fallbackSheet ?? null;
      case "Spill":
        return this.getSheetName(ref2.base, options);
      case "Structured": {
        const resolved = this.#adapter.structuredReferences.resolveArea(ref2.reference, toStructuredReferenceRuntimeOptions(options));
        if (resolved.kind === "Error") {
          return null;
        }
        return resolved.area.sheetName;
      }
      case "Named": {
        if (ref2.sheet?.sheetName) {
          return ref2.sheet.sheetName;
        }
        const fallbackSheet = options.fallbackSheet ?? "";
        const addresses = this.#adapter.expandRange(ref2, fallbackSheet, options.activeCellAddress);
        return addresses[0]?.sheet?.sheetName ?? options.fallbackSheet ?? null;
      }
      default:
        return options.fallbackSheet ?? null;
    }
  }
  getSheetSpan(ref2, options = {}) {
    switch (ref2.kind) {
      case "Range": {
        const startSheet = ref2.start.sheet?.sheetName ?? options.fallbackSheet ?? null;
        const endSheet = ref2.end.sheet?.sheetName ?? startSheet ?? options.fallbackSheet ?? null;
        if (!startSheet) {
          return null;
        }
        return {
          startSheet,
          endSheet: endSheet ?? startSheet
        };
      }
      case "Spill":
        return this.getSheetSpan(ref2.base, options);
      case "Structured": {
        const resolved = this.#adapter.structuredReferences.resolveArea(ref2.reference, toStructuredReferenceRuntimeOptions(options));
        if (resolved.kind === "Error") {
          return null;
        }
        return { startSheet: resolved.area.sheetName };
      }
      case "Named": {
        const sheetName = ref2.sheet?.sheetName ?? this.getSheetName(ref2, options);
        if (!sheetName) {
          return null;
        }
        return { startSheet: sheetName };
      }
      case "Cell": {
        const sheetName = ref2.addr.sheet?.sheetName ?? options.fallbackSheet ?? null;
        if (!sheetName) {
          return null;
        }
        return { startSheet: sheetName };
      }
      case "WholeColumn":
      case "ColumnRange":
      case "WholeRow": {
        const sheetName = ref2.sheet?.sheetName ?? options.fallbackSheet ?? null;
        if (!sheetName) {
          return null;
        }
        return { startSheet: sheetName };
      }
      default:
        return options.fallbackSheet ? { startSheet: options.fallbackSheet } : null;
    }
  }
  isSingleCell(ref2, options) {
    switch (ref2.kind) {
      case "Cell":
        return true;
      case "Spill":
        return this.isSingleCell(ref2.base, options);
      case "Structured": {
        const resolved = this.#adapter.structuredReferences.resolveArea(ref2.reference, toStructuredReferenceRuntimeOptions(options));
        if (resolved.kind === "Error") {
          return false;
        }
        return resolved.area.startRow === resolved.area.endRow && resolved.area.startCol === resolved.area.endCol;
      }
      default:
        return false;
    }
  }
  referencesBlankCell(ref2, options) {
    switch (ref2.kind) {
      case "Cell":
        return this.#adapter.cellAddressIsBlank(ref2.addr, options.fallbackSheet ?? "");
      case "Spill":
        return this.referencesBlankCell(ref2.base, options);
      case "Structured": {
        const addresses = this.#adapter.structuredReferences.expand(ref2.reference, toStructuredReferenceRuntimeOptions(options));
        const firstAddress = addresses[0];
        if (!firstAddress) {
          return false;
        }
        return this.#adapter.cellAddressIsBlank(firstAddress, options.fallbackSheet ?? "");
      }
      default:
        return false;
    }
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/engine/spill-manager.js
class SpillManager {
  #recordsByAnchor = new Map;
  #cellToAnchor = new Map;
  setRecord(record2, cellKeys) {
    this.clear(record2.anchorKey);
    this.#recordsByAnchor.set(record2.anchorKey, { record: record2, cellKeys });
    for (let r = 0;r < cellKeys.length; r += 1) {
      const row2 = cellKeys[r];
      if (!row2)
        continue;
      for (let c = 0;c < row2.length; c += 1) {
        const key = row2[c];
        if (!key)
          continue;
        this.#cellToAnchor.set(key, {
          anchorKey: record2.anchorKey,
          rowOffset: r,
          colOffset: c
        });
      }
    }
  }
  clear(anchorKey) {
    const entry = this.#recordsByAnchor.get(anchorKey);
    if (!entry) {
      return null;
    }
    this.#recordsByAnchor.delete(anchorKey);
    for (const row2 of entry.cellKeys) {
      for (const key of row2) {
        if (!key)
          continue;
        this.#cellToAnchor.delete(key);
      }
    }
    return entry.cellKeys;
  }
  getRecord(anchorKey) {
    const entry = this.#recordsByAnchor.get(anchorKey);
    return entry ? entry.record : null;
  }
  getCellProjection(cellKey) {
    const projection = this.#cellToAnchor.get(cellKey);
    if (!projection) {
      return null;
    }
    const entry = this.#recordsByAnchor.get(projection.anchorKey);
    if (!entry) {
      return null;
    }
    return {
      record: entry.record,
      isAnchor: projection.rowOffset === 0 && projection.colOffset === 0,
      rowOffset: projection.rowOffset,
      colOffset: projection.colOffset
    };
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/workbook-structured-reference-runtime.js
init_address_utils();

// node_modules/@oai/granola/dist/models/spreadsheet/structured-reference-resolver.js
init_address_utils();
function resolveStructuredReferenceArea(reference, context) {
  const tableInfo = resolveStructuredReferenceTable(reference, context);
  if (!tableInfo) {
    return { kind: "Error", code: "#NAME?" };
  }
  const bounds = getTableAreaBounds(tableInfo.table);
  if (!bounds) {
    return { kind: "Error", code: "#REF!" };
  }
  const columnBounds = resolveColumnBounds(reference, tableInfo.table, bounds);
  if (!columnBounds) {
    return { kind: "Error", code: "#REF!" };
  }
  const rowBounds = resolveRowBounds(reference, tableInfo, bounds, context);
  if (!rowBounds) {
    return { kind: "Error", code: "#REF!" };
  }
  if ("code" in rowBounds) {
    return { kind: "Error", code: rowBounds.code };
  }
  return {
    kind: "Resolved",
    tableInfo,
    area: {
      sheetName: tableInfo.sheetName,
      startRow: rowBounds.startRow,
      endRow: rowBounds.endRow,
      startCol: columnBounds.startCol,
      endCol: columnBounds.endCol
    }
  };
}
function buildStructuredReferenceAddressGrid(area) {
  if (area.endRow < area.startRow || area.endCol < area.startCol) {
    return [];
  }
  const rows = [];
  for (let row2 = area.startRow;row2 <= area.endRow; row2 += 1) {
    const addressRow = [];
    for (let col = area.startCol;col <= area.endCol; col += 1) {
      addressRow.push({
        sheet: { sheetName: area.sheetName },
        row: row2,
        col,
        absRow: false,
        absCol: false
      });
    }
    rows.push(addressRow);
  }
  return rows;
}
function flattenStructuredReferenceAddressGrid(area) {
  const addresses = [];
  for (const row2 of buildStructuredReferenceAddressGrid(area)) {
    for (const address of row2) {
      addresses.push(address);
    }
  }
  return addresses;
}
function resolveStructuredReferenceTable(reference, context) {
  if (reference.tableName) {
    return context.findTableByName(reference.tableName);
  }
  const activeCellAddress = context.activeCellAddress;
  if (!activeCellAddress?.sheet?.sheetName) {
    return null;
  }
  return context.findContainingTable(activeCellAddress);
}
function getTableAreaBounds(table2) {
  const parsedRange = parseRangeAddress(table2.ref ?? "");
  if (!parsedRange) {
    return null;
  }
  const headerRowCount = getEffectiveTableHeaderRowCount(table2);
  const totalsRowCount = getEffectiveTableTotalsRowCount(table2);
  const startRow = parsedRange.bounds.startRow + 1;
  const endRow = parsedRange.bounds.endRow + 1;
  const startCol = parsedRange.bounds.startCol + 1;
  const endCol = parsedRange.bounds.endCol + 1;
  const dataStartRow = startRow + headerRowCount;
  const dataEndRow = endRow - totalsRowCount;
  return {
    startRow,
    endRow,
    startCol,
    endCol,
    dataStartRow,
    dataEndRow,
    headerRowCount,
    totalsRowCount
  };
}
function resolveColumnBounds(reference, table2, bounds) {
  if (!reference.columnName) {
    return {
      startCol: bounds.startCol,
      endCol: bounds.endCol
    };
  }
  const columnOffset = findTableColumnOffset(reference.columnName, table2, bounds);
  if (columnOffset == null) {
    return null;
  }
  const resolvedCol = bounds.startCol + columnOffset;
  return {
    startCol: resolvedCol,
    endCol: resolvedCol
  };
}
function findTableColumnOffset(columnName, table2, bounds) {
  const normalizedColumnName = columnName.trim().toUpperCase();
  if (!normalizedColumnName) {
    return null;
  }
  const width = bounds.endCol - bounds.startCol + 1;
  for (let offset = 0;offset < width; offset += 1) {
    const normalizedTableColumnName = normalizeTableColumnName(table2.columns?.[offset]?.name, offset);
    if (normalizedTableColumnName === normalizedColumnName) {
      return offset;
    }
  }
  return null;
}
function normalizeTableColumnName(columnName, index) {
  const trimmed = columnName?.trim();
  if (trimmed) {
    return trimmed.toUpperCase();
  }
  return `COLUMN${index + 1}`;
}
function resolveRowBounds(reference, tableInfo, bounds, context) {
  switch (reference.section) {
    case "All":
      return {
        startRow: bounds.startRow,
        endRow: bounds.endRow
      };
    case "Data":
      return {
        startRow: bounds.dataStartRow,
        endRow: bounds.dataEndRow
      };
    case "Headers":
      if (bounds.headerRowCount === 0) {
        return null;
      }
      return {
        startRow: bounds.startRow,
        endRow: bounds.startRow + bounds.headerRowCount - 1
      };
    case "Totals":
      if (bounds.totalsRowCount === 0) {
        return null;
      }
      return {
        startRow: bounds.endRow - bounds.totalsRowCount + 1,
        endRow: bounds.endRow
      };
    case "ThisRow": {
      const activeCellAddress = context.activeCellAddress;
      if (!activeCellAddress || activeCellAddress.sheet?.sheetName !== tableInfo.sheetName) {
        return { code: "#VALUE!" };
      }
      if (activeCellAddress.row < bounds.dataStartRow || activeCellAddress.row > bounds.dataEndRow) {
        return { code: "#VALUE!" };
      }
      return {
        startRow: activeCellAddress.row,
        endRow: activeCellAddress.row
      };
    }
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/workbook-structured-reference-runtime.js
class WorkbookStructuredReferenceRuntime {
  #adapter;
  constructor(adapter) {
    this.#adapter = adapter;
  }
  findTableByName(name2) {
    const normalized = name2.trim().toUpperCase();
    if (!normalized) {
      return null;
    }
    for (const worksheet of this.#adapter.worksheets) {
      const sheetName = worksheet.name?.trim();
      if (!sheetName) {
        continue;
      }
      for (const table2 of worksheet.__getTables() ?? []) {
        const tableName = table2.name ?? table2.displayName ?? "";
        if (tableName.trim().toUpperCase() === normalized) {
          return { sheetName, table: table2 };
        }
      }
    }
    return null;
  }
  resolveArea(reference, options) {
    const normalizedActiveCell = this.#normalizeActiveCell(options.fallbackSheet, options.activeCellAddress);
    return resolveStructuredReferenceArea(reference, {
      activeCellAddress: normalizedActiveCell,
      findTableByName: (name2) => this.findTableByName(name2),
      findContainingTable: (cell) => this.#findTableContainingCell(cell)
    });
  }
  readValues(reference, ctx, fallbackSheet) {
    const resolved = this.resolveArea(reference, {
      fallbackSheet,
      activeCellAddress: ctx.activeCellAddress
    });
    if (resolved.kind === "Error") {
      return [[this.#adapter.makeError(resolved.code)]];
    }
    return this.#readResolvedAreaValues(resolved, ctx);
  }
  expand(reference, options) {
    const resolved = this.resolveArea(reference, options);
    if (resolved.kind === "Error") {
      return [];
    }
    return flattenStructuredReferenceAddressGrid(resolved.area);
  }
  #findTableContainingCell(cellAddress) {
    const sheetName = cellAddress.sheet?.sheetName?.trim();
    if (!sheetName) {
      return null;
    }
    const worksheet = this.#adapter.getWorksheetByName(sheetName);
    if (!worksheet) {
      return null;
    }
    for (const table2 of worksheet.__getTables() ?? []) {
      const parsedRange = parseRangeAddress(table2.ref ?? "");
      if (!parsedRange) {
        continue;
      }
      const startRow = parsedRange.bounds.startRow + 1;
      const endRow = parsedRange.bounds.endRow + 1;
      const startCol = parsedRange.bounds.startCol + 1;
      const endCol = parsedRange.bounds.endCol + 1;
      if (cellAddress.row >= startRow && cellAddress.row <= endRow && cellAddress.col >= startCol && cellAddress.col <= endCol) {
        return { sheetName, table: table2 };
      }
    }
    return null;
  }
  #normalizeActiveCell(fallbackSheet, activeCellAddress) {
    if (!activeCellAddress) {
      return;
    }
    const sheetName = activeCellAddress.sheet?.sheetName ?? fallbackSheet;
    if (!sheetName) {
      return;
    }
    return this.#adapter.normalizeCellAddress(activeCellAddress, sheetName);
  }
  #readResolvedAreaValues(resolved, ctx) {
    const addressGrid = buildStructuredReferenceAddressGrid(resolved.area);
    const rows = [];
    for (const addressRow of addressGrid) {
      const rowValues = [];
      for (const address of addressRow) {
        const key = ctx.cellAddressToKey(address);
        rowValues.push(key ? ctx.getCellValue(key) : this.#adapter.makeError("#REF!"));
      }
      rows.push(rowValues);
    }
    attachRangeMetadata(rows, addressGrid);
    return rows;
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/workbook-proto-export-utils.js
init_address_utils();
var DYNAMIC_ARRAY_METADATA_NAME = "XLDAPR";
var DYNAMIC_ARRAY_METADATA_EXTENSION_URI = "{bdbb8cdc-fa1e-496e-a857-3c3f30c029c3}";
var DYNAMIC_ARRAY_MIN_SUPPORTED_VERSION = 120000;
var DYNAMIC_ARRAY_COMPATIBILITY_FUNCTION_PREFIXES = [
  { name: "FILTER", prefix: "_xlfn._xlws." },
  { name: "SORT", prefix: "_xlfn._xlws." }
];
var LAMBDA_COMPATIBILITY_FUNCTION_PREFIXES = [
  { name: "LAMBDA", prefix: "_xlfn." }
];
function cloneWorkbookMetadataForExport(metadata) {
  if (!metadata) {
    return;
  }
  return {
    metadataTypes: (metadata.metadataTypes ?? []).map((record2) => ({
      ...record2
    })),
    futureMetadata: (metadata.futureMetadata ?? []).map((record2) => ({
      ...record2,
      blocks: (record2.blocks ?? []).map((block) => ({
        ...block,
        dynamicArrayProperties: block.dynamicArrayProperties ? { ...block.dynamicArrayProperties } : undefined
      }))
    })),
    cellMetadata: (metadata.cellMetadata ?? []).map((record2) => ({
      ...record2,
      blocks: (record2.blocks ?? []).map((block) => ({
        ...block,
        entries: (block.entries ?? []).map((entry) => ({ ...entry }))
      }))
    }))
  };
}
function applyWorkbookDynamicArrayExportMetadata(input) {
  const dynamicArrayAnchors = [];
  for (const sheet of input.proto.sheets ?? []) {
    const sheetName = sheet.name?.trim();
    if (!sheetName) {
      continue;
    }
    for (const row2 of sheet.rows ?? []) {
      for (const cell of row2.cells ?? []) {
        const address = cell.address?.trim().toUpperCase();
        if (!address) {
          continue;
        }
        const key = input.makeCellKey(sheetName, address);
        const projection = input.getSpillProjection(key);
        if (projection) {
          if (projection.isAnchor) {
            if (!cell.formula || !cell.formula.trim()) {
              continue;
            }
            cell.formula = applyDynamicArrayCompatibilityPrefixes(cell.formula);
            cell.formulaType = 2 /* CELL_FORMULA_TYPE_ARRAY */;
            cell.formulaRef = buildRangeRef({
              startRow: projection.record.startRow,
              startCol: projection.record.startCol,
              endRow: projection.record.startRow + Math.max(0, projection.record.rows - 1),
              endCol: projection.record.startCol + Math.max(0, projection.record.cols - 1)
            });
            cell.formulaAlwaysCalculateArray = undefined;
            cell.sharedFormulaSi = undefined;
            dynamicArrayAnchors.push(cell);
            continue;
          }
          cell.formula = undefined;
          cell.formulaType = undefined;
          cell.formulaRef = undefined;
          cell.formulaAlwaysCalculateArray = undefined;
          cell.sharedFormulaSi = undefined;
          continue;
        }
        if (!cell.formula || !cell.formula.trim()) {
          continue;
        }
        if (!formulaUsesLambdaSemantics({
          formula: cell.formula,
          contextSheet: sheetName,
          hasLambdaDefinedName: input.hasLambdaDefinedName,
          stripCompatibilityPrefixes: input.stripCompatibilityPrefixes
        })) {
          continue;
        }
        cell.formula = applyLambdaCompatibilityPrefixes(cell.formula);
        cell.formulaType = 2 /* CELL_FORMULA_TYPE_ARRAY */;
        cell.formulaRef = address;
        cell.formulaAlwaysCalculateArray = undefined;
        cell.sharedFormulaSi = undefined;
        dynamicArrayAnchors.push(cell);
      }
    }
  }
  if (dynamicArrayAnchors.length === 0) {
    return;
  }
  const metadataIndex = getOrCreateDynamicArrayMetadataIndex(input.proto);
  for (const cell of dynamicArrayAnchors) {
    cell.cellMetadataIndex = metadataIndex;
  }
}
function formulaUsesLambdaSemantics(input) {
  const normalizedFormula = input.formula.trim().startsWith("=") ? input.formula.trim() : `=${input.formula.trim()}`;
  const parsed = parseFormula(normalizedFormula);
  if (parsed.errors.length > 0) {
    return false;
  }
  return exprUsesLambdaSemantics({
    expr: parsed.expr,
    contextSheet: input.contextSheet,
    hasLambdaDefinedName: input.hasLambdaDefinedName,
    stripCompatibilityPrefixes: input.stripCompatibilityPrefixes
  });
}
function exprUsesLambdaSemantics(input) {
  switch (input.expr.kind) {
    case "FunctionCall": {
      const canonicalName = input.stripCompatibilityPrefixes(input.expr.name).trim().toUpperCase();
      if (canonicalName === "LAMBDA") {
        return true;
      }
      if (input.hasLambdaDefinedName(canonicalName, input.contextSheet)) {
        return true;
      }
      for (const arg of input.expr.args) {
        if (exprUsesLambdaSemantics({
          expr: arg,
          contextSheet: input.contextSheet,
          hasLambdaDefinedName: input.hasLambdaDefinedName,
          stripCompatibilityPrefixes: input.stripCompatibilityPrefixes
        })) {
          return true;
        }
      }
      return false;
    }
    case "CallExpr":
      if (exprUsesLambdaSemantics({
        expr: input.expr.callee,
        contextSheet: input.contextSheet,
        hasLambdaDefinedName: input.hasLambdaDefinedName,
        stripCompatibilityPrefixes: input.stripCompatibilityPrefixes
      })) {
        return true;
      }
      for (const arg of input.expr.args) {
        if (exprUsesLambdaSemantics({
          expr: arg,
          contextSheet: input.contextSheet,
          hasLambdaDefinedName: input.hasLambdaDefinedName,
          stripCompatibilityPrefixes: input.stripCompatibilityPrefixes
        })) {
          return true;
        }
      }
      return false;
    case "UnaryOp":
      return exprUsesLambdaSemantics({
        expr: input.expr.expr,
        contextSheet: input.contextSheet,
        hasLambdaDefinedName: input.hasLambdaDefinedName,
        stripCompatibilityPrefixes: input.stripCompatibilityPrefixes
      });
    case "BinaryOp":
      return exprUsesLambdaSemantics({
        expr: input.expr.left,
        contextSheet: input.contextSheet,
        hasLambdaDefinedName: input.hasLambdaDefinedName,
        stripCompatibilityPrefixes: input.stripCompatibilityPrefixes
      }) || exprUsesLambdaSemantics({
        expr: input.expr.right,
        contextSheet: input.contextSheet,
        hasLambdaDefinedName: input.hasLambdaDefinedName,
        stripCompatibilityPrefixes: input.stripCompatibilityPrefixes
      });
    case "ArrayLiteral":
      for (const row2 of input.expr.elements) {
        for (const item of row2) {
          if (exprUsesLambdaSemantics({
            expr: item,
            contextSheet: input.contextSheet,
            hasLambdaDefinedName: input.hasLambdaDefinedName,
            stripCompatibilityPrefixes: input.stripCompatibilityPrefixes
          })) {
            return true;
          }
        }
      }
      return false;
    default:
      return false;
  }
}
function applyDynamicArrayCompatibilityPrefixes(formula) {
  return applyCompatibilityFunctionPrefixes(formula, DYNAMIC_ARRAY_COMPATIBILITY_FUNCTION_PREFIXES);
}
function applyLambdaCompatibilityPrefixes(formula) {
  return applyCompatibilityFunctionPrefixes(formula, LAMBDA_COMPATIBILITY_FUNCTION_PREFIXES);
}
function applyCompatibilityFunctionPrefixes(formula, prefixes2) {
  if (!formula) {
    return formula;
  }
  let output = formula;
  for (const entry of prefixes2) {
    output = prefixCompatibilityFunction(output, entry.name, entry.prefix);
  }
  return output;
}
function prefixCompatibilityFunction(formula, name2, prefix) {
  const upperName = name2.toUpperCase();
  const nameLength = upperName.length;
  let result = "";
  let inString = false;
  let index = 0;
  while (index < formula.length) {
    const char = formula[index];
    if (char === '"') {
      const next2 = formula[index + 1];
      if (inString && next2 === '"') {
        result += '""';
        index += 2;
        continue;
      }
      inString = !inString;
      result += char;
      index += 1;
      continue;
    }
    if (!inString && matchesFunctionCall(formula, index, upperName, nameLength)) {
      result += `${prefix}${upperName}`;
      index += nameLength;
      continue;
    }
    result += char;
    index += 1;
  }
  return result;
}
function matchesFunctionCall(formula, index, upperName, nameLength) {
  const before = index > 0 ? formula[index - 1] : "";
  if (before && /[A-Za-z0-9_.]/.test(before)) {
    return false;
  }
  const token = formula.slice(index, index + nameLength).toUpperCase();
  if (token !== upperName) {
    return false;
  }
  let cursor = index + nameLength;
  while (cursor < formula.length && /\s/.test(formula[cursor] ?? "")) {
    cursor += 1;
  }
  return formula[cursor] === "(";
}
function getOrCreateDynamicArrayMetadataIndex(proto) {
  const metadata = proto.metadata ?? (proto.metadata = {
    metadataTypes: [],
    futureMetadata: [],
    cellMetadata: []
  });
  const metadataTypes = metadata.metadataTypes;
  const dynamicTypeId = getOrCreateDynamicArrayTypeId(metadataTypes);
  const futureMetadata = metadata.futureMetadata;
  upsertDynamicArrayFutureMetadata(futureMetadata);
  const cellMetadata = metadata.cellMetadata;
  const existingCellMetadataIndex = findCellMetadataIndex(cellMetadata, dynamicTypeId);
  if (existingCellMetadataIndex > 0) {
    return existingCellMetadataIndex;
  }
  cellMetadata.push({
    blocks: [{ entries: [{ type: dynamicTypeId, value: 0 }] }]
  });
  return cellMetadata.length;
}
function getOrCreateDynamicArrayTypeId(metadataTypes) {
  let dynamicTypeIndex = metadataTypes.findIndex((record2) => record2.name?.trim().toUpperCase() === DYNAMIC_ARRAY_METADATA_NAME);
  if (dynamicTypeIndex < 0) {
    metadataTypes.push({
      name: DYNAMIC_ARRAY_METADATA_NAME,
      minSupportedVersion: DYNAMIC_ARRAY_MIN_SUPPORTED_VERSION,
      copy: true,
      pasteAll: true,
      pasteValues: true,
      merge: true,
      splitFirst: true,
      rowColShift: true,
      clearFormats: true,
      clearComments: true,
      assign: true,
      coerce: true,
      cellMeta: true
    });
    dynamicTypeIndex = metadataTypes.length - 1;
    return dynamicTypeIndex + 1;
  }
  const dynamicType = metadataTypes[dynamicTypeIndex];
  if (!dynamicType) {
    return dynamicTypeIndex + 1;
  }
  dynamicType.name = DYNAMIC_ARRAY_METADATA_NAME;
  dynamicType.minSupportedVersion ??= DYNAMIC_ARRAY_MIN_SUPPORTED_VERSION;
  dynamicType.copy = true;
  dynamicType.pasteAll = true;
  dynamicType.pasteValues = true;
  dynamicType.merge = true;
  dynamicType.splitFirst = true;
  dynamicType.rowColShift = true;
  dynamicType.clearFormats = true;
  dynamicType.clearComments = true;
  dynamicType.assign = true;
  dynamicType.coerce = true;
  dynamicType.cellMeta = true;
  return dynamicTypeIndex + 1;
}
function upsertDynamicArrayFutureMetadata(futureMetadata) {
  let dynamicFuture = futureMetadata.find((record2) => record2.name?.trim().toUpperCase() === DYNAMIC_ARRAY_METADATA_NAME);
  if (!dynamicFuture) {
    dynamicFuture = {
      name: DYNAMIC_ARRAY_METADATA_NAME,
      count: 1,
      blocks: [buildDynamicArrayFutureMetadataBlock()]
    };
    futureMetadata.push(dynamicFuture);
    return;
  }
  dynamicFuture.name = DYNAMIC_ARRAY_METADATA_NAME;
  dynamicFuture.count = Math.max(1, dynamicFuture.count ?? 0);
  const blocks = dynamicFuture.blocks ?? (dynamicFuture.blocks = []);
  let dynamicBlock = blocks.find((record2) => record2.extensionUri?.trim().toLowerCase() === DYNAMIC_ARRAY_METADATA_EXTENSION_URI.toLowerCase());
  if (!dynamicBlock) {
    dynamicBlock = buildDynamicArrayFutureMetadataBlock();
    blocks.push(dynamicBlock);
    return;
  }
  dynamicBlock.extensionUri = DYNAMIC_ARRAY_METADATA_EXTENSION_URI;
  dynamicBlock.dynamicArrayProperties = {
    isDynamic: true,
    collapsed: false
  };
}
function buildDynamicArrayFutureMetadataBlock() {
  return {
    extensionUri: DYNAMIC_ARRAY_METADATA_EXTENSION_URI,
    dynamicArrayProperties: {
      isDynamic: true,
      collapsed: false
    }
  };
}
function findCellMetadataIndex(cellMetadata, dynamicTypeId) {
  for (let index = 0;index < cellMetadata.length; index += 1) {
    const record2 = cellMetadata[index];
    if (!record2) {
      continue;
    }
    const blocks = record2.blocks ?? [];
    for (const block of blocks) {
      const entries = block.entries ?? [];
      for (const entry of entries) {
        const entryType = entry.type ?? 0;
        const entryValue = entry.value ?? 0;
        if (entryType === dynamicTypeId && entryValue === 0) {
          return index + 1;
        }
      }
    }
  }
  return 0;
}

// node_modules/@oai/granola/dist/models/workbook.js
init_address_utils();
// node_modules/@oai/granola/dist/spreadsheet/build-clipboard-payload.js
function buildClipboardPayload(args2) {
  const { selectionRect, selRow, selCol, sheet, styleInfos } = args2;
  const cache = new Map;
  const sel = selectionRect ?? {
    r1: selRow,
    c1: selCol,
    r2: selRow,
    c2: selCol
  };
  const rCount = sel.r2 - sel.r1 + 1;
  const cCount = sel.c2 - sel.c1 + 1;
  const rows = Array.from({ length: rCount }, () => Array.from({ length: cCount }, () => ({})));
  for (let rr = sel.r1;rr <= sel.r2; rr++) {
    const row2 = sheet.rows.find((rw) => rw.index - 1 === rr);
    for (let cc = sel.c1;cc <= sel.c2; cc++) {
      const cel = row2?.cells.find((c) => columnIndex(c.address) === cc);
      const st = styleInfos[cel?.styleIndex ?? 0] ?? {};
      const outR = rr - sel.r1;
      const outC = cc - sel.c1;
      const cellOut = {};
      cellOut.v = cel ? formatCell(cel, styleInfos, cache) : "";
      const fontSizePt = typeof st.font?.size === "number" && st.font.size > 0 ? st.font.size * 72 / 96 : undefined;
      const align = st.align === "left" || st.align === "center" || st.align === "right" ? st.align : undefined;
      const valign = st.verticalAlign === 1 /* ANCHOR_TYPE_TOP */ ? "top" : st.verticalAlign === 2 /* ANCHOR_TYPE_MIDDLE */ ? "middle" : st.verticalAlign === 3 /* ANCHOR_TYPE_BOTTOM */ ? "bottom" : "bottom";
      cellOut.fmt = {
        bold: st.font?.bold,
        italic: st.font?.italic,
        underline: st.font?.underline,
        color: st.textColor ?? st.font?.color,
        bg: st.fill,
        align,
        valign,
        wrap: st.wrapText,
        numFmt: st.numberFormatCode,
        fontFamily: st.font?.family,
        fontSizePt,
        border: {
          top: st.borderStyles?.top ? { style: st.borderStyles.top, color: st.borders?.top } : undefined,
          right: st.borderStyles?.right ? { style: st.borderStyles.right, color: st.borders?.right } : undefined,
          bottom: st.borderStyles?.bottom ? { style: st.borderStyles.bottom, color: st.borders?.bottom } : undefined,
          left: st.borderStyles?.left ? { style: st.borderStyles.left, color: st.borders?.left } : undefined
        },
        diagonal: st.borderStyles?.diagonal || st.borders?.diagonal ? {
          style: st.borderStyles?.diagonal,
          color: st.borders?.diagonal,
          up: !!st.borderDiagonalUp,
          down: !!st.borderDiagonalDown
        } : undefined
      };
      const rowOutR = rows[outR];
      if (rowOutR) {
        rowOutR[outC] = cellOut;
      }
    }
  }
  const merges = [];
  for (const rg of sheet.mergedCells ?? []) {
    const c1 = Math.min(columnIndex(rg.startAddress), columnIndex(rg.endAddress));
    const c2 = Math.max(columnIndex(rg.startAddress), columnIndex(rg.endAddress));
    const r1 = Math.min(rowIndex(rg.startAddress), rowIndex(rg.endAddress));
    const r2 = Math.max(rowIndex(rg.startAddress), rowIndex(rg.endAddress));
    const iR1 = Math.max(sel.r1, r1);
    const iR2 = Math.min(sel.r2, r2);
    const iC1 = Math.max(sel.c1, c1);
    const iC2 = Math.min(sel.c2, c2);
    if (iR1 > iR2 || iC1 > iC2)
      continue;
    const anchorR = iR1 - sel.r1;
    const anchorC = iC1 - sel.c1;
    const rowspan = iR2 - iR1 + 1;
    const colspan = iC2 - iC1 + 1;
    if (rowspan > 1 || colspan > 1)
      merges.push({ r: anchorR, c: anchorC, rowspan, colspan });
  }
  return { rows, merges };
}

// node_modules/@oai/granola/dist/spreadsheet/build-html-table.js
function escapeHtml(s) {
  const map4 = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': "&quot;"
  };
  return String(s ?? "").replace(/[&<>"]/g, (m) => map4[m] ?? m);
}
function buildHtmlTable(rows, merges) {
  const mergeAt = new Map;
  const skip = new Set;
  for (const m of merges)
    mergeAt.set(`${m.r},${m.c}`, m);
  const numCols = rows.reduce((n, r) => Math.max(n, r?.length ?? 0), 0);
  const colWidthsPx = new Array(numCols).fill(0);
  const approximateTextWidthPx = (text3) => {
    const avgPxPerChar = 7;
    const paddingPx = 10;
    const length2 = text3.length;
    const raw = length2 * avgPxPerChar + paddingPx;
    const clamped = Math.max(20, Math.min(raw, 360));
    return Math.round(clamped);
  };
  for (let r = 0;r < rows.length; r++) {
    const cols = rows[r]?.length ?? 0;
    for (let c = 0;c < cols; c++) {
      const key = `${r},${c}`;
      if (skip.has(key))
        continue;
      const m = mergeAt.get(key);
      let colspan = 1;
      if (m) {
        colspan = Math.max(1, m.colspan);
        for (let rr = 0;rr < m.rowspan; rr++)
          for (let cc = 0;cc < m.colspan; cc++)
            if (rr || cc)
              skip.add(`${r + rr},${c + cc}`);
      }
      const cell = rows[r]?.[c] ?? {};
      const text3 = String(cell.v ?? "");
      if (!numCols)
        continue;
      const widthPx = approximateTextWidthPx(text3);
      const share = Math.max(1, Math.round(widthPx / colspan));
      for (let k = 0;k < colspan && c + k < numCols; k++) {
        const width = colWidthsPx[c + k] ?? 0;
        colWidthsPx[c + k] = Math.max(width, share);
      }
    }
  }
  for (let i = 0;i < colWidthsPx.length; i++) {
    const width = colWidthsPx[i];
    if (!width || !isFinite(width))
      colWidthsPx[i] = 32;
  }
  function toHexColor(c) {
    if (!c)
      return "#000";
    if (/^#/i.test(c))
      return c;
    const m = c.match(/^rgba?\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*[\d.]+)?\)$/i);
    if (m) {
      const rr = Number(m[1]);
      const gg = Number(m[2]);
      const bb = Number(m[3]);
      const to2 = (n) => Math.max(0, Math.min(255, n)).toString(16).padStart(2, "0");
      return `#${to2(rr)}${to2(gg)}${to2(bb)}`.toUpperCase();
    }
    return c;
  }
  let out = '<table style="table-layout:fixed;border-collapse:collapse;width:0px">';
  if (numCols > 0) {
    out += "<colgroup>";
    for (let i = 0;i < numCols; i++) {
      const w = Math.max(1, Math.round(colWidthsPx[i] ?? 0));
      out += `<col width="${w}"/>`;
    }
    out += "</colgroup>";
  }
  for (let r = 0;r < rows.length; r++) {
    out += "<tr>";
    const cols = rows[r]?.length ?? 0;
    for (let c = 0;c < cols; c++) {
      if (skip.has(`${r},${c}`))
        continue;
      const m = mergeAt.get(`${r},${c}`);
      let span = "";
      if (m) {
        if (m.rowspan > 1)
          span += ` rowspan="${m.rowspan}"`;
        if (m.colspan > 1)
          span += ` colspan="${m.colspan}"`;
        for (let rr = 0;rr < m.rowspan; rr++)
          for (let cc = 0;cc < m.colspan; cc++)
            if (rr || cc)
              skip.add(`${r + rr},${c + cc}`);
      }
      const cell = rows[r]?.[c] ?? {};
      const f = cell.fmt ?? {};
      const styles = [];
      if (f.bold)
        styles.push("font-weight:bold");
      if (f.italic)
        styles.push("font-style:italic");
      if (f.underline)
        styles.push("text-decoration:underline");
      if (f.strike)
        styles.push("text-decoration:line-through");
      if (f.color)
        styles.push(`color:${toHexColor(f.color)}`);
      if (f.fontFamily) {
        const fam = /\s/.test(f.fontFamily) ? `"${f.fontFamily}"` : f.fontFamily;
        styles.push(`font-family:${fam}`);
      }
      if (typeof f.fontSizePt === "number" && isFinite(f.fontSizePt) && f.fontSizePt > 0) {
        const sizeStr = `${Math.round(f.fontSizePt * 10) / 10}pt`;
        styles.push(`font-size:${sizeStr}`);
      }
      if (f.bg) {
        styles.push(`background-color:${f.bg}`);
        const bgHex = toHexColor(f.bg);
        styles.push(`background:${bgHex}`);
        styles.push("mso-pattern:black none");
      }
      if (f.align)
        styles.push(`text-align:${f.align}`);
      if (f.valign)
        styles.push(`vertical-align:${f.valign}`);
      if (f.wrap === false)
        styles.push("white-space:nowrap");
      if (f.wrap === true)
        styles.push("white-space:normal");
      if (f.numFmt) {
        styles.push(`mso-number-format:"${String(f.numFmt).replace(/"/g, "\\\"")}"`);
      } else {
        styles.push('mso-number-format:"General"');
      }
      if (typeof cell.v === "string" && /^\s*=/.test(cell.v)) {
        styles.push('mso-number-format:"\\@"');
      }
      const borderMap = (styleName) => {
        switch (styleName) {
          case "hair":
            return { widthPx: 1, cssStyle: "solid" };
          case "thin":
            return { widthPx: 1, cssStyle: "solid" };
          case "medium":
            return { widthPx: 2, cssStyle: "solid" };
          case "thick":
            return { widthPx: 3, cssStyle: "solid" };
          case "dotted":
            return { widthPx: 1, cssStyle: "dotted" };
          case "dashed":
            return { widthPx: 1, cssStyle: "dashed" };
          case "mediumDashed":
            return { widthPx: 2, cssStyle: "dashed" };
          case "dashDot":
            return { widthPx: 1, cssStyle: "dashed" };
          case "dashDotDot":
            return { widthPx: 1, cssStyle: "dotted" };
          case "mediumDashDot":
            return { widthPx: 2, cssStyle: "dashed" };
          case "mediumDashDotDot":
            return { widthPx: 2, cssStyle: "dotted" };
          case "double":
            return { widthPx: 3, cssStyle: "double" };
          case "slantDashDot":
            return { widthPx: 2, cssStyle: "dashed" };
          default:
            return null;
        }
      };
      const addBorder = (edge, styleName, color2) => {
        const m2 = borderMap(styleName);
        if (!m2)
          return;
        const cssColor = color2 ?? "#000";
        const css = `${m2.widthPx}px ${m2.cssStyle} ${cssColor}`;
        const pt = m2.widthPx * 72 / 96;
        const mso = `${pt}pt ${m2.cssStyle} ${toHexColor(cssColor)}`;
        styles.push(`border-${edge}:${css}`);
        styles.push(`mso-border-${edge}-alt:${mso}`);
      };
      if (f.border?.top)
        addBorder("top", f.border.top.style, f.border.top.color);
      if (f.border?.right)
        addBorder("right", f.border.right.style, f.border.right.color);
      if (f.border?.bottom)
        addBorder("bottom", f.border.bottom.style, f.border.bottom.color);
      if (f.border?.left)
        addBorder("left", f.border.left.style, f.border.left.color);
      if (f.diagonal?.up || f.diagonal?.down) {
        const diagStyle = f.diagonal.style;
        const diagColor = f.diagonal.color ?? "#000";
        const m2 = borderMap(diagStyle);
        if (m2) {
          const pt = m2.widthPx * 72 / 96;
          const mso = `${pt}pt ${m2.cssStyle} ${toHexColor(diagColor)}`;
          if (f.diagonal.up)
            styles.push(`mso-diagonal-up:${mso}`);
          if (f.diagonal.down)
            styles.push(`mso-diagonal-down:${mso}`);
        }
      }
      const styleAttr = styles.length ? ` style='${styles.join(";")}'` : "";
      out += `<td${span}${styleAttr}>${escapeHtml(cell.v ?? "")}</td>`;
    }
    out += "</tr>";
  }
  out += "</table>";
  const head = "<html><head>" + '<meta http-equiv=Content-Type content="text/html; charset=utf-8">' + '<meta name=ProgId content="Excel.Sheet">' + '<meta name=Generator content="Microsoft Excel 15">' + "<style>" + 'table{mso-displayed-decimal-separator:"\\.";mso-displayed-thousand-separator:"\\,";}' + "tr{mso-height-source:auto;}" + 'td{padding-top:1px;padding-right:1px;padding-left:1px;mso-ignore:padding;color:black;font-size:12.0pt;font-weight:400;font-style:normal;text-decoration:none;font-family:"Aptos Narrow", sans-serif;mso-font-charset:0;text-align:general;vertical-align:bottom;border:none;white-space:nowrap;mso-rotate:0;}' + "</style></head><body>";
  const start = "<!--StartFragment-->";
  const end = "<!--EndFragment-->";
  const tail = "</body></html>";
  return `${head}${start}${out}${end}${tail}`;
}

// node_modules/@oai/granola/dist/spreadsheet/workbook-html-import.js
init_address_utils();

// node_modules/@oai/granola/dist/spreadsheet/parse-html-table.js
var import_node_html_parser = __toESM(require_dist(), 1);
function parseHtmlTable(html) {
  const root = import_node_html_parser.parse(html ?? "", {
    comment: true,
    lowerCaseTagName: true,
    preserveTagNesting: true
  });
  const stylesheet = parseStylesheetRules(root);
  const table2 = root.querySelector("table");
  if (!table2) {
    return {
      rows: [[{ v: normalizeClipboardText(root.structuredText || root.text || "") }]],
      merges: [],
      colWidthsPx: []
    };
  }
  const tableStyle = resolveElementStyle(table2, stylesheet);
  const rows = [];
  const merges = [];
  const occupied = new Set;
  const rowElements = getTableRows(table2);
  rowElements.forEach((rowElement, rowIndex2) => {
    const row2 = rows[rowIndex2] ??= [];
    const rowStyle = mergeStyleMaps(tableStyle, resolveElementStyle(rowElement, stylesheet));
    let nextCol = 0;
    for (const cellElement of getRowCells(rowElement)) {
      while (occupied.has(`${rowIndex2}:${nextCol}`)) {
        nextCol += 1;
      }
      const rowspan = parseSpan(cellElement.getAttribute("rowspan"));
      const colspan = parseSpan(cellElement.getAttribute("colspan"));
      row2[nextCol] = parseClipboardCell(cellElement, rowStyle, stylesheet);
      for (let rowOffset = 0;rowOffset < rowspan; rowOffset += 1) {
        const targetRow = rowIndex2 + rowOffset;
        rows[targetRow] ??= [];
        for (let colOffset = 0;colOffset < colspan; colOffset += 1) {
          if (rowOffset === 0 && colOffset === 0) {
            continue;
          }
          occupied.add(`${targetRow}:${nextCol + colOffset}`);
        }
      }
      if (rowspan > 1 || colspan > 1) {
        merges.push({
          r: rowIndex2,
          c: nextCol,
          rowspan,
          colspan
        });
      }
      nextCol += colspan;
    }
  });
  return {
    rows,
    merges,
    colWidthsPx: parseColumnWidths(table2, stylesheet)
  };
}
function getTableRows(table2) {
  const rows = [];
  for (const child of table2.childNodes) {
    if (!(child instanceof import_node_html_parser.HTMLElement)) {
      continue;
    }
    if (child.rawTagName === "tr") {
      rows.push(child);
      continue;
    }
    if (child.rawTagName === "thead" || child.rawTagName === "tbody" || child.rawTagName === "tfoot") {
      for (const nested of child.childNodes) {
        if (nested instanceof import_node_html_parser.HTMLElement && nested.rawTagName === "tr") {
          rows.push(nested);
        }
      }
    }
  }
  return rows;
}
function getRowCells(row2) {
  const cells = [];
  for (const child of row2.childNodes) {
    if (child instanceof import_node_html_parser.HTMLElement && (child.rawTagName === "td" || child.rawTagName === "th")) {
      cells.push(child);
    }
  }
  return cells;
}
function parseColumnWidths(table2, stylesheet) {
  const widths = [];
  const colGroup = table2.childNodes.find((child) => child instanceof import_node_html_parser.HTMLElement && child.rawTagName === "colgroup");
  if (!colGroup) {
    return widths;
  }
  for (const child of colGroup.childNodes) {
    if (!(child instanceof import_node_html_parser.HTMLElement) || child.rawTagName !== "col") {
      continue;
    }
    const resolvedStyle = resolveElementStyle(child, stylesheet);
    const attrWidth = parsePixelValue(child.getAttribute("width"));
    const styleWidth = parsePixelValue(resolvedStyle.get("width"));
    widths.push(attrWidth ?? styleWidth ?? 0);
  }
  return widths;
}
function parseClipboardCell(cell, inheritedStyle, stylesheet) {
  const cellStyle = mergeStyleMaps(inheritedStyle, resolveElementStyle(cell, stylesheet));
  const style = mergeFallbackStyleMaps(cellStyle, collectDescendantStyles(cell));
  const text3 = normalizeClipboardText(extractCellText(cell));
  const border = parseBorders(style);
  const diagonal = parseDiagonalBorder(style);
  const numFmt = parseMsoNumberFormat(style.get("mso-number-format"));
  const fontSizePt = parseFontSizePt(style.get("font-size"));
  const fontFamily = normalizeFontFamily(style.get("font-family"));
  const decoration = parseTextDecoration(style.get("text-decoration"));
  const background = normalizeCssColor(style.get("background-color") ?? extractCssColor(style.get("background")));
  const align = normalizeHorizontalAlignment2(style.get("text-align"));
  const valign = normalizeVerticalAlignment2(style.get("vertical-align"));
  const wrap2 = parseWrap(style.get("white-space"));
  const bold = parseBold(style.get("font-weight"));
  const italic = parseItalic(style.get("font-style"));
  const fmt = {};
  if (bold !== undefined) {
    fmt.bold = bold;
  }
  if (italic !== undefined) {
    fmt.italic = italic;
  }
  if (decoration.underline !== undefined) {
    fmt.underline = decoration.underline;
  }
  if (decoration.strike !== undefined) {
    fmt.strike = decoration.strike;
  }
  const color2 = normalizeCssColor(style.get("color"));
  if (color2) {
    fmt.color = color2;
  }
  if (background) {
    fmt.bg = background;
  }
  if (align) {
    fmt.align = align;
  }
  if (valign) {
    fmt.valign = valign;
  }
  if (wrap2 !== undefined) {
    fmt.wrap = wrap2;
  }
  if (numFmt) {
    fmt.numFmt = numFmt;
  }
  if (fontFamily) {
    fmt.fontFamily = fontFamily;
  }
  if (fontSizePt !== undefined) {
    fmt.fontSizePt = fontSizePt;
  }
  if (Object.keys(border).length > 0) {
    fmt.border = border;
  }
  if (diagonal) {
    fmt.diagonal = diagonal;
  }
  return Object.keys(fmt).length > 0 ? { v: text3, fmt } : { v: text3 };
}
function extractCellText(node) {
  if (node instanceof import_node_html_parser.TextNode) {
    return node.text;
  }
  let text3 = "";
  for (const child of node.childNodes) {
    if (child.nodeType === import_node_html_parser.NodeType.TEXT_NODE && child instanceof import_node_html_parser.TextNode) {
      text3 += child.text;
      continue;
    }
    if (child instanceof import_node_html_parser.HTMLElement) {
      if (child.rawTagName === "br") {
        text3 += `
`;
        continue;
      }
      text3 += extractCellText(child);
    }
  }
  return text3;
}
function normalizeClipboardText(value2) {
  return value2.replace(/\r\n?/g, `
`).replace(/\u00a0/g, " ").replace(/[ \t]+\n/g, `
`).replace(/\n[ \t]+/g, `
`).trim();
}
function parseStylesheetRules(root) {
  const rules = [];
  for (const styleElement of root.querySelectorAll("style")) {
    const css = stripHtmlStyleComments(styleElement.text);
    for (const match of css.matchAll(/([^{}]+)\{([^{}]*)\}/gms)) {
      const selectorSource = match[1]?.trim();
      const body = match[2]?.trim();
      if (!selectorSource || !body || selectorSource.startsWith("@")) {
        continue;
      }
      const selectors = selectorSource.split(",").map((selector) => selector.trim()).filter(Boolean);
      if (selectors.length === 0) {
        continue;
      }
      rules.push({
        selectors,
        style: parseInlineStyle(body)
      });
    }
  }
  return rules;
}
function stripHtmlStyleComments(value2) {
  return value2.replace(/<!--/g, "").replace(/-->/g, "");
}
function resolveElementStyle(element, stylesheet) {
  const style = new Map;
  for (const rule2 of stylesheet) {
    if (rule2.selectors.some((selector) => matchesSelector(element, selector))) {
      mergeIntoStyleMap(style, rule2.style);
    }
  }
  mergeIntoStyleMap(style, parseInlineStyle(element.getAttribute("style")));
  return style;
}
function matchesSelector(element, selector) {
  const normalized = selector.trim().toLowerCase();
  if (!normalized || normalized.includes(" ") || normalized.includes(">") || normalized.includes(":") || normalized.includes("[") || normalized.includes("#")) {
    return false;
  }
  const parts = normalized.split(".").filter(Boolean);
  const tag2 = normalized.startsWith(".") ? undefined : parts.shift();
  if (tag2 && element.rawTagName !== tag2) {
    return false;
  }
  if (parts.length === 0) {
    return true;
  }
  const classNames = new Set((element.getAttribute("class") ?? "").split(/\s+/).map((part) => part.trim().toLowerCase()).filter(Boolean));
  return parts.every((className) => classNames.has(className));
}
function collectDescendantStyles(node) {
  const style = new Map;
  for (const child of node.childNodes) {
    if (!(child instanceof import_node_html_parser.HTMLElement)) {
      continue;
    }
    mergeIntoStyleMap(style, semanticElementStyle(child));
    mergeIntoStyleMap(style, parseInlineStyle(child.getAttribute("style")));
    mergeIntoStyleMap(style, collectDescendantStyles(child));
  }
  return style;
}
function semanticElementStyle(element) {
  switch (element.rawTagName) {
    case "b":
    case "strong":
      return new Map([["font-weight", "bold"]]);
    case "i":
    case "em":
      return new Map([["font-style", "italic"]]);
    case "u":
      return new Map([["text-decoration", "underline"]]);
    case "s":
    case "strike":
    case "del":
      return new Map([["text-decoration", "line-through"]]);
    default:
      return new Map;
  }
}
function parseInlineStyle(styleText) {
  const styles = new Map;
  if (!styleText) {
    return styles;
  }
  for (const chunk of styleText.split(";")) {
    const separator = chunk.indexOf(":");
    if (separator === -1) {
      continue;
    }
    const key = chunk.slice(0, separator).trim().toLowerCase();
    const value2 = chunk.slice(separator + 1).trim();
    if (key && value2) {
      styles.set(key, value2);
    }
  }
  return styles;
}
function mergeStyleMaps(...maps) {
  const merged = new Map;
  for (const style of maps) {
    if (!style) {
      continue;
    }
    mergeIntoStyleMap(merged, style);
  }
  return merged;
}
function mergeFallbackStyleMaps(primary, fallback) {
  const merged = new Map(primary);
  for (const [key, value2] of fallback) {
    if (!merged.has(key)) {
      merged.set(key, value2);
    }
  }
  return merged;
}
function mergeIntoStyleMap(target, source) {
  for (const [key, value2] of source) {
    target.set(key, value2);
  }
}
function parseBorders(style) {
  const border = {};
  for (const edge of ["top", "right", "bottom", "left"]) {
    const parsed = parseBorderLine(style.get(`mso-border-${edge}-alt`) ?? style.get(`border-${edge}`) ?? style.get("border"));
    if (parsed) {
      border[edge] = parsed;
    }
  }
  return border;
}
function parseDiagonalBorder(style) {
  const up = parseBorderLine(style.get("mso-diagonal-up"));
  const down = parseBorderLine(style.get("mso-diagonal-down"));
  if (!up && !down) {
    return;
  }
  return {
    style: up?.style ?? down?.style,
    color: up?.color ?? down?.color,
    up: Boolean(up),
    down: Boolean(down)
  };
}
function parseBorderLine(value2) {
  if (!value2) {
    return;
  }
  const normalized = value2.replaceAll('"', "").trim().toLowerCase();
  if (!normalized || normalized === "none" || normalized.includes("transparent")) {
    return;
  }
  const styleToken = normalized.match(/\b(double|dotted|dashed|solid|hair|thin|medium|thick)\b/)?.[1];
  const widthToken = normalized.match(/(\d+(?:\.\d+)?)(px|pt)\b/) ?? undefined;
  const rawColor = extractCssColor(value2);
  const cssColor = normalizeCssColor(rawColor);
  if (rawColor && !cssColor) {
    return;
  }
  const styleName = mapCssBorderStyle(styleToken, widthToken);
  if (!styleName && !cssColor) {
    return;
  }
  return {
    style: styleName,
    color: cssColor
  };
}
function mapCssBorderStyle(styleToken, widthToken) {
  if (!styleToken) {
    return;
  }
  switch (styleToken) {
    case "double":
    case "dotted":
    case "dashed":
    case "hair":
    case "thin":
    case "medium":
    case "thick":
      return styleToken;
    case "solid": {
      const width = widthToken ? Number(widthToken[1]) : 1;
      const unit2 = widthToken?.[2] ?? "px";
      const widthPx = unit2 === "pt" ? width * 96 / 72 : width;
      if (widthPx >= 2.5) {
        return "thick";
      }
      if (widthPx >= 1.5) {
        return "medium";
      }
      return "thin";
    }
    default:
      return;
  }
}
function parseWrap(value2) {
  if (!value2) {
    return;
  }
  const normalized = value2.toLowerCase();
  if (normalized.includes("nowrap")) {
    return false;
  }
  if (normalized.includes("normal") || normalized.includes("pre-wrap") || normalized.includes("break-spaces")) {
    return true;
  }
  return;
}
function parseMsoNumberFormat(value2) {
  if (!value2) {
    return;
  }
  const trimmed = value2.trim();
  const unquoted = trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'") ? trimmed.slice(1, -1) : trimmed;
  return unquoted.replace(/\\(.)/g, "$1");
}
function parseFontSizePt(value2) {
  if (!value2) {
    return;
  }
  const match = value2.trim().match(/^(\d+(?:\.\d+)?)(px|pt)$/i);
  if (!match) {
    return;
  }
  const magnitude = Number(match[1]);
  if (!Number.isFinite(magnitude) || magnitude <= 0) {
    return;
  }
  const unit2 = (match[2] ?? "px").toLowerCase();
  return unit2 === "px" ? magnitude * 72 / 96 : magnitude;
}
function normalizeFontFamily(value2) {
  if (!value2) {
    return;
  }
  const family = value2.split(",")[0]?.trim().replace(/^['"]|['"]$/g, "");
  return family || undefined;
}
function normalizeHorizontalAlignment2(value2) {
  switch (value2?.trim().toLowerCase()) {
    case "left":
      return "left";
    case "center":
      return "center";
    case "right":
      return "right";
    default:
      return;
  }
}
function normalizeVerticalAlignment2(value2) {
  switch (value2?.trim().toLowerCase()) {
    case "top":
      return "top";
    case "center":
    case "middle":
      return "middle";
    case "bottom":
      return "bottom";
    default:
      return;
  }
}
function parseBold(value2) {
  if (!value2) {
    return;
  }
  const normalized = value2.trim().toLowerCase();
  if (normalized === "bold") {
    return true;
  }
  if (normalized === "normal") {
    return false;
  }
  const numeric = Number(normalized);
  if (Number.isFinite(numeric)) {
    return numeric >= 600;
  }
  return;
}
function parseItalic(value2) {
  if (!value2) {
    return;
  }
  switch (value2.trim().toLowerCase()) {
    case "italic":
    case "oblique":
      return true;
    case "normal":
      return false;
    default:
      return;
  }
}
function parseTextDecoration(value2) {
  if (!value2) {
    return {};
  }
  const normalized = value2.trim().toLowerCase();
  return {
    underline: normalized.includes("underline") ? true : normalized.includes("none") ? false : undefined,
    strike: normalized.includes("line-through") ? true : normalized.includes("none") ? false : undefined
  };
}
function parseSpan(value2) {
  const parsed = Number(value2);
  return Number.isFinite(parsed) && parsed > 1 ? Math.floor(parsed) : 1;
}
function parsePixelValue(value2) {
  if (!value2) {
    return;
  }
  const match = value2.trim().match(/^(\d+(?:\.\d+)?)(px|pt)?$/i);
  if (!match) {
    return;
  }
  const numeric = Number(match[1]);
  if (!Number.isFinite(numeric) || numeric <= 0) {
    return;
  }
  return match[2]?.toLowerCase() === "pt" ? numeric * 96 / 72 : numeric;
}
function extractCssColor(value2) {
  if (!value2) {
    return;
  }
  const explicit = value2.match(/#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})\b|rgba?\([^)]+\)/i);
  if (explicit?.[0]) {
    return explicit[0];
  }
  const named2 = value2.match(/\b(black|white|red|green|blue|yellow|cyan|magenta|gray|grey|orange|purple|brown|pink)\b/i);
  return named2?.[1];
}
function normalizeCssColor(value2) {
  if (!value2) {
    return;
  }
  const trimmed = value2.trim();
  if (!trimmed) {
    return;
  }
  if (/^#[0-9a-f]{3}$/i.test(trimmed)) {
    const [r, g, b] = trimmed.slice(1).split("");
    return `#${r}${r}${g}${g}${b}${b}`.toUpperCase();
  }
  if (/^#[0-9a-f]{6}$/i.test(trimmed)) {
    return trimmed.toUpperCase();
  }
  if (/^#[0-9a-f]{8}$/i.test(trimmed)) {
    return `#${trimmed.slice(1, 7).toUpperCase()}`;
  }
  const rgb2 = trimmed.match(/^rgba?\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\)$/i);
  if (rgb2) {
    const alpha = rgb2[4] == null ? 1 : Number(rgb2[4]);
    if (!Number.isFinite(alpha) || alpha <= 0) {
      return;
    }
    const toHex = (numeric) => Math.max(0, Math.min(255, Number(numeric))).toString(16).padStart(2, "0").toUpperCase();
    return `#${toHex(rgb2[1] ?? "0")}${toHex(rgb2[2] ?? "0")}${toHex(rgb2[3] ?? "0")}`;
  }
  const namedColors = {
    black: "#000000",
    white: "#FFFFFF",
    red: "#FF0000",
    green: "#008000",
    blue: "#0000FF",
    yellow: "#FFFF00",
    cyan: "#00FFFF",
    magenta: "#FF00FF",
    gray: "#808080",
    grey: "#808080",
    orange: "#FFA500",
    purple: "#800080",
    brown: "#A52A2A",
    pink: "#FFC0CB"
  };
  return namedColors[trimmed.toLowerCase()] ?? trimmed;
}

// node_modules/@oai/granola/dist/spreadsheet/workbook-html-import.js
function importHtmlIntoWorkbook(args2) {
  const { workbook, sheetIndex, html, target, options } = args2;
  const sheetName = workbook.worksheets.getSheetNameByIndex(sheetIndex);
  if (!sheetName) {
    throw new Error(`Worksheet index ${sheetIndex} not found`);
  }
  const worksheet = workbook.worksheets.getItem(sheetName);
  const parsed = parseHtmlTable(html);
  const sourceRowCount = Math.max(parsed.rows.length, 1);
  const sourceColCount = Math.max(parsed.colWidthsPx.length, 1, ...parsed.rows.map((row2) => row2.length));
  const resolvedTarget = resolveHtmlImportTarget({
    sheetName,
    sourceRowCount,
    sourceColCount,
    target
  });
  const targetRangeAddress = buildSelectionRectAddress(resolvedTarget.selectionRect);
  const applyValues = options?.applyValues ?? true;
  worksheet.getRange(targetRangeAddress).unmerge();
  worksheet.getRange(targetRangeAddress).clear({
    applyTo: applyValues ? "all" : "formats"
  });
  for (let rowOffset = 0;rowOffset <= resolvedTarget.selectionRect.r2 - resolvedTarget.selectionRect.r1; rowOffset += 1) {
    for (let colOffset = 0;colOffset <= resolvedTarget.selectionRect.c2 - resolvedTarget.selectionRect.c1; colOffset += 1) {
      const sourceCell = parsed.rows[rowOffset % sourceRowCount]?.[colOffset % sourceColCount];
      const address = makeCellAddress(resolvedTarget.selectionRect.r1 + rowOffset, resolvedTarget.selectionRect.c1 + colOffset);
      applyImportedHtmlCell(worksheet.getRange(address), sourceCell, applyValues);
    }
  }
  const targetRowCount = resolvedTarget.selectionRect.r2 - resolvedTarget.selectionRect.r1 + 1;
  const targetColCount = resolvedTarget.selectionRect.c2 - resolvedTarget.selectionRect.c1 + 1;
  for (const merge2 of parsed.merges) {
    for (let tileRow = 0;tileRow < targetRowCount; tileRow += sourceRowCount) {
      for (let tileCol = 0;tileCol < targetColCount; tileCol += sourceColCount) {
        const startRow = resolvedTarget.selectionRect.r1 + tileRow + merge2.r;
        const startCol = resolvedTarget.selectionRect.c1 + tileCol + merge2.c;
        const endRow = startRow + merge2.rowspan - 1;
        const endCol = startCol + merge2.colspan - 1;
        if (startRow > resolvedTarget.selectionRect.r2 || startCol > resolvedTarget.selectionRect.c2 || endRow > resolvedTarget.selectionRect.r2 || endCol > resolvedTarget.selectionRect.c2) {
          continue;
        }
        worksheet.getRange(buildRangeRef({
          startRow,
          startCol,
          endRow,
          endCol
        })).merge();
      }
    }
  }
  if (parsed.colWidthsPx.length > 0) {
    for (let colOffset = 0;colOffset < targetColCount; colOffset += 1) {
      const width = parsed.colWidthsPx[colOffset % parsed.colWidthsPx.length];
      if (width == null || !Number.isFinite(width) || width <= 0) {
        continue;
      }
      const columnName = columnLabel(resolvedTarget.selectionRect.c1 + colOffset);
      worksheet.getRange(`${columnName}:${columnName}`).format.columnWidthPx = width;
    }
  }
  workbook.recalculate();
  return {
    range: targetRangeAddress,
    selectionRect: resolvedTarget.selectionRect
  };
}
function resolveHtmlImportTarget(args2) {
  const { sheetName, sourceRowCount, sourceColCount, target } = args2;
  if (!target) {
    return {
      range: buildRangeRef({
        startRow: 0,
        startCol: 0,
        endRow: sourceRowCount - 1,
        endCol: sourceColCount - 1
      }),
      selectionRect: {
        r1: 0,
        c1: 0,
        r2: sourceRowCount - 1,
        c2: sourceColCount - 1
      }
    };
  }
  if (typeof target !== "string") {
    return {
      range: buildRangeRef({
        startRow: target.row,
        startCol: target.col,
        endRow: target.row + sourceRowCount - 1,
        endCol: target.col + sourceColCount - 1
      }),
      selectionRect: {
        r1: target.row,
        c1: target.col,
        r2: target.row + sourceRowCount - 1,
        c2: target.col + sourceColCount - 1
      }
    };
  }
  const stripped = target.trim().startsWith("=") ? target.trim().slice(1) : target.trim();
  const bangIndex = stripped.lastIndexOf("!");
  const ref2 = bangIndex === -1 ? stripped : stripped.slice(bangIndex + 1);
  if (bangIndex >= 0) {
    const rawSheet = stripped.slice(0, bangIndex);
    const unescaped = rawSheet.startsWith("'") && rawSheet.endsWith("'") ? rawSheet.slice(1, -1).replace(/''/g, "'") : rawSheet;
    if (unescaped.trim() && unescaped.trim() !== sheetName) {
      throw new Error(`Range sheet "${unescaped.trim()}" does not match "${sheetName}"`);
    }
  }
  const parsed = parseRangeAddress(ref2);
  if (!parsed) {
    throw new Error(`Invalid target "${target}"`);
  }
  const isSingleCell = parsed.bounds.startRow === parsed.bounds.endRow && parsed.bounds.startCol === parsed.bounds.endCol;
  const selectionRect = isSingleCell ? {
    r1: parsed.bounds.startRow,
    c1: parsed.bounds.startCol,
    r2: parsed.bounds.startRow + sourceRowCount - 1,
    c2: parsed.bounds.startCol + sourceColCount - 1
  } : {
    r1: parsed.bounds.startRow,
    c1: parsed.bounds.startCol,
    r2: parsed.bounds.endRow,
    c2: parsed.bounds.endCol
  };
  return {
    range: buildSelectionRectAddress(selectionRect),
    selectionRect
  };
}
function buildSelectionRectAddress(selectionRect) {
  return buildRangeRef({
    startRow: selectionRect.r1,
    startCol: selectionRect.c1,
    endRow: selectionRect.r2,
    endCol: selectionRect.c2
  });
}
function applyImportedHtmlCell(range2, cell, applyValues) {
  const value2 = typeof cell?.v === "number" ? String(cell.v) : cell?.v ?? "";
  const format3 = cell?.fmt;
  if (applyValues) {
    const trimmed = value2.trimStart();
    const numberFormat = format3?.numFmt?.trim();
    const isExplicitText = numberFormat === "@" || numberFormat === "\\@";
    if (trimmed.startsWith("=") && !isExplicitText) {
      range2.formulas = [[trimmed]];
    } else if (value2 !== "") {
      range2.values = [[coerceImportedHtmlValue(value2, isExplicitText)]];
    }
  }
  if (!format3) {
    return;
  }
  if (format3.bold !== undefined) {
    range2.format.font.bold = format3.bold;
  }
  if (format3.italic !== undefined) {
    range2.format.font.italic = format3.italic;
  }
  if (format3.color) {
    range2.format.font.color = format3.color;
  }
  if (format3.bg) {
    range2.format.fill = format3.bg;
  }
  if (format3.align) {
    range2.format.horizontalAlignment = format3.align;
  }
  if (format3.valign) {
    range2.format.verticalAlignment = format3.valign === "middle" ? "center" : format3.valign;
  }
  if (format3.wrap !== undefined) {
    range2.format.wrapText = format3.wrap;
  }
  if (format3.numFmt) {
    range2.format.numberFormat = format3.numFmt;
  }
  if (format3.fontFamily) {
    range2.format.font.name = format3.fontFamily;
  }
  if (typeof format3.fontSizePt === "number" && Number.isFinite(format3.fontSizePt) && format3.fontSizePt > 0) {
    range2.format.font.size = format3.fontSizePt;
  }
  if (format3.border || format3.diagonal) {
    range2.format.borders = {
      ...format3.border?.top ? {
        top: {
          style: format3.border.top.style,
          color: format3.border.top.color
        }
      } : {},
      ...format3.border?.right ? {
        right: {
          style: format3.border.right.style,
          color: format3.border.right.color
        }
      } : {},
      ...format3.border?.bottom ? {
        bottom: {
          style: format3.border.bottom.style,
          color: format3.border.bottom.color
        }
      } : {},
      ...format3.border?.left ? {
        left: {
          style: format3.border.left.style,
          color: format3.border.left.color
        }
      } : {},
      ...format3.diagonal?.up ? {
        diagonalUp: {
          style: format3.diagonal.style,
          color: format3.diagonal.color
        }
      } : {},
      ...format3.diagonal?.down ? {
        diagonalDown: {
          style: format3.diagonal.style,
          color: format3.diagonal.color
        }
      } : {}
    };
  }
}
function coerceImportedHtmlValue(value2, isExplicitText) {
  if (isExplicitText) {
    return value2;
  }
  const trimmed = value2.trim();
  if (trimmed.length === 0) {
    return "";
  }
  if (trimmed.toLowerCase() === "true") {
    return true;
  }
  if (trimmed.toLowerCase() === "false") {
    return false;
  }
  const numeric = Number(trimmed);
  if (!Number.isNaN(numeric) && trimmed === String(numeric)) {
    return numeric;
  }
  return value2;
}

// node_modules/@oai/granola/dist/spreadsheet/workbook-raster-content.js
init_address_utils();
var DEFAULT_IMAGE_CONTENT_TYPE = "image/png";
var MIN_RASTER_DIMENSION = 1;
var FALLBACK_PASTED_IMAGE_WIDTH = 240;
var FALLBACK_PASTED_IMAGE_HEIGHT = 160;
async function renderWorkbookChartToImage(args2) {
  const { workbook, sheetIndex, chartId } = args2;
  const sheetName = workbook.worksheets.getSheetNameByIndex(sheetIndex);
  if (!sheetName) {
    throw new Error(`Worksheet index ${sheetIndex} not found`);
  }
  const worksheet = workbook.worksheets.getItem(sheetName);
  const chart2 = worksheet.charts.items.find((candidate) => candidate.id === chartId);
  if (!chart2) {
    throw new Error(`Chart "${chartId}" not found on worksheet "${sheetName}"`);
  }
  workbook.recalculate();
  const workbookProto = workbook.toProto();
  const sheetProto = workbookProto.sheets[sheetIndex];
  if (!sheetProto) {
    throw new Error(`Worksheet index ${sheetIndex} not found`);
  }
  const drawingProto = chart2.toDrawingProto({ preferPreview: true });
  if (!drawingProto.chart) {
    throw new Error(`Chart "${chartId}" could not be rendered`);
  }
  hydrateChartData2(drawingProto.chart, worksheet, buildSheetLookup2(workbook));
  const anchorSnapshot2 = chart2.captureAnchorSnapshot();
  const columnWidths = buildColumnWidthsPx(sheetProto);
  const rowHeights = buildRowHeightsPx(sheetProto);
  ensureLayoutSize(columnWidths, Math.max(anchorSnapshot2.from.col, anchorSnapshot2.to?.col ?? anchorSnapshot2.from.col) + 1, columnWidths[columnWidths.length - 1] ?? FALLBACK_COL_W_PX_RAW);
  ensureLayoutSize(rowHeights, Math.max(anchorSnapshot2.from.row, anchorSnapshot2.to?.row ?? anchorSnapshot2.from.row) + 1, rowHeights[rowHeights.length - 1] ?? pointsToPx(FALLBACK_ROW_H_PT));
  const bounds = chart2.resolveBoundsPx({
    columnWidths,
    rowHeights
  }, { preferPreview: true });
  if (!bounds) {
    throw new Error(`Chart "${chartId}" bounds could not be resolved`);
  }
  const widthPx = Math.max(MIN_RASTER_DIMENSION, Math.round(bounds.width));
  const heightPx = Math.max(MIN_RASTER_DIMENSION, Math.round(bounds.height));
  const { canvas, ctx } = createRasterCanvas(widthPx, heightPx);
  ctx.clearRect(0, 0, widthPx, heightPx);
  drawChartStandalone(ctx, drawingProto.chart, {
    x: 0,
    y: 0,
    width: widthPx,
    height: heightPx
  }, {
    themeMap: buildWorkbookThemeMap(workbookProto.theme),
    excelDefaults: true,
    elementId: chart2.id
  });
  const blob = await rasterCanvasToBlob(canvas, DEFAULT_IMAGE_CONTENT_TYPE);
  return {
    bytes: await blob.arrayBuffer(),
    contentType: blob.type || DEFAULT_IMAGE_CONTENT_TYPE,
    widthPx,
    heightPx
  };
}
function importImageIntoWorkbook(args2) {
  const { workbook, sheetIndex, source, target, options } = args2;
  const sheetName = workbook.worksheets.getSheetNameByIndex(sheetIndex);
  if (!sheetName) {
    throw new Error(`Worksheet index ${sheetIndex} not found`);
  }
  const resolvedTarget = resolveImageImportTarget({ sheetName, target });
  const selectionRect = {
    r1: resolvedTarget.row,
    c1: resolvedTarget.col,
    r2: resolvedTarget.row,
    c2: resolvedTarget.col
  };
  const range2 = buildSelectionRectAddress2(selectionRect);
  const imageSource = resolveImportedImageSource(source);
  const widthPx = sanitizeImageDimension(options?.widthPx ?? imageSource.widthPx, FALLBACK_PASTED_IMAGE_WIDTH);
  const heightPx = sanitizeImageDimension(options?.heightPx ?? imageSource.heightPx, FALLBACK_PASTED_IMAGE_HEIGHT);
  const worksheet = workbook.worksheets.getItem(sheetName);
  const image2 = worksheet.images.add({
    dataUrl: imageSource.dataUrl,
    anchor: {
      from: {
        row: resolvedTarget.row,
        col: resolvedTarget.col
      },
      extent: {
        widthPx,
        heightPx
      }
    }
  });
  return {
    range: range2,
    selectionRect,
    imageId: image2.imageId,
    widthPx,
    heightPx
  };
}
function sanitizeImageDimension(value2, fallback) {
  if (!Number.isFinite(value2)) {
    return fallback;
  }
  return Math.max(MIN_RASTER_DIMENSION, Math.round(value2));
}
function ensureLayoutSize(layout, size2, fallback) {
  while (layout.length < size2) {
    layout.push(fallback);
  }
}
function resolveImportedImageSource(source) {
  const payload = "dataUrl" in source ? resolveImageAssetPayload({ dataUrl: source.dataUrl }) : resolveImageAssetPayload({
    blob: source.bytes,
    contentType: source.contentType
  });
  if (!payload.data || payload.data.byteLength === 0) {
    throw new Error("Image import source did not resolve to bitmap bytes");
  }
  const contentType = payload.contentType ?? sourceContentType(source);
  if (!contentType || !contentType.startsWith("image/")) {
    throw new Error(`Unsupported image content type "${contentType ?? ""}"`);
  }
  const dimensions = resolveImageDimensions(payload.data, contentType);
  return {
    dataUrl: "dataUrl" in source ? source.dataUrl : encodeDataUrl(payload.data, contentType),
    widthPx: dimensions?.width,
    heightPx: dimensions?.height
  };
}
function sourceContentType(source) {
  return "dataUrl" in source ? undefined : source.contentType;
}
function encodeDataUrl(bytes, contentType) {
  return `data:${contentType};base64,${encodeBase642(bytes)}`;
}
function encodeBase642(bytes) {
  const globalObject = globalThis;
  const globalBuffer = globalObject["Buffer"];
  if (globalBuffer && typeof globalBuffer.from === "function") {
    return globalBuffer.from(bytes).toString("base64");
  }
  const globalBtoa = globalObject["btoa"];
  if (typeof globalBtoa === "function") {
    let binary = "";
    const chunkSize = 32768;
    for (let index = 0;index < bytes.length; index += chunkSize) {
      const chunk = bytes.subarray(index, index + chunkSize);
      binary += String.fromCharCode(...chunk);
    }
    return globalBtoa(binary);
  }
  throw new Error("Base64 encoding is unavailable in this environment");
}
async function rasterCanvasToBlob(canvas, contentType) {
  if ("convertToBlob" in canvas && typeof canvas.convertToBlob === "function") {
    return canvas.convertToBlob({ type: contentType });
  }
  if ("toBlob" in canvas && typeof canvas.toBlob === "function") {
    return new Promise((resolve2, reject) => {
      canvas.toBlob((blob) => {
        if (blob) {
          resolve2(blob);
          return;
        }
        reject(new Error("Canvas export produced an empty blob"));
      }, contentType);
    });
  }
  if ("toDataURL" in canvas && typeof canvas.toDataURL === "function") {
    const payload = resolveImageAssetPayload({ dataUrl: canvas.toDataURL(contentType) });
    if (!payload.data || !payload.contentType) {
      throw new Error("Canvas export data URL could not be decoded");
    }
    return new Blob([Uint8Array.from(payload.data)], {
      type: payload.contentType
    });
  }
  throw new Error("Canvas export is unavailable in this environment");
}
function createRasterCanvas(widthPx, heightPx) {
  const width = Math.max(MIN_RASTER_DIMENSION, Math.round(widthPx));
  const height = Math.max(MIN_RASTER_DIMENSION, Math.round(heightPx));
  if (typeof OffscreenCanvas !== "undefined") {
    const canvas = new OffscreenCanvas(width, height);
    const ctx = canvas.getContext("2d");
    if (!ctx) {
      throw new Error("OffscreenCanvas 2D context unavailable");
    }
    return { canvas, ctx };
  }
  if (typeof document !== "undefined" && typeof document.createElement === "function") {
    const canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    const ctx = canvas.getContext("2d");
    if (!ctx) {
      throw new Error("Canvas 2D context unavailable");
    }
    return { canvas, ctx };
  }
  throw new Error("No canvas implementation available for chart rasterization");
}
function resolveImageImportTarget(args2) {
  const { sheetName, target } = args2;
  if (!target) {
    return { row: 0, col: 0 };
  }
  if (typeof target !== "string") {
    return {
      row: Math.max(0, Math.floor(target.row ?? 0)),
      col: Math.max(0, Math.floor(target.col ?? 0))
    };
  }
  const trimmedTarget = target.trim();
  if (!trimmedTarget) {
    return { row: 0, col: 0 };
  }
  const stripped = trimmedTarget.startsWith("=") ? trimmedTarget.slice(1) : trimmedTarget;
  const bangIndex = stripped.lastIndexOf("!");
  const ref2 = bangIndex === -1 ? stripped : stripped.slice(bangIndex + 1);
  if (bangIndex >= 0) {
    const rawSheet = stripped.slice(0, bangIndex);
    const unescaped = rawSheet.startsWith("'") && rawSheet.endsWith("'") ? rawSheet.slice(1, -1).replace(/''/g, "'") : rawSheet;
    const normalizedRangeSheet = unescaped.trim();
    if (normalizedRangeSheet && normalizedRangeSheet !== sheetName) {
      throw new Error(`Target sheet "${normalizedRangeSheet}" does not match "${sheetName}"`);
    }
  }
  const parsed = parseRangeAddress(ref2);
  if (!parsed) {
    throw new Error(`Invalid image target "${target}"`);
  }
  return {
    row: parsed.bounds.startRow,
    col: parsed.bounds.startCol
  };
}
function buildSelectionRectAddress2(selectionRect) {
  return buildRangeRef({
    startRow: selectionRect.r1,
    startCol: selectionRect.c1,
    endRow: selectionRect.r2,
    endCol: selectionRect.c2
  });
}
function hydrateChartData2(chart2, currentSheet, sheetsByName) {
  if (!Array.isArray(chart2.series)) {
    return;
  }
  for (const series of chart2.series) {
    if (!series) {
      continue;
    }
    if (series.formula) {
      const values = readNumericRange2(series.formula, sheetsByName, currentSheet);
      if (values.length > 0) {
        series.values = values;
      }
    }
    if (series.categoryFormula) {
      const labels = readStringRange2(series.categoryFormula, sheetsByName, currentSheet);
      if (labels.length > 0) {
        series.categories = labels;
      }
    }
  }
  if (chart2.categories.length === 0) {
    const fallback = chart2.series.find((series) => series.categories.length > 0)?.categories ?? (() => {
      const firstFormula = chart2.series[0]?.categoryFormula;
      return firstFormula ? readStringRange2(firstFormula, sheetsByName, currentSheet) : [];
    })();
    if (fallback.length > 0) {
      chart2.categories = [...fallback];
    }
  }
}
function buildSheetLookup2(workbook) {
  const lookup = new Map;
  for (let index = 0;index < workbook.worksheets.getSheetCount(); index += 1) {
    const worksheet = workbook.worksheets.getItemAt(index);
    const key = sheetLookupKey2(worksheet.name);
    if (key) {
      lookup.set(key, worksheet);
    }
  }
  return lookup;
}
function readNumericRange2(formula, sheetsByName, fallbackSheet) {
  return collectRangeValues2(formula, sheetsByName, fallbackSheet, (cell) => {
    if (!cell || cell.value == null || cell.value === "") {
      return Number.NaN;
    }
    if (typeof cell.value === "number") {
      return cell.value;
    }
    if (typeof cell.value === "string") {
      const trimmed = cell.value.trim();
      if (!trimmed) {
        return Number.NaN;
      }
      const parsed = Number(trimmed);
      return Number.isFinite(parsed) ? parsed : Number.NaN;
    }
    return Number.NaN;
  });
}
function readStringRange2(formula, sheetsByName, fallbackSheet) {
  return collectRangeValues2(formula, sheetsByName, fallbackSheet, (cell) => {
    if (!cell || cell.value == null) {
      return "";
    }
    if (typeof cell.value === "string") {
      return cell.value;
    }
    if (typeof cell.value === "number") {
      return String(cell.value);
    }
    return "";
  });
}
function collectRangeValues2(formula, sheetsByName, fallbackSheet, project) {
  const parsed = parseA1Range2(formula);
  if (!parsed) {
    return [];
  }
  const targetSheet = getSheetForRange2(sheetsByName, parsed.sheetName, fallbackSheet);
  const results = [];
  for (let row2 = parsed.startRow;row2 <= parsed.endRow; row2 += 1) {
    for (let col = parsed.startCol;col <= parsed.endCol; col += 1) {
      results.push(project(targetSheet.__getCell(row2, col)));
    }
  }
  return results;
}
function parseA1Range2(ref2) {
  if (!ref2) {
    return null;
  }
  let input = ref2.trim();
  if (!input) {
    return null;
  }
  if (input.startsWith("=")) {
    input = input.slice(1);
  }
  if (!input) {
    return null;
  }
  const [firstSegment] = input.split(",");
  if (!firstSegment) {
    return null;
  }
  let sheetSegment;
  let addressSegment = firstSegment;
  const bangIndex = firstSegment.lastIndexOf("!");
  if (bangIndex !== -1) {
    sheetSegment = firstSegment.slice(0, bangIndex);
    addressSegment = firstSegment.slice(bangIndex + 1);
  }
  addressSegment = addressSegment.trim();
  if (!addressSegment) {
    return null;
  }
  const colonIndex = addressSegment.indexOf(":");
  const startRef = colonIndex === -1 ? addressSegment : addressSegment.slice(0, colonIndex);
  const endRef = colonIndex === -1 ? addressSegment : addressSegment.slice(colonIndex + 1);
  const start = parseCellAddress3(startRef);
  const end = parseCellAddress3(endRef);
  if (!start || !end) {
    return null;
  }
  return {
    sheetName: normalizeSheetName2(sheetSegment),
    startRow: Math.min(start.row, end.row),
    endRow: Math.max(start.row, end.row),
    startCol: Math.min(start.col, end.col),
    endCol: Math.max(start.col, end.col)
  };
}
function parseCellAddress3(address) {
  if (!address) {
    return null;
  }
  const normalized = address.replace(/\$/g, "").trim();
  if (!normalized) {
    return null;
  }
  const match = normalized.match(/^([A-Za-z]+)(\d+)$/);
  if (!match) {
    return null;
  }
  const [, lettersRaw, rowDigits] = match;
  if (!lettersRaw || !rowDigits) {
    return null;
  }
  const col = columnIndex(lettersRaw.toUpperCase());
  const row2 = Number.parseInt(rowDigits, 10) - 1;
  if (col < 0 || row2 < 0 || !Number.isFinite(row2)) {
    return null;
  }
  return { row: row2, col };
}
function normalizeSheetName2(raw) {
  if (!raw) {
    return;
  }
  let name2 = raw.trim();
  if (!name2) {
    return;
  }
  if (name2.startsWith("'") && name2.endsWith("'")) {
    name2 = name2.slice(1, -1).replace(/''/g, "'");
  }
  const bracketStart = name2.indexOf("[");
  const bracketEnd = name2.lastIndexOf("]");
  if (bracketStart !== -1 && bracketEnd > bracketStart) {
    name2 = name2.slice(bracketEnd + 1);
  }
  return name2;
}
function sheetLookupKey2(name2) {
  if (!name2) {
    return null;
  }
  const trimmed = name2.trim();
  return trimmed ? trimmed.toLowerCase() : null;
}
function getSheetForRange2(sheetsByName, requestedName, fallback) {
  if (requestedName) {
    const key = sheetLookupKey2(requestedName);
    if (key) {
      const hit = sheetsByName.get(key);
      if (hit) {
        return hit;
      }
    }
  }
  return fallback;
}

// node_modules/@oai/granola/dist/models/spreadsheet/conditional-formatting-render.js
init_address_utils();

// node_modules/@oai/granola/dist/models/spreadsheet/conditional-formatting-values.js
var EXCEL_EPOCH_MS6 = Date.UTC(1899, 11, 30);
var MS_PER_DAY6 = 24 * 60 * 60 * 1000;
var ISO_DATE_PATTERN2 = /^\d{4}-\d{2}-\d{2}(?:[T ][0-9:.+-Z]*)?$/;
function getConditionalFormattingCellValue(cell) {
  if (!cell || cell.value == null) {
    return null;
  }
  switch (cell.dataType) {
    case 5 /* CELL_DATA_TYPE_NUMBER */: {
      const numeric = Number(cell.value);
      return Number.isNaN(numeric) ? null : numeric;
    }
    case 4 /* CELL_DATA_TYPE_BOOLEAN */:
      return cell.value === "TRUE" || cell.value === "1";
    case 7 /* CELL_DATA_TYPE_DATE */:
      return coerceConditionalFormattingDate(cell.value);
    case 6 /* CELL_DATA_TYPE_ERROR */:
      return { kind: "Error", code: String(cell.value) };
    default:
      return cell.value;
  }
}
function getConditionalFormattingNumericValue(cell) {
  const value2 = getConditionalFormattingCellValue(cell);
  if (value2 == null) {
    return null;
  }
  if (typeof value2 === "number") {
    return Number.isNaN(value2) ? null : value2;
  }
  if (typeof value2 === "boolean") {
    return value2 ? 1 : 0;
  }
  if (typeof value2 === "string") {
    const numeric = Number(value2);
    return Number.isNaN(numeric) ? null : numeric;
  }
  if (value2 instanceof Date) {
    return dateToExcelSerial3(value2);
  }
  if (isErrorValue(value2)) {
    return null;
  }
  return null;
}
function getConditionalFormattingTextValue(cell) {
  if (!cell || cell.value == null) {
    return null;
  }
  const value2 = getConditionalFormattingCellValue(cell);
  if (value2 == null) {
    return null;
  }
  if (value2 instanceof Date) {
    return value2.toISOString();
  }
  if (isErrorValue(value2)) {
    return value2.code;
  }
  return String(value2);
}
function getConditionalFormattingDateValue(cell) {
  const value2 = getConditionalFormattingCellValue(cell);
  if (value2 instanceof Date) {
    return Number.isNaN(value2.getTime()) ? null : value2;
  }
  return cell?.value != null ? coerceConditionalFormattingDate(cell.value) : null;
}
function cellHasVisibleContent(cell) {
  if (!cell) {
    return false;
  }
  const hasValue = cell.value != null && String(cell.value).trim() !== "";
  const hasRichText = !!cell.paragraphs?.some((paragraph) => paragraph.runs?.some((run) => (run.text ?? "").length > 0));
  const hasFormula = !!cell.formula || typeof cell.sharedFormulaSi === "number";
  return hasValue || hasRichText || hasFormula;
}
function cellHasErrorValue(cell) {
  const value2 = getConditionalFormattingCellValue(cell);
  if (isErrorValue(value2)) {
    return true;
  }
  if (typeof value2 === "string") {
    const trimmed = value2.trim();
    return /^#[A-Z0-9\/!?:._-]+$/i.test(trimmed);
  }
  return false;
}
function getConditionalFormattingValueKey(cell) {
  const value2 = getConditionalFormattingCellValue(cell);
  if (value2 == null) {
    return null;
  }
  if (value2 instanceof Date) {
    const serial = dateToExcelSerial3(value2);
    return serial == null ? null : `d:${serial}`;
  }
  if (isErrorValue(value2)) {
    return `e:${value2.code.trim().toUpperCase()}`;
  }
  if (typeof value2 === "string") {
    return `s:${value2.trim().toLocaleLowerCase()}`;
  }
  if (typeof value2 === "number") {
    return `n:${normalizeNumberKey(value2)}`;
  }
  if (typeof value2 === "boolean") {
    return value2 ? "b:true" : "b:false";
  }
  return null;
}
function matchesTimePeriod(period, value2, now = new Date) {
  const cellDay = startOfUtcDay(value2);
  const today = startOfUtcDay(now);
  const normalized = period.replace(/[^a-z0-9]/gi, "").toLowerCase();
  switch (normalized) {
    case "today":
      return cellDay === today;
    case "yesterday":
      return cellDay === addUtcDays(today, -1);
    case "tomorrow":
      return cellDay === addUtcDays(today, 1);
    case "last7days":
      return cellDay >= addUtcDays(today, -6) && cellDay <= today;
    case "thisweek": {
      const start = startOfUtcWeek(today);
      return cellDay >= start && cellDay < addUtcDays(start, 7);
    }
    case "lastweek": {
      const start = startOfUtcWeek(today);
      return cellDay >= addUtcDays(start, -7) && cellDay < start;
    }
    case "nextweek": {
      const start = startOfUtcWeek(today);
      return cellDay >= addUtcDays(start, 7) && cellDay < addUtcDays(start, 14);
    }
    case "thismonth": {
      const start = startOfUtcMonth(today);
      return cellDay >= start && cellDay < startOfNextUtcMonth(today);
    }
    case "lastmonth": {
      const start = startOfUtcMonth(today);
      const previous2 = startOfUtcMonth(addUtcDays(start, -1));
      return cellDay >= previous2 && cellDay < start;
    }
    case "nextmonth": {
      const next2 = startOfNextUtcMonth(today);
      return cellDay >= next2 && cellDay < startOfNextUtcMonth(next2);
    }
    default:
      return false;
  }
}
function coerceConditionalFormattingDate(value2) {
  if (value2 instanceof Date) {
    return Number.isNaN(value2.getTime()) ? null : value2;
  }
  if (typeof value2 === "number") {
    return Number.isFinite(value2) ? new Date(EXCEL_EPOCH_MS6 + value2 * MS_PER_DAY6) : null;
  }
  if (typeof value2 !== "string") {
    return null;
  }
  const numeric = Number(value2);
  if (Number.isFinite(numeric)) {
    return new Date(EXCEL_EPOCH_MS6 + numeric * MS_PER_DAY6);
  }
  if (!ISO_DATE_PATTERN2.test(value2)) {
    return null;
  }
  const timestamp = Date.parse(value2);
  return Number.isNaN(timestamp) ? null : new Date(timestamp);
}
function dateToExcelSerial3(value2) {
  const timestamp = value2.getTime();
  if (Number.isNaN(timestamp)) {
    return null;
  }
  return (timestamp - EXCEL_EPOCH_MS6) / MS_PER_DAY6;
}
function normalizeNumberKey(value2) {
  return Number.isInteger(value2) ? `${value2}` : value2.toPrecision(15);
}
function startOfUtcDay(value2) {
  return Date.UTC(value2.getUTCFullYear(), value2.getUTCMonth(), value2.getUTCDate());
}
function addUtcDays(dayStart, days2) {
  return dayStart + days2 * MS_PER_DAY6;
}
function startOfUtcWeek(dayStart) {
  const date6 = new Date(dayStart);
  return addUtcDays(dayStart, -date6.getUTCDay());
}
function startOfUtcMonth(dayStart) {
  const date6 = new Date(dayStart);
  return Date.UTC(date6.getUTCFullYear(), date6.getUTCMonth(), 1);
}
function startOfNextUtcMonth(dayStart) {
  const date6 = new Date(dayStart);
  return Date.UTC(date6.getUTCFullYear(), date6.getUTCMonth() + 1, 1);
}

// node_modules/@oai/granola/dist/models/spreadsheet/conditional-formatting-matchers.js
function buildConditionalFormattingValueCounts(options) {
  const counts = new Map;
  for (const range2 of options.ranges) {
    for (let row2 = range2.startRow;row2 <= range2.endRow; row2 += 1) {
      for (let col = range2.startCol;col <= range2.endCol; col += 1) {
        const key = getConditionalFormattingValueKey(options.getCell(row2, col));
        if (key == null) {
          continue;
        }
        counts.set(key, (counts.get(key) ?? 0) + 1);
      }
    }
  }
  return counts;
}
function buildTop10Threshold(options) {
  const values = collectNumericValues(options.ranges, options.getCell);
  if (values.length === 0) {
    return null;
  }
  const requestedRank = typeof options.rank === "number" && Number.isFinite(options.rank) ? options.rank : 10;
  const rankCount = options.percent ? Math.ceil(values.length * requestedRank / 100) : Math.floor(requestedRank);
  const count3 = Math.max(1, Math.min(values.length, rankCount));
  const bottom = options.bottom ?? false;
  const sorted = values.slice().sort((left, right) => bottom ? left - right : right - left);
  const threshold = sorted[count3 - 1];
  if (threshold === undefined || Number.isNaN(threshold)) {
    return null;
  }
  return { bottom, threshold };
}
function buildAboveAverageThreshold(options) {
  const values = collectNumericValues(options.ranges, options.getCell);
  if (values.length === 0) {
    return null;
  }
  const average = values.reduce((sum3, value2) => sum3 + value2, 0) / values.length;
  const aboveAverage = options.aboveAverage ?? true;
  const equalAverage = options.equalAverage ?? false;
  let threshold = average;
  const deviationCount = typeof options.stdDev === "number" && Number.isFinite(options.stdDev) ? Math.abs(options.stdDev) : 0;
  if (deviationCount > 0) {
    const variance = values.reduce((sum3, value2) => sum3 + (value2 - average) ** 2, 0) / values.length;
    const deviation = Math.sqrt(variance);
    threshold = average + (aboveAverage ? deviation : -deviation) * deviationCount;
  }
  return {
    aboveAverage,
    equalAverage,
    threshold
  };
}
function matchesConditionalFormattingTextRule(type, text3, cell) {
  const needle = text3.trim().toLocaleLowerCase();
  if (!needle) {
    return false;
  }
  const haystack = getConditionalFormattingTextValue(cell)?.toLocaleLowerCase();
  if (!haystack) {
    return false;
  }
  switch (type) {
    case "containsText":
      return haystack.includes(needle);
    case "notContainsText":
      return !haystack.includes(needle);
    case "beginsWith":
      return haystack.startsWith(needle);
    case "endsWith":
      return haystack.endsWith(needle);
  }
}
function matchesConditionalFormattingBlankRule(type, cell) {
  const hasContent2 = cellHasVisibleContent(cell);
  return type === "containsBlanks" ? !hasContent2 : hasContent2;
}
function matchesConditionalFormattingErrorRule(type, cell) {
  const hasError = cellHasErrorValue(cell);
  return type === "containsErrors" ? hasError : !hasError;
}
function matchesConditionalFormattingValueCountRule(type, counts, cell) {
  const key = getConditionalFormattingValueKey(cell);
  if (key == null) {
    return false;
  }
  const frequency = counts.get(key) ?? 0;
  return type === "duplicateValues" ? frequency > 1 : frequency === 1;
}
function matchesConditionalFormattingTop10Rule(threshold, cell) {
  const value2 = getConditionalFormattingNumericValue(cell);
  if (value2 == null) {
    return false;
  }
  return threshold.bottom ? value2 <= threshold.threshold : value2 >= threshold.threshold;
}
function matchesConditionalFormattingAboveAverageRule(threshold, cell) {
  const value2 = getConditionalFormattingNumericValue(cell);
  if (value2 == null) {
    return false;
  }
  if (threshold.aboveAverage) {
    return threshold.equalAverage ? value2 >= threshold.threshold : value2 > threshold.threshold;
  }
  return threshold.equalAverage ? value2 <= threshold.threshold : value2 < threshold.threshold;
}
function matchesConditionalFormattingTimePeriodRule(period, cell, now) {
  const value2 = getConditionalFormattingDateValue(cell);
  if (!value2) {
    return false;
  }
  return matchesTimePeriod(period, value2, now);
}
function collectNumericValues(ranges, getCell) {
  const values = [];
  for (const range2 of ranges) {
    for (let row2 = range2.startRow;row2 <= range2.endRow; row2 += 1) {
      for (let col = range2.startCol;col <= range2.endCol; col += 1) {
        const value2 = getConditionalFormattingNumericValue(getCell(row2, col));
        if (value2 != null) {
          values.push(value2);
        }
      }
    }
  }
  return values;
}

// node_modules/@oai/granola/dist/models/spreadsheet/conditional-formatting-thresholds.js
function buildConditionalFormattingNumericStats(options) {
  const values = [];
  for (const range2 of options.ranges) {
    for (let row2 = range2.startRow;row2 <= range2.endRow; row2 += 1) {
      for (let col = range2.startCol;col <= range2.endCol; col += 1) {
        const value2 = getConditionalFormattingNumericValue(options.getCell(row2, col));
        if (value2 != null) {
          values.push(value2);
        }
      }
    }
  }
  if (values.length === 0) {
    return null;
  }
  const sortedValues = values.slice().sort((left, right) => left - right);
  const min4 = sortedValues[0] ?? 0;
  const max5 = sortedValues[sortedValues.length - 1] ?? min4;
  return { values, sortedValues, min: min4, max: max5 };
}
function resolveConditionalFormattingCfvoValue(options) {
  const { cfvo, stats, treatNumericValuesAsPercent = false } = options;
  const rawType = (cfvo.type ?? "").trim().toLowerCase();
  const normalizedType = treatNumericValuesAsPercent && (rawType === "" || rawType === "num") ? "percent" : rawType;
  switch (normalizedType) {
    case "min":
      return stats.min;
    case "max":
      return stats.max;
    case "percent":
      return resolvePercentOfRange(stats, Number(cfvo.val ?? 0));
    case "percentile":
      return resolvePercentile(stats, Number(cfvo.val ?? 0));
    default: {
      const numeric = Number(cfvo.val ?? 0);
      return Number.isFinite(numeric) ? numeric : 0;
    }
  }
}
function resolvePercentOfRange(stats, percent) {
  const clamped = clampPercent(percent);
  if (stats.max === stats.min) {
    return stats.min;
  }
  return stats.min + (stats.max - stats.min) * clamped / 100;
}
function resolvePercentile(stats, percentile) {
  const clamped = clampPercent(percentile);
  if (stats.sortedValues.length === 1) {
    return stats.sortedValues[0] ?? 0;
  }
  const position = clamped / 100 * (stats.sortedValues.length - 1);
  const lowerIndex = Math.floor(position);
  const upperIndex = Math.min(stats.sortedValues.length - 1, Math.ceil(position));
  const lower = stats.sortedValues[lowerIndex] ?? 0;
  const upper = stats.sortedValues[upperIndex] ?? lower;
  const fraction = position - lowerIndex;
  return lower + (upper - lower) * fraction;
}
function clampPercent(value2) {
  if (!Number.isFinite(value2)) {
    return 0;
  }
  return Math.max(0, Math.min(100, value2));
}

// node_modules/@oai/granola/dist/models/spreadsheet/conditional-formatting-render.js
var DEFAULT_CELLIS_FILL = "rgba(255,199,206,1)";
var DEFAULT_ACCENT_COLOR_FALLBACK = "#4F81BD";
var SPREADSHEET_COLOR_OPTIONS6 = { colorSpace: "spreadsheetml" };
var DEFAULT_DATABAR_COLOR = {
  type: 2 /* COLOR_TYPE_SCHEME */,
  value: "accent1",
  lastColor: "",
  transform: {
    tint: 60000,
    shade: 0,
    lumMod: 0,
    lumOff: 0,
    satMod: 0,
    alpha: 1e5
  }
};

class ConditionalFormattingRenderCache {
  #sheetName;
  #getCell;
  #evaluateExpression;
  #conditionalRules;
  #colorScaleRules;
  #dataBarRules;
  #iconSetRules;
  constructor(options) {
    this.#sheetName = options.sheetName;
    this.#getCell = options.getCell;
    this.#evaluateExpression = options.evaluateExpression;
    this.#conditionalRules = options.conditionalRules;
    this.#colorScaleRules = options.colorScaleRules;
    this.#dataBarRules = options.dataBarRules;
    this.#iconSetRules = options.iconSetRules;
  }
  getFillCss(rowIdx, colIdx, cell) {
    let fill2 = null;
    let bestPriority = Number.POSITIVE_INFINITY;
    const target = cell ?? this.#getCell(rowIdx, colIdx);
    for (const rule2 of this.#conditionalRules) {
      if (!inRanges(rowIdx, colIdx, rule2.ranges))
        continue;
      if (!this.#ruleMatches(rule2, rowIdx, colIdx, target))
        continue;
      const candidate = rule2.fillCss ?? (rule2.type === "cellIs" ? DEFAULT_CELLIS_FILL : null);
      if (candidate && rule2.priority < bestPriority) {
        fill2 = candidate;
        bestPriority = rule2.priority;
      }
    }
    if (this.#colorScaleRules.length > 0) {
      const v = getConditionalFormattingNumericValue(target);
      if (v != null) {
        for (const rule2 of this.#colorScaleRules) {
          if (!inRanges(rowIdx, colIdx, rule2.ranges))
            continue;
          const color2 = interpolateColorScale(rule2, v);
          if (!color2)
            continue;
          if (rule2.priority < bestPriority) {
            fill2 = color2;
            bestPriority = rule2.priority;
          }
        }
      }
    }
    return fill2;
  }
  getTextColor(rowIdx, colIdx, cell) {
    let bestPriority = Number.POSITIVE_INFINITY;
    let color2 = null;
    const target = cell ?? this.#getCell(rowIdx, colIdx);
    for (const rule2 of this.#conditionalRules) {
      if (!rule2.fontColor)
        continue;
      if (!inRanges(rowIdx, colIdx, rule2.ranges))
        continue;
      if (!this.#ruleMatches(rule2, rowIdx, colIdx, target))
        continue;
      if (rule2.priority < bestPriority) {
        color2 = rule2.fontColor;
        bestPriority = rule2.priority;
      }
    }
    return color2;
  }
  getDataBar(rowIdx, colIdx, cell) {
    const target = cell ?? this.#getCell(rowIdx, colIdx);
    const v = getConditionalFormattingNumericValue(target);
    if (v == null)
      return null;
    let best = null;
    for (const rule2 of this.#dataBarRules) {
      if (!inRanges(rowIdx, colIdx, rule2.ranges))
        continue;
      if (!best || rule2.priority < best.priority) {
        best = rule2;
      }
    }
    return best;
  }
  hasDataBar(rowIdx, colIdx, cell) {
    return this.getDataBar(rowIdx, colIdx, cell) != null;
  }
  getIconSet(rowIdx, colIdx, cell) {
    const target = cell ?? this.#getCell(rowIdx, colIdx);
    const value2 = getConditionalFormattingNumericValue(target);
    if (value2 == null) {
      return null;
    }
    let best = null;
    for (const rule2 of this.#iconSetRules) {
      if (!inRanges(rowIdx, colIdx, rule2.ranges))
        continue;
      if (!best || rule2.priority < best.priority) {
        best = rule2;
      }
    }
    if (!best) {
      return null;
    }
    return {
      iconSetName: best.iconSetName,
      iconIndex: selectIconSetIndex(best, value2),
      priority: best.priority,
      showValue: best.showValue
    };
  }
  #ruleMatches(rule2, rowIdx, colIdx, cell) {
    switch (rule2.type) {
      case "cellIs": {
        const v = getConditionalFormattingNumericValue(cell);
        return evalCellIs(rule2.operator ?? "", rule2.formula, v);
      }
      case "expression":
        return this.#evaluateExpressionRule(rule2, rowIdx, colIdx);
      case "containsText":
      case "notContainsText":
      case "beginsWith":
      case "endsWith":
        return matchesConditionalFormattingTextRule(rule2.type, rule2.text, cell);
      case "containsBlanks":
      case "notContainsBlanks":
        return matchesConditionalFormattingBlankRule(rule2.type, cell);
      case "containsErrors":
      case "notContainsErrors":
        return matchesConditionalFormattingErrorRule(rule2.type, cell);
      case "timePeriod":
        return matchesConditionalFormattingTimePeriodRule(rule2.timePeriod, cell);
      case "duplicateValues":
      case "uniqueValues":
        return matchesConditionalFormattingValueCountRule(rule2.type, rule2.valueCounts, cell);
      case "top10":
        return matchesConditionalFormattingTop10Rule(rule2.threshold, cell);
      case "aboveAverage":
        return matchesConditionalFormattingAboveAverageRule(rule2.threshold, cell);
      default:
        return false;
    }
  }
  #evaluateExpressionRule(rule2, rowIdx, colIdx) {
    const key = `${rowIdx}:${colIdx}`;
    const cached2 = rule2.matchCache.get(key);
    if (cached2 != null)
      return cached2;
    const rowOffset = rowIdx - rule2.anchor.row;
    const colOffset = colIdx - rule2.anchor.col;
    const shifted = shiftExpr(rule2.expr, rowOffset, colOffset);
    if (!shifted) {
      rule2.matchCache.set(key, false);
      return false;
    }
    const activeCell = {
      sheet: { sheetName: this.#sheetName },
      row: rowIdx + 1,
      col: colIdx + 1,
      absRow: false,
      absCol: false
    };
    const result = this.#evaluateExpression(shifted, activeCell);
    const matches = coerceToBoolean(result);
    rule2.matchCache.set(key, matches);
    return matches;
  }
}
function buildConditionalFormattingRenderCache(options) {
  const { sheetName, conditionalFormattings, dxfs, themeMap, getCell, evaluateExpression } = options;
  const { dxfFillById, dxfFontById } = buildDxfLookups(dxfs, themeMap);
  const conditionalRules = [];
  const colorScaleRules = [];
  const dataBarRules = [];
  const iconSetRules = [];
  for (const group of conditionalFormattings) {
    const ranges = toRangeBounds(group.ranges ?? [], sheetName);
    if (ranges.length === 0)
      continue;
    const anchor = {
      row: ranges[0]?.startRow ?? 0,
      col: ranges[0]?.startCol ?? 0
    };
    for (const rule2 of group.rules ?? []) {
      const priority = typeof rule2.priority === "number" ? rule2.priority : 9999;
      const fillCss = dxfFillById.get(rule2.dxfId ?? -1) ?? null;
      const fontColor = dxfFontById.get(rule2.dxfId ?? -1) ?? null;
      if (rule2.type === "cellIs") {
        conditionalRules.push({
          type: "cellIs",
          ranges,
          anchor,
          priority,
          operator: rule2.operator ?? undefined,
          formula: rule2.formula,
          fillCss,
          fontColor
        });
        continue;
      }
      if (rule2.type === "expression") {
        const expr = parseExpressionRule(rule2);
        if (!expr)
          continue;
        conditionalRules.push({
          type: "expression",
          ranges,
          anchor,
          priority,
          expr,
          matchCache: new Map,
          fillCss,
          fontColor
        });
        continue;
      }
      if (rule2.type === "containsText" || rule2.type === "notContainsText" || rule2.type === "beginsWith" || rule2.type === "endsWith") {
        conditionalRules.push({
          type: rule2.type,
          ranges,
          anchor,
          priority,
          text: rule2.text ?? "",
          fillCss,
          fontColor
        });
        continue;
      }
      if (rule2.type === "containsBlanks" || rule2.type === "notContainsBlanks") {
        conditionalRules.push({
          type: rule2.type,
          ranges,
          anchor,
          priority,
          fillCss,
          fontColor
        });
        continue;
      }
      if (rule2.type === "containsErrors" || rule2.type === "notContainsErrors") {
        conditionalRules.push({
          type: rule2.type,
          ranges,
          anchor,
          priority,
          fillCss,
          fontColor
        });
        continue;
      }
      if (rule2.type === "timePeriod" && rule2.formula.length > 0) {
        const expr = parseExpressionRule(rule2);
        if (!expr) {
          continue;
        }
        conditionalRules.push({
          type: "expression",
          ranges,
          anchor,
          priority,
          expr,
          matchCache: new Map,
          fillCss,
          fontColor
        });
        continue;
      }
      if (rule2.type === "timePeriod" && rule2.timePeriod) {
        conditionalRules.push({
          type: "timePeriod",
          ranges,
          anchor,
          priority,
          timePeriod: rule2.timePeriod,
          fillCss,
          fontColor
        });
        continue;
      }
      if (rule2.type === "duplicateValues" || rule2.type === "uniqueValues") {
        conditionalRules.push({
          type: rule2.type,
          ranges,
          anchor,
          priority,
          valueCounts: buildConditionalFormattingValueCounts({
            ranges,
            getCell
          }),
          fillCss,
          fontColor
        });
        continue;
      }
      if (rule2.type === "top10") {
        const threshold = buildTop10Threshold({
          ranges,
          getCell,
          rank: rule2.rank,
          percent: rule2.percent,
          bottom: rule2.bottom
        });
        if (!threshold) {
          continue;
        }
        conditionalRules.push({
          type: "top10",
          ranges,
          anchor,
          priority,
          threshold,
          fillCss,
          fontColor
        });
        continue;
      }
      if (rule2.type === "aboveAverage") {
        const threshold = buildAboveAverageThreshold({
          ranges,
          getCell,
          aboveAverage: rule2.aboveAverage,
          equalAverage: rule2.equalAverage,
          stdDev: rule2.stdDev
        });
        if (!threshold) {
          continue;
        }
        conditionalRules.push({
          type: "aboveAverage",
          ranges,
          anchor,
          priority,
          threshold,
          fillCss,
          fontColor
        });
        continue;
      }
      if (rule2.type === "colorScale" && rule2.colorScale) {
        const built = buildColorScaleRule2(rule2, ranges, priority, getCell, themeMap);
        if (built) {
          colorScaleRules.push(built);
        }
        continue;
      }
      if (rule2.type === "dataBar" && rule2.dataBar) {
        const built = buildDataBarRule2(rule2, ranges, priority, getCell, themeMap);
        if (built) {
          dataBarRules.push(built);
        }
        continue;
      }
      if (rule2.type === "iconSet" && rule2.iconSet) {
        const built = buildIconSetRenderRule(rule2, ranges, priority, getCell);
        if (built) {
          iconSetRules.push(built);
        }
      }
    }
  }
  return new ConditionalFormattingRenderCache({
    sheetName,
    getCell,
    evaluateExpression,
    conditionalRules,
    colorScaleRules,
    dataBarRules,
    iconSetRules
  });
}
function toRangeBounds(ranges, sheetName) {
  const out = [];
  for (const range2 of ranges) {
    if (range2.sheetName && range2.sheetName !== sheetName)
      continue;
    const parsed = parseRangeAddress(`${range2.startAddress}:${range2.endAddress}`);
    if (!parsed)
      continue;
    out.push(parsed.bounds);
  }
  return out;
}
function inRanges(rowIdx, colIdx, ranges) {
  for (const range2 of ranges) {
    if (rowIdx >= range2.startRow && rowIdx <= range2.endRow && colIdx >= range2.startCol && colIdx <= range2.endCol) {
      return true;
    }
  }
  return false;
}
function buildDxfLookups(dxfs, themeMap) {
  const dxfFillById = new Map;
  const dxfFontById = new Map;
  for (let i = 0;i < (dxfs?.length ?? 0); i += 1) {
    const dxf = dxfs?.[i];
    if (!dxf)
      continue;
    const fillColorObj = dxf.fill?.color ?? dxf.fill?.pattern?.color ?? dxf.font?.fill?.color;
    if (fillColorObj) {
      const css = resolveColor(fillColorObj, themeMap, {
        ...SPREADSHEET_COLOR_OPTIONS6,
        defaultFill: "rgba(0,0,0,1)"
      });
      dxfFillById.set(i, css);
    }
    if (dxf.font?.fill?.color) {
      dxfFontById.set(i, dxf.font.fill.color);
    }
  }
  return { dxfFillById, dxfFontById };
}
function parseExpressionRule(rule2) {
  const formula = Array.isArray(rule2.formula) ? rule2.formula[0] : rule2.formula;
  const raw = formula == null ? "" : String(formula).trim();
  if (!raw)
    return null;
  const normalized = raw.startsWith("=") ? raw : `=${raw}`;
  const parsed = parseFormula(normalized);
  if (parsed.errors.length > 0)
    return null;
  return parsed.expr;
}
function buildColorScaleRule2(rule2, ranges, priority, getCell, themeMap) {
  const stats = buildConditionalFormattingNumericStats({ ranges, getCell });
  if (!stats)
    return null;
  const cfvos = rule2.colorScale?.cfvos ?? [];
  const colors = rule2.colorScale?.colors ?? [];
  const stops = [];
  const vals = [];
  for (let i = 0;i < cfvos.length; i += 1) {
    const v = cfvos[i];
    if (!v)
      continue;
    const val = resolveConditionalFormattingCfvoValue({
      cfvo: v,
      stats
    });
    vals.push(val);
    const colorObj = colors[i];
    const rgba2 = colorObj ? resolveColor(colorObj, themeMap, {
      ...SPREADSHEET_COLOR_OPTIONS6,
      defaultFill: "rgba(0,0,0,1)"
    }) : "rgba(0,0,0,1)";
    const rgb2 = rgbaToRgb(rgba2) ?? [0, 0, 0];
    stops.push({ pos: 0, rgb: rgb2 });
  }
  if (stops.length === 0)
    return null;
  const vMin = Math.min(...vals);
  const vMax = Math.max(...vals);
  const norm = (x2) => vMax === vMin ? 0 : (x2 - vMin) / (vMax - vMin);
  for (let i = 0;i < stops.length; i += 1) {
    const stop = stops[i];
    if (stop) {
      stop.pos = norm(vals[i] ?? 0);
    }
  }
  return { ranges, priority, vMin, vMax, stops };
}
function buildDataBarRule2(rule2, ranges, priority, getCell, themeMap) {
  const stats = buildConditionalFormattingNumericStats({ ranges, getCell });
  if (!stats)
    return null;
  const colorCss = resolveColor(rule2.dataBar?.color ?? DEFAULT_DATABAR_COLOR, themeMap, {
    ...SPREADSHEET_COLOR_OPTIONS6,
    defaultFill: themeMap.colorMap?.["accent1"] || DEFAULT_ACCENT_COLOR_FALLBACK
  });
  return {
    ranges,
    priority,
    vMin: stats.min,
    vMax: stats.max,
    colorCss,
    borderColorCss: rule2.dataBar?.borderColor ? resolveColor(rule2.dataBar.borderColor, themeMap, {
      ...SPREADSHEET_COLOR_OPTIONS6,
      defaultFill: colorCss
    }) : null,
    negativeColorCss: rule2.dataBar?.negativeFillColor ? resolveColor(rule2.dataBar.negativeFillColor, themeMap, {
      ...SPREADSHEET_COLOR_OPTIONS6,
      defaultFill: "#FF0000"
    }) : null,
    negativeBorderColorCss: rule2.dataBar?.negativeBorderColor ? resolveColor(rule2.dataBar.negativeBorderColor, themeMap, {
      ...SPREADSHEET_COLOR_OPTIONS6,
      defaultFill: "#FF0000"
    }) : null,
    axisColorCss: rule2.dataBar?.axisColor ? resolveColor(rule2.dataBar.axisColor, themeMap, {
      ...SPREADSHEET_COLOR_OPTIONS6,
      defaultFill: "#000000"
    }) : null,
    axisPosition: rule2.dataBar?.axisPosition ?? undefined,
    border: rule2.dataBar?.border === true,
    negativeBorderColorSameAsPositive: rule2.dataBar?.negativeBarBorderColorSameAsPositive === true,
    gradient: rule2.dataBar?.gradient !== false,
    showValue: rule2.dataBar?.showValue !== false
  };
}
function buildIconSetRenderRule(rule2, ranges, priority, getCell) {
  const normalizedName = normalizeConditionalFormattingIconSetName(rule2.iconSet?.iconSet);
  const definition = getConditionalFormattingIconSetDefinition(normalizedName);
  if (!definition) {
    return null;
  }
  const stats = buildConditionalFormattingNumericStats({ ranges, getCell });
  if (!stats) {
    return null;
  }
  const iconCount = getConditionalFormattingIconSetThresholdCount({
    iconSetName: normalizedName,
    fallbackThresholdCount: rule2.iconSet?.cfvos?.length
  });
  const defaultCfvos2 = getDefaultConditionalFormattingIconSetThresholdPercents(iconCount).map((value2) => ({
    type: "percent",
    val: String(value2),
    gte: true
  }));
  const cfvos = rule2.iconSet?.cfvos?.length ? rule2.iconSet.cfvos : defaultCfvos2;
  const thresholds = cfvos.slice(0, iconCount).map((cfvo) => ({
    value: resolveConditionalFormattingCfvoValue({
      cfvo,
      stats,
      treatNumericValuesAsPercent: rule2.iconSet?.percent === true
    }),
    gte: cfvo.gte !== false
  }));
  return {
    ranges,
    priority,
    iconSetName: definition.name,
    iconCount,
    showValue: rule2.iconSet?.showValue !== false,
    reverse: rule2.iconSet?.reverse === true,
    thresholds
  };
}
function interpolateColorScale(rule2, value2) {
  const tRaw = rule2.vMax === rule2.vMin ? 0 : (value2 - rule2.vMin) / (rule2.vMax - rule2.vMin);
  const t = Math.max(0, Math.min(1, tRaw));
  if (Number.isNaN(t))
    return null;
  const stops = rule2.stops;
  if (stops.length === 0)
    return null;
  let rgb2 = stops[0]?.rgb ?? [0, 0, 0];
  if (stops.length === 1) {
    rgb2 = stops[0]?.rgb ?? [0, 0, 0];
  } else {
    let i = 0;
    while (i < stops.length - 1 && t > (stops[i + 1]?.pos ?? 0))
      i += 1;
    const a = stops[i];
    if (!a)
      return null;
    const b = stops[Math.min(i + 1, stops.length - 1)];
    if (!b)
      return null;
    const segT = a.pos === b.pos ? 0 : (t - a.pos) / (b.pos - a.pos);
    rgb2 = [
      Math.round(a.rgb[0] + (b.rgb[0] - a.rgb[0]) * segT),
      Math.round(a.rgb[1] + (b.rgb[1] - a.rgb[1]) * segT),
      Math.round(a.rgb[2] + (b.rgb[2] - a.rgb[2]) * segT)
    ];
  }
  return `rgba(${rgb2[0]},${rgb2[1]},${rgb2[2]},1)`;
}
function selectIconSetIndex(rule2, value2) {
  let bucketIndex = 0;
  for (let index = rule2.thresholds.length - 1;index >= 1; index -= 1) {
    const threshold = rule2.thresholds[index];
    if (!threshold) {
      continue;
    }
    const matches = threshold.gte ? value2 >= threshold.value : value2 > threshold.value;
    if (matches) {
      bucketIndex = index;
      break;
    }
  }
  return rule2.reverse ? rule2.iconCount - 1 - bucketIndex : bucketIndex;
}
function evalCellIs(op, formulasAny, v) {
  const formulas = Array.isArray(formulasAny) ? formulasAny : undefined;
  if (v == null)
    return false;
  const f0 = formulas?.[0] != null ? Number(formulas[0]) : NaN;
  const f1 = formulas?.[1] != null ? Number(formulas[1]) : NaN;
  switch (op) {
    case "greaterThan":
      return v > f0;
    case "greaterThanOrEqual":
      return v >= f0;
    case "lessThan":
      return v < f0;
    case "lessThanOrEqual":
      return v <= f0;
    case "equal":
      return v === f0;
    case "notEqual":
      return v !== f0;
    case "between":
      return v >= Math.min(f0, f1) && v <= Math.max(f0, f1);
    case "notBetween":
      return !(v >= Math.min(f0, f1) && v <= Math.max(f0, f1));
    default:
      return false;
  }
}
function coerceToBoolean(value2) {
  if (value2 == null)
    return false;
  if (isArrayValue(value2))
    return false;
  if (typeof value2 === "boolean")
    return value2;
  if (typeof value2 === "number")
    return value2 !== 0;
  if (typeof value2 === "string")
    return value2.trim().length > 0;
  if (typeof value2 === "object" && "kind" in value2)
    return false;
  return false;
}
function shiftExpr(expr, rowOffset, colOffset) {
  switch (expr.kind) {
    case "RangeRef": {
      const shifted = shiftRangeRef(expr.ref, rowOffset, colOffset);
      return shifted ? { ...expr, ref: shifted } : null;
    }
    case "UnaryOp": {
      const next2 = shiftExpr(expr.expr, rowOffset, colOffset);
      return next2 ? { ...expr, expr: next2 } : null;
    }
    case "BinaryOp": {
      const left = shiftExpr(expr.left, rowOffset, colOffset);
      if (!left)
        return null;
      const right = shiftExpr(expr.right, rowOffset, colOffset);
      if (!right)
        return null;
      return { ...expr, left, right };
    }
    case "FunctionCall": {
      const args2 = [];
      for (const arg of expr.args) {
        const next2 = shiftExpr(arg, rowOffset, colOffset);
        if (!next2)
          return null;
        args2.push(next2);
      }
      return { ...expr, args: args2 };
    }
    case "CallExpr": {
      const callee = shiftExpr(expr.callee, rowOffset, colOffset);
      if (!callee)
        return null;
      const args2 = [];
      for (const arg of expr.args) {
        const next2 = shiftExpr(arg, rowOffset, colOffset);
        if (!next2)
          return null;
        args2.push(next2);
      }
      return { ...expr, callee, args: args2 };
    }
    case "ArrayLiteral": {
      const rows = [];
      for (const row2 of expr.elements) {
        const outRow = [];
        for (const cell of row2) {
          const next2 = shiftExpr(cell, rowOffset, colOffset);
          if (!next2)
            return null;
          outRow.push(next2);
        }
        rows.push(outRow);
      }
      return { ...expr, elements: rows };
    }
    case "MissingArg":
    case "NumberLiteral":
    case "StringLiteral":
    case "BooleanLiteral":
    case "ErrorLiteral":
      return expr;
    default:
      return expr;
  }
}
function shiftRangeRef(ref2, rowOffset, colOffset) {
  switch (ref2.kind) {
    case "Cell": {
      const addr = shiftCellAddress(ref2.addr, rowOffset, colOffset);
      return addr ? { ...ref2, addr } : null;
    }
    case "Range": {
      const start = shiftCellAddress(ref2.start, rowOffset, colOffset);
      if (!start)
        return null;
      const end = shiftCellAddress(ref2.end, rowOffset, colOffset);
      if (!end)
        return null;
      return { ...ref2, start, end };
    }
    case "WholeColumn": {
      const next2 = ref2.col + colOffset;
      if (next2 < 1)
        return null;
      return { ...ref2, col: next2 };
    }
    case "ColumnRange": {
      const startCol = ref2.startCol + colOffset;
      const endCol = ref2.endCol + colOffset;
      if (startCol < 1 || endCol < 1)
        return null;
      return { ...ref2, startCol, endCol };
    }
    case "WholeRow": {
      const next2 = ref2.row + rowOffset;
      if (next2 < 1)
        return null;
      return { ...ref2, row: next2 };
    }
    case "Spill": {
      const base = shiftRangeRef(ref2.base, rowOffset, colOffset);
      return base ? { ...ref2, base } : null;
    }
    case "Named":
      return ref2;
    default:
      return ref2;
  }
}
function shiftCellAddress(addr, rowOffset, colOffset) {
  const row2 = addr.absRow ? addr.row : addr.row + rowOffset;
  const col = addr.absCol ? addr.col : addr.col + colOffset;
  if (row2 < 1 || col < 1)
    return null;
  return {
    ...addr,
    row: row2,
    col
  };
}

// node_modules/@oai/granola/dist/models/spreadsheet/workbook-awareness-state.js
function clonePresenceSelection(selection) {
  return {
    sheetName: selection.sheetName,
    rect: { ...selection.rect },
    selectedElementIds: [...selection.selectedElementIds ?? []],
    label: selection.label,
    status: selection.status
  };
}

class WorkbookAwarenessState {
  #sheets = new Map;
  #presence = new Map;
  #undoStack = [];
  #redoStack = [];
  activeSheetName;
  dialog = null;
  clipboard = null;
  showFormulas = false;
  missingActions = [];
  constructor(options = {}) {
    this.activeSheetName = options.activeSheetName ?? null;
  }
  getSheetState(sheetName) {
    const existing = this.#sheets.get(sheetName);
    if (existing) {
      return existing;
    }
    const created = this.#buildDefaultSheetState(sheetName);
    this.#sheets.set(sheetName, created);
    return created;
  }
  setActiveSheetName(sheetName) {
    this.activeSheetName = sheetName;
  }
  renameSheet(previousName, nextName) {
    const previous2 = previousName?.trim();
    const next2 = nextName?.trim();
    if (!previous2 || !next2 || previous2 === next2) {
      return;
    }
    if (this.activeSheetName === previous2) {
      this.activeSheetName = next2;
    }
    if (this.dialog?.args && this.dialog.args["sheetName"] === previous2) {
      this.dialog = {
        ...this.dialog,
        args: { ...this.dialog.args, sheetName: next2 }
      };
    }
    if (this.clipboard?.source.sheetName === previous2) {
      this.clipboard = {
        ...this.clipboard,
        source: { ...this.clipboard.source, sheetName: next2 }
      };
    }
    const state = this.#sheets.get(previous2);
    if (state) {
      state.sheetName = next2;
      this.#sheets.delete(previous2);
      this.#sheets.set(next2, state);
    }
    for (const presence of this.#presence.values()) {
      for (const selection of presence.selections) {
        if (selection.sheetName === previous2) {
          selection.sheetName = next2;
        }
      }
    }
  }
  forgetSheet(sheetName) {
    const key = sheetName?.trim();
    if (!key) {
      return;
    }
    if (this.activeSheetName === key) {
      this.activeSheetName = null;
    }
    if (this.dialog?.args && this.dialog.args["sheetName"] === key) {
      this.dialog = null;
    }
    if (this.clipboard?.source.sheetName === key) {
      this.clipboard = null;
    }
    this.#sheets.delete(key);
    for (const [presenceId, presence] of this.#presence.entries()) {
      const nextSelections = presence.selections.filter((selection) => selection.sheetName !== key);
      if (nextSelections.length === 0) {
        this.#presence.delete(presenceId);
        continue;
      }
      presence.selections = nextSelections;
    }
  }
  setDialog(dialog) {
    this.dialog = dialog;
  }
  setPresenceSelections(presenceId, selections, options = {}) {
    if (!presenceId) {
      throw new Error("Presence id is required.");
    }
    const existing = this.#presence.get(presenceId);
    const kind = options.kind ?? existing?.kind ?? "collaborator";
    const nextSelections = selections.map((selection) => clonePresenceSelection(selection));
    this.#presence.set(presenceId, {
      id: presenceId,
      kind,
      selections: nextSelections
    });
  }
  clearPresenceSelections(presenceId, options = {}) {
    if (!presenceId) {
      throw new Error("Presence id is required.");
    }
    const existing = this.#presence.get(presenceId);
    if (!existing) {
      return;
    }
    if (!options.sheetName) {
      this.#presence.delete(presenceId);
      return;
    }
    const remaining = existing.selections.filter((selection) => selection.sheetName !== options.sheetName);
    if (remaining.length === 0) {
      this.#presence.delete(presenceId);
      return;
    }
    this.#presence.set(presenceId, {
      id: existing.id,
      kind: existing.kind,
      selections: remaining.map((selection) => clonePresenceSelection(selection))
    });
  }
  getSelectionsForSheet(sheetName) {
    const selections = [];
    for (const presence of this.#presence.values()) {
      for (const selection of presence.selections) {
        if (selection.sheetName !== sheetName) {
          continue;
        }
        selections.push({
          presenceId: presence.id,
          kind: presence.kind,
          ...clonePresenceSelection(selection)
        });
      }
    }
    return selections;
  }
  recordMissingAction(action) {
    this.missingActions.push(action);
  }
  pushUndoEntry(entry) {
    this.#undoStack.push(entry);
    this.#redoStack = [];
  }
  popUndoEntry() {
    return this.#undoStack.pop() ?? null;
  }
  pushRedoEntry(entry) {
    this.#redoStack.push(entry);
  }
  popRedoEntry() {
    return this.#redoStack.pop() ?? null;
  }
  clearHistory() {
    this.#undoStack = [];
    this.#redoStack = [];
  }
  #buildDefaultSheetState(sheetName) {
    const origin = { row: 0, col: 0 };
    const selection = { r1: 0, c1: 0, r2: 0, c2: 0 };
    return {
      sheetName,
      mode: "grid",
      activeCell: { ...origin },
      anchorCell: { ...origin },
      selection: { ...selection },
      selectionRanges: [{ ...selection }],
      activeRangeIndex: 0,
      extendSelection: false,
      selectAllStage: 0,
      selectionCornerIndex: 0,
      selectionVisibility: "all",
      editBuffer: null,
      scroll: { row: 0, col: 0 },
      copyOutline: null
    };
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/apply/record.js
var WORKBOOK_ALIAS_STATES = new WeakMap;
var getOrCreateAliasState = (workbook) => {
  const existing = WORKBOOK_ALIAS_STATES.get(workbook);
  if (existing) {
    return existing;
  }
  const state = {
    aliases: new WeakMap,
    counts: {}
  };
  WORKBOOK_ALIAS_STATES.set(workbook, state);
  return state;
};

class WorkbookRecorder {
  #ops = [];
  #aliases;
  #idMap = {};
  #counts;
  #deferred = [];
  #deferredByKey = new Map;
  constructor(workbook) {
    if (workbook && typeof workbook === "object") {
      const state = getOrCreateAliasState(workbook);
      this.#aliases = state.aliases;
      this.#counts = state.counts;
      return;
    }
    this.#aliases = new WeakMap;
    this.#counts = {};
  }
  record(op) {
    this.#ops.push(op);
  }
  defer(builder) {
    this.#deferred.push(builder);
  }
  deferOnce(key, builder) {
    this.#deferredByKey.set(key, builder);
  }
  getPatch() {
    const next2 = [...this.#ops];
    const deferred = this.#deferred;
    const deferredByKey = this.#deferredByKey;
    this.#deferred = [];
    this.#deferredByKey = new Map;
    for (const build of deferred) {
      const op = build();
      if (op) {
        next2.push(op);
      }
    }
    for (const build of deferredByKey.values()) {
      const op = build();
      if (op) {
        next2.push(op);
      }
    }
    this.#ops = next2;
    return [...next2];
  }
  getIdMap() {
    return { ...this.#idMap };
  }
  getAlias(target) {
    return this.#aliases.get(target);
  }
  assignAlias(target, anchor, prefix) {
    const existing = this.#aliases.get(target);
    const alias = existing ?? this.#nextAlias(prefix);
    if (!existing) {
      this.#aliases.set(target, alias);
    }
    this.#idMap[alias] = anchor;
    return alias;
  }
  #nextAlias(prefix) {
    const count3 = (this.#counts[prefix] ?? 0) + 1;
    this.#counts[prefix] = count3;
    return `@${prefix}${count3}`;
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/apply/apply.js
function isPatchAlias2(value2) {
  return typeof value2 === "string" && value2.startsWith("@");
}
var APPLIED_ALIAS_STATE = new WeakMap;
function applyWorkbookPatch(workbook, patch) {
  const priorAliases = APPLIED_ALIAS_STATE.get(workbook) ?? {};
  const aliasAnchors = { ...priorAliases };
  const idMap = {};
  const warnings = [];
  const recordTodo = (op) => {
    warnings.push(`TODO: ${op} is not implemented yet.`);
  };
  const registerAlias = (alias, anchor) => {
    if (!alias) {
      return;
    }
    if (!isPatchAlias2(alias)) {
      throw new Error(`Alias must start with "@": ${alias}`);
    }
    const existing = aliasAnchors[alias];
    if (existing && existing !== anchor) {
      throw new Error(`Alias already defined with a different anchor: ${alias}`);
    }
    aliasAnchors[alias] = anchor;
    idMap[alias] = anchor;
  };
  const updateAliasAnchor = (alias, anchor) => {
    if (!isPatchAlias2(alias)) {
      return;
    }
    aliasAnchors[alias] = anchor;
    idMap[alias] = anchor;
  };
  const resolveAliasAnchor = (alias) => {
    const anchor = aliasAnchors[alias];
    if (!anchor) {
      throw new Error(`Unknown alias target: ${alias}`);
    }
    return anchor;
  };
  const resolveSheetTarget = (target) => {
    if (!isPatchAlias2(target)) {
      return target;
    }
    return resolveAliasAnchor(target);
  };
  const resolveTableTarget = (target) => {
    if (!isPatchAlias2(target)) {
      return target;
    }
    const anchor = resolveAliasAnchor(target);
    if (!anchor.startsWith("tb/")) {
      throw new Error(`Alias ${target} does not resolve to a table target.`);
    }
    return anchor.slice(3);
  };
  const resolveChartId = (target) => {
    if (!target || isPatchAlias2(target)) {
      return;
    }
    return target;
  };
  const resolveShapeId = (target) => {
    if (!target || isPatchAlias2(target)) {
      return;
    }
    return target;
  };
  const resolveSparklineUid = (target) => {
    if (!target || isPatchAlias2(target)) {
      return;
    }
    return target;
  };
  const resolveImageId = (target) => {
    if (!isPatchAlias2(target)) {
      return target;
    }
    const anchor = resolveAliasAnchor(target);
    if (!anchor.startsWith("im/")) {
      throw new Error(`Alias ${target} does not resolve to an image target.`);
    }
    return anchor.slice(3);
  };
  const resolveThreadTargetRef = (target) => {
    const rawValue = typeof target === "string" ? target : target.id;
    if (!rawValue) {
      return;
    }
    const ref2 = `${rawValue}`;
    if (ref2.startsWith("@")) {
      return;
    }
    return ref2.startsWith("th/") ? ref2 : `th/${ref2}`;
  };
  for (const op of patch) {
    switch (op.op) {
      case "theme.colorScheme.set": {
        workbook.setColorScheme(op.scheme);
        break;
      }
      case "sheet.add": {
        const sheet = workbook.worksheets.add(op.name);
        registerAlias(op.as, sheet.name);
        break;
      }
      case "sheet.set": {
        const sheet = workbook.worksheets.getItem(resolveSheetTarget(op.target));
        if (op.props.name !== undefined) {
          sheet.name = op.props.name;
        }
        if (op.props.index !== undefined) {
          sheet.index = op.props.index;
        }
        break;
      }
      case "sheet.remove": {
        const sheet = workbook.worksheets.getItem(resolveSheetTarget(op.target));
        sheet.delete();
        break;
      }
      case "range.values.set": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        const range2 = sheet.getRange(op.target.range);
        range2.values = op.values;
        break;
      }
      case "range.formulas.set": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        const range2 = sheet.getRange(op.target.range);
        range2.formulas = op.formulas;
        break;
      }
      case "range.merge": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        const range2 = sheet.getRange(op.target.range);
        range2.merge(op.across ?? false);
        break;
      }
      case "range.unmerge": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        const range2 = sheet.getRange(op.target.range);
        range2.unmerge();
        break;
      }
      case "range.format.set": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        const range2 = sheet.getRange(op.target.range);
        applyRangeFormatPatch(range2.format, op.props);
        break;
      }
      case "range.format.clear": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        const range2 = sheet.getRange(op.target.range);
        range2.clear({ applyTo: "formats" });
        break;
      }
      case "table.add": {
        const sheet = workbook.worksheets.getItem(op.props.range.sheet);
        const table2 = sheet.tables.add(op.props.range.range, op.props.hasHeaders ?? false, op.props.name);
        registerAlias(op.as, `tb/${table2.name}`);
        break;
      }
      case "table.rows.add": {
        const table2 = resolveTable(workbook, resolveTableTarget(op.target.name), op.target.sheet);
        table2.rows.add(op.props.index ?? null, op.props.values);
        break;
      }
      case "table.set": {
        const table2 = resolveTable(workbook, resolveTableTarget(op.target.name), op.target.sheet);
        if (op.props.name !== undefined) {
          table2.name = op.props.name;
          updateAliasAnchor(op.target.name, `tb/${table2.name}`);
        }
        if (op.props.style !== undefined) {
          table2.style = op.props.style;
        }
        if (op.props.showHeaders !== undefined) {
          table2.showHeaders = op.props.showHeaders;
        }
        if (op.props.showTotals !== undefined) {
          table2.showTotals = op.props.showTotals;
        }
        if (op.props.showBandedRows !== undefined) {
          table2.showBandedRows = op.props.showBandedRows;
        }
        if (op.props.highlightFirstColumn !== undefined) {
          table2.highlightFirstColumn = op.props.highlightFirstColumn;
        }
        if (op.props.highlightLastColumn !== undefined) {
          table2.highlightLastColumn = op.props.highlightLastColumn;
        }
        if (op.props.showBandedColumns !== undefined) {
          table2.showBandedColumns = op.props.showBandedColumns;
        }
        if (op.props.showFilterButton !== undefined) {
          table2.showFilterButton = op.props.showFilterButton;
        }
        break;
      }
      case "table.remove": {
        const table2 = resolveTable(workbook, resolveTableTarget(op.target.name), op.target.sheet);
        table2.delete();
        break;
      }
      case "conditionalformat.add": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        sheet.conditionalFormattings.add({
          range: op.target.range,
          rule: normalizeConditionalFormatRule(op.props.rule)
        });
        break;
      }
      case "conditionalformat.clear": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        sheet.conditionalFormattings.clear(op.target.range);
        break;
      }
      case "datavalidation.set": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        sheet.dataValidations.add({
          range: op.target.range,
          ...op.props
        });
        break;
      }
      case "datavalidation.clear": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        sheet.dataValidations.clear(op.target.range);
        break;
      }
      case "sparkline.add": {
        const targetSheet = workbook.worksheets.getItem(op.props.targetRange.sheet);
        const sourceSheet = workbook.worksheets.getItem(op.props.sourceData.sheet);
        const dateAxisRange = op.props.dateAxisRange ? workbook.worksheets.getItem(op.props.dateAxisRange.sheet).getRange(op.props.dateAxisRange.range) : undefined;
        const group = targetSheet.sparklineGroups.__addForApply({
          uid: op.props.uid ?? op.props.id,
          id: op.props.id,
          type: op.props.type,
          targetRange: targetSheet.getRange(op.props.targetRange.range),
          sourceData: sourceSheet.getRange(op.props.sourceData.range),
          dateAxisRange,
          lineWeight: op.props.lineWeight,
          displayEmptyCellsAs: mapSparklineDisplayBlanks(op.props.displayEmptyCellsAs),
          displayHidden: op.props.displayHidden,
          seriesColor: op.props.seriesColor,
          negativeColor: op.props.negativeColor,
          axisColor: op.props.axisColor,
          markersColor: op.props.markersColor,
          firstMarkerColor: op.props.firstMarkerColor,
          lastMarkerColor: op.props.lastMarkerColor,
          highMarkerColor: op.props.highMarkerColor,
          lowMarkerColor: op.props.lowMarkerColor,
          markers: op.props.markers,
          axis: mapSparklineAxis(op.props.axis)
        });
        registerAlias(op.as, `sp/${group.uid}`);
        break;
      }
      case "sparkline.set": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        const group = resolveWorksheetSparklineGroup(sheet, op.target, resolveSparklineUid);
        if (!group) {
          throw new Error(`Sparkline group not found: ${JSON.stringify(op.target)}`);
        }
        applySparklineProps(group, workbook, op.props);
        break;
      }
      case "sparkline.remove": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        const group = resolveWorksheetSparklineGroup(sheet, op.target, resolveSparklineUid);
        if (!group) {
          throw new Error(`Sparkline group not found: ${JSON.stringify(op.target)}`);
        }
        sheet.sparklineGroups.delete(group);
        break;
      }
      case "chart.add": {
        const sheet = workbook.worksheets.getItem(op.sheet);
        const chart2 = sheet.charts.__addForApply({
          chartType: op.props.chartType,
          anchor: op.props.anchor,
          id: op.props.id
        });
        registerAlias(op.as, `ch/${chart2.id}`);
        applyChartProps(chart2, op.props);
        break;
      }
      case "chart.set": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        const chart2 = resolveWorksheetChart(sheet, op.target, resolveChartId);
        if (!chart2) {
          throw new Error(`Chart not found: ${JSON.stringify(op.target)}`);
        }
        applyChartProps(chart2, op.props);
        break;
      }
      case "chart.remove": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        const chart2 = resolveWorksheetChart(sheet, op.target, resolveChartId);
        if (!chart2) {
          throw new Error(`Chart not found: ${JSON.stringify(op.target)}`);
        }
        chart2.delete();
        break;
      }
      case "shape.add": {
        const sheet = workbook.worksheets.getItem(op.sheet);
        if (op.props.geometry === "custom") {
          throw new Error("Spreadsheet patch shape.add does not support custom geometry.");
        }
        const shape2 = sheet.shapes.__addForApply({
          id: op.props.id,
          geometry: op.props.geometry,
          anchor: op.props.anchor,
          fill: op.props.fill,
          line: op.props.line
        });
        registerAlias(op.as, `sh/${shape2.id}`);
        break;
      }
      case "shape.set": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        const shape2 = resolveWorksheetShape(sheet, op.target, resolveShapeId);
        if (!shape2) {
          throw new Error(`Shape not found: ${JSON.stringify(op.target)}`);
        }
        applyShapeSetProps2(shape2, op.props);
        if (op.props.anchor) {
          applyDrawingAnchor(shape2.anchor, op.props.anchor);
        }
        break;
      }
      case "shape.remove": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        const shape2 = resolveWorksheetShape(sheet, op.target, resolveShapeId);
        if (!shape2) {
          throw new Error(`Shape not found: ${JSON.stringify(op.target)}`);
        }
        shape2.delete();
        break;
      }
      case "image.add": {
        const sheet = workbook.worksheets.getItem(op.sheet);
        const image2 = sheet.images.add(op.props);
        registerAlias(op.as, `im/${image2.imageId}`);
        break;
      }
      case "image.set": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        const image2 = resolveWorksheetImage(sheet, {
          ...op.target,
          imageId: resolveImageId(op.target.imageId)
        });
        if (!image2) {
          throw new Error(`Image not found: ${op.target.imageId}`);
        }
        const replacedSource = applyWorksheetImageSetSource(image2, op.props);
        if (op.props.anchor) {
          applyDrawingAnchor(image2.anchor, op.props.anchor);
        }
        if (replacedSource) {
          updateAliasAnchor(op.target.imageId, `im/${image2.imageId}`);
        } else if (op.props.imageId !== undefined) {
          image2.imageId = op.props.imageId;
          updateAliasAnchor(op.target.imageId, `im/${image2.imageId}`);
        }
        break;
      }
      case "image.remove": {
        const sheet = workbook.worksheets.getItem(op.target.sheet);
        const image2 = resolveWorksheetImage(sheet, {
          ...op.target,
          imageId: resolveImageId(op.target.imageId)
        });
        if (!image2) {
          throw new Error(`Image not found: ${op.target.imageId}`);
        }
        image2.delete();
        break;
      }
      case "names.range.add": {
        if (op.sheet) {
          workbook.worksheets.getItem(op.sheet).names.addRange(op.name, op.formula, {
            description: op.description
          });
          break;
        }
        workbook.names.addRange(op.name, op.formula, {
          description: op.description
        });
        break;
      }
      case "names.function.add": {
        if (op.sheet) {
          workbook.worksheets.getItem(op.sheet).names.addFunction(op.name, {
            lambda: op.lambda,
            description: op.description,
            parameters: op.parameters,
            returns: op.returns
          });
          break;
        }
        workbook.names.addFunction(op.name, {
          lambda: op.lambda,
          description: op.description,
          parameters: op.parameters,
          returns: op.returns
        });
        break;
      }
      case "names.remove": {
        if (op.sheet) {
          workbook.worksheets.getItem(op.sheet).names.getItem(op.name).delete();
          break;
        }
        workbook.names.getItem(op.name).delete();
        break;
      }
      case "comments.self.set": {
        workbook.comments.setSelf(op.person);
        break;
      }
      case "thread.add": {
        const thread = workbook.comments.__addThreadForApply(resolveThreadTarget(workbook, op.target), op.body, {
          id: op.id,
          author: op.author,
          createdAt: op.createdAt
        });
        registerAlias(op.as, `th/${thread.id}`);
        break;
      }
      case "thread.reply": {
        const thread = resolveWorkbookThread(workbook, op.target, resolveThreadTargetRef);
        if (thread) {
          thread.addReply(op.body, {
            author: op.author,
            createdAt: op.createdAt
          });
          break;
        }
        throw new Error(`Thread not found: ${op.target}`);
      }
      case "thread.resolve": {
        const thread = resolveWorkbookThread(workbook, op.target, resolveThreadTargetRef);
        if (thread) {
          thread.resolve();
          break;
        }
        throw new Error(`Thread not found: ${op.target}`);
      }
      case "thread.reopen": {
        const thread = resolveWorkbookThread(workbook, op.target, resolveThreadTargetRef);
        if (thread) {
          thread.reopen();
          break;
        }
        throw new Error(`Thread not found: ${op.target}`);
      }
      case "thread.remove": {
        const thread = resolveWorkbookThread(workbook, op.target, resolveThreadTargetRef);
        if (thread) {
          thread.delete();
          break;
        }
        throw new Error(`Thread not found: ${op.target}`);
      }
      default: {
        recordTodo(op.op);
        break;
      }
    }
  }
  APPLIED_ALIAS_STATE.set(workbook, aliasAnchors);
  return { idMap, warnings };
}
function applyRangeFormatPatch(format3, props) {
  if (props.fill !== undefined) {
    format3.fill = props.fill;
  }
  if (props.font) {
    applyRangeFontPatch(format3.font, props.font);
  }
  if (props.numberFormat !== undefined) {
    format3.numberFormat = props.numberFormat;
  }
  if (props.wrapText !== undefined) {
    format3.wrapText = props.wrapText;
  }
  if (props.horizontalAlignment !== undefined) {
    format3.horizontalAlignment = props.horizontalAlignment;
  }
  if (props.verticalAlignment !== undefined) {
    format3.verticalAlignment = props.verticalAlignment;
  }
  if (props.rowHeight !== undefined) {
    format3.rowHeight = props.rowHeight;
  }
  if (props.columnWidth !== undefined) {
    format3.columnWidth = props.columnWidth;
  }
  if (props.borders !== undefined) {
    format3.borders = props.borders;
  }
}
function applyRangeFontPatch(font, patch) {
  if (patch.bold !== undefined) {
    font.bold = patch.bold;
  }
  if (patch.italic !== undefined) {
    font.italic = patch.italic;
  }
  if (patch.size !== undefined) {
    font.size = patch.size;
  }
  if (patch.name !== undefined) {
    font.name = patch.name;
  }
  if (patch.color !== undefined) {
    font.color = patch.color;
  }
}
function normalizeConditionalFormatRule(rule2) {
  switch (rule2.type) {
    case "aboveAverage":
      return { ...rule2, format: rule2.format ? { ...rule2.format } : undefined };
    case "beginsWith":
    case "cellIs":
    case "containsText":
    case "endsWith":
    case "notContainsText":
      if (rule2.type !== "cellIs") {
        return {
          ...rule2,
          format: rule2.format ? { ...rule2.format } : undefined
        };
      }
      return {
        ...rule2,
        format: rule2.format ? { ...rule2.format } : undefined
      };
    case "colorScale":
      return {
        ...rule2,
        thresholds: rule2.thresholds?.map(normalizeCfvoInput)
      };
    case "dataBar":
      return {
        ...rule2,
        thresholds: rule2.thresholds?.map(normalizeCfvoInput)
      };
    case "containsBlanks":
    case "containsErrors":
    case "duplicateValues":
    case "notContainsBlanks":
    case "notContainsErrors":
    case "timePeriod":
    case "top10":
    case "uniqueValues":
      return {
        ...rule2,
        format: rule2.format ? { ...rule2.format } : undefined
      };
    case "iconSet":
      return {
        ...rule2,
        percent: rule2.percent,
        thresholds: rule2.thresholds?.map(normalizeCfvoInput)
      };
    case "expression":
      return {
        ...rule2,
        format: rule2.format ? { ...rule2.format } : undefined
      };
  }
}
function normalizeCfvoInput(value2) {
  if (typeof value2 === "string" || typeof value2 === "number") {
    return value2;
  }
  return { ...value2 };
}
function mapSparklineAxisMode(mode) {
  if (typeof mode === "number") {
    return mode;
  }
  if (typeof mode !== "string") {
    return;
  }
  switch (mode.toLowerCase()) {
    case "custom":
      return 3 /* SPARKLINE_AXIS_MIN_MAX_CUSTOM */;
    case "group":
      return 2 /* SPARKLINE_AXIS_MIN_MAX_GROUP */;
    case "individual":
      return 1 /* SPARKLINE_AXIS_MIN_MAX_INDIVIDUAL */;
    case "unspecified":
      return 0 /* SPARKLINE_AXIS_MIN_MAX_UNSPECIFIED */;
    default:
      return;
  }
}
function mapSparklineDisplayBlanks(value2) {
  if (typeof value2 === "number") {
    return value2;
  }
  if (typeof value2 !== "string") {
    return;
  }
  switch (value2.toLowerCase()) {
    case "gap":
      return 2 /* SPARKLINE_DISPLAY_BLANKS_AS_GAP */;
    case "span":
      return 1 /* SPARKLINE_DISPLAY_BLANKS_AS_SPAN */;
    case "zero":
      return 3 /* SPARKLINE_DISPLAY_BLANKS_AS_ZERO */;
    case "unspecified":
      return 0 /* SPARKLINE_DISPLAY_BLANKS_AS_UNSPECIFIED */;
    default:
      return;
  }
}
function mapSparklineAxis(axis) {
  if (!axis) {
    return;
  }
  return {
    ...axis,
    minMode: mapSparklineAxisMode(axis.minMode),
    maxMode: mapSparklineAxisMode(axis.maxMode)
  };
}
function normalizeSeriesNames(chart2) {
  return chart2.series.items.map((series) => series.name ?? "");
}
function narrowMatchesIfAny(matches, predicate) {
  const narrowed = matches.filter(predicate);
  return narrowed.length > 0 ? narrowed : matches;
}
function resolveWorksheetChart(sheet, target, resolveChartId) {
  const selector = target.selector;
  if (selector) {
    let matches = [...sheet.charts.items];
    if (selector.anchor) {
      const key = JSON.stringify(selector.anchor);
      matches = narrowMatchesIfAny(matches, (candidate) => JSON.stringify(candidate.anchor.toConfig()) === key);
    }
    if (selector.chartType !== undefined) {
      matches = narrowMatchesIfAny(matches, (candidate) => candidate.type === selector.chartType);
    }
    if (selector.title !== undefined) {
      matches = narrowMatchesIfAny(matches, (candidate) => candidate.titleText === selector.title);
    }
    if (selector.seriesNames && selector.seriesNames.length > 0) {
      matches = narrowMatchesIfAny(matches, (candidate) => JSON.stringify(normalizeSeriesNames(candidate)) === JSON.stringify(selector.seriesNames));
    }
    if (selector.occurrence !== undefined) {
      const byOccurrence = matches[selector.occurrence];
      if (byOccurrence) {
        return byOccurrence;
      }
    } else if (matches.length === 1) {
      return matches[0];
    }
  }
  const chartId = resolveChartId(target.id);
  if (chartId) {
    return sheet.charts.items.find((candidate) => candidate.id === chartId);
  }
  return;
}
function resolveWorksheetShape(sheet, target, resolveShapeId) {
  const selector = target.selector;
  if (selector) {
    let matches = [...sheet.shapes.items];
    if (selector.anchor) {
      const key = JSON.stringify(selector.anchor);
      matches = narrowMatchesIfAny(matches, (candidate) => JSON.stringify(candidate.anchor.toConfig()) === key);
    }
    if (selector.geometry !== undefined) {
      const protoGeometry = SHAPE_GEOMETRY_NAME_TO_PROTO[selector.geometry];
      if (protoGeometry === undefined) {
        return;
      }
      matches = narrowMatchesIfAny(matches, (candidate) => {
        const geometry = candidate.toProto().shape?.geometry;
        return geometry !== undefined && geometry === protoGeometry;
      });
    }
    if (selector.name !== undefined) {
      matches = narrowMatchesIfAny(matches, (candidate) => candidate.name === selector.name);
    }
    if (selector.occurrence !== undefined) {
      const byOccurrence = matches[selector.occurrence];
      if (byOccurrence) {
        return byOccurrence;
      }
    } else if (matches.length === 1) {
      return matches[0];
    }
  }
  const shapeId = resolveShapeId(target.id);
  if (shapeId) {
    return sheet.shapes.items.find((candidate) => candidate.id === shapeId);
  }
  return;
}
function matchSparklineRangeRef(range2, target) {
  if (!target) {
    return true;
  }
  const worksheet = getRangeWorksheet(range2);
  if (!worksheet) {
    return false;
  }
  return worksheet.name === target.sheet && range2.address === target.range;
}
function resolveWorksheetSparklineGroup(sheet, target, resolveSparklineUid) {
  const groupUid = resolveSparklineUid(target.uid ?? target.id);
  const groups = sheet.sparklineGroups.getAll();
  if (groupUid) {
    const byUid = groups.find((candidate) => candidate.uid === groupUid);
    if (byUid) {
      return byUid;
    }
    const byId = groups.find((candidate) => candidate.id === groupUid);
    if (byId) {
      return byId;
    }
  }
  const selector = target.selector;
  if (!selector) {
    return;
  }
  let matches = groups;
  const selectorUid = resolveSparklineUid(selector.uid);
  if (selectorUid) {
    matches = narrowMatchesIfAny(matches, (candidate) => candidate.uid === selectorUid || candidate.id === selectorUid);
  }
  matches = narrowMatchesIfAny(matches, (candidate) => matchSparklineRangeRef(candidate.locationRange, selector.targetRange));
  matches = narrowMatchesIfAny(matches, (candidate) => matchSparklineRangeRef(candidate.sourceData, selector.sourceData));
  if (selector.occurrence !== undefined) {
    return matches[selector.occurrence];
  }
  return matches.length === 1 ? matches[0] : undefined;
}
function resolveWorkbookThread(workbook, target, resolveThreadTargetRef) {
  const ref2 = resolveThreadTargetRef(target);
  if (ref2) {
    const resolved = workbook.resolve(ref2);
    if (resolved instanceof Thread2) {
      return resolved;
    }
  }
  if (typeof target === "string") {
    return;
  }
  const selector = target.selector;
  if (!selector) {
    return;
  }
  let matches = workbook.comments.threads.items;
  const targetSelector = selector.target;
  if (targetSelector) {
    if ("cell" in targetSelector) {
      const { sheet, address } = targetSelector.cell;
      matches = matches.filter((thread) => thread.target.spreadsheetCell?.sheetName === sheet && thread.target.spreadsheetCell?.address === address);
    } else if ("range" in targetSelector) {
      const { sheet, range: range2 } = targetSelector.range;
      matches = matches.filter((thread) => {
        const spreadsheetRange = thread.target.spreadsheetRange;
        if (!spreadsheetRange || spreadsheetRange.sheetName !== sheet) {
          return false;
        }
        const start = spreadsheetRange.startAddress ?? spreadsheetRange.endAddress;
        const end = spreadsheetRange.endAddress ?? spreadsheetRange.startAddress;
        if (!start) {
          return false;
        }
        const address = end && end !== start ? `${start}:${end}` : start;
        return address === range2;
      });
    }
  }
  if (selector.rootBody !== undefined) {
    matches = matches.filter((thread) => thread.comments[0]?.text === selector.rootBody);
  }
  if (selector.rootAuthorId !== undefined) {
    matches = matches.filter((thread) => thread.comments[0]?.authorId === selector.rootAuthorId);
  }
  if (selector.rootCreatedAt !== undefined) {
    matches = matches.filter((thread) => thread.comments[0]?.createdAt === selector.rootCreatedAt);
  }
  if (selector.occurrence !== undefined) {
    return matches[selector.occurrence];
  }
  return matches.length === 1 ? matches[0] : undefined;
}
function resolveTable(workbook, name2, sheetName) {
  if (sheetName) {
    return workbook.worksheets.getItem(sheetName).tables.getItem(name2);
  }
  for (const worksheet of workbook.worksheets) {
    const table2 = worksheet.tables.getItemOrNullObject(name2);
    if (!table2.isNullObject) {
      return table2;
    }
  }
  throw new Error(`Table ${name2} not found`);
}
function resolveThreadTarget(workbook, target) {
  if ("cell" in target) {
    const sheet2 = workbook.worksheets.getItem(target.cell.sheet);
    return { cell: sheet2.getRange(target.cell.address) };
  }
  const sheet = workbook.worksheets.getItem(target.range.sheet);
  return { range: sheet.getRange(target.range.range) };
}
function applySparklineProps(group, workbook, props) {
  group.type = props.type;
  group.locationRange = workbook.worksheets.getItem(props.targetRange.sheet).getRange(props.targetRange.range);
  group.sourceData = workbook.worksheets.getItem(props.sourceData.sheet).getRange(props.sourceData.range);
  group.dateAxisRange = props.dateAxisRange ? workbook.worksheets.getItem(props.dateAxisRange.sheet).getRange(props.dateAxisRange.range) : undefined;
  group.lineWeight = props.lineWeight;
  group.displayEmptyCellsAs = mapSparklineDisplayBlanks(props.displayEmptyCellsAs);
  group.displayHidden = Boolean(props.displayHidden);
  if (props.seriesColor !== undefined) {
    group.seriesColor = props.seriesColor;
  }
  if (props.negativeColor !== undefined) {
    group.negativeColor = props.negativeColor;
  }
  if (props.axisColor !== undefined) {
    group.axisColor = props.axisColor;
  }
  if (props.markersColor !== undefined) {
    group.markersColor = props.markersColor;
  }
  if (props.firstMarkerColor !== undefined) {
    group.firstMarkerColor = props.firstMarkerColor;
  }
  if (props.lastMarkerColor !== undefined) {
    group.lastMarkerColor = props.lastMarkerColor;
  }
  if (props.highMarkerColor !== undefined) {
    group.highMarkerColor = props.highMarkerColor;
  }
  if (props.lowMarkerColor !== undefined) {
    group.lowMarkerColor = props.lowMarkerColor;
  }
  group.markers.show = Boolean(props.markers?.show);
  group.markers.high = Boolean(props.markers?.high);
  group.markers.low = Boolean(props.markers?.low);
  group.markers.first = Boolean(props.markers?.first);
  group.markers.last = Boolean(props.markers?.last);
  group.markers.negative = Boolean(props.markers?.negative);
  const axis = mapSparklineAxis(props.axis);
  group.axis.manualMin = axis?.manualMin;
  group.axis.manualMax = axis?.manualMax;
  group.axis.minMode = axis?.minMode ?? 0 /* SPARKLINE_AXIS_MIN_MAX_UNSPECIFIED */;
  group.axis.maxMode = axis?.maxMode ?? 0 /* SPARKLINE_AXIS_MIN_MAX_UNSPECIFIED */;
  group.axis.showAxis = Boolean(axis?.showAxis);
  group.axis.rightToLeft = Boolean(axis?.rightToLeft);
}
function applyChartProps(chart2, props) {
  chart2.type = props.chartType;
  applyDrawingAnchor(chart2.anchor, props.anchor);
  chart2.title = props.title ?? "";
  chart2.categories = props.categories ? [...props.categories] : [];
  chart2.series.clear();
  if (props.series) {
    for (const seriesInput of props.series) {
      const series = chart2.series.add(seriesInput.name);
      if (seriesInput.values) {
        series.values = [...seriesInput.values];
      }
      if (seriesInput.xValues) {
        series.xValues = [...seriesInput.xValues];
      }
      if (seriesInput.categories) {
        series.categories = [...seriesInput.categories];
      }
      if (seriesInput.formula !== undefined) {
        series.formula = seriesInput.formula;
      }
      if (seriesInput.categoryFormula !== undefined) {
        series.categoryFormula = seriesInput.categoryFormula;
      }
      if (seriesInput.xFormula !== undefined) {
        series.xFormula = seriesInput.xFormula;
      }
      if (seriesInput.valuesFormatCode !== undefined) {
        series.valuesFormatCode = seriesInput.valuesFormatCode;
      }
      if (seriesInput.xValuesFormatCode !== undefined) {
        series.xValuesFormatCode = seriesInput.xValuesFormatCode;
      }
      if (seriesInput.fill !== undefined) {
        series.fill = seriesInput.fill;
      }
      if (seriesInput.stroke) {
        applyChartLinePatch(series.stroke, seriesInput.stroke);
      }
      if (seriesInput.marker) {
        if (seriesInput.marker.symbol !== undefined) {
          series.marker.symbol = seriesInput.marker.symbol;
        }
        if (seriesInput.marker.size !== undefined) {
          series.marker.size = seriesInput.marker.size;
        }
      }
    }
  }
  if (props.hasLegend !== undefined) {
    chart2.hasLegend = props.hasLegend;
  } else if (props.legend !== undefined) {
    chart2.hasLegend = true;
  }
  if (props.legend?.position !== undefined) {
    chart2.legend.position = props.legend.position;
  }
  chart2.dataLabels.showValue = Boolean(props.dataLabels?.showValue);
  chart2.dataLabels.showSeriesName = Boolean(props.dataLabels?.showSeriesName);
  chart2.dataLabels.showCategoryName = Boolean(props.dataLabels?.showCategoryName);
  chart2.dataLabels.showPercent = Boolean(props.dataLabels?.showPercent);
  chart2.dataLabels.showLeaderLines = Boolean(props.dataLabels?.showLeaderLines);
  if (props.displayBlanksAs !== undefined) {
    chart2.displayBlanksAs = props.displayBlanksAs;
  }
  if (props.barOptions) {
    if (props.barOptions.direction !== undefined) {
      chart2.barOptions.direction = props.barOptions.direction;
    }
    if (props.barOptions.grouping !== undefined) {
      chart2.barOptions.grouping = props.barOptions.grouping;
    }
    if (props.barOptions.varyColors !== undefined) {
      chart2.barOptions.varyColors = props.barOptions.varyColors;
    }
    if (props.barOptions.gapWidth !== undefined) {
      chart2.barOptions.gapWidth = props.barOptions.gapWidth;
    }
    if (props.barOptions.gapDepth !== undefined) {
      chart2.barOptions.gapDepth = props.barOptions.gapDepth;
    }
    if (props.barOptions.overlap !== undefined) {
      chart2.barOptions.overlap = props.barOptions.overlap;
    }
    if (props.barOptions.bar3dShape !== undefined) {
      chart2.barOptions.bar3dShape = props.barOptions.bar3dShape;
    }
  }
  if (props.pieOptions) {
    if (props.pieOptions.firstSliceAngle !== undefined) {
      chart2.pieOptions.firstSliceAngle = props.pieOptions.firstSliceAngle;
    }
  }
  if (props.doughnutOptions) {
    if (props.doughnutOptions.holeSize !== undefined) {
      chart2.doughnutOptions.holeSize = props.doughnutOptions.holeSize;
    }
    if (props.doughnutOptions.firstSliceAngle !== undefined) {
      chart2.doughnutOptions.firstSliceAngle = props.doughnutOptions.firstSliceAngle;
    }
  }
  if (props.plotArea) {
    applyChartAreaPatch(chart2.plotArea.format, props.plotArea);
  }
  if (props.chartArea) {
    applyChartAreaPatch(chart2.chartArea.format, props.chartArea);
  }
}
function applyChartAreaPatch(area, patch) {
  if (patch.fill !== undefined) {
    area.fill = patch.fill;
  }
  if (patch.line) {
    applyChartLinePatch(area.line, patch.line);
  }
}
function applyChartLinePatch(line, patch) {
  if (patch.fill !== undefined) {
    line.fill = patch.fill;
  } else if (patch.color !== undefined) {
    line.color = patch.color;
  }
  if (patch.style !== undefined) {
    line.style = patch.style;
  }
  if (patch.width !== undefined) {
    line.width = patch.width;
  }
}
function applyShapeSetProps2(shape2, props) {
  if (props.name !== undefined) {
    shape2.name = props.name;
  }
  if (props.zIndex !== undefined) {
    shape2.zIndex = props.zIndex;
  }
  if (props.placeholderType !== undefined) {
    shape2.placeholderType = props.placeholderType;
  }
  if (props.placeholderIndex !== undefined) {
    shape2.placeholderIndex = props.placeholderIndex;
  }
  if (props.position) {
    shape2.position = props.position;
  }
  if (props.fill !== undefined) {
    shape2.fill = props.fill;
  }
  if (props.line) {
    if (props.line.style !== undefined) {
      shape2.line.style = props.line.style;
    }
    if (props.line.width !== undefined) {
      shape2.line.width = props.line.width;
    }
    if (props.line.fill !== undefined) {
      shape2.line.fill = props.line.fill;
    }
  }
}
function applyDrawingAnchor(anchor, patch) {
  anchor.from = patch.from;
  if (patch.to !== undefined) {
    anchor.to = patch.to;
  } else {
    anchor.to = undefined;
  }
  if (patch.extent !== undefined) {
    anchor.extent = patch.extent;
  } else if (patch.to === undefined) {
    anchor.extent = undefined;
  }
}
function resolveWorksheetImage(sheet, target) {
  const targetKey = JSON.stringify(target.anchor);
  const exact = sheet.images.items.find((candidate) => candidate.imageId === target.imageId && JSON.stringify(candidate.anchor.toConfig()) === targetKey);
  if (exact) {
    return exact;
  }
  const byImageId = sheet.images.items.filter((candidate) => candidate.imageId === target.imageId);
  if (byImageId.length === 1) {
    return byImageId[0];
  }
  return;
}
function applyWorksheetImageSetSource(image2, props) {
  if (props.dataUrl !== undefined) {
    image2.replace({ dataUrl: props.dataUrl });
    return true;
  }
  if (props.path !== undefined) {
    image2.replace({ path: props.path });
    return true;
  }
  if (props.uri !== undefined) {
    image2.replace({ uri: props.uri });
    return true;
  }
  if (props.prompt !== undefined) {
    image2.replace({ prompt: props.prompt });
    return true;
  }
  return false;
}

// node_modules/@oai/granola/dist/models/spreadsheet/workbook-style-store.js
var STYLE_SCHEMA_VERSION = 1;
var STYLES_ENTRIES_BY_ID_KEY = "styles.entriesById";
var STYLES_ENTRY_ORDER_KEY = "styles.entryOrder";
var STYLES_SIGNATURE_TO_ID_KEY = "styles.signatureToId";
var STYLES_META_KEY = "styles.meta";

class WorkbookStyleStore {
  #isCollaborativeStateReady;
  #runLocalTransaction;
  #styleRegistry;
  #stylesRoot;
  #entriesById;
  #entryOrder;
  #signatureToId;
  #meta;
  #didSyncFromBranch = false;
  #styleIdByIndex;
  #styleIndexById;
  #listeners;
  #deepObserver;
  constructor(config3) {
    this.#isCollaborativeStateReady = config3.isCollaborativeStateReady ?? (() => true);
    this.#runLocalTransaction = config3.runLocalTransaction;
    this.#styleRegistry = config3.styleRegistry;
    this.#stylesRoot = config3.doc.getMap("styles");
    this.#entriesById = config3.doc.getMap(STYLES_ENTRIES_BY_ID_KEY);
    this.#entryOrder = config3.doc.getArray(STYLES_ENTRY_ORDER_KEY);
    this.#signatureToId = config3.doc.getMap(STYLES_SIGNATURE_TO_ID_KEY);
    this.#meta = config3.doc.getMap(STYLES_META_KEY);
    this.#styleIdByIndex = new Map;
    this.#styleIndexById = new Map;
    this.#listeners = new Set;
    this.#deepObserver = (events, transaction) => {
      this.#handleStylesTreeEvent(events, transaction);
    };
    this.#entriesById.observeDeep(this.#deepObserver);
    this.#entryOrder.observeDeep(this.#deepObserver);
    this.#signatureToId.observeDeep(this.#deepObserver);
    this.#meta.observeDeep(this.#deepObserver);
    this.#migrateLegacyBranchesIfNeeded();
    this.#syncFromBranchIfNeeded();
  }
  subscribe(listener) {
    this.#listeners.add(listener);
    return () => {
      this.#listeners.delete(listener);
    };
  }
  getOrCreateStyleIdForIndex(styleIndex) {
    const cached2 = this.#styleIdByIndex.get(styleIndex);
    if (cached2) {
      return cached2;
    }
    if (!this.#isCollaborativeStateReady()) {
      const styleId2 = `style-base-${styleIndex}`;
      this.#linkStyleIdToIndex(styleId2, styleIndex);
      return styleId2;
    }
    this.#activateBranch();
    const signatureToId = this.#signatureToId;
    if (!signatureToId) {
      throw new Error("Workbook style branch failed to initialize.");
    }
    const description = this.#styleRegistry.describe(styleIndex);
    const snapshot = snapshotFromStyleDescription(description);
    const signature = serializeStable(snapshot);
    const knownId = signatureToId.get(signature);
    if (knownId) {
      this.#linkStyleIdToIndex(knownId, styleIndex);
      this.#writeStyleEntryIfMissing(knownId, signature, snapshot);
      return knownId;
    }
    const styleId = `style-${hashText(signature)}`;
    this.#writeStyleEntryIfMissing(styleId, signature, snapshot);
    signatureToId.set(signature, styleId);
    this.#linkStyleIdToIndex(styleId, styleIndex);
    return styleId;
  }
  getStyleIndexForId(styleId) {
    const cached2 = this.#styleIndexById.get(styleId);
    if (cached2 !== undefined) {
      return cached2;
    }
    this.#loadBranchIfPresent();
    this.#syncFromBranchIfNeeded();
    const entriesById = this.#entriesById;
    const signatureToId = this.#signatureToId;
    if (!entriesById || !signatureToId) {
      return;
    }
    const entry = entriesById.get(styleId);
    if (!entry) {
      return;
    }
    const styleIndex = this.#styleRegistry.register(styleInputFromSnapshot(entry.style));
    this.#linkStyleIdToIndex(styleId, styleIndex);
    if (!signatureToId.has(entry.signature)) {
      signatureToId.set(entry.signature, styleId);
    }
    return styleIndex;
  }
  registerStyle(input) {
    if (!this.#isCollaborativeStateReady()) {
      const styleIndex2 = this.#styleRegistry.register(input);
      const styleId2 = `style-base-${styleIndex2}`;
      this.#linkStyleIdToIndex(styleId2, styleIndex2);
      return { styleId: styleId2, styleIndex: styleIndex2 };
    }
    this.#activateBranch();
    const entriesById = this.#entriesById;
    const signatureToId = this.#signatureToId;
    if (!entriesById || !signatureToId) {
      throw new Error("Workbook style branch failed to initialize.");
    }
    const styleIndex = this.#styleRegistry.register(input);
    const description = this.#styleRegistry.describe(styleIndex);
    const snapshot = snapshotFromStyleDescription(description);
    const signature = serializeStable(snapshot);
    const knownId = signatureToId.get(signature);
    if (knownId) {
      this.#linkStyleIdToIndex(knownId, styleIndex);
      this.#writeStyleEntryIfMissing(knownId, signature, snapshot);
      return { styleId: knownId, styleIndex };
    }
    let styleId = `style-${hashText(signature)}`;
    if (entriesById.has(styleId) && entriesById.get(styleId)?.signature !== signature) {
      let suffix = 1;
      while (entriesById.has(`${styleId}-${suffix}`)) {
        suffix += 1;
      }
      styleId = `${styleId}-${suffix}`;
    }
    this.#runLocalTransaction(() => {
      entriesById.set(styleId, {
        id: styleId,
        signature,
        style: clonePlain(snapshot)
      });
      this.#entryOrder.push([styleId]);
      signatureToId.set(signature, styleId);
    });
    this.#linkStyleIdToIndex(styleId, styleIndex);
    return { styleId, styleIndex };
  }
  hydrateFromStyleRegistry() {
    if (!this.#isCollaborativeStateReady()) {
      return;
    }
    this.#activateBranch();
  }
  #activateBranch() {
    this.#setSchemaVersion();
    this.#syncFromBranchIfNeeded();
    if (this.#entriesById.size === 0 && this.#entryOrder.length === 0 && this.#signatureToId.size === 0) {
      this.#seedFromRegistry();
      this.#didSyncFromBranch = true;
    }
  }
  #loadBranchIfPresent() {}
  #syncFromBranchIfNeeded() {
    if (this.#didSyncFromBranch) {
      return;
    }
    if (this.#entryOrder.length === 0 && this.#entriesById.size === 0) {
      this.#didSyncFromBranch = true;
      return;
    }
    this.#syncFromBranch();
    this.#didSyncFromBranch = true;
  }
  #syncFromBranch() {
    for (const styleId of this.#orderedStyleIds()) {
      const entry = this.#entriesById.get(styleId);
      if (!entry) {
        continue;
      }
      const styleIndex = this.#styleRegistry.register(styleInputFromSnapshot(entry.style));
      this.#linkStyleIdToIndex(styleId, styleIndex);
      if (!this.#signatureToId.has(entry.signature)) {
        this.#signatureToId.set(entry.signature, styleId);
      }
    }
  }
  #seedFromRegistry() {
    const entriesById = this.#entriesById;
    const entryOrder = this.#entryOrder;
    const signatureToId = this.#signatureToId;
    const meta3 = this.#meta;
    this.#runLocalTransaction(() => {
      for (let styleIndex = 0;styleIndex < this.#styleRegistry.getStyleCount(); styleIndex += 1) {
        const description = this.#styleRegistry.describe(styleIndex);
        const snapshot = snapshotFromStyleDescription(description);
        const signature = serializeStable(snapshot);
        const styleId = `style-base-${styleIndex}`;
        entriesById.set(styleId, {
          id: styleId,
          signature,
          style: clonePlain(snapshot)
        });
        entryOrder.push([styleId]);
        if (!signatureToId.has(signature)) {
          signatureToId.set(signature, styleId);
        }
        this.#linkStyleIdToIndex(styleId, styleIndex);
      }
      const defaultStyleId = this.#styleIdByIndex.get(0);
      if (defaultStyleId && meta3) {
        meta3.set("defaultStyleId", defaultStyleId);
      }
    });
  }
  #writeStyleEntryIfMissing(styleId, signature, snapshot) {
    const entriesById = this.#entriesById;
    const entryOrder = this.#entryOrder;
    if (entriesById.has(styleId)) {
      return;
    }
    this.#runLocalTransaction(() => {
      entriesById.set(styleId, {
        id: styleId,
        signature,
        style: clonePlain(snapshot)
      });
      entryOrder.push([styleId]);
    });
  }
  #linkStyleIdToIndex(styleId, styleIndex) {
    this.#styleIndexById.set(styleId, styleIndex);
    if (!this.#styleIdByIndex.has(styleIndex)) {
      this.#styleIdByIndex.set(styleIndex, styleId);
    }
  }
  #setSchemaVersion() {
    const current = this.#stylesRoot.get("schemaVersion");
    if (current === STYLE_SCHEMA_VERSION) {
      return;
    }
    this.#runLocalTransaction(() => {
      this.#stylesRoot.set("schemaVersion", STYLE_SCHEMA_VERSION);
    });
  }
  #handleStylesTreeEvent(events, transaction) {
    if (events.length === 0) {
      return;
    }
    this.#didSyncFromBranch = false;
    this.#notifyListeners();
  }
  #migrateLegacyBranchesIfNeeded() {
    const legacyEntriesById = this.#readLegacyEntriesById();
    const legacyEntryOrder = this.#readLegacyEntryOrder();
    const legacySignatureToId = this.#readLegacySignatureToId();
    const legacyMeta = this.#readLegacyMeta();
    if (!legacyEntriesById && !legacyEntryOrder && !legacySignatureToId && !legacyMeta) {
      return;
    }
    if (this.#entriesById.size > 0 || this.#entryOrder.length > 0 || this.#signatureToId.size > 0 || this.#meta.size > 0) {
      return;
    }
    this.#runLocalTransaction(() => {
      for (const [styleId, entry] of legacyEntriesById?.entries() ?? []) {
        this.#entriesById.set(styleId, clonePlain(entry));
      }
      for (const styleId of legacyEntryOrder?.toArray() ?? []) {
        this.#entryOrder.push([styleId]);
      }
      for (const [signature, styleId] of legacySignatureToId?.entries() ?? []) {
        this.#signatureToId.set(signature, styleId);
      }
      for (const [key, value2] of legacyMeta?.entries() ?? []) {
        this.#meta.set(key, clonePlain(value2));
      }
    });
  }
  #notifyListeners() {
    for (const listener of this.#listeners) {
      listener();
    }
  }
  #readLegacyEntriesById() {
    const existing = this.#stylesRoot.get("entriesById");
    if (existing instanceof YMap) {
      return existing;
    }
    return;
  }
  #readLegacyEntryOrder() {
    const existing = this.#stylesRoot.get("entryOrder");
    if (existing instanceof YArray) {
      return existing;
    }
    return;
  }
  #readLegacySignatureToId() {
    const existing = this.#stylesRoot.get("signatureToId");
    if (existing instanceof YMap) {
      return existing;
    }
    return;
  }
  #readLegacyMeta() {
    const existing = this.#stylesRoot.get("meta");
    if (existing instanceof YMap) {
      return existing;
    }
    return;
  }
  #orderedStyleIds() {
    const seen = new Set;
    const ordered = [];
    for (const styleId of this.#entryOrder.toArray()) {
      if (seen.has(styleId) || !this.#entriesById.has(styleId)) {
        continue;
      }
      seen.add(styleId);
      ordered.push(styleId);
    }
    for (const styleId of this.#entriesById.keys()) {
      if (seen.has(styleId)) {
        continue;
      }
      seen.add(styleId);
      ordered.push(styleId);
    }
    return ordered;
  }
}
function snapshotFromStyleDescription(description) {
  const fillProto = description.fill?.toProto();
  const fontProto = description.font?.toProto();
  const borderProto = description.border?.toProto();
  return {
    fillProto: fillProto ? clonePlain(fillProto) : undefined,
    fontProto: fontProto ? clonePlain(fontProto) : undefined,
    borderProto: borderProto ? clonePlain(borderProto) : undefined,
    numberFormatCode: description.numberFormatCode,
    numberFormatId: description.numberFormatId,
    wrapText: description.wrapText,
    horizontalAlignment: description.horizontalAlignment,
    verticalAlignment: description.verticalAlignment,
    featurePropertyBagIndex: description.featurePropertyBagIndex
  };
}
function styleInputFromSnapshot(snapshot) {
  return {
    fill: snapshot.fillProto ? new Fill2({ type: "proto", proto: clonePlain(snapshot.fillProto) }) : undefined,
    font: snapshot.fontProto ? new TextStyleModel(clonePlain(snapshot.fontProto)) : undefined,
    border: snapshot.borderProto ? new BorderModel(clonePlain(snapshot.borderProto)) : undefined,
    numberFormatCode: snapshot.numberFormatCode,
    numberFormatId: snapshot.numberFormatId,
    wrapText: snapshot.wrapText,
    horizontalAlignment: snapshot.horizontalAlignment,
    verticalAlignment: snapshot.verticalAlignment,
    featurePropertyBagIndex: snapshot.featurePropertyBagIndex
  };
}
function clonePlain(value2) {
  if (value2 == null) {
    return value2;
  }
  return JSON.parse(JSON.stringify(value2));
}
function serializeStable(value2) {
  return JSON.stringify(sortForStableSerialization(value2));
}
function sortForStableSerialization(value2) {
  if (Array.isArray(value2)) {
    return value2.map((item) => sortForStableSerialization(item));
  }
  if (value2 && typeof value2 === "object") {
    const record2 = value2;
    const sorted = {};
    const keys2 = Object.keys(record2).sort();
    for (const key of keys2) {
      sorted[key] = sortForStableSerialization(record2[key]);
    }
    return sorted;
  }
  return value2;
}
function hashText(value2) {
  let hash2 = 2166136261;
  for (let index = 0;index < value2.length; index += 1) {
    hash2 ^= value2.charCodeAt(index);
    hash2 = Math.imul(hash2, 16777619);
  }
  return (hash2 >>> 0).toString(36);
}

// node_modules/@oai/granola/dist/models/spreadsheet/workbook-worksheet-topology-store.js
var WORKSHEET_TOPOLOGY_SCHEMA_VERSION = 1;

class WorkbookWorksheetTopologyStore {
  #runLocalTransaction;
  #getCollabOrigins;
  #root;
  #entriesById;
  #entryOrder;
  #meta;
  #listeners;
  #rootObserver;
  #entriesObserver;
  #orderObserver;
  constructor(config3) {
    this.#runLocalTransaction = config3.runLocalTransaction;
    this.#getCollabOrigins = config3.getCollabOrigins;
    this.#root = config3.doc.getMap("worksheetTopology");
    this.#entriesById = this.#readEntriesById();
    this.#entryOrder = this.#readEntryOrder();
    this.#meta = this.#readMeta();
    this.#listeners = new Set;
    this.#rootObserver = (event, transaction) => {
      if (this.#isLocalTransaction(transaction)) {
        return;
      }
      if (!event.keysChanged.has("entriesById") && !event.keysChanged.has("entryOrder") && !event.keysChanged.has("meta")) {
        return;
      }
      this.#rebindBranches();
      this.#emitChange();
    };
    this.#entriesObserver = (event, transaction) => {
      if (event.keysChanged.size === 0) {
        return;
      }
      if (this.#isLocalTransaction(transaction)) {
        return;
      }
      this.#emitChange();
    };
    this.#orderObserver = (event, transaction) => {
      if (event.changes.delta.length === 0) {
        return;
      }
      if (this.#isLocalTransaction(transaction)) {
        return;
      }
      this.#emitChange();
    };
    this.#root.observe(this.#rootObserver);
    if (this.#entriesById) {
      this.#entriesById.observe(this.#entriesObserver);
    }
    if (this.#entryOrder) {
      this.#entryOrder.observe(this.#orderObserver);
    }
  }
  dispose() {
    this.#root.unobserve(this.#rootObserver);
    this.#entriesById?.unobserve(this.#entriesObserver);
    this.#entryOrder?.unobserve(this.#orderObserver);
    this.#listeners.clear();
  }
  onDidChange(handler) {
    this.#listeners.add(handler);
    return () => {
      this.#listeners.delete(handler);
    };
  }
  readEntries() {
    const entriesById = this.#entriesById ?? this.#readEntriesById();
    const entryOrder = this.#entryOrder ?? this.#readEntryOrder();
    if (!entriesById) {
      return [];
    }
    const orderedIds = [];
    const seen = new Set;
    for (const sheetId of entryOrder?.toArray() ?? []) {
      if (seen.has(sheetId)) {
        continue;
      }
      if (!entriesById.has(sheetId)) {
        continue;
      }
      seen.add(sheetId);
      orderedIds.push(sheetId);
    }
    for (const sheetId of entriesById.keys()) {
      if (seen.has(sheetId)) {
        continue;
      }
      seen.add(sheetId);
      orderedIds.push(sheetId);
    }
    const entries = [];
    for (const sheetId of orderedIds) {
      const node = entriesById.get(sheetId);
      if (!node) {
        continue;
      }
      const normalized = normalizeTopologyNode(node);
      if (!normalized) {
        continue;
      }
      entries.push({
        sheetId: normalized.sheetId,
        name: normalized.name,
        index: entries.length
      });
    }
    return entries;
  }
  replaceEntries(entries) {
    this.#activateBranch();
    const entriesById = this.#entriesById;
    const entryOrder = this.#entryOrder;
    if (!entriesById || !entryOrder) {
      return;
    }
    const normalizedEntries = normalizeTopologyEntries2(entries);
    const nextIds = new Set(normalizedEntries.map((entry) => entry.sheetId));
    const nextOrder = normalizedEntries.map((entry) => entry.sheetId);
    this.#runLocalTransaction(() => {
      for (const existingId of [...entriesById.keys()]) {
        if (!nextIds.has(existingId)) {
          entriesById.delete(existingId);
        }
      }
      for (const entry of normalizedEntries) {
        entriesById.set(entry.sheetId, {
          sheetId: entry.sheetId,
          name: entry.name
        });
      }
      entryOrder.delete(0, entryOrder.length);
      if (nextOrder.length > 0) {
        entryOrder.insert(0, nextOrder);
      }
    });
  }
  #emitChange() {
    for (const listener of this.#listeners) {
      listener();
    }
  }
  #isLocalTransaction(transaction) {
    const origins = this.#getCollabOrigins();
    return transaction.origin === origins.local || transaction.origin === origins.record;
  }
  #activateBranch() {
    const entriesById = this.#readEntriesById();
    if (entriesById) {
      this.#entriesById = entriesById;
    } else {
      const created = new YMap;
      this.#root.set("entriesById", created);
      this.#entriesById = created;
    }
    const entryOrder = this.#readEntryOrder();
    if (entryOrder) {
      this.#entryOrder = entryOrder;
    } else {
      const created = new YArray;
      this.#root.set("entryOrder", created);
      this.#entryOrder = created;
    }
    const meta3 = this.#readMeta();
    if (meta3) {
      this.#meta = meta3;
    } else {
      const created = new YMap;
      this.#root.set("meta", created);
      this.#meta = created;
    }
    this.#rebindBranches();
    this.#setSchemaVersion();
  }
  #rebindBranches() {
    const nextEntriesById = this.#readEntriesById();
    if (nextEntriesById !== this.#entriesById) {
      this.#entriesById?.unobserve(this.#entriesObserver);
      this.#entriesById = nextEntriesById;
      this.#entriesById?.observe(this.#entriesObserver);
    }
    const nextEntryOrder = this.#readEntryOrder();
    if (nextEntryOrder !== this.#entryOrder) {
      this.#entryOrder?.unobserve(this.#orderObserver);
      this.#entryOrder = nextEntryOrder;
      this.#entryOrder?.observe(this.#orderObserver);
    }
    const nextMeta = this.#readMeta();
    if (nextMeta !== this.#meta) {
      this.#meta = nextMeta;
    }
  }
  #setSchemaVersion() {
    if (!this.#meta) {
      return;
    }
    if (this.#meta.get("schemaVersion") === WORKSHEET_TOPOLOGY_SCHEMA_VERSION) {
      return;
    }
    this.#runLocalTransaction(() => {
      this.#meta?.set("schemaVersion", WORKSHEET_TOPOLOGY_SCHEMA_VERSION);
    });
  }
  #readEntriesById() {
    const existing = this.#root.get("entriesById");
    if (existing instanceof YMap) {
      return existing;
    }
    return;
  }
  #readEntryOrder() {
    const existing = this.#root.get("entryOrder");
    if (existing instanceof YArray) {
      return existing;
    }
    return;
  }
  #readMeta() {
    const existing = this.#root.get("meta");
    if (existing instanceof YMap) {
      return existing;
    }
    return;
  }
}
function normalizeTopologyNode(node) {
  const sheetId = node.sheetId?.trim();
  const name2 = node.name?.trim();
  if (!sheetId || !name2) {
    return null;
  }
  return { sheetId, name: name2 };
}
function normalizeTopologyEntries2(entries) {
  const normalizedEntries = [...entries].map((entry, index) => {
    const sheetId = entry.sheetId?.trim();
    const name2 = entry.name?.trim();
    const rawIndex = Number.isFinite(entry.index) ? entry.index : index;
    if (!sheetId || !name2) {
      return null;
    }
    return { sheetId, name: name2, index: rawIndex };
  }).filter((entry) => entry != null).sort((left, right) => left.index - right.index);
  const seen = new Set;
  const deduped = [];
  for (const entry of normalizedEntries) {
    if (seen.has(entry.sheetId)) {
      continue;
    }
    seen.add(entry.sheetId);
    deduped.push({
      sheetId: entry.sheetId,
      name: entry.name,
      index: deduped.length
    });
  }
  return deduped;
}

// node_modules/@oai/granola/dist/models/workbook-theme-collab-store.js
class WorkbookThemeCollabStore {
  #store;
  constructor(config3) {
    this.#store = new JsonSnapshotBranchStore({
      root: config3.root,
      prefix: config3.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION,
      runLocalTransaction: config3.runLocalTransaction,
      getCollabOrigins: config3.getCollabOrigins,
      readSnapshotFromOwner: config3.readTheme,
      applySnapshotToOwner: config3.applyTheme,
      encodeSnapshot: (theme) => theme,
      decodeSnapshot: (theme) => theme
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/workbook-feature-property-bags-collab-store.js
class WorkbookFeaturePropertyBagsCollabStore {
  #store;
  constructor(config3) {
    this.#store = new JsonSnapshotBranchStore({
      root: config3.root,
      prefix: config3.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION,
      runLocalTransaction: config3.runLocalTransaction,
      getCollabOrigins: config3.getCollabOrigins,
      readSnapshotFromOwner: config3.readFeaturePropertyBags,
      applySnapshotToOwner: config3.applyFeaturePropertyBags,
      encodeSnapshot: (bags) => bags,
      decodeSnapshot: (bags) => bags
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/defined-names-collab-store.js
class DefinedNamesCollabStore {
  #store;
  constructor(config3) {
    this.#store = new JsonSnapshotBranchStore({
      root: config3.root,
      prefix: config3.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION,
      runLocalTransaction: config3.runLocalTransaction,
      getCollabOrigins: config3.getCollabOrigins,
      readSnapshotFromOwner: config3.readDefinedNames,
      applySnapshotToOwner: (names) => config3.applyDefinedNames(names ?? []),
      encodeSnapshot: (names) => names,
      decodeSnapshot: (names) => names
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/workbook-image-assets-collab-store.js
class WorkbookImageAssetsCollabStore {
  #store;
  constructor(config3) {
    this.#store = new JsonSnapshotBranchStore({
      root: config3.root,
      prefix: config3.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION,
      runLocalTransaction: config3.runLocalTransaction,
      getCollabOrigins: config3.getCollabOrigins,
      readSnapshotFromOwner: config3.readImages,
      applySnapshotToOwner: (images) => config3.applyImages(images ?? []),
      encodeSnapshot: (images) => images.map((image2) => ({
        ...image2,
        data: Array.from(image2.data ?? [])
      })),
      decodeSnapshot: (images) => images.map((image2) => ({
        ...image2,
        data: new Uint8Array(image2.data ?? [])
      }))
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/notes-collab-store.js
class NotesCollabStore {
  #store;
  constructor(config3) {
    this.#store = new JsonSnapshotBranchStore({
      root: config3.root,
      prefix: config3.prefix,
      schemaVersion: SNAPSHOT_BRANCH_SCHEMA_VERSION,
      runLocalTransaction: config3.runLocalTransaction,
      getCollabOrigins: config3.getCollabOrigins,
      readSnapshotFromOwner: config3.readNotes,
      applySnapshotToOwner: (notes) => config3.applyNotes(notes ?? []),
      encodeSnapshot: (notes) => notes,
      decodeSnapshot: (notes) => notes
    });
  }
  dispose() {
    this.#store.dispose();
  }
  activate() {
    this.#store.activate();
  }
  flushFromOwner() {
    this.#store.flushFromOwner();
  }
}

// node_modules/@oai/granola/dist/models/workbook-collab-state.js
class WorkbookCollabState {
  #stores;
  constructor(config3) {
    this.#stores = [
      new WorkbookThemeCollabStore({
        root: config3.root,
        prefix: "theme",
        runLocalTransaction: config3.runLocalTransaction,
        getCollabOrigins: config3.getCollabOrigins,
        readTheme: config3.readTheme,
        applyTheme: config3.applyTheme
      }),
      new WorkbookFeaturePropertyBagsCollabStore({
        root: config3.root,
        prefix: "featurePropertyBags",
        runLocalTransaction: config3.runLocalTransaction,
        getCollabOrigins: config3.getCollabOrigins,
        readFeaturePropertyBags: config3.readFeaturePropertyBags,
        applyFeaturePropertyBags: config3.applyFeaturePropertyBags
      }),
      new DefinedNamesCollabStore({
        root: config3.root,
        prefix: "definedNames",
        runLocalTransaction: config3.runLocalTransaction,
        getCollabOrigins: config3.getCollabOrigins,
        readDefinedNames: config3.readDefinedNames,
        applyDefinedNames: config3.applyDefinedNames
      }),
      new WorkbookImageAssetsCollabStore({
        root: config3.root,
        prefix: "images",
        runLocalTransaction: config3.runLocalTransaction,
        getCollabOrigins: config3.getCollabOrigins,
        readImages: config3.readImages,
        applyImages: config3.applyImages
      }),
      new CommentsCollabStore({
        root: config3.root,
        prefix: "comments",
        runLocalTransaction: config3.runLocalTransaction,
        getCollabOrigins: config3.getCollabOrigins,
        readComments: config3.readComments,
        applyComments: config3.applyComments
      }),
      new NotesCollabStore({
        root: config3.root,
        prefix: "notes",
        runLocalTransaction: config3.runLocalTransaction,
        getCollabOrigins: config3.getCollabOrigins,
        readNotes: config3.readNotes,
        applyNotes: config3.applyNotes
      })
    ];
  }
  dispose() {
    for (const store of this.#stores) {
      store.dispose();
    }
  }
  activate() {
    for (const store of this.#stores) {
      store.activate();
    }
  }
  flushFromOwner() {
    for (const store of this.#stores) {
      store.flushFromOwner();
    }
  }
}

// node_modules/@oai/granola/dist/spreadsheet/adapter/style-snapshot.js
function styleSnapshot(range2) {
  const fmt = range2.format;
  const fillProto = fmt.fill?.toProto();
  const fontModel = new TextStyleModel;
  fontModel.bold = fmt.font.bold;
  fontModel.italic = fmt.font.italic;
  fontModel.size = fmt.font.size;
  fontModel.name = fmt.font.name;
  fontModel.color = fmt.font.color ?? undefined;
  const fontProto = fontModel.toProto();
  const borderProto = fmt.borders.toProto();
  return {
    fill: fillProto,
    font: fontProto,
    border: borderProto,
    numberFormat: fmt.numberFormat,
    wrapText: fmt.wrapText,
    horizontalAlignment: fmt.horizontalAlignment,
    styleId: fmt.styleId
  };
}

// node_modules/@oai/granola/dist/models/workbook-inspect.js
init_address_utils();
function cssToRgb(css) {
  const trimmed = css.trim();
  if (trimmed.startsWith("#") && trimmed.length === 7) {
    const r2 = parseInt(trimmed.slice(1, 3), 16);
    const g2 = parseInt(trimmed.slice(3, 5), 16);
    const b2 = parseInt(trimmed.slice(5, 7), 16);
    if ([r2, g2, b2].some((v) => Number.isNaN(v)))
      return null;
    return [r2, g2, b2];
  }
  const m = trimmed.match(/^rgba?\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\)$/i);
  if (!m)
    return null;
  const r = parseInt(m[1] ?? "", 10);
  const g = parseInt(m[2] ?? "", 10);
  const b = parseInt(m[3] ?? "", 10);
  if ([r, g, b].some((v) => Number.isNaN(v)))
    return null;
  return [r, g, b];
}
function rgbToProtoColor(r, g, b) {
  const to2 = (value3) => Math.max(0, Math.min(255, Math.round(value3))).toString(16).padStart(2, "0").toUpperCase();
  const value2 = `FF${to2(r)}${to2(g)}${to2(b)}`;
  return {
    type: 1 /* COLOR_TYPE_RGB */,
    value: value2,
    lastColor: value2,
    transform: undefined
  };
}
function cssToSolidFillProto(css) {
  const rgb2 = cssToRgb(css);
  if (!rgb2)
    return null;
  const [r, g, b] = rgb2;
  return {
    type: 1 /* FILL_TYPE_SOLID */,
    color: rgbToProtoColor(r, g, b),
    gradientStops: []
  };
}
var DEFAULT_KIND_TOKENS2 = [
  "workbook",
  "sheet",
  "table",
  "formula",
  "thread"
];
var KIND_ALIASES2 = {
  wb: "workbook",
  workbooks: "workbook",
  sheets: "sheet",
  worksheet: "sheet",
  worksheets: "sheet",
  tables: "table",
  range: "table",
  ranges: "table",
  region: "region",
  regions: "region",
  dataregion: "region",
  "data-region": "region",
  dataregions: "region",
  matches: "match",
  formulas: "formula",
  threads: "thread",
  comments: "thread",
  conditionalformat: "conditionalFormatting",
  "conditional-format": "conditionalFormatting",
  conditionalformatting: "conditionalFormatting",
  "conditional-formatting": "conditionalFormatting",
  conditionalformats: "conditionalFormatting",
  "conditional-formats": "conditionalFormatting",
  conditionalformattings: "conditionalFormatting",
  cf: "conditionalFormatting",
  styles: "computedStyle",
  computedstyle: "computedStyle",
  computedstyles: "computedStyle",
  definedname: "definedName",
  "defined-name": "definedName",
  definednames: "definedName",
  "defined-names": "definedName",
  names: "definedName",
  drawing: "drawing",
  drawings: "drawing",
  shape: "drawing",
  shapes: "drawing"
};
var DEFAULT_KIND_PROPERTIES2 = {
  workbook: ["id", "sheets", "tables", "threads"],
  sheet: [
    "id",
    "name",
    "index",
    "range",
    "address",
    "tables",
    "formulas",
    "threads"
  ],
  table: [
    "sheet",
    "address",
    "rows",
    "cols",
    "values",
    "valuesPreviewAddress",
    "valuesPreviewRows",
    "valuesPreviewCols",
    "valuesTruncated"
  ],
  region: [
    "sheet",
    "address",
    "rows",
    "cols",
    "nonEmpty",
    "blank",
    "numeric",
    "text",
    "bool",
    "date",
    "maxTextLength",
    "preview",
    "previewAddress",
    "previewRows",
    "previewCols"
  ],
  match: ["sheet", "address", "value", "formula", "match"],
  formula: ["sheet", "address", "formula"],
  thread: ["id", "sheet", "target", "status", "text", "comments"],
  conditionalFormatting: [
    "sheet",
    "address",
    "type",
    "priority",
    "operator",
    "formula",
    "text",
    "timePeriod",
    "rank",
    "percent",
    "bottom",
    "aboveAverage",
    "equalAverage",
    "stdDev",
    "dxfId",
    "stopIfTrue",
    "colorScale",
    "dataBar",
    "iconSet"
  ],
  definedName: ["name", "scope", "formula"],
  computedStyle: ["sheet", "for", "style"],
  drawing: ["sheet", "drawingType", "id", "name", "geometry", "anchor"],
  notice: ["message"]
};
var PROPERTY_ALIASES2 = {
  addr: "address",
  cell: "address",
  cells: "address",
  sheetname: "sheet",
  workbookid: "id",
  sheetid: "id",
  targetcell: "target",
  previewaddress: "previewAddress",
  previewrows: "previewRows",
  previewcols: "previewCols",
  valuespreviewaddress: "valuesPreviewAddress",
  valuespreviewrows: "valuesPreviewRows",
  valuespreviewcols: "valuesPreviewCols",
  valuestruncated: "valuesTruncated"
};
var KIND_TOKEN_SET2 = new Set(DEFAULT_KIND_TOKENS2);
KIND_TOKEN_SET2.add("match");
KIND_TOKEN_SET2.add("conditionalFormatting");
KIND_TOKEN_SET2.add("computedStyle");
KIND_TOKEN_SET2.add("region");
KIND_TOKEN_SET2.add("definedName");
KIND_TOKEN_SET2.add("drawing");
var PROPERTY_TOKEN_SET2 = new Set(Object.values(DEFAULT_KIND_PROPERTIES2).flat());
var DEFAULT_MAX_CHARS3 = 12000;
var DEFAULT_TABLE_PREVIEW_ROWS = 5;
var DEFAULT_TABLE_PREVIEW_COLS = 6;
var DEFAULT_TABLE_PREVIEW_CELL_CHARS = 80;
var SHAPE_GEOMETRY_PROTO_TO_NAME = Object.entries(SHAPE_GEOMETRY_NAME_TO_PROTO).reduce((acc, [name2, value2]) => {
  if (typeof value2 === "number") {
    acc[value2] = name2;
  }
  return acc;
}, {});
var isSameWorksheet = (left, right) => left.id === right.id || left.sheetId === right.sheetId || left.name === right.name;
var resolveRangeFilter = (workbook, options, metadata) => {
  const rawRange = typeof options.range === "string" ? options.range.trim() : "";
  const rangeParts = rawRange ? splitSheetAddress(rawRange) : { ref: "" };
  const parsedRange = rawRange ? parseRangeAddress(rangeParts.ref) : null;
  if (rawRange && !parsedRange) {
    metadata.notices ??= [];
    metadata.notices.push(`Invalid range filter: ${rawRange}`);
  }
  const rawSheetId = typeof options.sheetId === "string" ? options.sheetId.trim() : "";
  const sheetId = rawSheetId ? normalizeSheetId(rawSheetId) : "";
  let sheetFromId = null;
  if (sheetId) {
    try {
      sheetFromId = resolveWorksheetForSearch(workbook, sheetId);
    } catch (error49) {
      metadata.notices ??= [];
      metadata.notices.push(error49 instanceof Error ? error49.message : `Worksheet ${sheetId} not found.`);
    }
  }
  let sheetFromRange = null;
  if (rangeParts.sheetName) {
    try {
      sheetFromRange = resolveWorksheetForSearch(workbook, rangeParts.sheetName);
    } catch (error49) {
      if (!sheetFromId) {
        metadata.notices ??= [];
        metadata.notices.push(error49 instanceof Error ? error49.message : `Worksheet ${rangeParts.sheetName} not found.`);
      }
    }
  }
  if (sheetFromId && sheetFromRange && !isSameWorksheet(sheetFromId, sheetFromRange)) {
    metadata.notices ??= [];
    metadata.notices.push(`sheetId (${rawSheetId}) does not match range sheet (${rangeParts.sheetName}); using sheetId.`);
  }
  const sheets = sheetFromId ? [sheetFromId] : sheetFromRange ? [sheetFromRange] : Array.from(workbook.worksheets);
  return {
    sheets,
    rangeRef: parsedRange?.ref ?? null,
    bounds: parsedRange?.bounds ?? null
  };
};
var resolveTablePreviewOptions = (options) => {
  const maxRows = typeof options.tableMaxRows === "number" && Number.isFinite(options.tableMaxRows) ? Math.max(1, Math.floor(options.tableMaxRows)) : DEFAULT_TABLE_PREVIEW_ROWS;
  const maxCols = typeof options.tableMaxCols === "number" && Number.isFinite(options.tableMaxCols) ? Math.max(1, Math.floor(options.tableMaxCols)) : DEFAULT_TABLE_PREVIEW_COLS;
  const maxCellChars = typeof options.tableMaxCellChars === "number" && Number.isFinite(options.tableMaxCellChars) ? Math.max(1, Math.floor(options.tableMaxCellChars)) : DEFAULT_TABLE_PREVIEW_CELL_CHARS;
  return { maxRows, maxCols, maxCellChars };
};
async function inspectWorkbook(workbook, options = {}) {
  const normalizedOptions = {
    target: options.target ?? null,
    kind: options.kind ?? null,
    include: options.include ?? null,
    exclude: options.exclude ?? null,
    search: options.search ?? null,
    maxChars: options.maxChars ?? null,
    tableMaxRows: options.tableMaxRows ?? null,
    tableMaxCols: options.tableMaxCols ?? null,
    tableMaxCellChars: options.tableMaxCellChars ?? null,
    searchTerm: options.searchTerm ?? null,
    sheetId: options.sheetId ?? null,
    range: options.range ?? null,
    offset: options.offset ?? null,
    options: options.options ?? null
  };
  const hasSearchTerm = typeof normalizedOptions.searchTerm === "string" && normalizedOptions.searchTerm.trim().length > 0;
  if (normalizedOptions.kind == null && hasSearchTerm) {
    normalizedOptions.kind = "workbook,sheet,match";
  }
  const kindInfo = parseKindTokens2(normalizedOptions.kind);
  const includeInfo = parsePropertyTokens2(normalizedOptions.include, "include");
  const excludeInfo = parsePropertyTokens2(normalizedOptions.exclude, "exclude");
  const workbookId = `wb/${generateAidSuffix()}`;
  const target = normalizeTarget2(normalizedOptions.target, workbookId);
  const metadata = {
    revision: generateAidSuffix(),
    target,
    kind: {
      requested: normalizedOptions.kind ?? undefined,
      tokens: kindInfo.tokens
    },
    include: {
      requested: normalizedOptions.include ?? undefined,
      tokens: includeInfo.tokens
    },
    exclude: {
      requested: normalizedOptions.exclude ?? undefined,
      tokens: excludeInfo.tokens
    },
    search: normalizedOptions.search ?? undefined,
    notices: [
      ...kindInfo.notices,
      ...includeInfo.notices,
      ...excludeInfo.notices
    ]
  };
  const rangeFilter = resolveRangeFilter(workbook, normalizedOptions, metadata);
  const tablePreviewOptions = resolveTablePreviewOptions(normalizedOptions);
  const records = renderWorkbookRecords(workbook, kindInfo, workbookId, rangeFilter, tablePreviewOptions);
  const cellSearch = runCellSearch(workbook, normalizedOptions, metadata);
  if (cellSearch) {
    if (cellSearch.records.length === 0) {
      records.push({
        kind: "notice",
        message: "Cell search matched 0 entries."
      });
    } else {
      records.push(...cellSearch.records);
    }
    if (cellSearch.truncated) {
      records.push({
        kind: "notice",
        message: `Cell search truncated: returned ${cellSearch.limit} matches. Increase options.maxResults or narrow the range.`
      });
    }
  } else if (kindInfo.tokenSet.has("match")) {
    records.push({
      kind: "notice",
      message: "kind=match requires searchTerm."
    });
  }
  const projectedRecords = projectRecords2(records, includeInfo, excludeInfo);
  const windowedRecords = applyTargetWindow2(projectedRecords, target);
  const maxChars = typeof normalizedOptions.maxChars === "number" && Number.isFinite(normalizedOptions.maxChars) ? Math.max(0, Math.floor(normalizedOptions.maxChars)) : DEFAULT_MAX_CHARS3;
  const previewedRecords = applyTablePreviewFallbacks(windowedRecords, maxChars, tablePreviewOptions);
  const recordLines = previewedRecords.map((record2) => JSON.stringify(record2));
  const filteredLines = applySearchFilter2(recordLines, normalizedOptions.search, metadata);
  const { ndjson, truncated } = applyTruncation2(filteredLines, maxChars);
  return { ndjson, truncated, metadata };
}
var renderWorkbookRecords = (workbook, kindInfo, workbookId, rangeFilter, tablePreviewOptions) => {
  const records = [];
  const includeWorkbook = kindInfo.tokenSet.has("workbook");
  const includeSheet = kindInfo.tokenSet.has("sheet");
  const includeTable = kindInfo.tokenSet.has("table");
  const includeRegion = kindInfo.tokenSet.has("region");
  const includeFormula = kindInfo.tokenSet.has("formula");
  const includeThread = kindInfo.tokenSet.has("thread");
  const includeConditionalFormatting = kindInfo.tokenSet.has("conditionalFormatting");
  const includeStyle = kindInfo.tokenSet.has("computedStyle");
  const includeDefinedName = kindInfo.tokenSet.has("definedName");
  const includeDrawing = kindInfo.tokenSet.has("drawing");
  let tableCount = 0;
  let threadCount = 0;
  const sheets = rangeFilter.sheets.length ? rangeFilter.sheets : Array.from(workbook.worksheets);
  if (includeDefinedName) {
    const allSheets = Array.from(workbook.worksheets);
    const sheetNamesByIndex = new Map;
    for (const sheet of allSheets) {
      sheetNamesByIndex.set(sheet.index, sheet.name);
    }
    const filteredSheetIds = new Set(rangeFilter.sheets.map((sheet) => sheet.index));
    const hasSheetFilter = rangeFilter.sheets.length > 0 && rangeFilter.sheets.length < allSheets.length;
    const proto = workbook.toProto();
    const definedNames = proto.definedNames?.names ?? [];
    for (const definedName of definedNames) {
      const localSheetId = definedName.localSheetId;
      if (hasSheetFilter && typeof localSheetId === "number" && !filteredSheetIds.has(localSheetId)) {
        continue;
      }
      const scope = typeof localSheetId === "number" ? sheetNamesByIndex.get(localSheetId) ?? `localSheetId:${localSheetId}` : "workbook";
      const text3 = definedName.text?.trim();
      const formula = text3 ? text3.startsWith("=") ? text3 : `=${text3}` : "";
      records.push({
        kind: "definedName",
        name: definedName.name,
        scope,
        formula: formula || undefined
      });
    }
  }
  for (const sheet of sheets) {
    const sheetAnchor = buildSheetAnchor(sheet);
    const sheetName = sheet.name;
    const sheetIndex = sheet.index;
    const cfRenderCache = includeStyle ? workbook.getConditionalFormattingRenderCache(sheetName) : null;
    const protoSheet = includeSheet || includeTable || includeRegion || includeFormula || includeConditionalFormatting || includeStyle || includeDrawing ? sheet.toProto() : null;
    const usedRange = protoSheet ? getUsedRangeForSheet(protoSheet) : null;
    const effectiveRangeRef = rangeFilter.rangeRef ?? usedRange;
    const sheetTables = effectiveRangeRef && includeTable ? 1 : 0;
    let sheetFormulas = 0;
    let sheetThreads = 0;
    if (includeSheet) {
      records.push({
        kind: "sheet",
        id: sheetAnchor,
        name: sheetName,
        index: sheetIndex,
        range: usedRange ?? undefined,
        address: usedRange ?? undefined,
        tables: sheetTables || undefined,
        formulas: undefined,
        threads: undefined
      });
    }
    const range2 = effectiveRangeRef ? sheet.getRange(effectiveRangeRef) : null;
    if (includeTable && effectiveRangeRef && range2) {
      const valuesMatrix = range2.values.map((row2) => row2.map((value2) => serializeCellValue2(value2)));
      tableCount += 1;
      records.push({
        kind: "table",
        sheet: sheetName,
        address: effectiveRangeRef,
        rows: valuesMatrix.length || undefined,
        cols: valuesMatrix[0]?.length || undefined,
        values: valuesMatrix
      });
    }
    if (includeRegion && protoSheet) {
      const regions = buildRegionsForSheet(sheetName, protoSheet, rangeFilter, tablePreviewOptions);
      if (regions.length > 0) {
        records.push(...regions);
      }
    }
    if (includeFormula && effectiveRangeRef && range2) {
      const bounds = rangeFilter.rangeRef ? rangeFilter.bounds : parseRangeAddress(effectiveRangeRef)?.bounds;
      const formulas = range2.formulas;
      if (bounds) {
        for (let r = 0;r < formulas.length; r += 1) {
          const row2 = formulas[r] ?? [];
          for (let c = 0;c < row2.length; c += 1) {
            const formula = row2[c];
            if (!formula || !formula.trim()) {
              continue;
            }
            const address = makeCellAddress(bounds.startRow + r, bounds.startCol + c);
            sheetFormulas += 1;
            records.push({
              kind: "formula",
              sheet: sheetName,
              address,
              formula
            });
          }
        }
      }
    }
    if (includeStyle && effectiveRangeRef && range2) {
      const bounds = rangeFilter.rangeRef ? rangeFilter.bounds : parseRangeAddress(effectiveRangeRef)?.bounds;
      const values = range2.values;
      const formulas = range2.formulas;
      if (bounds) {
        for (let r = bounds.startRow;r <= bounds.endRow; r += 1) {
          for (let c = bounds.startCol;c <= bounds.endCol; c += 1) {
            const address = makeCellAddress(r, c);
            const value2 = values[r - bounds.startRow]?.[c - bounds.startCol];
            const formula = formulas[r - bounds.startRow]?.[c - bounds.startCol];
            if (value2 == null && !formula) {
              continue;
            }
            const cellRange = sheet.getRange(address);
            const base = styleSnapshot(cellRange);
            const cellProto = sheet.__getCell(r, c);
            const cfFillCss = cfRenderCache?.getFillCss(r, c, cellProto) ?? null;
            const cfTextColor = cfRenderCache?.getTextColor(r, c, cellProto) ?? null;
            const merged = { ...base };
            if (cfFillCss) {
              const fillProto = cssToSolidFillProto(cfFillCss);
              if (fillProto) {
                merged.fill = fillProto;
              }
            }
            if (cfTextColor) {
              merged.font = {
                ...merged.font ?? {},
                fill: {
                  type: 1 /* FILL_TYPE_SOLID */,
                  color: cfTextColor,
                  gradientStops: []
                }
              };
            }
            records.push({
              kind: "computedStyle",
              sheet: sheetName,
              for: address,
              style: merged
            });
          }
        }
      }
    }
    if (includeConditionalFormatting && protoSheet) {
      const conditionalFormattingRecords = buildConditionalFormattingRecordsForSheet(sheetName, protoSheet.conditionalFormattings ?? [], rangeFilter);
      if (conditionalFormattingRecords.length > 0) {
        records.push(...conditionalFormattingRecords);
      }
    }
    if (includeDrawing && protoSheet) {
      const drawings = buildDrawingRecordsForSheet(sheetName, protoSheet.drawings ?? []);
      if (drawings.length > 0) {
        records.push(...drawings);
      }
    }
    if (includeThread) {
      const matchingThreads = findThreadsForSheet(workbook.comments.threads.items, sheet);
      for (const thread of matchingThreads) {
        const threadRecord = buildThreadRecord(thread);
        if (threadRecord) {
          threadCount += 1;
          sheetThreads += 1;
          records.push(threadRecord);
        }
      }
    }
    if (includeSheet && (sheetFormulas > 0 || sheetThreads > 0)) {
      let lastSheet;
      for (let index = records.length - 1;index >= 0; index -= 1) {
        const record2 = records[index];
        if (record2 && record2.kind === "sheet" && "id" in record2 && record2.id === sheetAnchor) {
          lastSheet = record2;
          break;
        }
      }
      if (lastSheet) {
        lastSheet.formulas = sheetFormulas || undefined;
        lastSheet.threads = sheetThreads || undefined;
      }
    }
  }
  if (includeWorkbook) {
    records.unshift({
      kind: "workbook",
      id: workbookId,
      sheets: workbook.worksheets.getSheetCount(),
      tables: tableCount || undefined,
      threads: threadCount || undefined
    });
  }
  if (records.length === 0 && !kindInfo.tokenSet.has("match")) {
    records.push({
      kind: "notice",
      message: "No records matched the requested kinds."
    });
  }
  return records;
};
var parseAnchorIndex = (value2) => {
  const numeric = Number.parseInt(value2 ?? "", 10);
  return Number.isFinite(numeric) ? numeric : undefined;
};
var parseAnchorEmu = (value2) => {
  const numeric = Number.parseFloat(value2 ?? "");
  return Number.isFinite(numeric) ? Math.round(numeric) : undefined;
};
var anchorSnapshotFromProto = (anchor) => {
  if (!anchor) {
    return;
  }
  const row2 = parseAnchorIndex(anchor.rowId ?? undefined);
  const col = parseAnchorIndex(anchor.colId ?? undefined);
  if (row2 === undefined || col === undefined) {
    return;
  }
  const rowOffsetEmu = parseAnchorEmu(anchor.rowOffset ?? undefined) ?? 0;
  const colOffsetEmu = parseAnchorEmu(anchor.colOffset ?? undefined) ?? 0;
  return {
    row: row2,
    col,
    rowOffsetEmu,
    colOffsetEmu,
    rowOffsetPx: Math.round(rowOffsetEmu * PIXELS_PER_EMU),
    colOffsetPx: Math.round(colOffsetEmu * PIXELS_PER_EMU)
  };
};
var extentSnapshotFromProto = (drawing) => {
  const widthEmu = parseAnchorEmu(drawing.extentCx ?? undefined);
  const heightEmu = parseAnchorEmu(drawing.extentCy ?? undefined);
  if (widthEmu === undefined && heightEmu === undefined) {
    return;
  }
  const extent2 = {};
  if (widthEmu !== undefined) {
    extent2.widthEmu = widthEmu;
    extent2.widthPx = Math.round(widthEmu * PIXELS_PER_EMU);
  }
  if (heightEmu !== undefined) {
    extent2.heightEmu = heightEmu;
    extent2.heightPx = Math.round(heightEmu * PIXELS_PER_EMU);
  }
  return extent2;
};
var buildDrawingAnchorSnapshot = (drawing) => {
  const from2 = anchorSnapshotFromProto(drawing.fromAnchor ?? undefined);
  const to = anchorSnapshotFromProto(drawing.toAnchor ?? undefined);
  const extent2 = extentSnapshotFromProto(drawing);
  if (!from2 && !to && !extent2) {
    return;
  }
  const snapshot = {};
  if (from2) {
    snapshot.from = from2;
  }
  if (to) {
    snapshot.to = to;
  }
  if (extent2) {
    snapshot.extent = extent2;
  }
  return snapshot;
};
var buildDrawingRecordsForSheet = (sheetName, drawings) => {
  if (!drawings.length) {
    return [];
  }
  return drawings.map((drawing) => {
    const drawingType = drawing?.shape ? "shape" : drawing?.chart ? "chart" : drawing?.imageReference ? "image" : "other";
    const geometryValue = drawing?.shape?.shape?.geometry;
    const geometry = typeof geometryValue === "number" ? SHAPE_GEOMETRY_PROTO_TO_NAME[geometryValue] : undefined;
    const anchor = buildDrawingAnchorSnapshot(drawing ?? {});
    const record2 = {
      kind: "drawing",
      sheet: sheetName,
      drawingType,
      id: drawing?.shape?.id ?? drawing?.chart?.id ?? drawing?.imageReference?.id ?? undefined,
      name: drawing?.shape?.name ?? undefined,
      geometry,
      anchor
    };
    if (!anchor) {
      delete record2.anchor;
    }
    return record2;
  });
};
var MIN_REGION_AREA = 4;
var MIN_REGION_NONEMPTY = 3;
var buildRegionsForSheet = (sheetName, protoSheet, rangeFilter, previewOptions) => {
  const occupiedCells = [];
  const rowSet = new Set;
  const colSet = new Set;
  const bounds = rangeFilter.rangeRef ? rangeFilter.bounds : null;
  for (const row2 of protoSheet.rows ?? []) {
    for (const cell of row2.cells ?? []) {
      const address = cell.address;
      if (!address) {
        continue;
      }
      if (bounds && !isAddressInBounds(address, bounds)) {
        continue;
      }
      const value2 = cell.value ?? null;
      const formula = cell.formula ?? null;
      const hasValue = value2 !== "" && value2 != null;
      const hasFormula = formula != null && formula.trim().length > 0;
      if (!hasValue && !hasFormula) {
        continue;
      }
      const rowIdx = rowIndex(address);
      const colIdx = columnIndex(address);
      occupiedCells.push({ row: rowIdx, col: colIdx, value: value2, formula });
      rowSet.add(rowIdx);
      colSet.add(colIdx);
    }
  }
  if (occupiedCells.length === 0) {
    return [];
  }
  const rowBlocks = buildIndexBlocks(Array.from(rowSet));
  const colBlocks = buildIndexBlocks(Array.from(colSet));
  if (rowBlocks.length === 0 || colBlocks.length === 0) {
    return [];
  }
  const regions = [];
  for (const rowBlock of rowBlocks) {
    for (const colBlock of colBlocks) {
      const regionBounds = {
        startRow: rowBlock.start,
        endRow: rowBlock.end,
        startCol: colBlock.start,
        endCol: colBlock.end
      };
      const rows = regionBounds.endRow - regionBounds.startRow + 1;
      const cols = regionBounds.endCol - regionBounds.startCol + 1;
      const area = rows * cols;
      const regionCells = occupiedCells.filter((cell) => cell.row >= regionBounds.startRow && cell.row <= regionBounds.endRow && cell.col >= regionBounds.startCol && cell.col <= regionBounds.endCol);
      const nonEmpty = regionCells.length;
      if (area < MIN_REGION_AREA || nonEmpty < MIN_REGION_NONEMPTY) {
        continue;
      }
      let numeric = 0;
      let text3 = 0;
      let bool = 0;
      let date6 = 0;
      let maxTextLength = 0;
      for (const cell of regionCells) {
        const value2 = cell.value;
        if (typeof value2 === "number") {
          numeric += 1;
          continue;
        }
        if (typeof value2 === "boolean") {
          bool += 1;
          continue;
        }
        if (value2 instanceof Date) {
          date6 += 1;
          continue;
        }
        const textValue = typeof value2 === "string" ? value2 : cell.formula ?? null;
        if (textValue != null) {
          text3 += 1;
          maxTextLength = Math.max(maxTextLength, textValue.length);
        }
      }
      const preview = buildRegionPreview(regionBounds, regionCells, previewOptions);
      const regionRecord = {
        kind: "region",
        sheet: sheetName,
        address: buildRangeRef(regionBounds),
        rows: rows || undefined,
        cols: cols || undefined,
        nonEmpty: nonEmpty || undefined,
        blank: area - nonEmpty || undefined,
        numeric: numeric || undefined,
        text: text3 || undefined,
        bool: bool || undefined,
        date: date6 || undefined,
        maxTextLength: maxTextLength || undefined,
        preview: preview.values,
        previewAddress: preview.address,
        previewRows: preview.rows,
        previewCols: preview.cols
      };
      regions.push(regionRecord);
    }
  }
  regions.sort((a, b) => (b.nonEmpty ?? 0) - (a.nonEmpty ?? 0));
  return regions;
};
var buildIndexBlocks = (indices) => {
  if (indices.length === 0) {
    return [];
  }
  const sorted = [...indices].sort((a, b) => a - b);
  const blocks = [];
  const first = sorted[0];
  if (first == null) {
    return [];
  }
  let start = first;
  let end = first;
  for (let i = 1;i < sorted.length; i += 1) {
    const next2 = sorted[i];
    if (next2 == null) {
      continue;
    }
    if (next2 === end + 1) {
      end = next2;
      continue;
    }
    blocks.push({ start, end });
    start = next2;
    end = next2;
  }
  blocks.push({ start, end });
  return blocks;
};
var buildRegionPreview = (bounds, regionCells, previewOptions) => {
  const rows = Math.min(previewOptions.maxRows, bounds.endRow - bounds.startRow + 1);
  const cols = Math.min(previewOptions.maxCols, bounds.endCol - bounds.startCol + 1);
  const values = Array.from({ length: rows }, () => Array.from({ length: cols }, () => null));
  for (const cell of regionCells) {
    const rowOffset = cell.row - bounds.startRow;
    const colOffset = cell.col - bounds.startCol;
    if (rowOffset < 0 || rowOffset >= rows) {
      continue;
    }
    if (colOffset < 0 || colOffset >= cols) {
      continue;
    }
    const serialized = serializeCellValue2(cell.value);
    const rowValues = values[rowOffset];
    if (!rowValues) {
      continue;
    }
    rowValues[colOffset] = truncateCellValue(serialized, previewOptions.maxCellChars);
  }
  const previewBounds = {
    startRow: bounds.startRow,
    startCol: bounds.startCol,
    endRow: bounds.startRow + rows - 1,
    endCol: bounds.startCol + cols - 1
  };
  return {
    values,
    rows: rows || undefined,
    cols: cols || undefined,
    address: buildRangeRef(previewBounds)
  };
};
var buildThreadRecord = (thread) => {
  const snapshot = thread.toSnapshot();
  const target = snapshot.target?.spreadsheetCell?.address ?? formatRangeTarget(snapshot.target?.spreadsheetRange) ?? undefined;
  const sheet = snapshot.target?.spreadsheetCell?.sheetName ?? snapshot.target?.spreadsheetRange?.sheetName;
  const comments = snapshot.comments.map((comment) => ({
    id: comment.id,
    text: comment.text,
    authorId: comment.authorId,
    createdAt: comment.createdAt
  }));
  return {
    kind: "thread",
    id: `th/${snapshot.id}`,
    sheet,
    target,
    status: snapshot.status != null ? String(snapshot.status) : undefined,
    text: comments[0]?.text,
    comments
  };
};
var formatRangeTarget = (target) => {
  if (!target) {
    return null;
  }
  const start = target.startAddress ?? "";
  const end = target.endAddress ?? "";
  if (start && end && start !== end) {
    return `${start}:${end}`;
  }
  return start || end || null;
};
var buildConditionalFormattingRecordsForSheet = (sheetName, conditionalFormattings, rangeFilter) => {
  if (!conditionalFormattings.length) {
    return [];
  }
  const records = [];
  for (const group of conditionalFormattings) {
    const addresses = (group.ranges ?? []).map((target) => formatRangeTarget(target)).filter((address2) => Boolean(address2));
    if (addresses.length === 0) {
      continue;
    }
    if (rangeFilter.bounds && !addresses.some((address2) => {
      const bounds = parseRangeAddress(address2)?.bounds;
      return bounds ? doRangeBoundsIntersect(bounds, rangeFilter.bounds) : false;
    })) {
      continue;
    }
    const address = addresses.join(", ");
    for (const rule2 of group.rules ?? []) {
      records.push({
        kind: "conditionalFormatting",
        sheet: sheetName,
        address,
        type: rule2.type,
        priority: typeof rule2.priority === "number" ? rule2.priority : undefined,
        operator: rule2.operator ?? undefined,
        formula: normalizeConditionalFormattingFormula(rule2.formula),
        text: rule2.text ?? undefined,
        timePeriod: rule2.timePeriod ?? undefined,
        rank: typeof rule2.rank === "number" ? rule2.rank : undefined,
        percent: typeof rule2.percent === "boolean" ? rule2.percent : undefined,
        bottom: typeof rule2.bottom === "boolean" ? rule2.bottom : undefined,
        aboveAverage: typeof rule2.aboveAverage === "boolean" ? rule2.aboveAverage : undefined,
        equalAverage: typeof rule2.equalAverage === "boolean" ? rule2.equalAverage : undefined,
        stdDev: typeof rule2.stdDev === "number" ? rule2.stdDev : undefined,
        dxfId: typeof rule2.dxfId === "number" ? rule2.dxfId : undefined,
        stopIfTrue: typeof rule2.stopIfTrue === "boolean" ? rule2.stopIfTrue : undefined,
        colorScale: summarizeConditionalFormattingColorScale(rule2),
        dataBar: summarizeConditionalFormattingDataBar(rule2),
        iconSet: summarizeConditionalFormattingIconSet(rule2)
      });
    }
  }
  return records;
};
var normalizeConditionalFormattingFormula = (formula) => {
  if (!Array.isArray(formula)) {
    return;
  }
  const normalized = formula.map((entry) => String(entry ?? "").trim()).filter(Boolean);
  return normalized.length > 0 ? normalized : undefined;
};
var summarizeConditionalFormattingThresholds = (entries) => {
  if (!entries || entries.length === 0) {
    return;
  }
  const normalized = entries.map((entry) => ({
    type: entry.type ?? undefined,
    value: entry.val ?? undefined
  })).filter((entry) => entry.type || entry.value);
  return normalized.length > 0 ? normalized : undefined;
};
var summarizeConditionalFormattingColorValues = (entries) => {
  if (!entries || entries.length === 0) {
    return;
  }
  const values = entries.map((entry) => entry.value ?? entry.lastColor ?? "").filter(Boolean);
  return values.length > 0 ? values : undefined;
};
var summarizeConditionalFormattingColorScale = (rule2) => {
  if (!rule2.colorScale) {
    return;
  }
  const colors = summarizeConditionalFormattingColorValues(rule2.colorScale.colors);
  const thresholds = summarizeConditionalFormattingThresholds(rule2.colorScale.cfvos);
  if (!colors && !thresholds) {
    return;
  }
  return {
    colors,
    thresholds
  };
};
var summarizeConditionalFormattingDataBar = (rule2) => {
  if (!rule2.dataBar) {
    return;
  }
  const color2 = rule2.dataBar.color?.value ?? rule2.dataBar.color?.lastColor ?? undefined;
  const gradient = typeof rule2.dataBar.gradient === "boolean" ? rule2.dataBar.gradient : undefined;
  const thresholds = summarizeConditionalFormattingThresholds(rule2.dataBar.cfvos);
  if (!color2 && gradient === undefined && !thresholds) {
    return;
  }
  return {
    color: color2,
    gradient,
    thresholds
  };
};
var summarizeConditionalFormattingIconSet = (rule2) => {
  if (!rule2.iconSet) {
    return;
  }
  const thresholds = summarizeConditionalFormattingThresholds(rule2.iconSet.cfvos);
  return {
    iconSet: rule2.iconSet.iconSet ?? undefined,
    showValue: typeof rule2.iconSet.showValue === "boolean" ? rule2.iconSet.showValue : undefined,
    reverse: typeof rule2.iconSet.reverse === "boolean" ? rule2.iconSet.reverse : undefined,
    custom: typeof rule2.iconSet.custom === "boolean" ? rule2.iconSet.custom : undefined,
    percent: typeof rule2.iconSet.percent === "boolean" ? rule2.iconSet.percent : undefined,
    thresholds
  };
};
var findThreadsForSheet = (threads, sheet) => {
  const sheetId = sheet.sheetId ?? sheet.id ?? null;
  const sheetName = sheet.name;
  return threads.filter((thread) => {
    const snapshot = thread.toSnapshot();
    const target = snapshot.target;
    const targetSheetId = target?.spreadsheetCell?.sheetId ?? target?.spreadsheetRange?.sheetId;
    const targetSheetName = target?.spreadsheetCell?.sheetName ?? target?.spreadsheetRange?.sheetName;
    if (targetSheetId && sheetId && targetSheetId === sheetId) {
      return true;
    }
    if (targetSheetName && targetSheetName === sheetName) {
      return true;
    }
    return false;
  });
};
var buildSheetAnchor = (sheet) => {
  const suffix = sheet.id ?? generateAidSuffix();
  return `ws/${suffix}`;
};
var serializeCellValue2 = (value2) => {
  if (value2 instanceof Date) {
    return value2.toISOString();
  }
  return value2 ?? null;
};
var truncateCellValue = (value2, maxChars) => {
  if (typeof value2 !== "string") {
    return value2;
  }
  if (value2.length <= maxChars) {
    return value2;
  }
  if (maxChars <= 3) {
    return value2.slice(0, maxChars);
  }
  return `${value2.slice(0, maxChars - 3)}...`;
};
var DEFAULT_MAX_RESULTS = 200;
function normalizeSheetId(value2) {
  const trimmed = value2.trim();
  if (trimmed.startsWith("ws/")) {
    return trimmed.slice(3);
  }
  return trimmed;
}
function resolveWorksheetForSearch(workbook, sheetId) {
  const normalized = normalizeSheetId(sheetId);
  const byName = workbook.worksheets.getItemOrNullObject(normalized);
  if (!byName.isNullObject) {
    return byName;
  }
  for (const sheet of workbook.worksheets) {
    if (sheet.sheetId === normalized || sheet.id === normalized || sheet.name === normalized) {
      return sheet;
    }
  }
  throw new Error(`Worksheet ${sheetId} not found.`);
}
var isAddressInBounds = (address, bounds) => {
  const row2 = rowIndex(address);
  const col = columnIndex(address);
  return row2 >= bounds.startRow && row2 <= bounds.endRow && col >= bounds.startCol && col <= bounds.endCol;
};
var doRangeBoundsIntersect = (left, right) => left.startRow <= right.endRow && left.endRow >= right.startRow && left.startCol <= right.endCol && left.endCol >= right.startCol;
var normalizeSearchValue = (value2, matchCase, ignoreDiacritics) => {
  let next2 = value2;
  if (ignoreDiacritics) {
    next2 = next2.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
  }
  if (!matchCase) {
    next2 = next2.toLowerCase();
  }
  return next2;
};
var buildCellSearchMatcher = (config3) => {
  if (config3.useRegex) {
    const source = config3.matchEntireCell ? `^(?:${config3.searchTerm})$` : config3.searchTerm;
    const regex = new RegExp(source, config3.matchCase ? "" : "i");
    return (value2) => regex.test(value2);
  }
  const normalizedTerm = normalizeSearchValue(config3.searchTerm, config3.matchCase, config3.ignoreDiacritics);
  return (value2) => {
    const normalizedValue = normalizeSearchValue(value2, config3.matchCase, config3.ignoreDiacritics);
    return config3.matchEntireCell ? normalizedValue === normalizedTerm : normalizedValue.includes(normalizedTerm);
  };
};
var runCellSearch = (workbook, options, metadata) => {
  const rawTerm = typeof options.searchTerm === "string" ? options.searchTerm : "";
  const searchTerm = rawTerm.trim();
  if (!searchTerm) {
    return null;
  }
  const rawSearchOptions = options.options;
  const matchCase = rawSearchOptions?.matchCase === true;
  const matchEntireCell = rawSearchOptions?.matchEntireCell === true;
  const useRegex = rawSearchOptions?.useRegex === true;
  const matchFormulas = rawSearchOptions?.matchFormulas === true;
  const ignoreDiacritics = rawSearchOptions?.ignoreDiacritics === true;
  const limit = typeof rawSearchOptions?.maxResults === "number" && Number.isFinite(rawSearchOptions.maxResults) ? Math.max(1, Math.floor(rawSearchOptions.maxResults)) : DEFAULT_MAX_RESULTS;
  const offset = typeof options.offset === "number" && Number.isFinite(options.offset) ? Math.max(0, Math.floor(options.offset)) : 0;
  const rawRange = typeof options.range === "string" ? options.range.trim() : "";
  const rangeParts = rawRange ? splitSheetAddress(rawRange) : { ref: "" };
  const bounds = rawRange ? parseRangeAddress(rangeParts.ref)?.bounds : null;
  if (rawRange && !bounds) {
    metadata.notices ??= [];
    metadata.notices.push(`Invalid range filter: ${rawRange}`);
  }
  const rawSheetId = typeof options.sheetId === "string" ? options.sheetId.trim() : "";
  const sheetId = rawSheetId || rangeParts.sheetName;
  const sheets = sheetId ? [resolveWorksheetForSearch(workbook, sheetId)] : Array.from(workbook.worksheets);
  let matcher;
  try {
    matcher = buildCellSearchMatcher({
      searchTerm,
      matchCase,
      matchEntireCell,
      useRegex,
      ignoreDiacritics
    });
  } catch (error49) {
    const message = error49 instanceof Error ? error49.message : "Invalid regular expression";
    throw new Error(`Invalid search regex: ${message}`);
  }
  const records = [];
  let skipped = 0;
  let total = 0;
  for (const sheet of sheets) {
    const proto = sheet.toProto();
    for (const row2 of proto.rows ?? []) {
      for (const cell of row2.cells ?? []) {
        const address = cell.address;
        if (!address) {
          continue;
        }
        if (bounds && !isAddressInBounds(address, bounds)) {
          continue;
        }
        const candidates = [];
        if (cell.value != null) {
          candidates.push({
            type: "value",
            value: String(cell.value)
          });
        }
        if (matchFormulas && cell.formula) {
          candidates.push({ type: "formula", value: cell.formula });
        }
        if (!candidates.length) {
          continue;
        }
        const matched = candidates.find((candidate) => matcher(candidate.value));
        if (!matched) {
          continue;
        }
        total += 1;
        if (skipped < offset) {
          skipped += 1;
          continue;
        }
        if (records.length < limit) {
          records.push({
            kind: "match",
            sheet: sheet.name,
            address,
            value: cell.value ?? null,
            formula: cell.formula ?? null,
            match: matched.type
          });
        }
      }
    }
  }
  return {
    records,
    truncated: total > offset + records.length,
    offset,
    limit,
    total
  };
};
function searchWorkbookCells(workbook, options = {}) {
  const normalizedOptions = {
    target: null,
    kind: null,
    include: null,
    exclude: null,
    search: null,
    maxChars: null,
    tableMaxRows: null,
    tableMaxCols: null,
    tableMaxCellChars: null,
    searchTerm: options.searchTerm ?? null,
    sheetId: options.sheetId ?? null,
    range: options.range ?? null,
    offset: options.offset ?? null,
    options: options.options ? {
      matchCase: options.options.matchCase ?? null,
      matchEntireCell: options.options.matchEntireCell ?? null,
      useRegex: options.options.useRegex ?? null,
      matchFormulas: options.options.matchFormulas ?? null,
      ignoreDiacritics: options.options.ignoreDiacritics ?? null,
      maxResults: options.options.maxResults ?? null
    } : null
  };
  const metadata = {
    revision: "search/v1",
    target: {
      id: "wb/search",
      beforeLines: 0,
      afterLines: 0
    },
    notices: [],
    search: normalizedOptions.searchTerm ?? undefined
  };
  const result = runCellSearch(workbook, normalizedOptions, metadata);
  if (!result) {
    return {
      matches: [],
      truncated: false,
      offset: 0,
      limit: DEFAULT_MAX_RESULTS,
      total: 0,
      notices: metadata.notices ?? []
    };
  }
  return {
    matches: result.records,
    truncated: result.truncated,
    offset: result.offset,
    limit: result.limit,
    total: result.total,
    notices: metadata.notices ?? []
  };
}
var parseKindTokens2 = (value2) => {
  const raw = value2 ?? DEFAULT_KIND_TOKENS2.join(",");
  const tokensRaw = raw.split(/[^A-Za-z0-9-]+/).map((token) => token.trim().toLowerCase()).filter(Boolean);
  const tokens = [];
  const tokenSet = new Set;
  const unknown2 = [];
  for (const token of tokensRaw) {
    const normalized = KIND_ALIASES2[token] ?? token;
    if (!KIND_TOKEN_SET2.has(normalized)) {
      if (!unknown2.includes(token)) {
        unknown2.push(token);
      }
      continue;
    }
    const canonical = normalized;
    if (!tokenSet.has(canonical)) {
      tokenSet.add(canonical);
      tokens.push(canonical);
    }
  }
  const notices = [];
  if (unknown2.length > 0) {
    notices.push(`Unknown kind tokens: ${unknown2.join(", ")}`);
  }
  return {
    tokens,
    tokenSet,
    notices
  };
};
var parsePropertyTokens2 = (value2, label) => {
  if (!value2) {
    return { tokens: [], tokenSet: new Set, notices: [] };
  }
  const tokensRaw = value2.split(/[^A-Za-z0-9-]+/).map((token) => token.trim().toLowerCase()).filter(Boolean);
  const tokens = [];
  const tokenSet = new Set;
  const unknown2 = [];
  for (const token of tokensRaw) {
    const normalized = PROPERTY_ALIASES2[token] ?? token;
    if (!PROPERTY_TOKEN_SET2.has(normalized)) {
      if (!unknown2.includes(token)) {
        unknown2.push(token);
      }
      continue;
    }
    if (!tokenSet.has(normalized)) {
      tokenSet.add(normalized);
      tokens.push(normalized);
    }
  }
  const notices = [];
  if (unknown2.length > 0) {
    notices.push(`Unknown ${label === "include" ? "include" : "exclude"} tokens: ${unknown2.join(", ")}`);
  }
  return {
    tokens,
    tokenSet,
    notices
  };
};
var projectRecords2 = (records, includeInfo, excludeInfo) => {
  return records.map((record2) => projectRecord2(record2, includeInfo, excludeInfo));
};
var projectRecord2 = (record2, includeInfo, excludeInfo) => {
  const defaultProps = DEFAULT_KIND_PROPERTIES2[record2.kind] ?? [];
  const allowed = new Set(defaultProps);
  includeInfo.tokens.forEach((token) => allowed.add(token));
  excludeInfo.tokens.forEach((token) => allowed.delete(token));
  const projected = { kind: record2.kind };
  for (const [key, value2] of Object.entries(record2)) {
    if (key === "kind") {
      continue;
    }
    if (!allowed.has(key)) {
      continue;
    }
    if (value2 === undefined) {
      continue;
    }
    projected[key] = value2;
  }
  return projected;
};
var applySearchFilter2 = (lines, search, metadata) => {
  if (!search) {
    return lines;
  }
  let regex;
  try {
    regex = new RegExp(search, "i");
  } catch (error49) {
    const message = error49 instanceof Error ? error49.message : "Invalid regular expression";
    throw new Error(`Invalid search regex: ${message}`);
  }
  const filtered = lines.filter((line) => line.includes('"kind":"notice"') || regex.test(line));
  const matched = lines.some((line) => regex.test(line));
  if (!matched) {
    metadata.notices ??= [];
    metadata.notices.push("Search matched 0 entries");
  }
  if (filtered.length === 0) {
    return [
      JSON.stringify({
        kind: "notice",
        message: "Search matched 0 entries."
      })
    ];
  }
  return filtered;
};
var normalizeTarget2 = (target, id2) => {
  if (!target) {
    return { id: id2, beforeLines: 0, afterLines: 0 };
  }
  const normalized = {
    id: target.id,
    beforeLines: Number.isFinite(target.beforeLines) ? Math.max(0, Math.floor(target.beforeLines)) : 0,
    afterLines: Number.isFinite(target.afterLines) ? Math.max(0, Math.floor(target.afterLines)) : 0
  };
  return normalized;
};
var buildTruncationNoticeLine3 = (omittedLines) => JSON.stringify({
  kind: "notice",
  message: `Truncated: omitted ${omittedLines} lines. Increase maxChars, narrow range, or use tableMaxRows/tableMaxCols/tableMaxCellChars.`
});
var applyTruncation2 = (lines, maxChars) => {
  const baseNdjson = lines.join(`
`);
  if (maxChars <= 0 || baseNdjson.length <= maxChars) {
    return { ndjson: baseNdjson, truncated: false };
  }
  let omittedLines = lines.length;
  let noticeLine = buildTruncationNoticeLine3(omittedLines);
  let truncatedLines = [];
  for (let pass = 0;pass < 3; pass += 1) {
    truncatedLines = [];
    let length2 = 0;
    for (const line of lines) {
      const lineLength = line.length + (truncatedLines.length > 0 ? 1 : 0);
      const noticeLength = noticeLine.length + (truncatedLines.length > 0 ? 1 : 0);
      if (length2 + lineLength + noticeLength > maxChars) {
        break;
      }
      truncatedLines.push(line);
      length2 += lineLength;
    }
    const nextOmitted = lines.length - truncatedLines.length;
    if (nextOmitted === omittedLines) {
      break;
    }
    omittedLines = nextOmitted;
    noticeLine = buildTruncationNoticeLine3(omittedLines);
  }
  const ndjson = truncatedLines.length > 0 ? `${truncatedLines.join(`
`)}
${noticeLine}` : noticeLine;
  if (truncatedLines.length === 0 && lines.length === 1) {
    return { ndjson: lines[0] ?? "", truncated: true };
  }
  return { ndjson, truncated: true };
};
function applyTablePreviewFallbacks(records, maxChars, previewOptions) {
  if (maxChars <= 0) {
    return records;
  }
  return records.map((record2) => {
    if (record2.kind !== "table") {
      return record2;
    }
    const values = record2["values"];
    if (!Array.isArray(values)) {
      return record2;
    }
    const fullLine = JSON.stringify(record2);
    if (fullLine.length <= maxChars) {
      return record2;
    }
    const typedRecord = record2;
    const previewRecord = buildTablePreviewRecord(typedRecord, previewOptions);
    const previewLine = JSON.stringify(previewRecord);
    if (previewLine.length <= maxChars) {
      return previewRecord;
    }
    return shrinkTablePreviewRecord(previewRecord, typedRecord, previewOptions, maxChars);
  });
}
function buildTablePreviewRecord(record2, previewOptions) {
  const values = record2["values"];
  const previewRows = Math.min(values.length, previewOptions.maxRows);
  const previewCols = Math.min(values[0]?.length ?? 0, previewOptions.maxCols);
  const previewValues = values.slice(0, previewRows).map((row2) => row2.slice(0, previewCols).map((value2) => truncateCellValue(value2, previewOptions.maxCellChars)));
  const address = typeof record2["address"] === "string" ? record2["address"] : null;
  const bounds = address ? parseRangeAddress(address)?.bounds : null;
  const hasPreview = previewRows > 0 && previewCols > 0;
  const previewBounds = bounds && hasPreview ? {
    startRow: bounds.startRow,
    startCol: bounds.startCol,
    endRow: bounds.startRow + previewRows - 1,
    endCol: bounds.startCol + previewCols - 1
  } : null;
  return {
    ...record2,
    values: previewValues,
    valuesTruncated: true,
    valuesPreviewRows: previewRows || undefined,
    valuesPreviewCols: previewCols || undefined,
    valuesPreviewAddress: previewBounds ? buildRangeRef(previewBounds) : undefined
  };
}
function shrinkTablePreviewRecord(previewRecord, originalRecord, previewOptions, maxChars) {
  let rows = typeof previewRecord["valuesPreviewRows"] === "number" ? previewRecord["valuesPreviewRows"] : 1;
  let cols = typeof previewRecord["valuesPreviewCols"] === "number" ? previewRecord["valuesPreviewCols"] : 1;
  let maxCellChars = previewOptions.maxCellChars;
  let current = previewRecord;
  for (let pass = 0;pass < 6; pass += 1) {
    const line = JSON.stringify(current);
    if (line.length <= maxChars) {
      return current;
    }
    if (rows > 1 || cols > 1) {
      if (rows >= cols && rows > 1) {
        rows -= 1;
      } else if (cols > 1) {
        cols -= 1;
      }
    } else if (maxCellChars > 10) {
      maxCellChars = Math.max(10, Math.floor(maxCellChars * 0.7));
    } else {
      break;
    }
    current = buildTablePreviewRecord(originalRecord, {
      maxRows: rows,
      maxCols: cols,
      maxCellChars
    });
  }
  const currentValues = current["values"];
  const compactPreviewValues = Array.isArray(currentValues) ? currentValues : originalRecord["values"];
  const sheet = originalRecord["sheet"];
  const address = originalRecord["address"];
  const compactRecord = {
    kind: "table",
    sheet,
    address,
    values: compactPreviewValues,
    valuesTruncated: true
  };
  if (JSON.stringify(compactRecord).length <= maxChars) {
    return compactRecord;
  }
  const compactValues = originalRecord["values"].slice(0, 1).map((row2) => row2.slice(0, 1).map((value2) => truncateCellValue(value2, previewOptions.maxCellChars)));
  const smallestRecord = {
    kind: "table",
    sheet,
    address,
    values: compactValues,
    valuesTruncated: true
  };
  return smallestRecord;
}
var applyTargetWindow2 = (records, target) => {
  const beforeLines = target.beforeLines;
  const afterLines = target.afterLines;
  if (beforeLines <= 0 && afterLines <= 0) {
    return records;
  }
  const recordLines = records.map((record2) => JSON.stringify(record2));
  const index = recordLines.findIndex((line) => line.includes(target.id));
  if (index === -1) {
    return records;
  }
  const start = Math.max(0, index - beforeLines);
  const end = Math.min(records.length, index + afterLines + 1);
  const windowRecords = records.slice(start, end);
  const keepRecords = records.filter((record2) => record2.kind === "workbook");
  const combined = [];
  const seen = new Set;
  for (const record2 of keepRecords) {
    const line = JSON.stringify(record2);
    if (!seen.has(line)) {
      seen.add(line);
      combined.push(record2);
    }
  }
  for (const record2 of windowRecords) {
    const line = JSON.stringify(record2);
    if (!seen.has(line)) {
      seen.add(line);
      combined.push(record2);
    }
  }
  return combined;
};

// node_modules/@oai/granola/dist/models/workbook/anchors.js
var splitAnchorId = (id2) => {
  const slashIndex = id2.indexOf("/");
  if (slashIndex <= 0 || slashIndex === id2.length - 1) {
    return { prefix: "", suffix: "" };
  }
  return {
    prefix: id2.slice(0, slashIndex),
    suffix: id2.slice(slashIndex + 1)
  };
};

// node_modules/@oai/granola/dist/models/workbook/comments.js
var THREAD_NOTE_HEADER = `[Threaded comment]

` + `Your version of Excel allows you to read this threaded comment; however, any edits to it will get removed if the file is opened in a newer version of Excel. Learn more: https://go.microsoft.com/fwlink/?linkid=870924

`;
var normalizeThreadTargets = (threads) => {
  return threads.map((thread) => {
    const normalizedTarget = normalizeThreadTarget(thread.target);
    return {
      id: thread.id,
      target: normalizedTarget,
      comments: (thread.comments ?? []).map((comment) => ({
        id: comment.id,
        parentId: comment.parentId,
        authorId: comment.authorId,
        createdAt: comment.createdAt,
        editedAt: comment.editedAt,
        body: comment.body ? { plainText: comment.body.plainText } : undefined,
        isDeleted: comment.isDeleted,
        reactions: (comment.reactions ?? []).map((reaction) => ({
          type: reaction.type,
          instances: (reaction.instances ?? []).map((instance) => ({
            authorId: instance.authorId,
            time: instance.time
          }))
        })),
        citations: comment.citations ? [...comment.citations] : [],
        position: comment.position ? { xEmu: comment.position.xEmu, yEmu: comment.position.yEmu } : undefined
      })),
      status: thread.status,
      resolvedBy: thread.resolvedBy,
      resolvedAt: thread.resolvedAt
    };
  });
};
var buildThreadedNotes = (options) => {
  const { threads, existingNotes, people } = options;
  const notes = existingNotes.map((note) => ({
    id: note.id,
    target: note.target ? cloneNoteTarget(note.target) : undefined,
    authorId: note.authorId,
    createdAt: note.createdAt,
    body: note.body ? { plainText: note.body.plainText } : undefined
  }));
  const peopleIndex = new Set(people.map((person) => person.id));
  const authorIndexBySheet = seedAuthorIndexBySheet(people);
  const noteIndex = new Set(notes.map((note) => note.id));
  for (const thread of threads) {
    const cellTarget = thread.target?.spreadsheetCell;
    if (!cellTarget) {
      continue;
    }
    const sheetName = cellTarget.sheetName;
    const address = cellTarget.address;
    if (!sheetName || !address) {
      continue;
    }
    const noteId = `${sheetName}:${address}`;
    if (noteIndex.has(noteId)) {
      continue;
    }
    const authorIndex = authorIndexBySheet.get(sheetName) ?? 0;
    const authorId = `authors/${sheetName}/${authorIndex}`;
    authorIndexBySheet.set(sheetName, authorIndex + 1);
    if (!peopleIndex.has(authorId)) {
      people.push({
        id: authorId,
        displayName: `tc=${thread.id}`
      });
      peopleIndex.add(authorId);
    }
    notes.push({
      id: noteId,
      target: { cell: toNoteCellTarget(cellTarget) },
      authorId,
      createdAt: "",
      body: { plainText: buildThreadedNoteText(thread.comments ?? []) }
    });
    noteIndex.add(noteId);
  }
  return { notes, people };
};
var normalizeThreadTarget = (target) => {
  if (!target) {
    return;
  }
  if (target.spreadsheetRange) {
    const range2 = target.spreadsheetRange;
    const address = range2.startAddress ?? range2.endAddress ?? "";
    return {
      spreadsheetCell: {
        sheetName: range2.sheetName,
        sheetId: range2.sheetId,
        address
      }
    };
  }
  if (target.spreadsheetCell) {
    return {
      spreadsheetCell: {
        sheetName: target.spreadsheetCell.sheetName,
        sheetId: target.spreadsheetCell.sheetId,
        address: target.spreadsheetCell.address
      }
    };
  }
  if (target.slide) {
    return { slide: { slideId: target.slide.slideId } };
  }
  if (target.element) {
    return {
      element: {
        slideId: target.element.slideId,
        elementId: target.element.elementId
      }
    };
  }
  if (target.textRange) {
    return {
      textRange: {
        slideId: target.textRange.slideId,
        elementId: target.textRange.elementId,
        startCp: target.textRange.startCp,
        length: target.textRange.length,
        context: target.textRange.context ? {
          contextLength: target.textRange.context.contextLength,
          contextHash: target.textRange.context.contextHash
        } : undefined
      }
    };
  }
  return {};
};
var buildThreadedNoteText = (comments) => {
  const root = comments[0]?.body?.plainText ?? "";
  const replies = comments.slice(1).map((comment) => comment.body?.plainText ?? "").filter((text4) => text4.length > 0);
  let text3 = THREAD_NOTE_HEADER;
  text3 += `Comment:
    ${root}`;
  if (replies.length > 0) {
    text3 += `
Reply:
`;
    text3 += replies.map((reply) => `    ${reply}`).join(`
`);
  }
  return text3;
};
var toNoteCellTarget = (target) => {
  return {
    sheetName: target.sheetName,
    sheetId: target.sheetId,
    address: target.address
  };
};
var cloneNoteTarget = (target) => {
  if (target.cell) {
    return { cell: toNoteCellTarget(target.cell) };
  }
  if (target.range) {
    const range2 = target.range;
    return {
      range: {
        sheetName: range2.sheetName,
        sheetId: range2.sheetId,
        startAddress: range2.startAddress,
        endAddress: range2.endAddress
      }
    };
  }
  return {};
};
var seedAuthorIndexBySheet = (people) => {
  const indexBySheet = new Map;
  for (const person of people) {
    const id2 = person.id ?? "";
    if (!id2.startsWith("authors/")) {
      continue;
    }
    const parts = id2.split("/");
    const sheetName = parts[1];
    const indexPart = parts[2];
    if (!sheetName || indexPart === undefined) {
      continue;
    }
    const index = Number(indexPart);
    if (!Number.isFinite(index)) {
      continue;
    }
    const nextIndex = Math.max(indexBySheet.get(sheetName) ?? 0, index + 1);
    indexBySheet.set(sheetName, nextIndex);
  }
  return indexBySheet;
};

// node_modules/@oai/granola/dist/models/workbook/cell-keys.js
var COLUMN_DEPENDENCY_PREFIX = "#COL";
var ROW_DEPENDENCY_PREFIX = "#ROW";
var makeCellKey = (sheetName, address) => {
  return `${sheetName}!${address}`;
};
var makeColumnDependencyKey = (sheetName, col) => {
  return `${sheetName}!${COLUMN_DEPENDENCY_PREFIX}${col}`;
};
var makeRowDependencyKey = (sheetName, row2) => {
  return `${sheetName}!${ROW_DEPENDENCY_PREFIX}${row2}`;
};
var splitCellKey = (key) => {
  const bang = key.indexOf("!");
  if (bang === -1) {
    return { sheetName: "", address: key };
  }
  return {
    sheetName: key.slice(0, bang),
    address: key.slice(bang + 1)
  };
};
var isStructuralDependencyKey = (key) => {
  const { address } = splitCellKey(key);
  return address.startsWith(COLUMN_DEPENDENCY_PREFIX) || address.startsWith(ROW_DEPENDENCY_PREFIX);
};
var filterDependencyKeys = (keys2) => {
  const filtered = [];
  for (const candidate of keys2) {
    if (!isStructuralDependencyKey(candidate)) {
      filtered.push(candidate);
    }
  }
  return filtered;
};

// node_modules/@oai/granola/dist/models/spreadsheet/engine/formula-ids.js
var FORMULA_IDS = {
  COUNT: 1,
  IF: 2,
  ISNA: 3,
  ISERROR: 4,
  SUM: 5,
  AVERAGE: 6,
  MIN: 7,
  MAX: 8,
  ROW: 9,
  COLUMN: 10,
  NA: 11,
  NPV: 12,
  STDEV: 13,
  DOLLAR: 14,
  FIXED: 15,
  SIN: 16,
  COS: 17,
  TAN: 18,
  ATAN: 19,
  PI: 20,
  SQRT: 21,
  EXP: 22,
  LN: 23,
  LOG10: 24,
  ABS: 25,
  INT: 26,
  SIGN: 27,
  ROUND: 28,
  LOOKUP: 29,
  INDEX: 30,
  REPT: 31,
  MID: 32,
  LEN: 33,
  VALUE: 34,
  TRUE: 35,
  FALSE: 36,
  AND: 37,
  OR: 38,
  NOT: 39,
  MOD: 40,
  DCOUNT: 41,
  DSUM: 42,
  DAVERAGE: 43,
  DMIN: 44,
  DMAX: 45,
  DSTDEV: 46,
  VAR: 47,
  DVAR: 48,
  TEXT: 49,
  LINEST: 50,
  TREND: 51,
  LOGEST: 52,
  GROWTH: 53,
  PV: 54,
  FV: 55,
  NPER: 56,
  PMT: 57,
  RATE: 58,
  MIRR: 59,
  IRR: 60,
  RAND: 61,
  MATCH: 62,
  DATE: 63,
  TIME: 64,
  DAY: 65,
  MONTH: 66,
  YEAR: 67,
  WEEKDAY: 68,
  HOUR: 69,
  MINUTE: 70,
  SECOND: 71,
  NOW: 72,
  AREAS: 73,
  ROWS: 74,
  COLUMNS: 75,
  OFFSET: 76,
  SEARCH: 77,
  TRANSPOSE: 78,
  TYPE: 79,
  ATAN2: 80,
  ASIN: 81,
  ACOS: 82,
  CHOOSE: 83,
  HLOOKUP: 84,
  VLOOKUP: 85,
  ISREF: 86,
  LOG: 87,
  CHAR: 88,
  LOWER: 89,
  UPPER: 90,
  PROPER: 91,
  LEFT: 92,
  RIGHT: 93,
  EXACT: 94,
  TRIM: 95,
  REPLACE: 96,
  SUBSTITUTE: 97,
  CODE: 98,
  FIND: 99,
  ISERR: 100,
  ISTEXT: 101,
  ISNUMBER: 102,
  ISBLANK: 103,
  T: 104,
  N: 105,
  DATEVALUE: 106,
  TIMEVALUE: 107,
  SLN: 108,
  SYD: 109,
  DDB: 110,
  INDIRECT: 111,
  CLEAN: 112,
  MDETERM: 113,
  MINVERSE: 114,
  MMULT: 115,
  IPMT: 116,
  PPMT: 117,
  COUNTA: 118,
  PRODUCT: 119,
  FACT: 120,
  DPRODUCT: 121,
  ISNONTEXT: 122,
  STDEVP: 123,
  VARP: 124,
  DSTDEVP: 125,
  DVARP: 126,
  TRUNC: 127,
  ISLOGICAL: 128,
  DCOUNTA: 129,
  ROUNDUP: 130,
  ROUNDDOWN: 131,
  RANK: 132,
  ADDRESS: 133,
  DAYS360: 134,
  TODAY: 135,
  VDB: 136,
  MEDIAN: 137,
  SUMPRODUCT: 138,
  SINH: 139,
  COSH: 140,
  TANH: 141,
  ASINH: 142,
  ACOSH: 143,
  ATANH: 144,
  DGET: 145,
  DB: 146,
  FREQUENCY: 147,
  "ERROR.TYPE": 148,
  AVEDEV: 149,
  BETADIST: 150,
  GAMMALN: 151,
  BETAINV: 152,
  BINOMDIST: 153,
  CHIDIST: 154,
  CHIINV: 155,
  COMBIN: 156,
  CONFIDENCE: 157,
  CRITBINOM: 158,
  EVEN: 159,
  EXPONDIST: 160,
  FDIST: 161,
  FINV: 162,
  FISHER: 163,
  FISHERINV: 164,
  FLOOR: 165,
  GAMMADIST: 166,
  GAMMAINV: 167,
  CEILING: 168,
  HYPGEOMDIST: 169,
  LOGNORMDIST: 170,
  LOGINV: 171,
  NEGBINOMDIST: 172,
  NORMDIST: 173,
  NORMSDIST: 174,
  NORMINV: 175,
  NORMSINV: 176,
  STANDARDIZE: 177,
  ODD: 178,
  PERMUT: 179,
  POISSON: 180,
  TDIST: 181,
  WEIBULL: 182,
  SUMXMY2: 183,
  SUMX2MY2: 184,
  SUMX2PY2: 185,
  CHITEST: 186,
  CORREL: 187,
  COVAR: 188,
  FORECAST: 189,
  FTEST: 190,
  INTERCEPT: 191,
  PEARSON: 192,
  RSQ: 193,
  STEYX: 194,
  SLOPE: 195,
  TTEST: 196,
  PROB: 197,
  DEVSQ: 198,
  GEOMEAN: 199,
  HARMEAN: 200,
  SUMSQ: 201,
  KURT: 202,
  SKEW: 203,
  ZTEST: 204,
  LARGE: 205,
  SMALL: 206,
  QUARTILE: 207,
  PERCENTILE: 208,
  PERCENTRANK: 209,
  MODE: 210,
  TRIMMEAN: 211,
  TINV: 212,
  CONCATENATE: 213,
  POWER: 214,
  RADIANS: 215,
  DEGREES: 216,
  SUBTOTAL: 217,
  SUMIF: 218,
  COUNTIF: 219,
  COUNTBLANK: 220,
  ISPMT: 221,
  ROMAN: 222,
  GETPIVOTDATA: 223,
  HYPERLINK: 224,
  AVERAGEA: 225,
  MAXA: 226,
  MINA: 227,
  STDEVPA: 228,
  VARPA: 229,
  STDEVA: 230,
  VARA: 231,
  BAHTTEXT: 232,
  CUBEVALUE: 233,
  CUBEMEMBER: 234,
  CUBEMEMBERPROPERTY: 235,
  CUBERANKEDMEMBER: 236,
  HEX2BIN: 237,
  HEX2DEC: 238,
  HEX2OCT: 239,
  DEC2BIN: 240,
  DEC2HEX: 241,
  DEC2OCT: 242,
  OCT2BIN: 243,
  OCT2HEX: 244,
  OCT2DEC: 245,
  BIN2DEC: 246,
  BIN2OCT: 247,
  BIN2HEX: 248,
  IMSUB: 249,
  IMDIV: 250,
  IMPOWER: 251,
  IMABS: 252,
  IMSQRT: 253,
  IMLN: 254,
  IMLOG2: 255,
  IMLOG10: 256,
  IMSIN: 257,
  IMCOS: 258,
  IMEXP: 259,
  IMARGUMENT: 260,
  IMCONJUGATE: 261,
  IMAGINARY: 262,
  IMREAL: 263,
  COMPLEX: 264,
  IMSUM: 265,
  IMPRODUCT: 266,
  SERIESSUM: 267,
  FACTDOUBLE: 268,
  SQRTPI: 269,
  QUOTIENT: 270,
  DELTA: 271,
  GESTEP: 272,
  ISEVEN: 273,
  ISODD: 274,
  MROUND: 275,
  ERF: 276,
  ERFC: 277,
  BESSELJ: 278,
  BESSELK: 279,
  BESSELY: 280,
  BESSELI: 281,
  XIRR: 282,
  XNPV: 283,
  PRICEMAT: 284,
  YIELDMAT: 285,
  INTRATE: 286,
  RECEIVED: 287,
  DISC: 288,
  PRICEDISC: 289,
  YIELDDISC: 290,
  TBILLEQ: 291,
  TBILLPRICE: 292,
  TBILLYIELD: 293,
  PRICE: 294,
  YIELD: 295,
  DOLLARDE: 296,
  DOLLARFR: 297,
  NOMINAL: 298,
  EFFECT: 299,
  CUMPRINC: 300,
  CUMIPMT: 301,
  EDATE: 302,
  EOMONTH: 303,
  YEARFRAC: 304,
  COUPDAYBS: 305,
  COUPDAYS: 306,
  COUPDAYSNC: 307,
  COUPNCD: 308,
  COUPNUM: 309,
  COUPPCD: 310,
  DURATION: 311,
  MDURATION: 312,
  ODDLPRICE: 313,
  ODDLYIELD: 314,
  ODDFPRICE: 315,
  ODDFYIELD: 316,
  RANDBETWEEN: 317,
  WEEKNUM: 318,
  AMORLINC: 319,
  CONVERT: 320,
  ACCRINT: 321,
  ACCRINTM: 322,
  WORKDAY: 323,
  NETWORKDAYS: 324,
  GCD: 325,
  MULTINOMIAL: 326,
  LCM: 327,
  FVSCHEDULE: 328,
  CUBEKPIMEMBER: 329,
  CUBESET: 330,
  CUBESETCOUNT: 331,
  IFERROR: 332,
  COUNTIFS: 333,
  SUMIFS: 334,
  AVERAGEIF: 335,
  AVERAGEIFS: 336,
  AGGREGATE: 337,
  "BINOM.DIST": 338,
  "BINOM.INV": 339,
  "CONFIDENCE.NORM": 340,
  "CONFIDENCE.T": 341,
  "CHISQ.TEST": 342,
  "F.TEST": 343,
  "COVARIANCE.P": 344,
  "COVARIANCE.S": 345,
  "EXPON.DIST": 346,
  "GAMMA.DIST": 347,
  "GAMMA.INV": 348,
  "MODE.MULT": 349,
  "MODE.SNGL": 350,
  "NORM.DIST": 351,
  "NORM.INV": 352,
  "PERCENTILE.EXC": 353,
  "PERCENTILE.INC": 354,
  "PERCENTRANK.EXC": 355,
  "PERCENTRANK.INC": 356,
  "POISSON.DIST": 357,
  "QUARTILE.EXC": 358,
  "QUARTILE.INC": 359,
  "RANK.AVG": 360,
  "RANK.EQ": 361,
  "STDEV.S": 362,
  "STDEV.P": 363,
  "T.DIST": 364,
  "T.DIST.2T": 365,
  "T.DIST.RT": 366,
  "T.INV": 367,
  "T.INV.2T": 368,
  "VAR.S": 369,
  "VAR.P": 370,
  "WEIBULL.DIST": 371,
  "NETWORKDAYS.INTL": 372,
  "WORKDAY.INTL": 373,
  "BETA.DIST": 374,
  "BETA.INV": 375,
  "CHISQ.DIST": 376,
  "CHISQ.DIST.RT": 377,
  "CHISQ.INV": 378,
  "CHISQ.INV.RT": 379,
  "F.DIST": 380,
  "F.DIST.RT": 381,
  "F.INV": 382,
  "F.INV.RT": 383,
  "HYPGEOM.DIST": 384,
  "LOGNORM.DIST": 385,
  "LOGNORM.INV": 386,
  "NEGBINOM.DIST": 387,
  "NORM.S.DIST": 388,
  "NORM.S.INV": 389,
  "T.TEST": 390,
  "Z.TEST": 391,
  "ERF.PRECISE": 392,
  "ERFC.PRECISE": 393,
  "GAMMALN.PRECISE": 394,
  ACOT: 395,
  ACOTH: 396,
  COT: 397,
  COTH: 398,
  CSC: 399,
  CSCH: 400,
  SEC: 401,
  SECH: 402,
  IMTAN: 403,
  IMCOT: 404,
  IMCSC: 405,
  IMCSCH: 406,
  IMSEC: 407,
  IMSECH: 408,
  BITAND: 409,
  BITOR: 410,
  BITXOR: 411,
  BITLSHIFT: 412,
  BITRSHIFT: 413,
  PERMUTATIONA: 414,
  COMBINA: 415,
  XOR: 416,
  PDURATION: 417,
  BASE: 418,
  DECIMAL: 419,
  DAYS: 420,
  "BINOM.DIST.RANGE": 421,
  GAMMA: 422,
  "SKEW.P": 423,
  GAUSS: 424,
  PHI: 425,
  RRI: 426,
  UNICHAR: 427,
  UNICODE: 428,
  MUNIT: 429,
  ARABIC: 430,
  ISOWEEKNUM: 431,
  NUMBERVALUE: 432,
  SHEET: 433,
  SHEETS: 434,
  FORMULATEXT: 435,
  ISFORMULA: 436,
  IFNA: 437,
  "CEILING.MATH": 438,
  "FLOOR.MATH": 439,
  IMSINH: 440,
  IMCOSH: 441,
  "FORECAST.LINEAR": 442,
  MAXIFS: 443,
  MINIFS: 444,
  TEXTJOIN: 445,
  CONCAT: 446,
  IFS: 447,
  SWITCH: 448,
  FIELDVALUE: 449,
  FILTER: 450,
  SORT: 451,
  UNIQUE: 452,
  TEXTBEFORE: 453,
  TEXTAFTER: 454,
  TEXTSPLIT: 455,
  XMATCH: 456,
  XLOOKUP: 457,
  SORTBY: 458,
  RANDARRAY: 459,
  SEQUENCE: 460,
  STOCKHISTORY: 461,
  WRAPROWS: 462,
  VSTACK: 463,
  HSTACK: 464,
  CHOOSEROWS: 465,
  CHOOSECOLS: 466,
  LET: 467,
  LAMBDA: 468,
  MAKEARRAY: 469,
  PERCENTOF: 470,
  VALUETOTEXT: 471,
  ARRAYTOTEXT: 472,
  TOCOL: 473,
  TOROW: 474,
  WRAPCOLS: 475,
  MAP: 476,
  REDUCE: 477,
  SCAN: 478,
  BYROW: 479,
  BYCOL: 480,
  ISOMITTED: 481,
  EXPAND: 482,
  TAKE: 483,
  DROP: 484,
  PY: 485,
  IMAGE: 486,
  GROUPBY: 487,
  PIVOTBY: 488,
  TRANSLATE: 489,
  DETECTLANGUAGE: 490,
  REGEXTEST: 491,
  REGEXREPLACE: 492,
  REGEXEXTRACT: 493,
  TRIMRANGE: 494
};

// node_modules/@oai/granola/dist/models/workbook/formulas.js
var VOLATILE_FUNCTIONS = new Set([
  "NOW",
  "TODAY",
  "RAND",
  "RANDBETWEEN",
  "OFFSET",
  "INDIRECT",
  "CELL",
  "INFO",
  "AREAS"
]);
var COMPATIBILITY_PREFIX_REGEXES = [
  /_xlfn\._xlws\./gi,
  /_xlfn\./gi,
  /_xlws\./gi,
  /_xlpm\./gi
];
var USER_DEFINED_FUNCTION_PREFIX_REGEX = /_xludf\./i;
function makeScalarError(code) {
  return { kind: "Error", code };
}
function exprContainsVolatile(expr) {
  if (!expr) {
    return false;
  }
  switch (expr.kind) {
    case "FunctionCall":
      if (VOLATILE_FUNCTIONS.has(expr.name.toUpperCase())) {
        return true;
      }
      return expr.args.some((arg) => exprContainsVolatile(arg));
    case "UnaryOp":
      return exprContainsVolatile(expr.expr);
    case "BinaryOp":
      return exprContainsVolatile(expr.left) || exprContainsVolatile(expr.right);
    case "ArrayLiteral":
      for (const row2 of expr.elements) {
        for (const item of row2) {
          if (exprContainsVolatile(item)) {
            return true;
          }
        }
      }
      return false;
    default:
      return false;
  }
}
function getTopLevelFunctionKind(expr) {
  if (!expr || expr.kind !== "FunctionCall") {
    return null;
  }
  const normalized = expr.name.toUpperCase();
  if (normalized === "SUBTOTAL" || normalized === "_XLFN.SUBTOTAL") {
    return "SUBTOTAL";
  }
  if (normalized === "AGGREGATE" || normalized === "_XLFN.AGGREGATE") {
    return "AGGREGATE";
  }
  return null;
}
function stripCompatibilityPrefixes(formula) {
  if (!formula) {
    return "";
  }
  let result = formula;
  for (const pattern of COMPATIBILITY_PREFIX_REGEXES) {
    result = result.replace(pattern, "");
  }
  return result;
}
function formulaUsesUserDefinedFunction(formula) {
  return USER_DEFINED_FUNCTION_PREFIX_REGEX.test(formula);
}
function buildFormulaUsageStats(state) {
  const counts = new Map;
  for (const parsed of state.parsed.values()) {
    collectFormulaUsage(parsed.expr, counts);
  }
  const stats = {};
  for (const [id2, total] of counts) {
    stats[id2] = total;
  }
  return stats;
}
function collectFormulaUsage(expr, counts) {
  if (!expr) {
    return;
  }
  switch (expr.kind) {
    case "FunctionCall":
      recordFormulaUsage(expr.name, counts);
      for (const arg of expr.args) {
        collectFormulaUsage(arg, counts);
      }
      break;
    case "CallExpr":
      collectFormulaUsage(expr.callee, counts);
      for (const arg of expr.args) {
        collectFormulaUsage(arg, counts);
      }
      break;
    case "UnaryOp":
      collectFormulaUsage(expr.expr, counts);
      break;
    case "BinaryOp":
      collectFormulaUsage(expr.left, counts);
      collectFormulaUsage(expr.right, counts);
      break;
    case "ArrayLiteral":
      for (const row2 of expr.elements) {
        for (const item of row2) {
          collectFormulaUsage(item, counts);
        }
      }
      break;
    default:
      break;
  }
}
function recordFormulaUsage(name2, counts) {
  const canonical = stripCompatibilityPrefixes(name2).trim().toUpperCase();
  if (!canonical) {
    return;
  }
  const id2 = FORMULA_IDS[canonical];
  if (id2 === undefined) {
    return;
  }
  counts.set(id2, (counts.get(id2) ?? 0) + 1);
}

// node_modules/@oai/granola/dist/models/workbook/loading.js
var markdownUtilsPromise = null;
var loadMarkdownUtils = () => {
  markdownUtilsPromise ??= Promise.resolve().then(() => (init_workbook_from_markdown(), exports_workbook_from_markdown));
  return markdownUtilsPromise;
};
var csvUtilsPromise = null;
var loadCsvUtils = () => {
  csvUtilsPromise ??= Promise.resolve().then(() => (init_workbook_from_csv(), exports_workbook_from_csv));
  return csvUtilsPromise;
};

// node_modules/@oai/granola/dist/models/workbook/normalization.js
function normalizeWorkbook(workbook) {
  const rawWorkbook = workbook;
  workbook.sheets ??= [];
  workbook.contentReferences ??= [];
  workbook.images ??= [];
  workbook.people ??= [];
  workbook.threads ??= [];
  workbook.notes ??= [];
  workbook.slicerCaches ??= [];
  workbook.pivotCaches ??= [];
  workbook.timelineCaches ??= [];
  return {
    sheets: workbook.sheets,
    theme: workbook.theme,
    contentReferences: workbook.contentReferences,
    images: workbook.images,
    people: workbook.people,
    threads: workbook.threads,
    notes: workbook.notes,
    slicerCaches: workbook.slicerCaches,
    pivotCaches: workbook.pivotCaches,
    timelineCaches: workbook.timelineCaches,
    metadata: rawWorkbook.metadata,
    featurePropertyBags: rawWorkbook.featurePropertyBags
  };
}

// node_modules/@oai/granola/dist/models/workbook.js
var CHECKBOX_FEATURE_BAG_TYPE = 1 /* FEATURE_PROPERTY_BAG_TYPE_CHECKBOX */;
var XF_CONTROLS_FEATURE_BAG_TYPE = 2 /* FEATURE_PROPERTY_BAG_TYPE_XF_CONTROLS */;
var XF_COMPLEMENT_FEATURE_BAG_TYPE = 3 /* FEATURE_PROPERTY_BAG_TYPE_XF_COMPLEMENT */;
var XF_COMPLEMENTS_FEATURE_BAG_TYPE = 4 /* FEATURE_PROPERTY_BAG_TYPE_XF_COMPLEMENTS */;
var FEATURE_PROPERTY_BAG_EXT_REF = "XFComplementsMapperExtRef";
var FEATURE_PROPERTY_BAG_KEY_CELL_CONTROL = "CellControl";
var FEATURE_PROPERTY_BAG_KEY_XF_CONTROLS = "XFControls";
var FEATURE_PROPERTY_BAG_KEY_MAPPED_FEATURE_BAGS = "MappedFeaturePropertyBags";
var EXCEL_EPOCH_MS7 = Date.UTC(1899, 11, 30);
var MS_PER_DAY7 = 24 * 60 * 60 * 1000;
var MS_PER_MINUTE = 60 * 1000;
var CANONICAL_DATE_SYMBOL = Symbol("excelCanonicalDate");
var DATE_FORMULA_HINTS = [
  "DATE",
  "EDATE",
  "EOMONTH",
  "TODAY",
  "NOW",
  "TIME",
  "DATEVALUE",
  "TIMEVALUE",
  "WORKDAY",
  "WORKDAY.INTL",
  "NETWORKDAYS",
  "NETWORKDAYS.INTL"
];
var ISO_DATE_PATTERN3 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
var TRACE_FAILURE_CODE = "#TRACE!";
var CIRCULAR_TRACE_CODE = "#CIRC!";

class Workbook2 {
  #styles;
  #styleStore;
  #theme;
  #featurePropertyBags;
  #metadata;
  #contentReferences;
  #images;
  comments;
  awareness;
  #slicerCaches;
  #pivotCaches;
  #timelineCaches;
  #pivotTables;
  #slicers;
  #worksheets;
  #notes;
  #pivotTableContext;
  #slicerContext;
  #worksheetContext;
  #calcState;
  #cellRefContexts;
  #evaluatingCells;
  #definedNames;
  #names;
  #namesBySheet;
  #conditionalFormattingRenderCaches;
  #rangeReferenceAnalysis;
  #structuredReferenceRuntime;
  #sheetNamesByLocalId;
  #spillManager;
  #dataTableCells;
  #yDoc;
  #collabState;
  #worksheetTopologyStore;
  #isApplyingWorksheetTopology = false;
  #isPublishingWorksheetTopology = false;
  #undoManager;
  #recordOrigin;
  #localOrigin;
  #recorder;
  #cellInputOrigin;
  #cellInputTransactionDepth = 0;
  #cellInputWriteDepth = 0;
  #cellInputWriteNeedsRecalc = false;
  #googleSheets;
  #workbookCollabDirty = false;
  #worksheetTopologyDirty = false;
  #dirtyWorksheetSheetIds = new Set;
  #collabPublishQueued = false;
  #isApplyingCrdtUpdate = false;
  #collaborativeStateReady = false;
  constructor(workbook) {
    const normalized = normalizeWorkbook(workbook);
    this.#styles = new StyleRegistry(workbook.styles);
    this.#theme = new Theme3(normalized.theme);
    this.#featurePropertyBags = normalized.featurePropertyBags;
    this.#metadata = normalized.metadata;
    this.#contentReferences = normalized.contentReferences;
    this.#images = normalized.images;
    this.comments = new Comments({
      people: normalized.people,
      threads: normalized.threads,
      recordOp: (op) => {
        this.queueWorkbookCollabPublish();
        if (op.op === "comments.self.set" || op.op === "thread.add" || op.op === "thread.reply" || op.op === "thread.resolve" || op.op === "thread.reopen" || op.op === "thread.remove") {
          this.#recorder?.record(op);
        }
      }
    });
    this.#yDoc = new Doc;
    this.#recordOrigin = {};
    this.#localOrigin = {};
    this.#undoManager = new UndoManager(this.#yDoc, {
      trackedOrigins: new Set([this.#recordOrigin]),
      captureTimeout: 0
    });
    this.#styleStore = new WorkbookStyleStore({
      doc: this.#yDoc,
      isCollaborativeStateReady: () => this.#collaborativeStateReady,
      styleRegistry: this.#styles,
      runLocalTransaction: (fn) => this.runLocalCollabTransaction(fn)
    });
    this.#slicerCaches = normalized.slicerCaches;
    this.#pivotCaches = normalized.pivotCaches;
    this.#timelineCaches = normalized.timelineCaches;
    this.#pivotTableContext = {
      pivotCaches: this.#pivotCaches
    };
    this.#slicerContext = {
      slicerCaches: this.#slicerCaches
    };
    this.#worksheetContext = {
      workbook: this,
      pivotTables: this.#pivotTableContext,
      slicers: this.#slicerContext,
      getOrCreateWorksheetState: (sheetId) => this.#getOrCreateWorksheetState(sheetId),
      getOrCreateWorksheetStyleRefsState: (sheetId) => this.#getOrCreateWorksheetStyleRefsState(sheetId),
      getWorksheetByName: (name2) => this.__getWorksheetByName(name2),
      getWorksheetBySheetId: (sheetId) => this.__getWorksheetBySheetId(sheetId),
      onWorksheetCollectionChanged: () => this.#queueWorksheetTopologyPublish(),
      notifyCellFormulaChanged: (worksheet, address, formulaText) => this.__handleCellFormulaChanged(worksheet, address, formulaText),
      notifyCellValueChanged: (worksheet, address) => this.__handleCellValueChanged(worksheet, address)
    };
    this.#worksheets = new WorksheetCollection(normalized.sheets, this.#worksheetContext);
    this.#structuredReferenceRuntime = new WorkbookStructuredReferenceRuntime({
      worksheets: this.#worksheets,
      getWorksheetByName: (name2) => this.#getWorksheetByName(name2),
      normalizeCellAddress: (addr, fallbackSheet) => this.#normalizeCellAddress(addr, fallbackSheet),
      makeError: (code3) => makeScalarError(code3)
    });
    this.#rangeReferenceAnalysis = new WorkbookRangeReferenceAnalysis({
      structuredReferences: this.#structuredReferenceRuntime,
      expandRange: (ref2, fallbackSheet, activeCellAddress) => this.#expandRange(ref2, fallbackSheet, activeCellAddress),
      cellAddressIsBlank: (addr, fallbackSheet) => this.#cellAddressIsBlank(addr, fallbackSheet)
    });
    this.#worksheetTopologyStore = new WorkbookWorksheetTopologyStore({
      doc: this.#yDoc,
      runLocalTransaction: (fn) => this.runLocalCollabTransaction(fn),
      getCollabOrigins: () => this.getCollabOrigins()
    });
    this.#worksheetTopologyStore.onDidChange(() => {
      this.#applyWorksheetTopologyFromCollab();
    });
    this.#applyWorksheetTopologyFromCollab();
    const activeSheetName = this.#worksheets.getSheetNameByIndex(0);
    this.awareness = new WorkbookAwarenessState({
      activeSheetName: activeSheetName ?? null
    });
    this.#pivotTables = new PivotTableCollection({
      workbook: this,
      context: this.#pivotTableContext
    });
    this.#slicers = new SlicerCollection({
      workbook: this,
      context: this.#slicerContext
    });
    this.#notes = new NotesCollection(normalized.notes, {}, () => {
      this.queueWorkbookCollabPublish();
    });
    this.#sheetNamesByLocalId = [];
    this.#refreshSheetNamesByLocalId();
    this.#definedNames = new DefinedNames2({
      getSheetNameByLocalId: (id2) => this.#getSheetNameByLocalId(id2),
      getLocalSheetIdByName: (name2) => this.#getLocalSheetIdByName(name2),
      getWorksheetByName: (name2) => this.__getWorksheetByName(name2),
      onChange: () => {
        this.#invalidateCalcState();
        this.queueWorkbookCollabPublish();
      },
      recordOp: (op) => {
        this.#recorder?.record(op);
      }
    });
    this.#definedNames.ingest(workbook.definedNames?.names ?? []);
    this.#names = this.#definedNames.createApi();
    this.#namesBySheet = new Map;
    this.#collabState = this.#createWorkbookCollabState();
    this.#conditionalFormattingRenderCaches = new Map;
    this.#cellRefContexts = new Map;
    this.#evaluatingCells = new Set;
    this.#spillManager = new SpillManager;
    this.#dataTableCells = new Map;
    this.#calcState = {
      graph: { precedents: new Map, dependents: new Map },
      parsed: new Map,
      dirty: new Set,
      initialized: false,
      volatility: new Map,
      evaluations: new Map,
      formulaKinds: new Map
    };
    this.#initializeCalcState(this.#calcState);
    this.#calcState.initialized = true;
    this.#pivotTables.hydrateLayouts();
    this.#primeWorksheetRawValues();
    this.#refreshSparklineRenderContexts();
  }
  static create() {
    return new Workbook2({
      sheets: [],
      styles: undefined,
      theme: undefined,
      contentReferences: [],
      images: [],
      people: [],
      threads: [],
      notes: [],
      slicerCaches: [],
      pivotCaches: [],
      timelineCaches: [],
      textStyles: [],
      codeEnvironments: [],
      codeBlocks: []
    });
  }
  static load(workbook) {
    return new Workbook2(workbook);
  }
  static async fromGoogleSheets(config3) {
    return getGoogleSheetsProviderOrThrow().loadWorkbook(config3);
  }
  static async fromMarkdown(markdown, options) {
    const { buildTableValuesFromMarkdown: buildTableValuesFromMarkdown2, sanitizeSheetName: sanitizeSheetName3 } = await loadMarkdownUtils();
    const tableValues = buildTableValuesFromMarkdown2(markdown);
    const shouldFormat = options?.format ?? true;
    const workbook = Workbook2.create();
    const sheet = workbook.worksheets.add(sanitizeSheetName3(options?.sheetName));
    const columnCount = tableValues.reduce((max5, row2) => Math.max(max5, row2.length), 0);
    if (columnCount === 0) {
      return workbook;
    }
    for (let rowIndex2 = 0;rowIndex2 < tableValues.length; rowIndex2 += 1) {
      const row2 = tableValues[rowIndex2] ?? [];
      const paddedRow = row2.slice();
      while (paddedRow.length < columnCount) {
        paddedRow.push("");
      }
      const startAddress = `${columnLabel(0)}${rowIndex2 + 1}`;
      const endAddress = `${columnLabel(columnCount - 1)}${rowIndex2 + 1}`;
      const rangeAddress = columnCount === 1 ? startAddress : `${startAddress}:${endAddress}`;
      sheet.getRange(rangeAddress).values = [paddedRow];
    }
    if (tableValues.length > 0 && columnCount > 0) {
      const startAddress = `${columnLabel(0)}1`;
      const endAddress = `${columnLabel(columnCount - 1)}${tableValues.length}`;
      const rangeAddress = columnCount === 1 && tableValues.length === 1 ? startAddress : `${startAddress}:${endAddress}`;
      if (shouldFormat) {
        sheet.tables.add(rangeAddress, true);
      }
      sheet.getRange(rangeAddress).format.autofitColumns();
    }
    return workbook;
  }
  static async fromCSV(csv, options) {
    const { planCsvImport: planCsvImport2 } = await loadCsvUtils();
    const plan = planCsvImport2(csv, options);
    const workbook = Workbook2.create();
    const sheet = workbook.worksheets.add(plan.sheetName);
    if (plan.values.length > 0 && plan.rangeRef) {
      const rangeRef = plan.rangeRef;
      workbook.record(() => {
        sheet.getRange(rangeRef).values = plan.values;
      });
    }
    return workbook;
  }
  async fromCSV(csv, options) {
    const { planCsvImport: planCsvImport2 } = await loadCsvUtils();
    const plan = planCsvImport2(csv, options);
    const sheet = this.worksheets.getOrAdd(plan.sheetName, {
      renameFirstIfOnlyNewSpreadsheet: true
    });
    if (plan.values.length > 0 && plan.rangeRef) {
      const rangeRef = plan.rangeRef;
      this.record(() => {
        sheet.getRange(rangeRef).values = plan.values;
      });
      return { sheet, range: sheet.getRange(rangeRef) };
    }
    return { sheet, range: null };
  }
  get pivotTables() {
    return this.#pivotTables;
  }
  get sheets() {
    return this.#worksheets;
  }
  get slicers() {
    return this.#slicers;
  }
  get worksheets() {
    return this.#worksheets;
  }
  getStyleRegistry() {
    return this.#styles;
  }
  __registerCollaborativeStyle(input) {
    return this.#styleStore.registerStyle(input);
  }
  __getOrCreateStyleIdForStyleIndex(styleIndex) {
    return this.#styleStore.getOrCreateStyleIdForIndex(styleIndex);
  }
  __resolveStyleIndexForStyleId(styleId) {
    return this.#styleStore.getStyleIndexForId(styleId);
  }
  __subscribeToCollaborativeStyles(listener) {
    return this.#styleStore.subscribe(listener);
  }
  #getOrCreateWorksheetState(sheetId) {
    if (sheetId.length === 0) {
      throw new Error("Worksheet state requires a non-empty sheetId.");
    }
    return this.#yDoc.getMap(`sheet:${sheetId}`);
  }
  #getOrCreateWorksheetStyleRefsState(sheetId) {
    if (sheetId.length === 0) {
      throw new Error("Worksheet style refs require a non-empty sheetId.");
    }
    return this.#yDoc.getMap(getWorksheetStyleRefsMapName(sheetId));
  }
  hydrateCrdtFromProto() {
    this.#throwIfCrdtDocIsNotEmpty("hydrateCrdtFromProto");
    this.runLocalCollabTransaction(() => {
      this.#activateWorkbookCollabRoot();
      this.#collaborativeStateReady = true;
      this.#publishWorksheetTopologyToCollab();
      this.#styleStore.hydrateFromStyleRegistry();
      for (const worksheet of this.#worksheets) {
        worksheet.hydrateCollaborativeRefsFromProto();
      }
      this.#hydrateCellInputsFromProtoToCrdt();
      this.#collabState.activate();
      this.#collabState.flushFromOwner();
      for (const worksheet of this.#worksheets) {
        worksheet.flushCollaborativeState();
      }
    });
  }
  loadInitialCrdtStateV2(update, options = {}) {
    this.#throwIfCrdtDocIsNotEmpty("loadInitialCrdtStateV2");
    this.applyCrdtUpdateV2(update, options);
  }
  getCrdtDoc() {
    return this.#yDoc;
  }
  isCollaborativeStateReady() {
    return this.#collaborativeStateReady;
  }
  __flushPendingCollaborativePublishes() {
    this.#flushPendingCollaborativePublishes();
  }
  getCollabOrigins() {
    return { record: this.#recordOrigin, local: this.#localOrigin };
  }
  queueWorkbookCollabPublish() {
    if (!this.#collaborativeStateReady || this.#isApplyingCrdtUpdate) {
      return;
    }
    this.#workbookCollabDirty = true;
    this.#queueCollaborativePublishFlush();
  }
  queueWorksheetCollabPublish(sheetId) {
    if (!this.#collaborativeStateReady || this.#isApplyingCrdtUpdate) {
      return;
    }
    if (sheetId.length === 0) {
      return;
    }
    this.#dirtyWorksheetSheetIds.add(sheetId);
    this.#queueCollaborativePublishFlush();
  }
  runLocalCollabTransaction(fn) {
    return this.#runCellInputTransaction(this.#localOrigin, fn);
  }
  batchCellInputWrites(fn) {
    const origin = this.#cellInputOrigin ?? this.#localOrigin;
    this.#cellInputWriteDepth += 1;
    try {
      const result = this.#runCellInputTransaction(origin, fn);
      this.#cellInputWriteNeedsRecalc = true;
      return result;
    } finally {
      this.#cellInputWriteDepth -= 1;
      if (this.#cellInputWriteDepth === 0 && this.#cellInputWriteNeedsRecalc) {
        this.#cellInputWriteNeedsRecalc = false;
        this.recalculate();
      }
    }
  }
  undo() {
    this.#undoManager.undo();
  }
  redo() {
    this.#undoManager.redo();
  }
  canUndo() {
    return this.#undoManager.canUndo();
  }
  canRedo() {
    return this.#undoManager.canRedo();
  }
  getConditionalFormattingRenderCache(sheetName) {
    const key = sheetName?.trim();
    if (!key) {
      return null;
    }
    const cached2 = this.#conditionalFormattingRenderCaches.get(key);
    if (cached2) {
      return cached2;
    }
    const worksheet = this.#getWorksheetByName(key);
    if (!worksheet) {
      return null;
    }
    const themeMap = buildWorkbookThemeMap(this.theme);
    const dxfs = this.#styles.toProto().dxfs;
    const state = this.#ensureCalcState();
    const context = this.#createEvaluationContext(key, new Map, state);
    const evaluateExpression = (expr, activeCell) => {
      context.activeCellAddress = activeCell;
      return evaluateExpr(expr, context);
    };
    const cache = buildConditionalFormattingRenderCache({
      sheetName: key,
      conditionalFormattings: worksheet.__getConditionalFormattings(),
      dxfs,
      themeMap,
      getCell: (rowIdx, colIdx) => worksheet.__getCell(rowIdx, colIdx),
      evaluateExpression
    });
    this.#conditionalFormattingRenderCaches.set(key, cache);
    return cache;
  }
  invalidateConditionalFormattingCache(sheetName) {
    if (!sheetName) {
      this.#conditionalFormattingRenderCaches.clear();
      return;
    }
    const key = sheetName.trim();
    if (!key) {
      return;
    }
    this.#conditionalFormattingRenderCaches.delete(key);
  }
  __getOrCreateCheckboxFeaturePropertyBagIndex() {
    const bags = this.#featurePropertyBags?.bags ?? [];
    const existingIndex = bags.findIndex((bag) => bag?.type === CHECKBOX_FEATURE_BAG_TYPE);
    if (existingIndex >= 0) {
      return existingIndex;
    }
    const nextBags = bags.slice();
    const checkboxIndex = nextBags.length;
    const xfControlsIndex = checkboxIndex + 1;
    const xfComplementIndex = checkboxIndex + 2;
    nextBags.push({ type: CHECKBOX_FEATURE_BAG_TYPE, properties: [] });
    nextBags.push({
      type: XF_CONTROLS_FEATURE_BAG_TYPE,
      properties: [
        {
          key: FEATURE_PROPERTY_BAG_KEY_CELL_CONTROL,
          bagIdValue: checkboxIndex
        }
      ]
    });
    nextBags.push({
      type: XF_COMPLEMENT_FEATURE_BAG_TYPE,
      properties: [
        {
          key: FEATURE_PROPERTY_BAG_KEY_XF_CONTROLS,
          bagIdValue: xfControlsIndex
        }
      ]
    });
    nextBags.push({
      type: XF_COMPLEMENTS_FEATURE_BAG_TYPE,
      extRef: FEATURE_PROPERTY_BAG_EXT_REF,
      properties: [
        {
          key: FEATURE_PROPERTY_BAG_KEY_MAPPED_FEATURE_BAGS,
          arrayValue: {
            values: [{ bagIdValue: xfComplementIndex }]
          }
        }
      ]
    });
    this.#featurePropertyBags = { bags: nextBags };
    this.queueWorkbookCollabPublish();
    return checkboxIndex;
  }
  __isCheckboxStyleIndex(styleIndex) {
    const bagIndex = this.#styles.describe(styleIndex).featurePropertyBagIndex;
    return this.#isCheckboxBagIndex(bagIndex);
  }
  __resolveCheckboxStyleIndex(styleIndex) {
    const checkboxIndex = this.__getOrCreateCheckboxFeaturePropertyBagIndex();
    return this.#styles.resolveFeaturePropertyBagStyleIndex(styleIndex, checkboxIndex);
  }
  __removeCheckboxStyleIndex(styleIndex) {
    if (!this.__isCheckboxStyleIndex(styleIndex)) {
      return styleIndex;
    }
    return this.#styles.resolveFeaturePropertyBagStyleIndex(styleIndex, undefined);
  }
  createImageAsset(options) {
    const payload = resolveImageAssetPayload(options);
    if (!payload.data && !payload.prompt && !payload.uri) {
      throw new Error("Image assets need data, a prompt, or a uri.");
    }
    const image3 = {
      id: generateUuid(),
      contentType: payload.contentType ?? "",
      data: payload.data ? new Uint8Array(payload.data) : new Uint8Array,
      prompt: payload.prompt,
      uri: payload.uri
    };
    this.#images.push(image3);
    this.queueWorkbookCollabPublish();
    return image3;
  }
  #createWorkbookCollabState() {
    return new WorkbookCollabState({
      root: getWorkbookCollabRoot(this.#yDoc),
      runLocalTransaction: (fn) => this.runLocalCollabTransaction(fn),
      getCollabOrigins: () => this.getCollabOrigins(),
      readTheme: () => this.theme,
      applyTheme: (theme) => {
        this.#theme.replace(theme);
        this.invalidateConditionalFormattingCache();
        this.queueWorkbookCollabPublish();
      },
      readFeaturePropertyBags: () => this.#featurePropertyBags,
      applyFeaturePropertyBags: (bags) => {
        this.#featurePropertyBags = bags;
        this.queueWorkbookCollabPublish();
      },
      readDefinedNames: () => this.#definedNames.buildProto(),
      applyDefinedNames: (names) => {
        this.#definedNames.replace(names);
        this.#namesBySheet.clear();
        this.#invalidateCalcState();
        this.queueWorkbookCollabPublish();
      },
      readImages: () => this.#images,
      applyImages: (images) => {
        this.#images = images;
        this.queueWorkbookCollabPublish();
      },
      readComments: () => this.comments.toProto(),
      applyComments: (snapshot) => {
        this.comments.replaceFromProto(snapshot);
        this.queueWorkbookCollabPublish();
      },
      readNotes: () => this.#notes.proto,
      applyNotes: (notes) => {
        this.#notes.replace(notes);
        this.queueWorkbookCollabPublish();
      }
    });
  }
  get images() {
    return this.#images;
  }
  get notes() {
    return this.#notes;
  }
  get names() {
    return this.#names;
  }
  get definedNames() {
    return this.#names;
  }
  get utils() {
    return {
      columnToLetter: (index1Based) => {
        if (!Number.isFinite(index1Based) || !Number.isInteger(index1Based)) {
          throw new Error("columnToLetter(index) requires an integer index.");
        }
        if (index1Based < 1) {
          throw new Error("columnToLetter(index) requires a 1-based index >= 1.");
        }
        return columnNumberToLabel(index1Based);
      },
      letterToColumn: (label) => {
        if (typeof label !== "string") {
          throw new Error("letterToColumn(label) requires a string label.");
        }
        const normalized = label.trim().replace(/\$/g, "");
        const value2 = columnLabelToNumber(normalized);
        if (!value2) {
          throw new Error(`Invalid column label: ${label}`);
        }
        return value2;
      },
      toA1String: (row1Based, col1Based, endRow1Based, endCol1Based) => {
        const validate = (value2, name2) => {
          if (!Number.isFinite(value2) || !Number.isInteger(value2)) {
            throw new Error(`toA1String(${name2}) requires an integer.`);
          }
          if (value2 < 1) {
            throw new Error(`toA1String(${name2}) requires a 1-based index >= 1.`);
          }
        };
        validate(row1Based, "row1Based");
        validate(col1Based, "col1Based");
        const start = `${columnNumberToLabel(col1Based)}${row1Based}`;
        if (endRow1Based === undefined && endCol1Based === undefined) {
          return start;
        }
        const finalEndRow = endRow1Based ?? row1Based;
        const finalEndCol = endCol1Based ?? col1Based;
        validate(finalEndRow, "endRow1Based");
        validate(finalEndCol, "endCol1Based");
        const end = `${columnNumberToLabel(finalEndCol)}${finalEndRow}`;
        return start === end ? start : `${start}:${end}`;
      },
      fillRight: (matrix, width) => {
        if (!Array.isArray(matrix)) {
          throw new Error("fillRight(matrix, width) requires a 2D array.");
        }
        if (!Number.isFinite(width) || !Number.isInteger(width) || width < 1) {
          throw new Error("fillRight(matrix, width) requires width >= 1.");
        }
        const rows = matrix.length;
        if (rows === 0) {
          throw new Error("fillRight(matrix, width) requires at least one row.");
        }
        return matrix.map((row2, r) => {
          if (!Array.isArray(row2) || row2.length === 0) {
            throw new Error(`fillRight(matrix, width) row ${r} must be a non-empty array.`);
          }
          const out = row2.slice(0, width);
          const last2 = out[out.length - 1];
          while (out.length < width) {
            out.push(last2);
          }
          return out;
        });
      },
      fillDown: (matrix, height) => {
        if (!Array.isArray(matrix)) {
          throw new Error("fillDown(matrix, height) requires a 2D array.");
        }
        if (!Number.isFinite(height) || !Number.isInteger(height) || height < 1) {
          throw new Error("fillDown(matrix, height) requires height >= 1.");
        }
        if (matrix.length === 0) {
          throw new Error("fillDown(matrix, height) requires at least one row.");
        }
        const base = matrix.map((row2, r) => {
          if (!Array.isArray(row2) || row2.length === 0) {
            throw new Error(`fillDown(matrix, height) row ${r} must be a non-empty array.`);
          }
          return [...row2];
        });
        const out = base.slice(0, height).map((row2) => [...row2]);
        const last2 = out[out.length - 1] ?? [];
        while (out.length < height) {
          out.push([...last2]);
        }
        return out;
      }
    };
  }
  #isCheckboxBagIndex(bagIndex) {
    if (typeof bagIndex !== "number") {
      return false;
    }
    const bag = this.#featurePropertyBags?.bags?.[bagIndex];
    return bag?.type === CHECKBOX_FEATURE_BAG_TYPE;
  }
  __getWorksheetByName(name2) {
    return this.#getWorksheetByName(name2);
  }
  __getWorksheetBySheetId(sheetId) {
    return this.#worksheets.getItemBySheetId(sheetId);
  }
  __getNamesFacadeForSheet(sheetName) {
    const key = sheetName.trim();
    if (!key) {
      return this.#names;
    }
    const cached2 = this.#namesBySheet.get(key);
    if (cached2) {
      return cached2;
    }
    const scoped = this.#definedNames.createApi(key);
    this.#namesBySheet.set(key, scoped);
    return scoped;
  }
  get theme() {
    return this.#theme.toProto();
  }
  setColorScheme(update) {
    if (!update) {
      return;
    }
    const partial2 = typeof update === "object" && "themeColors" in update ? {
      name: update.name,
      colors: update.themeColors ? (() => {
        const colors = [];
        for (const [name2, config3] of Object.entries(update.themeColors)) {
          if (config3 === undefined) {
            continue;
          }
          if (config3 === null) {
            throw new Error(`themeColors.${name2} cannot be null; omit the key to leave it unchanged.`);
          }
          const proto = new Color4(config3).toProto();
          if (!proto) {
            throw new Error(`themeColors.${name2} must be a valid color; got an unset proto color.`);
          }
          colors.push({ name: name2, color: proto });
        }
        return colors.length > 0 ? colors : undefined;
      })() : undefined
    } : update;
    this.#theme.setColorScheme(partial2);
    this.invalidateConditionalFormattingCache();
    this.queueWorkbookCollabPublish();
    const recorder = this.#recorder;
    if (!recorder) {
      return;
    }
    const theme = this.theme;
    const themeColors = Object.fromEntries((theme?.colorScheme?.colors ?? []).map((entry) => {
      if (!entry?.name || !entry.color) {
        return null;
      }
      const config3 = new Color4({
        type: "proto",
        proto: entry.color
      }).toConfig();
      if (!config3 || typeof config3 === "object" && config3 !== null && config3.type === "proto") {
        return null;
      }
      return [entry.name, config3];
    }).filter((entry) => entry !== null));
    recorder.record({
      op: "theme.colorScheme.set",
      scheme: {
        name: theme?.colorScheme?.name ?? "Custom",
        themeColors
      }
    });
  }
  recalculate() {
    const state = this.#ensureCalcState();
    if (state.dirty.size === 0) {
      this.#evaluateDataTables(state);
      return;
    }
    const formulaTargets = new Set;
    for (const key of state.dirty) {
      if (state.parsed.has(key)) {
        formulaTargets.add(key);
      }
    }
    if (formulaTargets.size === 0) {
      state.dirty.clear();
      return;
    }
    const { order: order2, circular } = buildCalculationChain(state.graph, formulaTargets);
    const circularCells = new Set;
    for (const cycle of circular) {
      for (const key of cycle) {
        circularCells.add(key);
      }
    }
    const computed = new Map;
    for (const key of order2) {
      if (circularCells.has(key)) {
        continue;
      }
      const parsed = state.parsed.get(key);
      if (!parsed) {
        continue;
      }
      const { sheetName, address } = splitCellKey(key);
      const worksheet = this.#getWorksheetByName(sheetName);
      if (!worksheet) {
        continue;
      }
      const coord = this.#addressToIndices(address);
      const ctx = this.#createEvaluationContext(sheetName, computed, state, key);
      let value2;
      if (parsed.errors.length === 0) {
        value2 = evaluateExpr(parsed.expr, ctx);
        value2 = this.#coerceBlankRangeRefResult(parsed.expr, value2, sheetName);
      } else {
        value2 = makeScalarError("#ERROR!");
      }
      if (isArrayValue(value2)) {
        const topLeft = value2.values[0]?.[0] === undefined ? null : value2.values[0][0];
        this.#applySpillResult({
          key,
          worksheet,
          coord,
          arrayValue: value2,
          sheetName
        });
        computed.set(key, topLeft ?? null);
        this.#recordEvaluationSnapshot(key, topLeft ?? null, state, {
          worksheet,
          coord
        });
      } else {
        this.#clearSpillForAnchor(key);
        computed.set(key, value2);
        this.#writeComputedValue(key, value2);
        this.#recordEvaluationSnapshot(key, value2, state, {
          worksheet,
          coord
        });
      }
    }
    for (const key of order2) {
      state.dirty.delete(key);
    }
    if (circular.length > 0) {
      for (const cycle of circular) {
        for (const key of cycle) {
          state.dirty.delete(key);
        }
      }
    }
    this.#evaluateDataTables(state);
  }
  trace(cellReference) {
    const target = this.#normalizeTraceTarget(cellReference);
    if (!target) {
      return null;
    }
    this.recalculate();
    const state = this.#ensureCalcState();
    const key = makeCellKey(target.sheetName, target.address);
    return this.#buildTraceNode(key, state, new Set);
  }
  collectFormulaUsageStats() {
    const state = this.#ensureCalcState();
    return buildFormulaUsageStats(state);
  }
  __getDisplayFormulaForCell(sheetName, rowIdx, colIdx) {
    const address = makeCellAddress(rowIdx, colIdx);
    const cellKey = makeCellKey(sheetName, address);
    const dataTableEntry = this.#dataTableCells.get(cellKey);
    if (dataTableEntry) {
      return stripCompatibilityPrefixes(dataTableEntry.display);
    }
    const projection = this.#spillManager.getCellProjection(cellKey);
    if (projection && !projection.isAnchor) {
      return stripCompatibilityPrefixes(projection.record.displayFormula);
    }
    const worksheet = this.#getWorksheetByName(sheetName);
    if (!worksheet) {
      return "";
    }
    const cell = worksheet.__getCell(rowIdx, colIdx);
    if (!cell?.formula) {
      return "";
    }
    const trimmed = cell.formula.trim();
    if (!trimmed) {
      return "";
    }
    const withEquals = trimmed.startsWith("=") ? trimmed : `=${trimmed}`;
    return stripCompatibilityPrefixes(withEquals);
  }
  __getFormulaPresenceForCell(sheetName, rowIdx, colIdx) {
    const address = makeCellAddress(rowIdx, colIdx);
    const cellKey = makeCellKey(sheetName, address);
    const dataTableEntry = this.#dataTableCells.get(cellKey);
    if (dataTableEntry) {
      return {
        kind: "projected",
        source: "dataTable",
        display: dataTableEntry.display,
        master: dataTableEntry.master,
        ref: dataTableEntry.ref,
        rowInput: dataTableEntry.rowInput,
        columnInput: dataTableEntry.columnInput,
        isEditable: false
      };
    }
    const projection = this.#spillManager.getCellProjection(cellKey);
    if (projection && !projection.isAnchor) {
      const anchor = splitCellKey(projection.record.anchorKey);
      return {
        kind: "projected",
        source: "spill",
        display: projection.record.displayFormula,
        anchor: `${anchor.sheetName}!${anchor.address}`,
        ref: projection.record.ref,
        isEditable: false
      };
    }
    const worksheet = this.#getWorksheetByName(sheetName);
    const cell = worksheet?.__getCell(rowIdx, colIdx);
    if (cell?.formula && cell.formula.trim()) {
      const text7 = cell.formula.trim();
      const withEquals = text7.startsWith("=") ? text7 : `=${text7}`;
      return {
        kind: "stored",
        formula: withEquals,
        display: withEquals,
        isEditable: true
      };
    }
    return;
  }
  toProto() {
    this.#rebuildExcludedCollaborativeSidecars();
    const definedNames = this.#definedNames.buildProto();
    const threadProtos = normalizeThreadTargets(this.comments.threads.toProto());
    const basePeople = this.comments.people.toProto();
    const legacy = buildThreadedNotes({
      threads: threadProtos,
      existingNotes: this.#notes.proto,
      people: basePeople
    });
    const featurePropertyBags = this.#featurePropertyBags?.bags && this.#featurePropertyBags.bags.length ? this.#featurePropertyBags : undefined;
    const proto = {
      sheets: this.#worksheets.toProto(),
      styles: this.#styles.toProto(),
      featurePropertyBags,
      theme: this.theme,
      contentReferences: this.#contentReferences,
      images: this.#images,
      people: legacy.people,
      threads: threadProtos,
      notes: legacy.notes,
      slicerCaches: this.#slicerCaches,
      pivotCaches: this.#pivotCaches,
      timelineCaches: this.#timelineCaches,
      metadata: cloneWorkbookMetadataForExport(this.#metadata),
      definedNames: definedNames.length > 0 ? { names: definedNames } : undefined,
      textStyles: [],
      codeEnvironments: [],
      codeBlocks: []
    };
    applyWorkbookDynamicArrayExportMetadata({
      proto,
      makeCellKey: (sheetName, address) => makeCellKey(sheetName, address),
      getSpillProjection: (cellKey) => this.#spillManager.getCellProjection(cellKey),
      hasLambdaDefinedName: (canonicalName, contextSheet) => {
        const entry = this.#definedNames.lookup(canonicalName, contextSheet);
        if (!entry) {
          return false;
        }
        this.#definedNames.parseEntry(entry);
        return entry.isLambda;
      },
      stripCompatibilityPrefixes: (formula) => stripCompatibilityPrefixes(formula)
    });
    return proto;
  }
  inspect(options) {
    return inspectWorkbook(this, options);
  }
  findCells(options) {
    return searchWorkbookCells(this, options);
  }
  help(query, options) {
    return getWorkbookHelpProviderOrThrow().buildWorkbookHelp(query, options);
  }
  resolve(id2) {
    const { prefix, suffix } = splitAnchorId(id2);
    if (!prefix || !suffix) {
      throw new Error(`Unknown resolve anchor: ${id2}`);
    }
    if (prefix === "wb") {
      return this;
    }
    if (prefix === "ws") {
      for (const worksheet of this.worksheets) {
        if (worksheet.id === suffix || worksheet.sheetId === suffix || worksheet.name === suffix) {
          return worksheet;
        }
      }
      throw new Error(`Worksheet not found: ${id2}`);
    }
    if (prefix === "th") {
      const thread = this.comments.getThread(suffix);
      if (!thread) {
        throw new Error(`Thread not found: ${id2}`);
      }
      return thread;
    }
    if (prefix === "ch") {
      const dotIndex = suffix.lastIndexOf(".");
      if (dotIndex > 0 && dotIndex < suffix.length - 1) {
        const sheetRef = suffix.slice(0, dotIndex);
        const chartRef = suffix.slice(dotIndex + 1);
        let worksheet;
        for (const candidate of this.worksheets) {
          if (candidate.id === sheetRef || candidate.sheetId === sheetRef || candidate.name === sheetRef) {
            worksheet = candidate;
            break;
          }
        }
        if (!worksheet) {
          throw new Error(`Worksheet not found: ch/${sheetRef}`);
        }
        const chart2 = worksheet.charts.getItemOrNullObject(chartRef);
        if (chart2.isNullObject) {
          throw new Error(`Chart not found: ${id2}`);
        }
        return chart2;
      }
      const chartId = suffix;
      if (!chartId) {
        throw new Error(`Invalid chart anchor: ${id2}`);
      }
      for (const worksheet of this.worksheets) {
        for (const chart2 of worksheet.charts.items) {
          if (chart2.id === chartId) {
            return chart2;
          }
        }
      }
      throw new Error(`Chart not found: ${id2}`);
    }
    throw new Error(`Unknown resolve anchor: ${id2}`);
  }
  apply(patch, options) {
    if (!options) {
      return applyWorkbookPatch(this, patch);
    }
    if (!this.#googleSheets) {
      throw new Error("Google Sheets adapter is not configured.");
    }
    const preApplyState = this.#buildGoogleSheetsPreApplyState();
    const result = applyWorkbookPatch(this, patch);
    const adapter = this.#googleSheets;
    return adapter.applyPatch(patch, result, preApplyState);
  }
  configureGoogleSheets(config3) {
    this.#googleSheets = getGoogleSheetsProviderOrThrow().configureWorkbook(this, config3);
    return this;
  }
  #buildGoogleSheetsPreApplyState() {
    return {
      sheets: this.worksheets.items.map((worksheet) => ({
        name: worksheet.name,
        index: worksheet.index ?? 0,
        sheetId: worksheet.sheetId,
        conditionalFormattings: worksheet.conditionalFormattings.items.map((group) => ({
          ranges: structuredClone(group.ranges ?? []),
          ruleCount: group.rules?.length ?? 0
        }))
      }))
    };
  }
  applyCrdtUpdateV2(update, options = {}) {
    this.#collaborativeStateReady = true;
    this.#isApplyingCrdtUpdate = true;
    try {
      applyUpdateV2(this.#yDoc, update instanceof Uint8Array ? update : new Uint8Array(update));
    } finally {
      this.#isApplyingCrdtUpdate = false;
    }
    if (options.recalculate ?? true) {
      this.recalculate();
    }
  }
  onCrdtUpdateV2(handler) {
    const wrapped = (update, origin) => {
      handler(new Uint8Array(update), origin);
    };
    this.#yDoc.on("updateV2", wrapped);
    return () => {
      this.#yDoc.off("updateV2", wrapped);
    };
  }
  record(fn) {
    if (this.#recorder) {
      throw new Error("Workbook.record does not support nested recordings.");
    }
    if (!this.#collaborativeStateReady) {
      this.hydrateCrdtFromProto();
    }
    const recorder = new WorkbookRecorder(this);
    const crdtUpdates = [];
    const onUpdateV2 = (update, origin) => {
      if (origin !== this.#recordOrigin && origin !== this.#localOrigin) {
        return;
      }
      crdtUpdates.push(new Uint8Array(update));
    };
    this.#yDoc.on("updateV2", onUpdateV2);
    this.#recorder = recorder;
    try {
      const result = this.#runCellInputTransaction(this.#recordOrigin, fn);
      this.#flushPendingCollaborativePublishes();
      return {
        result,
        patch: recorder.getPatch(),
        idMap: recorder.getIdMap(),
        crdtUpdateV2: crdtUpdates.length > 0 ? mergeUpdatesV2(crdtUpdates) : undefined
      };
    } finally {
      this.#yDoc.off("updateV2", onUpdateV2);
      this.#undoManager.stopCapturing();
      this.#recorder = undefined;
    }
  }
  getRecorder() {
    return this.#recorder;
  }
  __reloadPivotCollectionsFromCollab() {
    this.#pivotTables.reload();
  }
  __reloadSlicerCollectionsFromCollab() {
    this.#slicers.reload();
  }
  __refreshSparklineRenderContextsFromCollab() {
    this.#refreshSparklineRenderContexts();
  }
  __invalidateCalcStateFromCollab() {
    this.#invalidateCalcState();
  }
  get googleSheets() {
    return this.#googleSheets;
  }
  render(options = {}) {
    return getWorkbookExportProviderOrThrow().renderWorkbook(this, options);
  }
  export(options = {}) {
    return getWorkbookExportProviderOrThrow().exportWorkbook(this, options);
  }
  toHTML(sheetIndex, range2, options) {
    const sheetName = this.#worksheets.getSheetNameByIndex(sheetIndex);
    if (!sheetName) {
      throw new Error(`Worksheet index ${sheetIndex} not found`);
    }
    this.recalculate();
    const workbookProto = this.toProto();
    const sheet = workbookProto.sheets[sheetIndex];
    if (!sheet) {
      throw new Error(`Worksheet index ${sheetIndex} not found`);
    }
    const styleInfos = buildStyleMaps(workbookProto);
    const resolveSelectionRect = () => {
      const trimmedRange = range2?.trim();
      if (trimmedRange) {
        const stripped = trimmedRange.startsWith("=") ? trimmedRange.slice(1) : trimmedRange;
        const bangIndex = stripped.lastIndexOf("!");
        const ref2 = bangIndex === -1 ? stripped : stripped.slice(bangIndex + 1);
        if (bangIndex >= 0) {
          const rawSheet = stripped.slice(0, bangIndex);
          const unescaped = rawSheet.startsWith("'") && rawSheet.endsWith("'") ? rawSheet.slice(1, -1).replace(/''/g, "'") : rawSheet;
          const normalizedRangeSheet = unescaped.trim();
          if (normalizedRangeSheet && normalizedRangeSheet !== sheetName) {
            throw new Error(`Range sheet "${normalizedRangeSheet}" does not match "${sheetName}"`);
          }
        }
        const parsed = parseRangeAddress(ref2);
        if (!parsed) {
          throw new Error(`Invalid range "${range2}"`);
        }
        return {
          r1: parsed.bounds.startRow,
          c1: parsed.bounds.startCol,
          r2: parsed.bounds.endRow,
          c2: parsed.bounds.endCol
        };
      }
      let minRow = Number.POSITIVE_INFINITY;
      let minCol = Number.POSITIVE_INFINITY;
      let maxRow = -1;
      let maxCol = -1;
      const trackBounds = (row2, col) => {
        minRow = Math.min(minRow, row2);
        minCol = Math.min(minCol, col);
        maxRow = Math.max(maxRow, row2);
        maxCol = Math.max(maxCol, col);
      };
      for (const row2 of sheet.rows ?? []) {
        for (const cell of row2.cells ?? []) {
          const coord = cell.address ? this.#addressToIndices(cell.address) : null;
          if (!coord) {
            continue;
          }
          trackBounds(coord.row, coord.col);
        }
      }
      for (const merge2 of sheet.mergedCells ?? []) {
        const start = merge2.startAddress && this.#addressToIndices(merge2.startAddress);
        const end = merge2.endAddress && this.#addressToIndices(merge2.endAddress);
        if (start) {
          trackBounds(start.row, start.col);
        }
        if (end) {
          trackBounds(end.row, end.col);
        }
      }
      if (maxRow >= 0 && maxCol >= 0) {
        return { r1: minRow, c1: minCol, r2: maxRow, c2: maxCol };
      }
      return { r1: 0, c1: 0, r2: 0, c2: 0 };
    };
    const selectionRect = resolveSelectionRect();
    const { rows, merges } = buildClipboardPayload({
      selectionRect,
      selRow: selectionRect.r1,
      selCol: selectionRect.c1,
      sheet,
      styleInfos
    });
    if (options?.formulas) {
      for (let row2 = selectionRect.r1;row2 <= selectionRect.r2; row2 += 1) {
        const rowOut = rows[row2 - selectionRect.r1];
        if (!rowOut) {
          continue;
        }
        for (let col = selectionRect.c1;col <= selectionRect.c2; col += 1) {
          const formula = this.__getDisplayFormulaForCell(sheetName, row2, col);
          if (!formula) {
            continue;
          }
          const cellOut = rowOut[col - selectionRect.c1];
          if (cellOut) {
            cellOut.v = formula;
          }
        }
      }
    }
    return buildHtmlTable(rows, merges);
  }
  fromHTML(sheetIndex, html2, target, options) {
    return importHtmlIntoWorkbook({
      workbook: this,
      sheetIndex,
      html: html2,
      target,
      options
    });
  }
  chartToImage(sheetIndex, chartId) {
    return renderWorkbookChartToImage({
      workbook: this,
      sheetIndex,
      chartId
    });
  }
  fromImage(sheetIndex, source, target, options) {
    return importImageIntoWorkbook({
      workbook: this,
      sheetIndex,
      source,
      target,
      options
    });
  }
  __handleCellFormulaChanged(worksheet, address, formulaText) {
    const sheetName = worksheet.name;
    if (!sheetName) {
      return;
    }
    const normalizedAddress = address.trim().toUpperCase();
    if (!normalizedAddress) {
      return;
    }
    this.invalidateConditionalFormattingCache(sheetName);
    const state = this.#ensureCalcState();
    const key = makeCellKey(sheetName, normalizedAddress);
    const normalizedFormula = this.#normalizeFormulaText(formulaText);
    const coord = this.#addressToIndices(normalizedAddress);
    const markStructuralDependents = () => {
      if (coord) {
        this.#markRowAndColumnDependentsDirty(sheetName, coord, state);
      }
    };
    if (!normalizedFormula) {
      this.#removeFormula(key, state);
      this.#markDependentsDirty(key, state);
      state.formulaKinds.delete(key);
      markStructuralDependents();
      return;
    }
    if (formulaUsesUserDefinedFunction(normalizedFormula)) {
      this.#recordUserDefinedFunctionFailure(key, normalizedFormula, state);
      this.#removeDependenciesForCell(state.graph, key);
      state.parsed.delete(key);
      state.dirty.delete(key);
      state.formulaKinds.delete(key);
      this.#markDependentsDirty(key, state);
      markStructuralDependents();
      return;
    }
    const parsed = parseFormula(normalizedFormula);
    if (parsed.errors.length > 0) {
      this.#setCellError(key, "#NAME?");
      this.#recordEvaluationSnapshot(key, makeScalarError("#NAME?"), state, {
        formulaText: normalizedFormula,
        precedents: []
      });
      this.#removeDependenciesForCell(state.graph, key);
      state.parsed.delete(key);
      state.dirty.delete(key);
      state.formulaKinds.delete(key);
      this.#markDependentsDirty(key, state);
      markStructuralDependents();
      return;
    }
    state.parsed.set(key, parsed);
    const ctx = this.#getCellRefContext(sheetName);
    updateDependenciesForFormula(state.graph, key, parsed.expr, ctx, this.#cellKeyToAddress(key) ?? undefined);
    this.#recomputeVolatilityFrom([key], state);
    this.#updateFormulaKindForCell(state, key, parsed.expr);
    markStructuralDependents();
    this.#markCellDirty(key, state);
  }
  __handleCellValueChanged(worksheet, address) {
    const sheetName = worksheet.name;
    if (!sheetName) {
      return;
    }
    const normalizedAddress = address.trim().toUpperCase();
    if (!normalizedAddress) {
      return;
    }
    this.invalidateConditionalFormattingCache(sheetName);
    const state = this.#ensureCalcState();
    const key = makeCellKey(sheetName, normalizedAddress);
    this.#markDependentsDirty(key, state);
    const coord = this.#addressToIndices(normalizedAddress);
    if (coord) {
      this.#markRowAndColumnDependentsDirty(sheetName, coord, state);
    }
  }
  __getVolatileChain(sheetName, address) {
    const normalizedSheet = sheetName?.trim();
    const normalizedAddress = address?.trim().toUpperCase();
    if (!normalizedSheet || !normalizedAddress) {
      return null;
    }
    const state = this.#ensureCalcState();
    const key = makeCellKey(normalizedSheet, normalizedAddress);
    const info = state.volatility.get(key);
    if (!info || !info.hasVolatileChain || info.chain.length === 0) {
      return null;
    }
    return info.chain.map((cellKey) => {
      const parts = splitCellKey(cellKey);
      return `${parts.sheetName}!${parts.address}`;
    });
  }
  #ensureCalcState() {
    if (!this.#calcState) {
      this.#calcState = {
        graph: { precedents: new Map, dependents: new Map },
        parsed: new Map,
        dirty: new Set,
        initialized: false,
        volatility: new Map,
        evaluations: new Map,
        formulaKinds: new Map
      };
    }
    if (!this.#calcState.initialized) {
      this.#initializeCalcState(this.#calcState);
      this.#calcState.initialized = true;
    }
    return this.#calcState;
  }
  #initializeCalcState(state) {
    this.#cellRefContexts.clear();
    state.graph.precedents.clear();
    state.graph.dependents.clear();
    state.parsed.clear();
    state.dirty.clear();
    state.volatility.clear();
    state.evaluations.clear();
    state.formulaKinds.clear();
    for (const worksheet of this.#worksheets) {
      const sheetName = worksheet.name?.trim();
      if (!sheetName) {
        continue;
      }
      for (const cell of worksheet.cells) {
        const normalizedFormula = this.#normalizeFormulaText(cell.formula);
        if (!normalizedFormula) {
          continue;
        }
        const address = cell.address?.trim();
        if (!address) {
          continue;
        }
        const key = makeCellKey(sheetName, address);
        if (formulaUsesUserDefinedFunction(normalizedFormula)) {
          this.#recordUserDefinedFunctionFailure(key, normalizedFormula, state);
          state.formulaKinds.delete(key);
          continue;
        }
        const parsed = parseFormula(normalizedFormula);
        state.parsed.set(key, parsed);
        if (parsed.errors.length > 0) {
          const errorValue = makeScalarError("#NAME?");
          this.#writeComputedValue(key, errorValue);
          state.evaluations.set(key, {
            value: errorValue,
            formula: normalizedFormula,
            precedents: []
          });
          state.formulaKinds.delete(key);
          continue;
        }
        const ctx = this.#getCellRefContext(sheetName);
        updateDependenciesForFormula(state.graph, key, parsed.expr, ctx, this.#cellKeyToAddress(key) ?? undefined);
        state.dirty.add(key);
        this.#updateFormulaKindForCell(state, key, parsed.expr);
      }
    }
    this.#recomputeVolatilityFrom(state.parsed.keys(), state);
  }
  #updateFormulaKindForCell(state, key, expr) {
    const kind = getTopLevelFunctionKind(expr);
    if (kind) {
      state.formulaKinds.set(key, kind);
    } else {
      state.formulaKinds.delete(key);
    }
  }
  #getFormulaKindForAddress(addr, fallbackSheet, state) {
    const normalized = {
      sheet: { sheetName: addr.sheet?.sheetName ?? fallbackSheet },
      row: addr.row,
      col: addr.col,
      absRow: addr.absRow,
      absCol: addr.absCol
    };
    const key = this.#cellAddressToKey(normalized, normalized.sheet?.sheetName ?? fallbackSheet);
    return state.formulaKinds.get(key) ?? null;
  }
  #cellKeyToAddress(key) {
    const { sheetName, address } = splitCellKey(key);
    if (!sheetName || !address) {
      return null;
    }
    const coord = this.#addressToIndices(address);
    if (!coord) {
      return null;
    }
    return {
      sheet: { sheetName },
      row: coord.row + 1,
      col: coord.col + 1,
      absRow: false,
      absCol: false
    };
  }
  #normalizeTraceTarget(cellReference) {
    if (!cellReference) {
      return null;
    }
    const trimmed = cellReference.trim();
    if (!trimmed) {
      return null;
    }
    let sheetName;
    let addressPart;
    const bangIndex = trimmed.indexOf("!");
    if (bangIndex >= 0) {
      sheetName = trimmed.slice(0, bangIndex).trim();
      addressPart = trimmed.slice(bangIndex + 1).trim();
    } else {
      let active;
      try {
        active = this.#worksheets.getActiveWorksheet();
      } catch {
        return null;
      }
      sheetName = active.name;
      addressPart = trimmed;
    }
    const normalizedSheet = sheetName?.trim();
    const normalizedAddress = addressPart.trim().toUpperCase();
    if (!normalizedSheet || !normalizedAddress) {
      return null;
    }
    if (!this.#getWorksheetByName(normalizedSheet)) {
      return null;
    }
    if (!this.#addressToIndices(normalizedAddress)) {
      return null;
    }
    return { sheetName: normalizedSheet, address: normalizedAddress };
  }
  #getSheetNameByLocalId(localSheetId) {
    if (localSheetId === undefined || localSheetId === null || localSheetId < 0) {
      return;
    }
    return this.#sheetNamesByLocalId[localSheetId]?.trim() || undefined;
  }
  #getLocalSheetIdByName(name2) {
    const target = name2?.trim();
    if (!target) {
      return;
    }
    for (const worksheet of this.#worksheets) {
      if (worksheet.name?.trim() === target) {
        this.#sheetNamesByLocalId[worksheet.index] = worksheet.name ?? "";
        return worksheet.index;
      }
    }
    return;
  }
  #refreshSheetNamesByLocalId() {
    this.#sheetNamesByLocalId = [];
    for (const worksheet of this.#worksheets) {
      this.#sheetNamesByLocalId[worksheet.index] = worksheet.name ?? "";
    }
  }
  #resolveNamedReferenceInternal(name2, mode, ctx, lambdaScopes, resolvingNames, sheetHint) {
    const normalizedName = this.#definedNames.normalizeName(name2);
    if (!normalizedName) {
      return null;
    }
    for (let i = lambdaScopes.length - 1;i >= 0; i -= 1) {
      const frame = lambdaScopes[i];
      if (!frame) {
        continue;
      }
      if (frame.has(normalizedName)) {
        const value2 = frame.get(normalizedName);
        if (mode === "range") {
          return Array.isArray(value2) ? value2 : null;
        }
        return this.#functionArgToScalar(value2);
      }
    }
    const entry = this.#definedNames.lookup(normalizedName, sheetHint ?? ctx.currentSheet);
    if (!entry) {
      return this.#resolveTableNameReference(normalizedName, ctx, sheetHint);
    }
    if (entry.isLambda && mode === "scalar") {
      const parsed = this.#definedNames.parseEntry(entry);
      if (!parsed || parsed.errors.length > 0) {
        return makeScalarError("#NAME?");
      }
      if (parsed.expr.kind !== "FunctionCall") {
        return makeScalarError("#NAME?");
      }
      return this.#buildLambdaValueFromCall(parsed.expr, entry.scopeSheet ?? ctx.currentSheet, ctx, lambdaScopes);
    }
    if (mode === "range") {
      return this.#evaluateDefinedNameRange(entry, ctx, lambdaScopes, resolvingNames);
    }
    return this.#evaluateDefinedNameScalar(entry, ctx, resolvingNames);
  }
  #resolveTableNameReference(name2, ctx, sheetHint) {
    const tableInfo = this.#structuredReferenceRuntime.findTableByName(name2);
    if (!tableInfo) {
      return null;
    }
    return this.#structuredReferenceRuntime.readValues({
      tableName: tableInfo.table.name ?? tableInfo.table.displayName ?? name2,
      section: "All"
    }, ctx, sheetHint ?? ctx.currentSheet ?? tableInfo.sheetName);
  }
  #evaluateDefinedNameScalar(entry, ctx, resolvingNames) {
    const parsed = this.#definedNames.parseEntry(entry);
    if (!parsed || parsed.errors.length > 0) {
      return makeScalarError("#NAME?");
    }
    const guardKey = this.#definedNames.makeGuardKey(entry);
    if (resolvingNames.has(guardKey)) {
      return makeScalarError("#CIRC!");
    }
    resolvingNames.add(guardKey);
    const previousSheet = ctx.currentSheet;
    if (entry.scopeSheet) {
      ctx.currentSheet = entry.scopeSheet;
    }
    let result;
    try {
      result = evaluateExpr(parsed.expr, ctx);
    } finally {
      if (entry.scopeSheet) {
        ctx.currentSheet = previousSheet;
      }
      resolvingNames.delete(guardKey);
    }
    return result;
  }
  #evaluateDefinedNameRange(entry, ctx, lambdaScopes, resolvingNames) {
    if (entry.isLambda) {
      return [[makeScalarError("#VALUE!")]];
    }
    const parsed = this.#definedNames.parseEntry(entry);
    if (!parsed || parsed.errors.length > 0) {
      return [[makeScalarError("#NAME?")]];
    }
    const fallbackSheet = entry.scopeSheet ?? ctx.currentSheet ?? this.#sheetNamesByLocalId[0] ?? "";
    if (!fallbackSheet) {
      return [[makeScalarError("#REF!")]];
    }
    if (parsed.expr.kind === "RangeRef") {
      return this.#readValuesForRangeRef(parsed.expr.ref, ctx, fallbackSheet, lambdaScopes, resolvingNames);
    }
    const scalar = this.#evaluateDefinedNameScalar(entry, ctx, resolvingNames);
    if (this.#isErrorValue(scalar)) {
      return [[scalar]];
    }
    return [[scalar]];
  }
  #functionArgToScalar(arg) {
    if (Array.isArray(arg)) {
      const firstRow = arg[0];
      if (!firstRow || firstRow.length === 0) {
        return "";
      }
      return firstRow[0] ?? "";
    }
    return arg ?? null;
  }
  #handleSpecialFunctionCall(expr, ctx, lambdaScopes) {
    const normalized = expr.name.toUpperCase();
    if (normalized === "LAMBDA" || normalized === "_XLFN.LAMBDA") {
      return this.#buildLambdaValueFromCall(expr, ctx.currentSheet, ctx, lambdaScopes);
    }
    if (normalized === "COLUMN" || normalized === "_XLFN.COLUMN") {
      return this.#evaluateColumnFunction(expr, ctx);
    }
    if (normalized === "LET" || normalized === "_XLFN.LET") {
      return this.#evaluateLetFunction(expr, ctx, lambdaScopes);
    }
    if (normalized === "SHEET" || normalized === "_XLFN.SHEET") {
      return this.#evaluateSheetFunctionFromExpr(expr, ctx);
    }
    if (normalized === "SHEETS" || normalized === "_XLFN.SHEETS") {
      return this.#evaluateSheetsFunctionFromExpr(expr, ctx);
    }
    return;
  }
  #evaluateSheetFunctionFromArgs(args2, ctx) {
    const targetNamesOrError = this.#extractSheetNamesFromArg(args2[0], ctx, true);
    if (this.#isErrorValue(targetNamesOrError)) {
      return targetNamesOrError;
    }
    const targetName = targetNamesOrError[0] ?? ctx.currentSheet ?? null;
    if (!targetName) {
      return makeScalarError("#N/A");
    }
    const sheetNumber = this.#getSheetNumberByName(targetName);
    if (sheetNumber == null) {
      return makeScalarError("#N/A");
    }
    return sheetNumber;
  }
  #evaluateSheetsFunctionFromArgs(args2, ctx) {
    if (args2.length === 0 || args2[0] === undefined) {
      return this.#getWorksheetCount();
    }
    const targetNamesOrError = this.#extractSheetNamesFromArg(args2[0], ctx, false);
    if (this.#isErrorValue(targetNamesOrError)) {
      return targetNamesOrError;
    }
    if (targetNamesOrError.length === 0) {
      return makeScalarError("#REF!");
    }
    const unique = new Set(targetNamesOrError);
    return unique.size;
  }
  #extractSheetNamesFromArg(arg, ctx, treatUndefinedAsCurrent) {
    if (arg === undefined) {
      return treatUndefinedAsCurrent && ctx.currentSheet ? [ctx.currentSheet] : [];
    }
    const metadataSheets = this.#extractSheetNamesFromMetadata(arg);
    if (metadataSheets.length > 0) {
      return metadataSheets;
    }
    const scalar = this.#extractScalarFromArg(arg);
    if (scalar === undefined) {
      return [];
    }
    if (this.#isErrorValue(scalar)) {
      return scalar;
    }
    if (scalar == null) {
      return ctx.currentSheet ? [ctx.currentSheet] : [];
    }
    if (typeof scalar === "string") {
      const normalized = this.#normalizeSheetNameToken(scalar);
      return normalized ? [normalized] : [];
    }
    if (typeof scalar === "number") {
      return makeScalarError("#N/A");
    }
    return [];
  }
  #extractSheetNamesFromMetadata(arg) {
    const matrix = this.#coerceFunctionArgMatrix(arg);
    if (!matrix) {
      return [];
    }
    const metadata = getRangeMetadata(matrix);
    if (!metadata) {
      return [];
    }
    const names = new Set;
    for (const row2 of metadata) {
      if (!row2)
        continue;
      for (const addr of row2) {
        if (addr?.sheet?.sheetName) {
          names.add(addr.sheet.sheetName);
        }
      }
    }
    return Array.from(names);
  }
  #coerceFunctionArgMatrix(arg) {
    if (Array.isArray(arg)) {
      return arg;
    }
    if (isArrayValue(arg)) {
      const arrayValue = arg;
      return arrayValue.values;
    }
    return null;
  }
  #extractScalarFromArg(arg) {
    if (Array.isArray(arg)) {
      return arg[0]?.[0];
    }
    if (isArrayValue(arg)) {
      const arrayValue = arg;
      return arrayValue.values[0]?.[0];
    }
    return arg;
  }
  #normalizeSheetNameToken(input) {
    let token = input.trim();
    if (!token) {
      return null;
    }
    const exclamationIndex = token.indexOf("!");
    if (exclamationIndex >= 0) {
      token = token.slice(0, exclamationIndex);
    }
    if (token.startsWith("'") && token.endsWith("'")) {
      token = token.slice(1, -1).replace(/''/g, "'");
    }
    return token.trim() || null;
  }
  #getWorksheetCount() {
    let count3 = 0;
    for (const _ of this.#worksheets) {
      count3 += 1;
    }
    return count3;
  }
  #callFunctionWithDefinedNames(name2, args2, ctx, lambdaScopes) {
    const normalizedName = this.#definedNames.normalizeName(name2);
    if (!normalizedName) {
      return;
    }
    const entry = this.#definedNames.lookup(normalizedName, ctx.currentSheet);
    if (!entry) {
      return;
    }
    const parsed = this.#definedNames.parseEntry(entry);
    if (!entry.isLambda || !parsed || parsed.errors.length > 0) {
      return;
    }
    if (parsed.expr.kind !== "FunctionCall") {
      return makeScalarError("#NAME?");
    }
    const lambda = this.#buildLambdaValueFromCall(parsed.expr, entry.scopeSheet ?? ctx.currentSheet, ctx, lambdaScopes);
    if (this.#isLambdaValue(lambda)) {
      return lambda.invoke(args2, ctx);
    }
    return lambda;
  }
  #evaluateColumnFunction(expr, ctx) {
    const argExpr = expr.args[0];
    if (!argExpr || argExpr.kind === "MissingArg") {
      const hostColumn = ctx.activeCellAddress?.col;
      if (hostColumn == null) {
        return makeScalarError("#VALUE!");
      }
      return hostColumn;
    }
    if (argExpr.kind !== "RangeRef") {
      return makeScalarError("#VALUE!");
    }
    const columnIndex2 = this.#rangeReferenceAnalysis.getColumnIndex(argExpr.ref, {
      fallbackSheet: ctx.currentSheet,
      activeCellAddress: ctx.activeCellAddress
    });
    if (columnIndex2 == null) {
      return makeScalarError("#VALUE!");
    }
    return columnIndex2;
  }
  #evaluateSheetFunctionFromExpr(expr, ctx) {
    const argExpr = expr.args[0];
    const resolved = argExpr ? this.#resolveSheetNameFromExpr(argExpr, ctx, ctx.currentSheet) : ctx.currentSheet ?? null;
    if (resolved == null) {
      return makeScalarError("#N/A");
    }
    if (this.#isErrorValue(resolved)) {
      return resolved;
    }
    const sheetNumber = this.#getSheetNumberByName(resolved);
    return sheetNumber ?? makeScalarError("#N/A");
  }
  #evaluateSheetsFunctionFromExpr(expr, ctx) {
    const argExpr = expr.args[0];
    if (!argExpr || argExpr.kind === "MissingArg") {
      return this.#worksheets.getSheetCount();
    }
    if (argExpr.kind === "RangeRef") {
      const span = this.#rangeReferenceAnalysis.getSheetSpan(argExpr.ref, {
        fallbackSheet: ctx.currentSheet,
        activeCellAddress: ctx.activeCellAddress
      });
      if (span == null) {
        return makeScalarError("#N/A");
      }
      if (this.#isErrorValue(span)) {
        return span;
      }
      const count3 = this.#countSheetsBetween(span.startSheet, span.endSheet ?? span.startSheet);
      return count3 ?? makeScalarError("#N/A");
    }
    const resolved = this.#resolveSheetNameFromExpr(argExpr, ctx, ctx.currentSheet);
    if (resolved == null) {
      return makeScalarError("#N/A");
    }
    if (this.#isErrorValue(resolved)) {
      return resolved;
    }
    return this.#countSheetsBetween(resolved, resolved) ?? makeScalarError("#N/A");
  }
  #evaluateLetFunction(expr, ctx, lambdaScopes) {
    const argCount = expr.args.length;
    if (argCount < 3 || argCount % 2 === 0) {
      return makeScalarError("#VALUE!");
    }
    const frame = new Map;
    lambdaScopes.push(frame);
    try {
      let index2 = 0;
      while (index2 + 2 < argCount) {
        const nameExpr = expr.args[index2];
        const valueExpr = expr.args[index2 + 1];
        if (!nameExpr || !valueExpr) {
          return makeScalarError("#VALUE!");
        }
        const nameResult = this.#extractLetName(nameExpr);
        if (nameResult == null) {
          return makeScalarError("#VALUE!");
        }
        if (this.#isErrorValue(nameResult)) {
          return nameResult;
        }
        const { primary, alias } = nameResult;
        const valueResult = evaluateExpr(valueExpr, ctx);
        if (this.#isErrorValue(valueResult)) {
          return valueResult;
        }
        frame.set(primary, valueResult);
        if (alias && alias !== primary) {
          frame.set(alias, valueResult);
        }
        index2 += 2;
      }
      const calculationExpr = expr.args[index2];
      if (!calculationExpr) {
        return makeScalarError("#VALUE!");
      }
      return evaluateExpr(calculationExpr, ctx);
    } finally {
      lambdaScopes.pop();
    }
  }
  #resolveSheetNameFromExpr(expr, ctx, fallbackSheet) {
    if (expr.kind === "RangeRef") {
      return this.#rangeReferenceAnalysis.getSheetName(expr.ref, {
        fallbackSheet,
        activeCellAddress: ctx.activeCellAddress
      });
    }
    const value2 = evaluateExpr(expr, ctx);
    return this.#resolveSheetNameFromValue(value2);
  }
  #resolveSheetNameFromValue(value2) {
    if (this.#isErrorValue(value2)) {
      return value2;
    }
    if (isArrayValue(value2)) {
      const first = value2.values[0]?.[0] ?? null;
      return this.#resolveSheetNameFromValue(first);
    }
    if (value2 == null) {
      return null;
    }
    if (typeof value2 === "string") {
      const trimmed = value2.trim();
      return trimmed === "" ? null : trimmed;
    }
    if (typeof value2 === "number") {
      if (!Number.isFinite(value2)) {
        return null;
      }
      const position2 = Math.trunc(value2) - 1;
      if (position2 < 0) {
        return null;
      }
      return this.#worksheets.getSheetNameByIndex(position2);
    }
    return null;
  }
  #getSheetNumberByName(name2) {
    if (!name2) {
      return null;
    }
    const normalized = name2.trim();
    if (!normalized) {
      return null;
    }
    const index2 = this.#worksheets.getSheetIndex(normalized);
    if (index2 == null) {
      return null;
    }
    return index2 + 1;
  }
  #countSheetsBetween(startSheet, endSheet) {
    const normalizedStart = startSheet.trim();
    if (!normalizedStart) {
      return null;
    }
    const startIndex = this.#worksheets.getSheetIndex(normalizedStart);
    if (startIndex == null) {
      return null;
    }
    if (!endSheet) {
      return 1;
    }
    const normalizedEnd = endSheet.trim();
    if (!normalizedEnd) {
      return null;
    }
    const endIndex = this.#worksheets.getSheetIndex(normalizedEnd);
    if (endIndex == null) {
      return null;
    }
    return Math.abs(endIndex - startIndex) + 1;
  }
  #extractLetName(expr) {
    let rawName = null;
    if (expr.kind === "RangeRef" && expr.ref.kind === "Named") {
      rawName = expr.ref.name;
    } else if (expr.kind === "StringLiteral") {
      rawName = expr.value;
    } else {
      return makeScalarError("#VALUE!");
    }
    if (!rawName) {
      return null;
    }
    const normalized = this.#definedNames.normalizeName(rawName);
    if (!normalized) {
      return null;
    }
    const cleaned = rawName.replace(/^_XLPM\./i, "");
    const alias = this.#definedNames.normalizeName(cleaned);
    if (alias && alias !== normalized) {
      return { primary: normalized, alias };
    }
    return { primary: normalized };
  }
  #buildLambdaValueFromCall(expr, scopeSheet, ctx, lambdaScopes) {
    if (expr.args.length === 0) {
      return makeScalarError("#VALUE!");
    }
    const paramExprs = expr.args.slice(0, -1);
    const body = expr.args[expr.args.length - 1];
    const parameterNames = [];
    for (const arg of paramExprs) {
      const paramName = this.#extractLambdaParameterName(arg);
      if (!paramName) {
        return makeScalarError("#VALUE!");
      }
      parameterNames.push(paramName);
    }
    const lambda = {
      kind: "Lambda",
      invoke: (providedArgs, invocationCtx) => this.#invokeLambdaBody(parameterNames, body, providedArgs, invocationCtx, scopeSheet ?? ctx.currentSheet, lambdaScopes)
    };
    return lambda;
  }
  #extractLambdaParameterName(expr) {
    if (expr.kind === "RangeRef" && expr.ref.kind === "Named") {
      return this.#definedNames.normalizeName(expr.ref.name);
    }
    if (expr.kind === "StringLiteral") {
      return this.#definedNames.normalizeName(expr.value);
    }
    return null;
  }
  #invokeLambdaBody(parameterNames, body, args2, ctx, scopeSheet, lambdaScopes) {
    if (args2.length !== parameterNames.length) {
      return makeScalarError("#VALUE!");
    }
    const frame = new Map;
    for (let i = 0;i < parameterNames.length; i += 1) {
      frame.set(parameterNames[i], args2[i]);
    }
    lambdaScopes.push(frame);
    const previousSheet = ctx.currentSheet;
    if (scopeSheet) {
      ctx.currentSheet = scopeSheet;
    }
    try {
      return evaluateExpr(body, ctx);
    } finally {
      if (scopeSheet) {
        ctx.currentSheet = previousSheet;
      }
      lambdaScopes.pop();
    }
  }
  #expandNamedReferenceInternal(name2, fallbackSheet, visitedNames, activeCellAddress) {
    const normalizedName = this.#definedNames.normalizeName(name2);
    if (!normalizedName) {
      return [];
    }
    const guardKey = `${fallbackSheet ?? ""}::${normalizedName}`;
    if (visitedNames.has(guardKey)) {
      return [];
    }
    visitedNames.add(guardKey);
    const entry = this.#definedNames.lookup(normalizedName, fallbackSheet);
    if (!entry) {
      const tableAddresses = this.#structuredReferenceRuntime.expand({ tableName: normalizedName, section: "All" }, { fallbackSheet });
      visitedNames.delete(guardKey);
      return tableAddresses;
    }
    const parsed = this.#definedNames.parseEntry(entry);
    if (!parsed || parsed.errors.length > 0) {
      visitedNames.delete(guardKey);
      return [];
    }
    const scopeSheet = entry.scopeSheet ?? fallbackSheet;
    let addresses = [];
    if (parsed.expr.kind === "RangeRef") {
      addresses = this.#expandRangeInternal(parsed.expr.ref, scopeSheet, visitedNames, activeCellAddress);
    } else {
      for (const rangeRef of collectRangeRefs(parsed.expr)) {
        addresses = addresses.concat(this.#expandRangeInternal(rangeRef, scopeSheet, visitedNames, activeCellAddress));
      }
    }
    visitedNames.delete(guardKey);
    return addresses;
  }
  #readValuesForRangeRef(ref2, ctx, fallbackSheet, lambdaScopes, resolvingNames) {
    switch (ref2.kind) {
      case "Cell": {
        const key = ctx.cellAddressToKey(this.#normalizeCellAddress(ref2.addr, fallbackSheet));
        if (!key) {
          return [[makeScalarError("#REF!")]];
        }
        return [[ctx.getCellValue(key)]];
      }
      case "Range": {
        const startRow = Math.min(ref2.start.row, ref2.end.row);
        const endRow = Math.max(ref2.start.row, ref2.end.row);
        const startCol = Math.min(ref2.start.col, ref2.end.col);
        const endCol = Math.max(ref2.start.col, ref2.end.col);
        const sheetName = ref2.start.sheet?.sheetName ?? ref2.end.sheet?.sheetName ?? fallbackSheet;
        const rows = [];
        for (let row2 = startRow;row2 <= endRow; row2 += 1) {
          const rowValues = [];
          for (let col = startCol;col <= endCol; col += 1) {
            const key = ctx.cellAddressToKey({
              sheet: { sheetName },
              row: row2,
              col,
              absRow: false,
              absCol: false
            });
            rowValues.push(key ? ctx.getCellValue(key) : makeScalarError("#REF!"));
          }
          rows.push(rowValues);
        }
        return rows;
      }
      case "WholeColumn": {
        const sheetName = ref2.sheet?.sheetName ?? fallbackSheet;
        const bounds = ctx.getColumnExtent?.(sheetName, ref2.col);
        if (!bounds) {
          return [];
        }
        const values2 = [];
        for (let row2 = bounds.startRow;row2 <= bounds.endRow; row2 += 1) {
          const key = ctx.cellAddressToKey({
            sheet: { sheetName },
            row: row2,
            col: ref2.col,
            absRow: false,
            absCol: false
          });
          values2.push([key ? ctx.getCellValue(key) : makeScalarError("#REF!")]);
        }
        return values2;
      }
      case "WholeRow": {
        const sheetName = ref2.sheet?.sheetName ?? fallbackSheet;
        const bounds = ctx.getRowExtent?.(sheetName, ref2.row);
        if (!bounds) {
          return [];
        }
        const rowValues = [];
        for (let col = bounds.startCol;col <= bounds.endCol; col += 1) {
          const key = ctx.cellAddressToKey({
            sheet: { sheetName },
            row: ref2.row,
            col,
            absRow: false,
            absCol: false
          });
          rowValues.push(key ? ctx.getCellValue(key) : makeScalarError("#REF!"));
        }
        return [rowValues];
      }
      case "Spill":
        return this.#readValuesForRangeRef(ref2.base, ctx, fallbackSheet, lambdaScopes, resolvingNames);
      case "Structured":
        return this.#structuredReferenceRuntime.readValues(ref2.reference, ctx, fallbackSheet);
      case "Named": {
        const resolved = this.#resolveNamedReferenceInternal(ref2.name, "range", ctx, lambdaScopes, resolvingNames, ref2.sheet?.sheetName ?? fallbackSheet);
        if (!resolved) {
          return [[makeScalarError("#NAME?")]];
        }
        if (Array.isArray(resolved)) {
          return resolved;
        }
        if (this.#isErrorValue(resolved)) {
          return [[resolved]];
        }
        if (this.#isLambdaValue(resolved)) {
          return [[makeScalarError("#VALUE!")]];
        }
        return [[resolved]];
      }
      default:
        return [[makeScalarError("#VALUE!")]];
    }
  }
  #invalidateCalcState() {
    if (!this.#calcState) {
      return;
    }
    this.#calcState.initialized = false;
    this.#initializeCalcState(this.#calcState);
    this.#calcState.initialized = true;
  }
  #buildTraceNode(key, state, visiting) {
    if (visiting.has(key)) {
      return this.#makeTraceErrorNode(key, CIRCULAR_TRACE_CODE);
    }
    visiting.add(key);
    const { sheetName, address } = splitCellKey(key);
    const worksheet = this.#getWorksheetByName(sheetName);
    if (!worksheet) {
      visiting.delete(key);
      return this.#makeTraceErrorNode(key, TRACE_FAILURE_CODE);
    }
    const snapshot = state.evaluations.get(key);
    const value2 = snapshot?.value ?? this.#readScalarValue(key);
    const formula = snapshot?.formula ?? this.#getCellFormulaText(worksheet, address);
    const node2 = {
      cell: key,
      sheetName,
      address,
      formula,
      value: value2,
      params: []
    };
    if (this.#isErrorValue(value2)) {
      node2.error = value2.code;
    } else if (value2 instanceof Error) {
      node2.error = value2.message ?? "#ERROR!";
    }
    const precedentSource = snapshot?.precedents ?? Array.from(state.graph.precedents.get(key) ?? []);
    const precedentKeys = precedentSource.filter((candidate) => !isStructuralDependencyKey(candidate));
    for (const precedent of precedentKeys) {
      if (precedent === key) {
        continue;
      }
      const child = this.#buildTraceNode(precedent, state, visiting);
      node2.params.push(child);
      if (child.error === TRACE_FAILURE_CODE && node2.error !== TRACE_FAILURE_CODE) {
        node2.value = child.value;
        node2.error = TRACE_FAILURE_CODE;
      }
    }
    visiting.delete(key);
    return node2;
  }
  #getCellFormulaText(worksheet, address) {
    const coord = this.#addressToIndices(address);
    if (!coord) {
      return null;
    }
    const cell = worksheet.__getCell(coord.row, coord.col);
    return this.#normalizeFormulaText(cell?.formula) ?? cell?.formula ?? null;
  }
  #makeTraceErrorNode(key, code3) {
    const { sheetName, address } = splitCellKey(key);
    const value2 = makeScalarError(code3);
    return {
      cell: key,
      sheetName,
      address,
      formula: null,
      value: value2,
      params: [],
      error: code3
    };
  }
  #normalizeFormulaText(text7) {
    if (!text7) {
      return null;
    }
    const trimmed = text7.trim();
    if (!trimmed) {
      return null;
    }
    const normalized = trimmed.startsWith("=") ? trimmed : `=${trimmed}`;
    return this.#sanitizeEmbeddedFormulaEquals(normalized);
  }
  #getCellRefContext(sheetName) {
    const cached2 = this.#cellRefContexts.get(sheetName);
    if (cached2) {
      return cached2;
    }
    const context = {
      cellAddressToKey: (addr) => this.#cellAddressToKey(addr, sheetName),
      expandRange: (ref2, activeCellAddress) => this.#expandRange(ref2, sheetName, activeCellAddress),
      columnDependencyKey: (targetSheet, col) => makeColumnDependencyKey(targetSheet, col),
      rowDependencyKey: (targetSheet, row2) => makeRowDependencyKey(targetSheet, row2)
    };
    this.#cellRefContexts.set(sheetName, context);
    return context;
  }
  #cellAddressToKey(addr, fallbackSheet) {
    const sheetName = addr.sheet?.sheetName ?? fallbackSheet;
    const col = columnNumberToLabel(addr.col);
    return makeCellKey(sheetName, `${col}${addr.row}`);
  }
  #expandRange(ref2, fallbackSheet, activeCellAddress) {
    return this.#expandRangeInternal(ref2, fallbackSheet, new Set, activeCellAddress);
  }
  #expandRangeInternal(ref2, fallbackSheet, visitedNames, activeCellAddress) {
    switch (ref2.kind) {
      case "Cell":
        return [this.#normalizeCellAddress(ref2.addr, fallbackSheet)];
      case "Range": {
        const start = this.#normalizeCellAddress(ref2.start, fallbackSheet);
        const end = this.#normalizeCellAddress(ref2.end, fallbackSheet);
        const sheetName = start.sheet?.sheetName ?? end.sheet?.sheetName ?? fallbackSheet;
        const cells = [];
        const startRow = Math.min(start.row, end.row);
        const endRow = Math.max(start.row, end.row);
        const startCol = Math.min(start.col, end.col);
        const endCol = Math.max(start.col, end.col);
        for (let row2 = startRow;row2 <= endRow; row2 += 1) {
          for (let col = startCol;col <= endCol; col += 1) {
            cells.push({
              sheet: { sheetName },
              row: row2,
              col,
              absRow: false,
              absCol: false
            });
          }
        }
        return cells;
      }
      case "WholeColumn": {
        const sheetName = ref2.sheet?.sheetName ?? fallbackSheet;
        if (!sheetName) {
          return [];
        }
        const worksheet = this.#getWorksheetByName(sheetName);
        if (!worksheet) {
          return [];
        }
        const extent2 = worksheet.__getColumnExtent(ref2.col - 1);
        if (!extent2) {
          return [];
        }
        const cells = [];
        for (let row2 = extent2.minRow;row2 <= extent2.maxRow; row2 += 1) {
          cells.push({
            sheet: { sheetName },
            row: row2 + 1,
            col: ref2.col,
            absRow: false,
            absCol: false
          });
        }
        return cells;
      }
      case "WholeRow": {
        const sheetName = ref2.sheet?.sheetName ?? fallbackSheet;
        if (!sheetName) {
          return [];
        }
        const worksheet = this.#getWorksheetByName(sheetName);
        if (!worksheet) {
          return [];
        }
        const extent2 = worksheet.__getRowExtent(ref2.row - 1);
        if (!extent2) {
          return [];
        }
        const cells = [];
        for (let col = extent2.minCol;col <= extent2.maxCol; col += 1) {
          cells.push({
            sheet: { sheetName },
            row: ref2.row,
            col: col + 1,
            absRow: false,
            absCol: false
          });
        }
        return cells;
      }
      case "Spill":
        return this.#expandRangeInternal(ref2.base, fallbackSheet, visitedNames, activeCellAddress);
      case "Structured":
        return this.#structuredReferenceRuntime.expand(ref2.reference, {
          fallbackSheet,
          activeCellAddress
        });
      case "Named":
        return this.#expandNamedReferenceInternal(ref2.name, ref2.sheet?.sheetName ?? fallbackSheet, visitedNames, activeCellAddress);
      default:
        return [];
    }
  }
  #normalizeCellAddress(addr, fallbackSheet) {
    return {
      sheet: { sheetName: addr.sheet?.sheetName ?? fallbackSheet },
      row: addr.row,
      col: addr.col,
      absRow: addr.absRow,
      absCol: addr.absCol
    };
  }
  #markCellDirty(key, state) {
    state.dirty.add(key);
    this.#markDependentsDirty(key, state);
  }
  #markDependentsDirty(key, state) {
    const queue = [key];
    const visited = new Set;
    while (queue.length > 0) {
      const current = queue.shift();
      const dependents = state.graph.dependents.get(current);
      if (!dependents) {
        continue;
      }
      for (const dependent of dependents) {
        if (visited.has(dependent)) {
          continue;
        }
        visited.add(dependent);
        state.dirty.add(dependent);
        queue.push(dependent);
      }
    }
  }
  #markRowAndColumnDependentsDirty(sheetName, coord, state) {
    const columnKey = makeColumnDependencyKey(sheetName, coord.col + 1);
    const rowKey = makeRowDependencyKey(sheetName, coord.row + 1);
    this.#markDependentsDirty(columnKey, state);
    this.#markDependentsDirty(rowKey, state);
  }
  #removeFormula(key, state) {
    state.parsed.delete(key);
    this.#removeDependenciesForCell(state.graph, key);
    state.dirty.delete(key);
    this.#recomputeVolatilityFrom([key], state);
    state.evaluations.delete(key);
  }
  #removeDependenciesForCell(graph, key) {
    const precedents = graph.precedents.get(key);
    if (!precedents) {
      return;
    }
    for (const precedent of precedents) {
      const dependents = graph.dependents.get(precedent);
      if (dependents) {
        dependents.delete(key);
        if (dependents.size === 0) {
          graph.dependents.delete(precedent);
        }
      }
    }
    graph.precedents.delete(key);
  }
  #recomputeVolatilityFrom(seeds, state) {
    const queue = [];
    const pending = new Set;
    for (const seed of seeds) {
      if (seed) {
        queue.push(seed);
        pending.add(seed);
      }
    }
    while (queue.length > 0) {
      const current = queue.shift();
      pending.delete(current);
      if (!state.parsed.has(current)) {
        const removed = state.volatility.delete(current);
        if (removed) {
          const dependents = state.graph.dependents.get(current);
          if (dependents) {
            for (const dependent of dependents) {
              if (!pending.has(dependent)) {
                queue.push(dependent);
                pending.add(dependent);
              }
            }
          }
        }
        continue;
      }
      const nextInfo = this.#computeVolatilityInfo(current, state);
      const prevInfo = state.volatility.get(current);
      if (!prevInfo || !this.#volatilityInfoEquals(prevInfo, nextInfo)) {
        state.volatility.set(current, nextInfo);
        const dependents = state.graph.dependents.get(current);
        if (dependents) {
          for (const dependent of dependents) {
            if (!pending.has(dependent)) {
              queue.push(dependent);
              pending.add(dependent);
            }
          }
        }
      }
    }
  }
  #computeVolatilityInfo(key, state) {
    const parsed = state.parsed.get(key);
    const defaultInfo = {
      isVolatileFormula: false,
      hasVolatileChain: false,
      chain: []
    };
    if (!parsed) {
      return defaultInfo;
    }
    const volatileFormula = exprContainsVolatile(parsed.expr);
    if (volatileFormula) {
      return {
        isVolatileFormula: true,
        hasVolatileChain: true,
        head: key,
        chain: [key]
      };
    }
    const precedents = state.graph.precedents.get(key);
    if (precedents) {
      for (const precedent of precedents) {
        const precedentInfo = state.volatility.get(precedent);
        if (precedentInfo && precedentInfo.hasVolatileChain && !precedentInfo.chain.includes(key)) {
          return {
            isVolatileFormula: false,
            hasVolatileChain: true,
            head: precedentInfo.head ?? precedentInfo.chain[0] ?? precedent,
            chain: [...precedentInfo.chain, key]
          };
        }
      }
    }
    return defaultInfo;
  }
  #volatilityInfoEquals(left, right) {
    if (left.isVolatileFormula !== right.isVolatileFormula) {
      return false;
    }
    if (left.hasVolatileChain !== right.hasVolatileChain) {
      return false;
    }
    if ((left.head ?? "") !== (right.head ?? "")) {
      return false;
    }
    if (left.chain.length !== right.chain.length) {
      return false;
    }
    for (let i = 0;i < left.chain.length; i += 1) {
      if (left.chain[i] !== right.chain[i]) {
        return false;
      }
    }
    return true;
  }
  #createEvaluationContext(sheetName, computed, state, activeCellKey) {
    const lambdaScopes = [];
    const resolvingDefinedNames = new Set;
    const activeCellAddress = activeCellKey ? this.#cellKeyToAddress(activeCellKey) : null;
    const context = {
      currentSheet: sheetName,
      activeCellAddress: activeCellAddress ?? undefined,
      cellAddressToKey: (addr) => this.#cellAddressToKey(addr, sheetName),
      getCellValue: (key) => {
        if (computed.has(key)) {
          return computed.get(key);
        }
        const rawValue = this.#readScalarValue(key);
        return this.#coerceReferencedBlankValue(key, sheetName, rawValue, state);
      },
      callFunction: () => makeScalarError("#NAME?"),
      resolveNamedReference: (name2, mode, sheetHint) => this.#resolveNamedReferenceInternal(name2, mode, context, lambdaScopes, resolvingDefinedNames, sheetHint),
      resolveStructuredReference: (reference) => this.#structuredReferenceRuntime.readValues(reference, context, context.currentSheet ?? sheetName),
      handleFunctionCall: (expr) => this.#handleSpecialFunctionCall(expr, context, lambdaScopes),
      getColumnExtent: (targetSheet, col) => this.#getColumnExtent(targetSheet, col),
      getRowExtent: (targetSheet, row2) => this.#getRowExtent(targetSheet, row2),
      getCellFormulaType: state ? (addr) => this.#getFormulaKindForAddress(addr, sheetName, state) : undefined
    };
    context.callFunction = (name2, args2) => {
      return withEvaluationContext(context, () => {
        const handled = this.#callFunctionWithDefinedNames(name2, args2, context, lambdaScopes);
        if (handled !== undefined) {
          return handled;
        }
        const normalized = name2?.toUpperCase();
        if (normalized === "SHEET" || normalized === "_XLFN.SHEET") {
          return this.#evaluateSheetFunctionFromArgs(args2, context);
        }
        if (normalized === "SHEETS" || normalized === "_XLFN.SHEETS") {
          return this.#evaluateSheetsFunctionFromArgs(args2, context);
        }
        const result = callSpreadsheetFunction(name2, args2);
        return result;
      });
    };
    return context;
  }
  #readScalarValue(key) {
    const { sheetName, address } = splitCellKey(key);
    const worksheet = this.#getWorksheetByName(sheetName);
    if (!worksheet) {
      return makeScalarError("#REF!");
    }
    const coord = this.#addressToIndices(address);
    if (!coord) {
      return makeScalarError("#REF!");
    }
    const fromRaw = worksheet.__getRawValue(coord.row, coord.col);
    if (fromRaw !== undefined) {
      return this.#coerceRawToScalarValue(fromRaw, false);
    }
    const cell = this.#getCell(worksheet, coord.row, coord.col);
    if (!cell) {
      return null;
    }
    const deserialized = this.#deserializeProtoRawValue(cell);
    worksheet.__setRawValue(coord.row, coord.col, deserialized);
    worksheet.__setExcelRawValue(coord.row, coord.col, cell.value ?? null);
    const coerced = this.#coerceRawToScalarValue(deserialized, false);
    if (coerced !== null) {
      return coerced;
    }
    const state = this.#ensureCalcState();
    if (state.parsed.has(key)) {
      return this.#evaluateCellOnDemand(key, state);
    }
    return coerced;
  }
  #getColumnExtent(sheetName, col) {
    const worksheet = this.#getWorksheetByName(sheetName);
    if (!worksheet) {
      return null;
    }
    const extent2 = worksheet.__getColumnExtent(col - 1);
    if (!extent2) {
      return null;
    }
    return {
      startRow: extent2.minRow + 1,
      endRow: extent2.maxRow + 1
    };
  }
  #getRowExtent(sheetName, row2) {
    const worksheet = this.#getWorksheetByName(sheetName);
    if (!worksheet) {
      return null;
    }
    const extent2 = worksheet.__getRowExtent(row2 - 1);
    if (!extent2) {
      return null;
    }
    return {
      startCol: extent2.minCol + 1,
      endCol: extent2.maxCol + 1
    };
  }
  #writeComputedValue(key, value2) {
    const { sheetName, address } = splitCellKey(key);
    const worksheet = this.#getWorksheetByName(sheetName);
    if (!worksheet) {
      return;
    }
    const coord = this.#addressToIndices(address);
    if (!coord) {
      return;
    }
    const cell = this.#ensureCell(worksheet, coord.row, coord.col);
    const previousRaw = worksheet.__getRawValue(coord.row, coord.col);
    const sanitizedValue = this.#isLambdaValue(value2) ? makeScalarError("#VALUE!") : value2;
    const normalizedInput = sanitizedValue == null ? 0 : sanitizedValue;
    const normalizedRaw = this.#normalizeRawValueForCell(normalizedInput, previousRaw);
    worksheet.__setRawValue(coord.row, coord.col, normalizedRaw);
    this.#applyCellDisplayFromRaw(cell, normalizedRaw);
  }
  #recordEvaluationSnapshot(key, value2, state, options) {
    let formula = null;
    if (options?.formulaText !== undefined) {
      formula = options.formulaText ?? null;
    } else if (options?.worksheet && options.coord) {
      const cell = options.worksheet.__getCell(options.coord.row, options.coord.col);
      formula = this.#normalizeFormulaText(cell?.formula) ?? cell?.formula ?? null;
    }
    let precedents;
    if (options?.precedents) {
      precedents = filterDependencyKeys(options.precedents);
    } else {
      const fromGraph = state.graph.precedents.get(key);
      precedents = fromGraph ? filterDependencyKeys(fromGraph) : [];
    }
    const snapshotValue = value2 == null ? 0 : value2;
    state.evaluations.set(key, {
      value: snapshotValue,
      formula,
      precedents
    });
  }
  #evaluateDataTables(state) {
    this.#dataTableCells.clear();
    for (const worksheet of this.#worksheets) {
      const sheetName = worksheet.name;
      if (!sheetName) {
        continue;
      }
      const definitions = worksheet.__getDataTables();
      for (const def of definitions) {
        this.#evaluateDataTable(sheetName, def, state);
      }
    }
  }
  #evaluateDataTable(sheetName, def, state) {
    const bounds = def.range;
    const rows = bounds.endRow - bounds.startRow + 1;
    const cols = bounds.endCol - bounds.startCol + 1;
    const formulaRow = bounds.startRow - 1;
    const formulaCol = bounds.startCol - 1;
    if (formulaRow < 0 || formulaCol < 0) {
      return;
    }
    const formulaAddress = makeCellAddress(formulaRow, formulaCol);
    const formulaKey = makeCellKey(sheetName, formulaAddress);
    const rowInputValues = def.rowInput ? this.#readRowHeaderValues(sheetName, def) : undefined;
    const columnInputValues = def.columnInput ? this.#readColumnHeaderValues(sheetName, def) : undefined;
    const rowInputKey = def.rowInput ? makeCellKey(sheetName, def.rowInput) : null;
    const columnInputKey = def.columnInput ? makeCellKey(sheetName, def.columnInput) : null;
    const masterAddress = `${sheetName}!${makeCellAddress(def.anchor.row, def.anchor.col)}`;
    for (let r = 0;r < rows; r += 1) {
      for (let c = 0;c < cols; c += 1) {
        const overrides = new Map;
        if (rowInputKey && rowInputValues) {
          overrides.set(rowInputKey, rowInputValues[c] ?? null);
        }
        if (columnInputKey && columnInputValues) {
          overrides.set(columnInputKey, columnInputValues[r] ?? null);
        }
        let value2 = this.#evaluateFormulaWithOverrides(formulaKey, overrides, state, sheetName);
        if (typeof value2 === "number") {
          value2 = this.#roundDataTableNumber(value2);
        }
        const targetRow = bounds.startRow + r;
        const targetCol = bounds.startCol + c;
        const address = makeCellAddress(targetRow, targetCol);
        const cellKey = makeCellKey(sheetName, address);
        this.#writeComputedValue(cellKey, value2);
        this.#dataTableCells.set(cellKey, {
          display: def.displayFormula,
          master: masterAddress,
          ref: `${sheetName}!${def.formulaRef}`,
          rowInput: def.rowInput,
          columnInput: def.columnInput
        });
      }
    }
  }
  #evaluateFormulaWithOverrides(key, overrides, state, sheetName) {
    const parsed = state.parsed.get(key);
    if (!parsed) {
      return this.#readScalarValue(key);
    }
    const computed = new Map(overrides);
    const visiting = new Set;
    const ctx = this.#createEvaluationContext(sheetName, computed, state, key);
    const evaluateParsedCell = (targetKey, expr) => {
      if (visiting.has(targetKey)) {
        return makeScalarError("#CIRC!");
      }
      visiting.add(targetKey);
      let value2 = evaluateExpr(expr, ctx);
      value2 = this.#coerceBlankRangeRefResult(expr, value2, sheetName);
      visiting.delete(targetKey);
      computed.set(targetKey, value2);
      return value2;
    };
    ctx.getCellValue = (targetKey) => {
      if (computed.has(targetKey)) {
        return computed.get(targetKey);
      }
      const parsedTarget = state.parsed.get(targetKey);
      if (parsedTarget) {
        return evaluateParsedCell(targetKey, parsedTarget.expr);
      }
      const rawValue = this.#readScalarValue(targetKey);
      return this.#coerceReferencedBlankValue(targetKey, sheetName, rawValue, state);
    };
    return evaluateParsedCell(key, parsed.expr);
  }
  #readRowHeaderValues(sheetName, def) {
    const headerRow = def.range.startRow - 1;
    const cols = def.range.endCol - def.range.startCol + 1;
    const result = [];
    if (headerRow < 0) {
      return result;
    }
    for (let c = 0;c < cols; c += 1) {
      result.push(this.#readWorksheetCellValue(sheetName, headerRow, def.range.startCol + c));
    }
    return result;
  }
  #readColumnHeaderValues(sheetName, def) {
    const headerCol = def.range.startCol - 1;
    const rows = def.range.endRow - def.range.startRow + 1;
    const result = [];
    if (headerCol < 0) {
      return result;
    }
    for (let r = 0;r < rows; r += 1) {
      result.push(this.#readWorksheetCellValue(sheetName, def.range.startRow + r, headerCol));
    }
    return result;
  }
  #readWorksheetCellValue(sheetName, rowIdx, colIdx) {
    const address = makeCellAddress(rowIdx, colIdx);
    const key = makeCellKey(sheetName, address);
    return this.#readScalarValue(key);
  }
  #roundDataTableNumber(value2) {
    const factor = 10000000000000;
    return Math.round(value2 * factor) / factor;
  }
  #applySpillResult(options) {
    if (!options.coord) {
      return;
    }
    const cleared = this.#spillManager.clear(options.key);
    if (cleared) {
      this.#clearSpillCells(cleared);
    }
    const { row: row2, col } = options.coord;
    const rows = options.arrayValue.rows || options.arrayValue.values.length;
    const cols = options.arrayValue.cols || options.arrayValue.values[0]?.length || 0;
    const cellKeys = [];
    for (let r = 0;r < rows; r += 1) {
      const keyRow = [];
      for (let c = 0;c < cols; c += 1) {
        const targetRow = row2 + r;
        const targetCol = col + c;
        const address = makeCellAddress(targetRow, targetCol);
        const cellKey = makeCellKey(options.sheetName, address);
        const rowValues = options.arrayValue.values[r];
        const rawValue = rowValues?.[c];
        const cellValue = rawValue === undefined ? null : rawValue;
        this.#writeComputedValue(cellKey, cellValue ?? null);
        keyRow.push(cellKey);
      }
      cellKeys.push(keyRow);
    }
    const ref2 = buildRangeRef({
      startRow: row2,
      startCol: col,
      endRow: row2 + rows - 1,
      endCol: col + cols - 1
    });
    this.#spillManager.setRecord({
      anchorKey: options.key,
      sheetName: options.sheetName,
      startRow: row2,
      startCol: col,
      rows,
      cols,
      ref: `${options.sheetName}!${ref2}`,
      displayFormula: this.#readDisplayFormula(options.worksheet, row2, col)
    }, cellKeys);
  }
  #clearSpillForAnchor(anchorKey) {
    const cleared = this.#spillManager.clear(anchorKey);
    if (cleared) {
      this.#clearSpillCells(cleared);
    }
  }
  #clearSpillCells(cellKeys) {
    for (const row2 of cellKeys) {
      for (const key of row2) {
        if (!key)
          continue;
        const { sheetName, address } = splitCellKey(key);
        if (!sheetName || !address)
          continue;
        const worksheet = this.#getWorksheetByName(sheetName);
        if (!worksheet)
          continue;
        const coord = this.#addressToIndices(address);
        if (!coord)
          continue;
        worksheet.__setRawValue(coord.row, coord.col, null);
        worksheet.__setExcelRawValue(coord.row, coord.col, null);
      }
    }
  }
  #readDisplayFormula(worksheet, row2, col) {
    const cell = worksheet.__getCell(row2, col);
    if (!cell?.formula) {
      return "";
    }
    const trimmed = cell.formula.trim();
    if (!trimmed) {
      return "";
    }
    const withEquals = trimmed.startsWith("=") ? trimmed : `=${trimmed}`;
    return stripCompatibilityPrefixes(withEquals);
  }
  #evaluateCellOnDemand(key, state) {
    if (this.#evaluatingCells.has(key)) {
      return makeScalarError("#CIRC!");
    }
    const parsed = state.parsed.get(key);
    if (!parsed) {
      return null;
    }
    const { sheetName } = splitCellKey(key);
    if (!sheetName) {
      return makeScalarError("#REF!");
    }
    this.#evaluatingCells.add(key);
    try {
      const computed = new Map;
      const ctx = this.#createEvaluationContext(sheetName, computed, state, key);
      let value2 = evaluateExpr(parsed.expr, ctx);
      value2 = this.#coerceBlankRangeRefResult(parsed.expr, value2, sheetName, ctx.activeCellAddress);
      computed.set(key, value2);
      this.#writeComputedValue(key, value2);
      this.#recordEvaluationSnapshot(key, value2, state);
      return value2;
    } finally {
      this.#evaluatingCells.delete(key);
    }
  }
  #coerceBlankRangeRefResult(expr, value2, fallbackSheet, activeCellAddress) {
    if (value2 != null && value2 !== "") {
      return value2;
    }
    if (expr.kind !== "RangeRef") {
      return value2;
    }
    if (!this.#rangeReferenceAnalysis.isSingleCell(expr.ref, {
      fallbackSheet,
      activeCellAddress
    })) {
      return value2;
    }
    const isBlankRef = this.#rangeReferenceAnalysis.referencesBlankCell(expr.ref, {
      fallbackSheet,
      activeCellAddress
    });
    if (!isBlankRef) {
      return value2;
    }
    return 0;
  }
  #cellAddressIsBlank(addr, fallbackSheet) {
    const normalized = this.#normalizeCellAddress(addr, fallbackSheet);
    const sheetName = normalized.sheet?.sheetName;
    if (!sheetName) {
      return false;
    }
    const worksheet = this.#getWorksheetByName(sheetName);
    if (!worksheet) {
      return false;
    }
    const rawValue = worksheet.__getRawValue(normalized.row, normalized.col);
    if (rawValue !== undefined) {
      if (rawValue === null) {
        return true;
      }
      if (rawValue === "") {
        const cell2 = worksheet.__getCell(normalized.row, normalized.col);
        const hasFormula2 = Boolean(cell2?.formula?.trim());
        const hasValue2 = cell2?.value !== undefined && cell2?.value !== null && cell2?.value !== "";
        return !hasFormula2 && !hasValue2;
      }
      return false;
    }
    const cell = worksheet.__getCell(normalized.row, normalized.col);
    if (!cell) {
      return true;
    }
    const hasFormula = Boolean(cell.formula?.trim());
    const hasValue = cell.value !== undefined && cell.value !== null && cell.value !== "";
    return !hasFormula && !hasValue;
  }
  #coerceReferencedBlankValue(key, fallbackSheet, value2, state) {
    if (value2 != null && value2 !== "") {
      return value2;
    }
    if (!state) {
      return value2;
    }
    const parsed = state.parsed.get(key);
    if (!parsed || parsed.expr.kind !== "RangeRef") {
      return value2;
    }
    const activeCellAddress = this.#cellKeyToAddress(key) ?? undefined;
    if (!this.#rangeReferenceAnalysis.isSingleCell(parsed.expr.ref, {
      fallbackSheet,
      activeCellAddress
    })) {
      return value2;
    }
    if (!this.#rangeReferenceAnalysis.referencesBlankCell(parsed.expr.ref, {
      fallbackSheet,
      activeCellAddress
    })) {
      return value2;
    }
    return 0;
  }
  #publishWorksheetTopologyToCollab() {
    if (this.#isApplyingWorksheetTopology) {
      return;
    }
    const entries = this.#worksheets.getTopologyEntries();
    if (entries.length === 0) {
      this.#refreshSheetNamesByLocalId();
      return;
    }
    const existingEntries = this.#worksheetTopologyStore.readEntries();
    if (this.#isSingleDefaultWorksheetTopology(entries) && existingEntries.length === 0) {
      this.#refreshSheetNamesByLocalId();
      return;
    }
    this.#isPublishingWorksheetTopology = true;
    try {
      this.#activateWorkbookCollabRoot();
      this.#worksheetTopologyStore.replaceEntries(entries);
      this.#refreshSheetNamesByLocalId();
    } finally {
      this.#isPublishingWorksheetTopology = false;
    }
  }
  #applyWorksheetTopologyFromCollab() {
    if (this.#isPublishingWorksheetTopology) {
      return;
    }
    const entries = this.#worksheetTopologyStore.readEntries();
    if (entries.length === 0) {
      return;
    }
    this.#isApplyingWorksheetTopology = true;
    try {
      this.#worksheets.syncTopology(entries);
      this.#refreshSheetNamesByLocalId();
    } finally {
      this.#isApplyingWorksheetTopology = false;
    }
  }
  #isSingleDefaultWorksheetTopology(entries) {
    return entries.length === 1 && entries[0]?.name === "New spreadsheet";
  }
  #queueWorksheetTopologyPublish() {
    if (this.#isApplyingCrdtUpdate) {
      return;
    }
    this.#worksheetTopologyDirty = true;
    this.#queueCollaborativePublishFlush();
  }
  #queueCollaborativePublishFlush() {
    if (this.#collabPublishQueued) {
      return;
    }
    this.#collabPublishQueued = true;
    queueMicrotask(() => {
      this.#flushPendingCollaborativePublishes();
    });
  }
  #flushPendingCollaborativePublishes() {
    this.#collabPublishQueued = false;
    if (this.#isApplyingCrdtUpdate) {
      return;
    }
    if (!this.#workbookCollabDirty && !this.#worksheetTopologyDirty && this.#dirtyWorksheetSheetIds.size === 0) {
      return;
    }
    const publishWorkbookState = this.#workbookCollabDirty;
    const publishWorksheetTopology = this.#worksheetTopologyDirty;
    const dirtyWorksheetSheetIds = new Set(this.#dirtyWorksheetSheetIds);
    this.#workbookCollabDirty = false;
    this.#worksheetTopologyDirty = false;
    this.#dirtyWorksheetSheetIds.clear();
    this.runLocalCollabTransaction(() => {
      if (publishWorksheetTopology) {
        this.#publishWorksheetTopologyToCollab();
      }
      if (publishWorkbookState) {
        this.#activateWorkbookCollabRoot();
        this.#collabState.activate();
        this.#collabState.flushFromOwner();
      }
      for (const sheetId of dirtyWorksheetSheetIds) {
        const worksheet = this.__getWorksheetBySheetId(sheetId);
        if (!worksheet) {
          continue;
        }
        worksheet.flushCollaborativeState();
      }
    });
  }
  #activateWorkbookCollabRoot() {
    activateWorkbookCollabRoot({
      root: getWorkbookCollabRoot(this.#yDoc),
      runLocalTransaction: (fn) => this.runLocalCollabTransaction(fn)
    });
  }
  #throwIfCrdtDocIsNotEmpty(methodName) {
    if (!this.#hasCollaborativeContent()) {
      return;
    }
    throw new Error(`${methodName} requires an empty collaborative document.`);
  }
  #hasCollaborativeContent() {
    return decodeUpdateV2(encodeStateAsUpdateV2(this.#yDoc)).structs.length > 0;
  }
  #addressToIndices(address) {
    return getAddressIndices(address);
  }
  #runCellInputTransaction(origin, fn) {
    if (this.#cellInputTransactionDepth > 0) {
      return fn();
    }
    this.#cellInputTransactionDepth += 1;
    const previousOrigin = this.#cellInputOrigin;
    this.#cellInputOrigin = origin;
    try {
      let result;
      this.#yDoc.transact(() => {
        result = fn();
      }, origin);
      return result;
    } finally {
      this.#cellInputOrigin = previousOrigin;
      this.#cellInputTransactionDepth -= 1;
    }
  }
  #getWorksheetByName(name2) {
    const worksheet = this.#worksheets.getItemOrNullObject(name2);
    return worksheet.isNullObject ? undefined : worksheet;
  }
  #getCell(worksheet, rowIdx, colIdx) {
    return worksheet.__getCell(rowIdx, colIdx);
  }
  #ensureCell(worksheet, rowIdx, colIdx) {
    return worksheet.__getOrCreateCell(rowIdx, colIdx);
  }
  #setCellError(key, code3) {
    this.#writeComputedValue(key, makeScalarError(code3));
  }
  #isErrorValue(value2) {
    return typeof value2 === "object" && value2 !== null && "kind" in value2 && value2.kind === "Error";
  }
  #isLambdaValue(value2) {
    return typeof value2 === "object" && value2 !== null && "kind" in value2 && value2.kind === "Lambda";
  }
  #primeWorksheetRawValues() {
    for (const worksheet of this.#worksheets) {
      for (const cell of worksheet.cells) {
        const address = cell.address?.trim();
        if (!address) {
          continue;
        }
        const coord = this.#addressToIndices(address);
        if (!coord) {
          continue;
        }
        const pbCell = worksheet.__getCell(coord.row, coord.col);
        if (!pbCell) {
          continue;
        }
        const existing = worksheet.__getRawValue(coord.row, coord.col);
        if (existing !== undefined) {
          continue;
        }
        const excelRaw = pbCell.value;
        const raw = this.#deserializeProtoRawValue(pbCell);
        worksheet.__setExcelRawValue(coord.row, coord.col, excelRaw);
        worksheet.__setRawValue(coord.row, coord.col, raw);
      }
    }
  }
  #hydrateCellInputsFromProtoToCrdt() {
    this.#runCellInputTransaction(this.#localOrigin, () => {
      for (const worksheet of this.#worksheets) {
        for (const row2 of worksheet.__getRows()) {
          for (const cell of row2.cells ?? []) {
            worksheet.writeCellInputToYjs(cell);
          }
        }
      }
    });
  }
  #refreshSparklineRenderContexts() {
    for (const worksheet of this.#worksheets) {
      worksheet.__refreshSparklineRenderContext();
    }
  }
  #rebuildExcludedCollaborativeSidecars() {
    for (const pivotTable of this.#pivotTables.items) {
      pivotTable.rebuildCache();
    }
    this.#slicers.synthesizeCaches();
  }
  #normalizeRawValueForCell(next2, previous4) {
    if (next2 == null) {
      return null;
    }
    if (this.#isErrorValue(next2)) {
      return next2;
    }
    if (next2 instanceof Date) {
      return this.#canonicalizeDateValue(next2);
    }
    if (typeof next2 === "string") {
      const parsedDate = this.#parseIsoDate(next2);
      if (parsedDate) {
        return this.#canonicalizeDateValue(parsedDate);
      }
      return next2;
    }
    if (typeof next2 === "number" && previous4 instanceof Date) {
      return this.#convertExcelSerialToDate(next2) ?? next2;
    }
    return next2;
  }
  #coerceRawToScalarValue(value2, convertStrings = true) {
    if (value2 == null) {
      return null;
    }
    if (value2 instanceof Date) {
      const serial = this.#dateToExcelSerial(value2);
      return serial == null ? "" : serial;
    }
    if (this.#isErrorValue(value2)) {
      return value2;
    }
    if (value2 instanceof Error) {
      return makeScalarError(value2.message || "#VALUE!");
    }
    if (typeof value2 === "number" || typeof value2 === "boolean") {
      return value2;
    }
    if (typeof value2 === "string") {
      if (value2.startsWith("#")) {
        return { kind: "Error", code: value2 };
      }
      if (value2 === "") {
        return "";
      }
      const trimmed = value2.trim();
      if (trimmed === "") {
        return value2;
      }
      if (convertStrings) {
        const numeric = Number(trimmed);
        if (!Number.isNaN(numeric)) {
          return numeric;
        }
      }
      return value2;
    }
    return null;
  }
  #deserializeProtoRawValue(cell) {
    const source = cell.value !== undefined && cell.value !== null ? cell.value : null;
    if (source == null) {
      return null;
    }
    const dataType = cell.dataType ?? 0 /* CELL_DATA_TYPE_UNSPECIFIED */;
    let typedValue;
    switch (dataType) {
      case 0 /* CELL_DATA_TYPE_UNSPECIFIED */: {
        if (typeof source === "number" && Number.isFinite(source)) {
          typedValue = source;
        } else if (typeof source === "boolean") {
          typedValue = source;
        } else if (typeof source === "string") {
          if (source === "") {
            typedValue = "";
            break;
          }
          const trimmed = source.trim();
          if (trimmed === "") {
            typedValue = source;
            break;
          }
          const parsed = Number(trimmed);
          if (Number.isFinite(parsed)) {
            typedValue = parsed;
          }
        }
        break;
      }
      case 7 /* CELL_DATA_TYPE_DATE */: {
        const dateValue = this.#convertExcelSerialToDate(source) ?? (typeof source === "string" ? this.#parseIsoDate(source) : null);
        if (dateValue) {
          return this.#canonicalizeDateValue(dateValue);
        }
        break;
      }
      case 4 /* CELL_DATA_TYPE_BOOLEAN */: {
        const boolValue = this.#coerceBooleanRaw(source);
        if (boolValue != null) {
          return boolValue;
        }
        break;
      }
      case 5 /* CELL_DATA_TYPE_NUMBER */: {
        const numericValue = this.#coerceNumericValue(source);
        if (numericValue != null) {
          typedValue = numericValue;
        }
        break;
      }
      case 6 /* CELL_DATA_TYPE_ERROR */: {
        const errorValue = this.#coerceErrorRaw(source);
        if (errorValue) {
          return errorValue;
        }
        break;
      }
      case 3 /* CELL_DATA_TYPE_STRING */:
      case 1 /* CELL_DATA_TYPE_SHARED_STRING */: {
        if (typeof source === "string") {
          return source;
        }
        return String(source);
      }
      default:
        break;
    }
    if (this.#formulaLooksDateLike(cell.formula)) {
      const formulaDate = this.#convertExcelSerialToDate(source) ?? (typeof source === "string" ? this.#parseIsoDate(source) : null);
      if (formulaDate) {
        return this.#canonicalizeDateValue(formulaDate);
      }
    }
    if (typedValue !== undefined) {
      return typedValue;
    }
    if (typeof source === "string") {
      const isoDate = this.#parseIsoDate(source);
      if (isoDate) {
        return this.#canonicalizeDateValue(isoDate);
      }
    }
    return source;
  }
  #coerceBooleanRaw(value2) {
    if (typeof value2 === "boolean") {
      return value2;
    }
    if (typeof value2 === "number") {
      if (value2 === 1) {
        return true;
      }
      if (value2 === 0) {
        return false;
      }
      return null;
    }
    if (typeof value2 === "string") {
      const normalized = value2.trim().toUpperCase();
      if (normalized === "TRUE" || normalized === "1") {
        return true;
      }
      if (normalized === "FALSE" || normalized === "0") {
        return false;
      }
    }
    return null;
  }
  #coerceNumericValue(value2) {
    if (typeof value2 === "number" && Number.isFinite(value2)) {
      return value2;
    }
    if (typeof value2 === "string") {
      const parsed = Number(value2);
      return Number.isFinite(parsed) ? parsed : null;
    }
    return null;
  }
  #coerceErrorRaw(value2) {
    if (this.#isErrorValue(value2)) {
      return value2;
    }
    if (value2 instanceof Error) {
      return { kind: "Error", code: value2.message };
    }
    if (typeof value2 === "string" && value2.startsWith("#")) {
      return { kind: "Error", code: value2 };
    }
    return null;
  }
  #convertExcelSerialToDate(value2) {
    if (value2 instanceof Date) {
      return value2;
    }
    if (typeof value2 === "string") {
      const parsed = Number(value2);
      if (!Number.isFinite(parsed)) {
        return null;
      }
      const millis2 = EXCEL_EPOCH_MS7 + parsed * MS_PER_DAY7;
      return this.#markCanonicalDate(new Date(millis2));
    }
    const serial = this.#coerceNumericValue(value2);
    if (serial == null || !Number.isFinite(serial)) {
      return null;
    }
    const millis = EXCEL_EPOCH_MS7 + serial * MS_PER_DAY7;
    return this.#markCanonicalDate(new Date(millis));
  }
  #canonicalizeDateValue(date6) {
    const serial = this.#dateToExcelSerial(date6);
    if (serial == null) {
      return date6;
    }
    return this.#convertExcelSerialToDate(serial) ?? date6;
  }
  #dateToExcelSerial(date6) {
    if (!(date6 instanceof Date)) {
      return null;
    }
    const timestamp = date6.getTime();
    if (!Number.isFinite(timestamp)) {
      return null;
    }
    const isCanonical = Boolean(date6[CANONICAL_DATE_SYMBOL]);
    const isLocalMidnight = date6.getHours() === 0 && date6.getMinutes() === 0 && date6.getSeconds() === 0 && date6.getMilliseconds() === 0;
    const adjustedTimestamp = isCanonical || !isLocalMidnight ? timestamp : timestamp - date6.getTimezoneOffset() * MS_PER_MINUTE;
    return (adjustedTimestamp - EXCEL_EPOCH_MS7) / MS_PER_DAY7;
  }
  #markCanonicalDate(date6) {
    if (!date6[CANONICAL_DATE_SYMBOL]) {
      Object.defineProperty(date6, CANONICAL_DATE_SYMBOL, {
        value: true,
        enumerable: false,
        configurable: false
      });
    }
    return date6;
  }
  __formatRawValueForDisplay(raw) {
    if (raw == null) {
      return {
        value: "",
        dataType: 0 /* CELL_DATA_TYPE_UNSPECIFIED */
      };
    }
    if (this.#isErrorValue(raw)) {
      return {
        value: raw.code,
        dataType: 6 /* CELL_DATA_TYPE_ERROR */
      };
    }
    if (raw instanceof Date) {
      return {
        value: this.#formatExcelDateValue(raw),
        dataType: 5 /* CELL_DATA_TYPE_NUMBER */
      };
    }
    if (typeof raw === "number") {
      return {
        value: Number.isFinite(raw) ? String(raw) : "",
        dataType: 5 /* CELL_DATA_TYPE_NUMBER */
      };
    }
    if (typeof raw === "boolean") {
      return {
        value: raw ? "1" : "0",
        dataType: 4 /* CELL_DATA_TYPE_BOOLEAN */
      };
    }
    if (raw == null) {
      return {
        value: "",
        dataType: 0 /* CELL_DATA_TYPE_UNSPECIFIED */
      };
    }
    return {
      value: String(raw),
      dataType: 3 /* CELL_DATA_TYPE_STRING */
    };
  }
  #applyCellDisplayFromRaw(cell, raw) {
    const formatted = this.__formatRawValueForDisplay(raw);
    cell.value = formatted.value;
    cell.dataType = formatted.dataType;
  }
  #formatExcelDateValue(date6) {
    const serial = this.#dateToExcelSerial(date6);
    return serial == null ? "" : serial.toString();
  }
  #parseIsoDate(value2) {
    if (!ISO_DATE_PATTERN3.test(value2)) {
      return null;
    }
    const timestamp = Date.parse(value2);
    if (Number.isNaN(timestamp)) {
      return null;
    }
    return new Date(timestamp);
  }
  #formulaLooksDateLike(formula) {
    if (!formula) {
      return false;
    }
    const upper = formula.toUpperCase();
    return DATE_FORMULA_HINTS.some((hint) => upper.includes(`${hint}(`));
  }
  #sanitizeEmbeddedFormulaEquals(formula) {
    if (formula.length <= 1) {
      return formula;
    }
    let mutated = "";
    for (let index2 = 0;index2 < formula.length; index2 += 1) {
      const char = formula[index2];
      if (char === "=" && index2 > 0 && this.#shouldStripEmbeddedEquals(formula, index2)) {
        continue;
      }
      mutated += char;
    }
    return mutated;
  }
  #shouldStripEmbeddedEquals(formula, index2) {
    let left = index2 - 1;
    while (left >= 0 && /\s/.test(formula[left] ?? "")) {
      left -= 1;
    }
    if (left < 0) {
      return false;
    }
    const leftChar = formula[left] ?? "";
    if (!"(+-,*/^,".includes(leftChar)) {
      return false;
    }
    let right = index2 + 1;
    while (right < formula.length && /\s/.test(formula[right] ?? "")) {
      right += 1;
    }
    if (right >= formula.length) {
      return false;
    }
    const rightChar = formula[right] ?? "";
    if (rightChar === "(" || rightChar === "$" || rightChar === "'" || /[A-Za-z0-9_]/.test(rightChar)) {
      return true;
    }
    return false;
  }
  #recordUserDefinedFunctionFailure(key, formula, state) {
    const errorValue = makeScalarError("#NAME?");
    this.#writeComputedValue(key, errorValue);
    state.evaluations.set(key, {
      value: errorValue,
      formula,
      precedents: []
    });
  }
}

// node_modules/@oai/granola/dist/models/presentation/c-star-mini.js
var BOX_WHISKER_CONFIG = {
  chartType: "boxWhisker",
  family: "distribution"
};
var TYPE_CONFIG = {
  bar: { chartType: "bar", family: "categorical" },
  line: { chartType: "line", family: "categorical" },
  area: { chartType: "area", family: "categorical" },
  pie: { chartType: "pie", family: "pie" },
  doughnut: { chartType: "doughnut", family: "pie" },
  funnel: { chartType: "funnel", family: "categorical" },
  "box-whisker": BOX_WHISKER_CONFIG,
  boxWhisker: BOX_WHISKER_CONFIG,
  bubble: { chartType: "bubble", family: "scatter" },
  scatter: {
    chartType: "scatter",
    family: "scatter",
    apply: (chart2) => {
      chart2.scatterOptions.style = "smoothWithMarkers";
    }
  },
  histogram: { chartType: "histogram", family: "distribution" },
  treemap: { chartType: "treemap", family: "hierarchy" },
  sunburst: { chartType: "sunburst", family: "hierarchy" },
  map: { chartType: "map", family: "map" },
  radar: { chartType: "radar", family: "categorical" },
  waterfall: { chartType: "waterfall", family: "categorical" }
};
var CHART_KINDS = [
  "category",
  "xy",
  "hierarchy",
  "distribution",
  "map",
  "combo"
];
var CANONICAL_KIND_TO_SUBTYPE = {
  category: {
    bar: "bar",
    line: "line",
    area: "area",
    pie: "pie",
    boxWhisker: "box-whisker",
    doughnut: "doughnut",
    funnel: "funnel",
    radar: "radar",
    waterfall: "waterfall"
  },
  xy: {
    scatter: "scatter",
    bubble: "bubble"
  },
  hierarchy: {
    treemap: "treemap",
    sunburst: "sunburst"
  },
  distribution: {
    histogram: "histogram"
  },
  map: {
    map: "map"
  },
  combo: {}
};
var ERROR_PREFIX = "c-star-mini: ";
var GRIDLINE_COLOR_HEX = "#E1E1E1";
class CStarMini {
  static load(yamlSource) {
    const root2 = parseRootDocument(yamlSource);
    const typeValue = root2["type"];
    if (isSpreadsheetType(typeValue)) {
      const doc2 = parseSpreadsheetDocument(root2, typeValue);
      const workbook = buildWorkbookFromSpreadsheetDoc(doc2);
      return { kind: "workbook", workbook };
    }
    const chart2 = CStarMini.loadChartFromRoot(yamlSource, root2);
    return { kind: "chart", chart: chart2 };
  }
  static addChartToSlide(yamlSource, slide) {
    const trimmed = yamlSource.trim();
    if (!trimmed) {
      throw new Error(`${ERROR_PREFIX}chart YAML cannot be empty`);
    }
    const root2 = parseRootDocument(trimmed);
    if (isSpreadsheetType(root2["type"])) {
      throw new Error(`${ERROR_PREFIX}expected a chart document when adding to a slide`);
    }
    const chart2 = CStarMini.loadChartFromRoot(trimmed, root2);
    const chartElement = slide.charts.attach(chart2);
    const frame = slide.frame;
    chartElement.position = {
      left: frame.left,
      top: frame.top,
      width: frame.width,
      height: frame.height
    };
    return chart2;
  }
  static loadChart(yamlSource) {
    return CStarMini.loadChartFromRoot(yamlSource);
  }
  static loadChartFromRoot(yamlSource, root2) {
    const doc2 = parseDocument(yamlSource, root2);
    return CStarMini.buildChartFromDocument(doc2);
  }
  static buildChartFromDocument(doc2) {
    const config3 = TYPE_CONFIG[doc2.type];
    const chart2 = new Chart2({ type: CHART_TYPE_TO_PROTO[config3.chartType] });
    chart2.titleTextStyle.fontSize = 14;
    chart2.titleTextStyle.bold = true;
    config3.apply?.(chart2);
    const seriesCount = applyData(chart2, config3, doc2);
    applyOptions(chart2, config3, doc2.options);
    applyGridlineDefaults(chart2, config3.chartType, doc2.options);
    applyDimensionOverrides(chart2, doc2);
    applyLegendDefault(chart2, doc2.options, seriesCount);
    return chart2;
  }
}
function parseRootDocument(source) {
  let raw;
  try {
    raw = $parse(source);
  } catch (error49) {
    throw new Error(`${ERROR_PREFIX}failed to parse YAML: ${errorMessage(error49)}`);
  }
  if (!isObject2(raw)) {
    throw new Error(`${ERROR_PREFIX}root YAML value must be an object`);
  }
  const root2 = raw;
  const version2 = root2["version"];
  if (typeof version2 !== "number" || version2 !== 1) {
    throw new Error(`${ERROR_PREFIX}only version 1 documents are supported`);
  }
  return root2;
}
function parseDocument(source, rootOverride) {
  const root2 = rootOverride ?? parseRootDocument(source);
  const typeValue = root2["type"];
  if (typeof typeValue !== "string") {
    throw new Error(`${ERROR_PREFIX}unsupported chart type "${String(typeValue)}"`);
  }
  const dataValue = root2["data"];
  if (!isObject2(dataValue)) {
    throw new Error(`${ERROR_PREFIX}"data" must be an object`);
  }
  const encodingValue = root2["encoding"];
  const encoding = isObject2(encodingValue) ? encodingValue : undefined;
  const optionsValue = root2["options"];
  const options = isObject2(optionsValue) ? optionsValue : undefined;
  const normalized = normalizeChartType(typeValue, options);
  return {
    type: normalized.type,
    data: dataValue,
    encoding,
    options: normalized.options
  };
}
function applyData(chart2, config3, doc2) {
  switch (config3.family) {
    case "categorical":
      return buildCategoricalSeries(chart2, config3.chartType, doc2);
    case "pie":
      return buildPieSeries(chart2, doc2);
    case "scatter":
      return buildScatterSeries(chart2, config3.chartType, doc2);
    case "hierarchy":
      return buildHierarchySeries(chart2, doc2);
    case "map":
      return buildMapSeries(chart2, doc2);
    case "distribution":
      return buildDistributionSeries(chart2, config3.chartType, doc2);
    default:
      throw new Error(`${ERROR_PREFIX}unsupported chart family "${config3.family}"`);
  }
}
function buildCategoricalSeries(chart2, chartType, doc2) {
  const categories = ensureStringArray(doc2.data["categories"], '"data.categories" must be an array of strings');
  const seriesList = ensureCategorySeries(doc2.data["series"], categories.length);
  const selectedSeries = selectSeries(seriesList, doc2.encoding?.["y"]);
  if (selectedSeries.length === 0) {
    throw new Error(`${ERROR_PREFIX}encoding.y must reference at least one series`);
  }
  chart2.categories = categories;
  selectedSeries.forEach((series) => {
    const chartSeries = chart2.series.add(series.name);
    chartSeries.values = series.values;
  });
  applyStacking(chart2, chartType, doc2.encoding);
  return selectedSeries.length;
}
function buildPieSeries(chart2, doc2) {
  const categories = ensureStringArray(doc2.data["categories"], '"data.categories" must be an array of strings');
  const seriesList = ensureCategorySeries(doc2.data["series"], categories.length);
  const selectedSeries = selectSeries(seriesList, doc2.encoding?.["y"]);
  if (selectedSeries.length !== 1) {
    throw new Error(`${ERROR_PREFIX}pie charts require exactly one series; received ${selectedSeries.length}`);
  }
  const series = selectedSeries[0];
  chart2.categories = categories;
  const chartSeries = chart2.series.add(series.name);
  chartSeries.values = series.values;
  chartSeries.categories = categories;
  return 1;
}
function buildScatterSeries(chart2, chartType, doc2) {
  const includeSize = chartType === "bubble";
  const seriesList = ensureScatterSeries(doc2.data["series"], { includeSize });
  seriesList.forEach((series) => {
    const chartSeries = chart2.series.add(series.name);
    chartSeries.values = series.yValues;
    chartSeries.xValues = series.xValues;
    if (series.labels) {
      chartSeries.categories = series.labels;
    }
    if (includeSize) {
      chartSeries.bubbleSizes = series.sizeValues ?? [];
    }
  });
  return seriesList.length;
}
function buildHierarchySeries(chart2, doc2) {
  const points = ensureTreemapPoints(doc2.data["points"]);
  const chartSeries = chart2.series.add("Values");
  chartSeries.values = points.map((point5) => point5.value);
  chartSeries.categoryPaths = points.map((point5) => point5.path);
  return 1;
}
function buildMapSeries(chart2, doc2) {
  const regions = ensureMapRegions(doc2.data["regions"]);
  const categories = regions.map((region) => region.key);
  chart2.categories = categories;
  const chartSeries = chart2.series.add("Values");
  chartSeries.values = regions.map((region) => region.value);
  chartSeries.categories = categories;
  return 1;
}
function buildDistributionSeries(chart2, chartType, doc2) {
  switch (chartType) {
    case "histogram":
      return buildHistogramSeries(chart2, doc2);
    case "boxWhisker":
      return buildBoxWhiskerSeries(chart2, doc2);
    default:
      throw new Error(`${ERROR_PREFIX}unsupported distribution chart type "${chartType}"`);
  }
}
function buildHistogramSeries(chart2, doc2) {
  const samples = ensureHistogramValues(doc2.data["values"]);
  const chartSeries = chart2.series.add("Values");
  chartSeries.values = samples;
  return 1;
}
function buildBoxWhiskerSeries(chart2, doc2) {
  const categories = ensureStringArray(doc2.data["categories"], '"data.categories" must be an array of strings');
  const samples = ensureBoxWhiskerSamples(doc2.data["samples"]);
  const orderedCategories = [...categories];
  const seen = new Set(orderedCategories);
  samples.forEach(({ category }) => {
    if (!seen.has(category)) {
      seen.add(category);
      orderedCategories.push(category);
    }
  });
  chart2.categories = orderedCategories;
  const chartSeries = chart2.series.add("Samples");
  const values2 = [];
  const categoriesPerSample = [];
  samples.forEach(({ category, values: sampleValues }) => {
    sampleValues.forEach((value2) => {
      values2.push(value2);
      categoriesPerSample.push(category);
    });
  });
  chartSeries.values = values2;
  chartSeries.categories = categoriesPerSample;
  return 1;
}
function applyOptions(chart2, config3, options) {
  if (!options) {
    return;
  }
  const title = options["title"];
  if (typeof title === "string") {
    chart2.title = title;
  }
  applyLegendOptions(chart2, getObject(options["legend"]));
  applyDataLabelOptions(chart2, getObject(options["dataLabels"]));
  applyAxisOptions(chart2.xAxis, getObject(options["axisX"]));
  applyAxisOptions(chart2.yAxis, getObject(options["axisY"]));
  if (config3.chartType === "bar" || config3.chartType === "bar3D") {
    applyBarOptions(chart2, getObject(options["bar"]));
  }
  if (config3.family === "scatter") {
    applyScatterOptions(chart2, getObject(options["scatter"]));
  }
  if (config3.chartType === "pie") {
    applyPieOptions(chart2, getObject(options["pie"]));
  }
  if (config3.chartType === "doughnut") {
    applyDoughnutOptions(chart2, getObject(options["doughnut"]));
  }
  if (config3.chartType === "boxWhisker") {
    applyBoxWhiskerOptions(chart2, getObject(options["boxWhisker"]));
  }
  if (config3.chartType === "treemap" || config3.chartType === "sunburst") {
    applyTreemapOptions(chart2, getObject(options["treemap"]));
  }
  if (config3.chartType === "map") {
    applyMapOptions(chart2, getObject(options["map"]));
  }
  if (config3.chartType === "funnel") {
    applyFunnelOptions(chart2, getObject(options["funnel"]));
  }
  if (config3.chartType === "histogram") {
    applyHistogramOptions(chart2, getObject(options["histogram"]));
  }
}
function applyLegendOptions(chart2, legend) {
  if (!legend) {
    return;
  }
  if ("show" in legend) {
    chart2.hasLegend = Boolean(legend["show"]);
  }
  const position2 = legend["position"];
  if (typeof position2 === "string") {
    chart2.legend.position = normalizeLegendPosition2(position2);
  }
  if ("overlay" in legend) {
    chart2.legend.overlay = Boolean(legend["overlay"]);
  }
}
function applyDataLabelOptions(chart2, dataLabels) {
  if (!dataLabels) {
    return;
  }
  if ("show" in dataLabels) {
    chart2.dataLabels.showValue = Boolean(dataLabels["show"]);
  }
  if ("showValue" in dataLabels) {
    chart2.dataLabels.showValue = Boolean(dataLabels["showValue"]);
  }
  if ("showPercent" in dataLabels) {
    chart2.dataLabels.showPercent = Boolean(dataLabels["showPercent"]);
  }
  if ("showCategory" in dataLabels) {
    chart2.dataLabels.showCategoryName = Boolean(dataLabels["showCategory"]);
  }
  if ("showCategoryName" in dataLabels) {
    chart2.dataLabels.showCategoryName = Boolean(dataLabels["showCategoryName"]);
  }
  if ("showSeries" in dataLabels) {
    chart2.dataLabels.showSeriesName = Boolean(dataLabels["showSeries"]);
  }
  if ("showSeriesName" in dataLabels) {
    chart2.dataLabels.showSeriesName = Boolean(dataLabels["showSeriesName"]);
  }
  if ("showLeaderLines" in dataLabels) {
    chart2.dataLabels.showLeaderLines = Boolean(dataLabels["showLeaderLines"]);
  }
  const position2 = dataLabels["position"];
  if (typeof position2 === "string") {
    chart2.dataLabels.position = normalizeDataLabelPosition(position2);
  }
}
function applyAxisOptions(axis, options) {
  if (!options) {
    return;
  }
  const title = options["title"];
  if (typeof title === "string") {
    axis.title = title;
  }
  const format3 = options["format"];
  if (typeof format3 === "string") {
    axis.numberFormatCode = format3;
  }
  if ("min" in options) {
    axis.min = toOptionalFiniteNumber(options["min"], "axis.min");
  }
  if ("max" in options) {
    axis.max = toOptionalFiniteNumber(options["max"], "axis.max");
  }
  if ("majorUnit" in options) {
    axis.majorUnit = toOptionalFiniteNumber(options["majorUnit"], "axis.majorUnit");
  }
  if ("minorUnit" in options) {
    axis.minorUnit = toOptionalFiniteNumber(options["minorUnit"], "axis.minorUnit");
  }
  if ("grid" in options) {
    const grid2 = options["grid"];
    if (typeof grid2 === "boolean") {
      if (grid2) {
        axis.majorGridlines.width = 1;
        axis.majorGridlines.style = "solid";
        if (!axis.majorGridlines.fill) {
          axis.majorGridlines.fill = GRIDLINE_COLOR_HEX;
        }
      } else {
        axis.majorGridlines.width = undefined;
        axis.majorGridlines.style = undefined;
        axis.majorGridlines.fill = undefined;
      }
    }
  }
}
function applyBarOptions(chart2, options) {
  if (!options) {
    return;
  }
  const orientation = options["orientation"];
  if (typeof orientation === "string") {
    const normalized = normalizeBarOrientation(orientation);
    if (normalized) {
      chart2.barOptions.direction = normalized;
    }
  }
  const direction = options["direction"];
  if (typeof direction === "string") {
    const normalized = normalizeBarDirection(direction);
    if (normalized) {
      chart2.barOptions.direction = normalized;
    }
  }
  const grouping = options["grouping"];
  if (typeof grouping === "string") {
    const normalized = normalizeBarGrouping(grouping);
    if (normalized) {
      chart2.barOptions.grouping = normalized;
    }
  }
  if ("varyColors" in options) {
    chart2.barOptions.varyColors = Boolean(options["varyColors"]);
  }
  if ("gapWidth" in options) {
    chart2.barOptions.gapWidth = toOptionalFiniteNumber(options["gapWidth"], "options.bar.gapWidth");
  }
  if ("gapDepth" in options) {
    chart2.barOptions.gapDepth = toOptionalFiniteNumber(options["gapDepth"], "options.bar.gapDepth");
  }
  if ("overlap" in options) {
    chart2.barOptions.overlap = toOptionalFiniteNumber(options["overlap"], "options.bar.overlap");
  }
  if ("bar3dShape" in options) {
    chart2.barOptions.bar3dShape = toOptionalFiniteNumber(options["bar3dShape"], "options.bar.bar3dShape");
  }
}
function normalizeBarOrientation(value2) {
  const normalized = value2.trim().toLowerCase();
  if (normalized === "horizontal") {
    return "bar";
  }
  if (normalized === "vertical") {
    return "column";
  }
  return;
}
function applyScatterOptions(chart2, options) {
  if (!options) {
    return;
  }
  const style = options["style"];
  if (typeof style === "string") {
    const normalized = normalizeScatterStyle(style);
    if (normalized) {
      chart2.scatterOptions.style = normalized;
    }
  }
  if ("varyColors" in options) {
    chart2.scatterOptions.varyColors = Boolean(options["varyColors"]);
  }
}
function applyPieOptions(chart2, options) {
  if (!options) {
    return;
  }
  if ("firstSliceAngle" in options) {
    chart2.pieOptions.firstSliceAngle = toOptionalFiniteNumber(options["firstSliceAngle"], "options.pie.firstSliceAngle");
  }
}
function applyDoughnutOptions(chart2, options) {
  if (!options) {
    return;
  }
  if ("holeSize" in options) {
    chart2.doughnutOptions.holeSize = toOptionalFiniteNumber(options["holeSize"], "options.doughnut.holeSize");
  }
  if ("firstSliceAngle" in options) {
    chart2.doughnutOptions.firstSliceAngle = toOptionalFiniteNumber(options["firstSliceAngle"], "options.doughnut.firstSliceAngle");
  }
}
function applyBoxWhiskerOptions(chart2, options) {
  if (!options) {
    return;
  }
  if ("showMeanLine" in options) {
    chart2.boxWhiskerOptions.showMeanLine = Boolean(options["showMeanLine"]);
  }
  if ("showMeanMarker" in options) {
    chart2.boxWhiskerOptions.showMeanMarker = Boolean(options["showMeanMarker"]);
  }
  if ("showNonOutliers" in options) {
    chart2.boxWhiskerOptions.showNonOutliers = Boolean(options["showNonOutliers"]);
  }
  if ("showOutliers" in options) {
    chart2.boxWhiskerOptions.showOutliers = Boolean(options["showOutliers"]);
  }
  if ("quartileMethod" in options) {
    chart2.boxWhiskerOptions.quartileMethod = normalizeQuartileMethod(options["quartileMethod"]);
  }
}
function applyTreemapOptions(chart2, options) {
  if (!options) {
    return;
  }
  const layout = options["parentLabelLayout"];
  if (typeof layout === "string") {
    const normalized = normalizeTreemapParentLabelLayout(layout);
    if (normalized) {
      chart2.treemapOptions.parentLabelLayout = normalized;
    }
  }
}
function normalizeTreemapParentLabelLayout(value2) {
  const normalized = value2.trim().toLowerCase();
  switch (normalized) {
    case "banner":
      return "banner";
    case "none":
      return "none";
    case "overlapping":
      return "overlapping";
  }
}
function applyMapOptions(chart2, options) {
  if (!options) {
    return;
  }
  const mapArea = options["mapArea"];
  if (typeof mapArea === "string") {
    const normalized = normalizeMapArea(mapArea);
    if (normalized) {
      chart2.mapOptions.mapArea = normalized;
    }
  }
  const projection = options["projection"];
  if (typeof projection === "string") {
    const normalized = normalizeMapProjection(projection);
    if (normalized) {
      chart2.mapOptions.projection = normalized;
    }
  }
  const labelLayout = options["labelLayout"];
  if (typeof labelLayout === "string") {
    const normalized = normalizeMapLabelLayout(labelLayout);
    if (normalized) {
      chart2.mapOptions.labelLayout = normalized;
    }
  }
  const dataLevel = options["dataLevel"];
  if (typeof dataLevel === "string") {
    const normalized = normalizeMapDataLevel(dataLevel);
    if (normalized) {
      chart2.mapOptions.dataLevel = normalized;
    }
  }
  if ("showUnknown" in options) {
    chart2.mapOptions.showUnknown = Boolean(options["showUnknown"]);
  }
  if ("onlyRegionsWithData" in options) {
    chart2.mapOptions.onlyRegionsWithData = Boolean(options["onlyRegionsWithData"]);
  }
}
function applyFunnelOptions(chart2, options) {
  if (!options) {
    return;
  }
  if ("gapWidth" in options) {
    chart2.funnelOptions.gapWidth = toOptionalFiniteNumber(options["gapWidth"], "options.funnel.gapWidth");
  }
}
function applyHistogramOptions(chart2, options) {
  if (!options) {
    return;
  }
  const normalized = {
    ...chart2.histogramOptions ?? {}
  };
  let changed = false;
  if ("binWidth" in options) {
    normalized.binWidth = toOptionalFiniteNumber(options["binWidth"], "options.histogram.binWidth");
    changed = true;
  }
  if ("intervalClosed" in options) {
    normalized.intervalClosed = normalizeHistogramInterval(options["intervalClosed"]);
    changed = true;
  }
  if ("aggregated" in options) {
    normalized.aggregated = Boolean(options["aggregated"]);
    changed = true;
  }
  if (changed) {
    chart2.histogramOptions = normalized;
  }
}
function applyStacking(chart2, chartType, encoding) {
  const rawStack = encoding?.["stack"];
  if (typeof rawStack !== "string") {
    return;
  }
  if (chartType === "bar" || chartType === "bar3D") {
    const grouping = normalizeBarGrouping(rawStack);
    if (grouping) {
      chart2.barOptions.grouping = grouping;
    }
  } else if (chartType === "line" || chartType === "area") {
    const grouping = normalizeLineGrouping(rawStack);
    if (grouping) {
      chart2.lineOptions.grouping = grouping;
    }
  }
}
function normalizeChartType(value2, options) {
  const canonical = normalizeCanonicalType(value2, options);
  if (canonical) {
    return canonical;
  }
  const legacy = normalizeLegacyType(value2, options);
  if (legacy) {
    return legacy;
  }
  if (isSupportedType(value2)) {
    return { type: value2, options };
  }
  throw new Error(`${ERROR_PREFIX}unsupported chart type "${value2}"`);
}
function normalizeCanonicalType(value2, options) {
  if (!isChartKind(value2)) {
    return null;
  }
  const subtypeMap = CANONICAL_KIND_TO_SUBTYPE[value2];
  if (!subtypeMap || Object.keys(subtypeMap).length === 0) {
    throw new Error(`${ERROR_PREFIX}chart kind "${value2}" is not supported yet`);
  }
  if ((!options || !Object.prototype.hasOwnProperty.call(options, "subtype")) && isSupportedType(value2)) {
    return null;
  }
  const subtype = ensureSubtype(value2, options);
  const normalizedType = subtypeMap[subtype];
  if (!normalizedType) {
    const supported = Object.keys(subtypeMap).map((entry) => `"${entry}"`).join(", ");
    throw new Error(`${ERROR_PREFIX}unsupported subtype "${subtype}" for chart kind "${value2}". Supported subtypes: ${supported}`);
  }
  return { type: normalizedType, options };
}
var LEGACY_TYPE_PATCHES = {
  "bar-horizontal": (options) => ({
    type: "bar",
    options: mergeOptions(options, {
      bar: { orientation: "horizontal" }
    })
  }),
  "bar-3d": (options) => ({
    type: "bar",
    options: mergeOptions(options, { bar: { dimension: "3d" } })
  }),
  "pie-3d": (options) => ({
    type: "pie",
    options: mergeOptions(options, { pie: { dimension: "3d" } })
  }),
  "line-3d": (options) => ({
    type: "line",
    options: mergeOptions(options, { line: { dimension: "3d" } })
  }),
  "scatter-line": (options) => ({
    type: "scatter",
    options: mergeOptions(options, { scatter: { style: "lineMarker" } })
  }),
  "scatter-smooth": (options) => ({
    type: "scatter",
    options: mergeOptions(options, { scatter: { style: "smooth" } })
  })
};
function normalizeLegacyType(value2, options) {
  const handler = LEGACY_TYPE_PATCHES[value2];
  return handler ? handler(options) : null;
}
function ensureSubtype(kind, options) {
  if (!options) {
    throw new Error(`${ERROR_PREFIX}"options.subtype" is required when type is set to "${kind}"`);
  }
  const subtype = options["subtype"];
  if (typeof subtype !== "string" || !subtype.trim()) {
    throw new Error(`${ERROR_PREFIX}"options.subtype" must be a non-empty string when type is "${kind}"`);
  }
  return subtype.trim();
}
function isChartKind(value2) {
  return CHART_KINDS.includes(value2);
}
function mergeOptions(base, patch) {
  const result = { ...base ?? {} };
  for (const [key, value2] of Object.entries(patch)) {
    const existing = result[key];
    if (isObject2(value2) && isObject2(existing)) {
      result[key] = mergeOptions(existing, value2);
    } else if (isObject2(value2)) {
      result[key] = mergeOptions(undefined, value2);
    } else {
      result[key] = value2;
    }
  }
  return result;
}
function applyDimensionOverrides(chart2, doc2) {
  const options = doc2.options;
  switch (doc2.type) {
    case "bar": {
      const dimension = normalizeDimension3(getObject(options?.["bar"])?.["dimension"]);
      chart2.type = dimension === "3d" ? "bar3D" : "bar";
      break;
    }
    case "line": {
      const dimension = normalizeDimension3(getObject(options?.["line"])?.["dimension"]);
      chart2.type = dimension === "3d" ? "line3D" : "line";
      break;
    }
    case "pie": {
      const dimension = normalizeDimension3(getObject(options?.["pie"])?.["dimension"]);
      chart2.type = dimension === "3d" ? "pie3D" : "pie";
      break;
    }
    default:
      break;
  }
}
function normalizeDimension3(value2) {
  if (typeof value2 !== "string") {
    return;
  }
  const normalized = value2.trim().toLowerCase();
  if (normalized === "3d") {
    return "3d";
  }
  if (normalized === "2d") {
    return "2d";
  }
  return;
}
function applyLegendDefault(chart2, options, seriesCount) {
  if (seriesCount < 2) {
    return;
  }
  const legend = getObject(options?.["legend"]);
  if (legend && Object.prototype.hasOwnProperty.call(legend, "show")) {
    return;
  }
  chart2.hasLegend = true;
}
function applyGridlineDefaults(chart2, chartType, options) {
  const shouldEnable = chartType === "scatter" || chartType === "bubble" || chartType === "bar" || chartType === "bar3D" || chartType === "histogram" || chartType === "boxWhisker";
  if (!shouldEnable) {
    return;
  }
  const axisYOptions = getObject(options?.["axisY"]);
  const hasExplicitGridSetting = axisYOptions ? Object.prototype.hasOwnProperty.call(axisYOptions, "grid") : false;
  if (hasExplicitGridSetting) {
    return;
  }
  const gridlines = chart2.yAxis.majorGridlines;
  if (!gridlines.fill) {
    gridlines.fill = GRIDLINE_COLOR_HEX;
  }
  if (gridlines.width === undefined) {
    gridlines.width = 1;
  }
  if (!gridlines.style) {
    gridlines.style = "solid";
  }
}
function parseSpreadsheetDocument(root2, typeValue) {
  const cf = normalizeConditionalFormattingInput(root2["cf"]);
  if (typeValue === "sheet") {
    const dataValue2 = root2["data"];
    if (!isObject2(dataValue2)) {
      throw new Error(`${ERROR_PREFIX}"data" must be an object for sheets`);
    }
    const fallbackCells = getRecordOrUndefined(root2["cells"], '"cells"');
    return {
      type: "sheet",
      sheet: normalizeSheetConfig(dataValue2, fallbackCells, "data"),
      cf
    };
  }
  const dataValue = root2["data"];
  if (!isObject2(dataValue)) {
    throw new Error(`${ERROR_PREFIX}"data" must be an object for workbooks`);
  }
  const sheetsValue = dataValue["sheets"];
  if (!Array.isArray(sheetsValue) || sheetsValue.length === 0) {
    throw new Error(`${ERROR_PREFIX}"data.sheets" must be a non-empty array`);
  }
  const sheets = sheetsValue.map((entry, index2) => {
    if (!isObject2(entry)) {
      throw new Error(`${ERROR_PREFIX}data.sheets[${index2}] must be an object`);
    }
    return normalizeSheetConfig(entry, undefined, `data.sheets[${index2}]`);
  });
  return { type: "workbook", sheets, cf };
}
function buildWorkbookFromSpreadsheetDoc(doc2) {
  const workbook = Workbook2.create();
  const sheetNames = [];
  if (doc2.type === "sheet") {
    const name2 = addSheetToWorkbook(workbook, doc2.sheet, 0);
    sheetNames.push(name2);
  } else {
    doc2.sheets.forEach((sheet, index2) => {
      const name2 = addSheetToWorkbook(workbook, sheet, index2);
      sheetNames.push(name2);
    });
  }
  applyConditionalFormattingEntries(workbook, doc2.cf, sheetNames);
  return workbook;
}
function addSheetToWorkbook(workbook, config3, index2) {
  const sheetName = normalizeSheetName3(config3.name, index2);
  const worksheet = workbook.worksheets.add(sheetName);
  applyRowsToWorksheet(worksheet, config3.rows);
  applyCellsToWorksheet(worksheet, config3.cells);
  return worksheet.name;
}
function normalizeSheetConfig(source, fallbackCells, context) {
  const nameValue = source["name"];
  const name2 = typeof nameValue === "string" && nameValue.trim() ? nameValue.trim() : undefined;
  const rows = getRecordOrUndefined(source["rows"], `${context}.rows`);
  const cells = getRecordOrUndefined(source["cells"], `${context}.cells`) ?? fallbackCells;
  return { name: name2, rows, cells };
}
function getRecordOrUndefined(value2, context) {
  if (value2 === null || value2 === undefined) {
    return;
  }
  if (!isObject2(value2)) {
    throw new Error(`${ERROR_PREFIX}${context} must be an object`);
  }
  return value2;
}
function normalizeSheetName3(name2, index2) {
  if (name2 && name2.trim()) {
    return name2.trim();
  }
  return `Sheet${index2 + 1}`;
}
function applyRowsToWorksheet(worksheet, rows) {
  if (!rows) {
    return;
  }
  const entries = Object.entries(rows).map(([key, value2]) => {
    const rowIndex2 = Number(key);
    if (!Number.isFinite(rowIndex2) || rowIndex2 < 1) {
      throw new Error(`${ERROR_PREFIX}row keys must be 1-based positive integers`);
    }
    if (!Array.isArray(value2)) {
      throw new Error(`${ERROR_PREFIX}data.rows[${rowIndex2}] must be an array of values`);
    }
    return { rowIndex: rowIndex2, values: value2 };
  });
  entries.sort((a, b) => a.rowIndex - b.rowIndex);
  entries.forEach((row2) => {
    row2.values.forEach((cellValue, columnIndex2) => {
      if (cellValue === undefined) {
        return;
      }
      const address = makeCellAddress(row2.rowIndex - 1, columnIndex2);
      setWorksheetCell(worksheet, address, cellValue, {
        context: `rows[${row2.rowIndex}][${columnIndex2}]`
      });
    });
  });
}
function applyCellsToWorksheet(worksheet, cells) {
  if (!cells) {
    return;
  }
  for (const [address, value2] of Object.entries(cells)) {
    const normalizedAddress = normalizeCellAddressStrict(address);
    setWorksheetCell(worksheet, normalizedAddress, value2, {
      context: `cells["${address}"]`
    });
  }
}
function normalizeCellAddressStrict(address) {
  if (typeof address !== "string") {
    throw new Error(`${ERROR_PREFIX}cell references must be strings, received ${String(address)}`);
  }
  const normalized = normalizeAddress(address);
  if (!normalized) {
    throw new Error(`${ERROR_PREFIX}invalid cell reference "${address}"`);
  }
  return normalized;
}
function setWorksheetCell(worksheet, address, rawValue, options) {
  const range2 = worksheet.getRange(address);
  if (isFormulaValue(rawValue)) {
    range2.formulas = [[normalizeFormulaText(rawValue)]];
    return;
  }
  range2.values = [[normalizeCellValue(rawValue, options.context)]];
}
function isFormulaValue(value2) {
  return typeof value2 === "string" && value2.trim().startsWith("=");
}
function normalizeFormulaText(value2) {
  const trimmed = value2.trim();
  return trimmed.startsWith("=") ? trimmed : `=${trimmed}`;
}
function normalizeCellValue(value2, context) {
  if (value2 === undefined || value2 === null) {
    return null;
  }
  if (typeof value2 === "number") {
    if (!Number.isFinite(value2)) {
      throw new Error(`${ERROR_PREFIX}${context} must be a finite number, received ${value2}`);
    }
    return value2;
  }
  if (typeof value2 === "boolean") {
    return value2;
  }
  if (value2 instanceof Date) {
    return value2;
  }
  if (typeof value2 === "string") {
    return value2;
  }
  throw new Error(`${ERROR_PREFIX}${context} has unsupported value type "${typeof value2}"`);
}
function normalizeConditionalFormattingInput(value2) {
  if (value2 === null || value2 === undefined) {
    return [];
  }
  if (!Array.isArray(value2)) {
    throw new Error(`${ERROR_PREFIX}"cf" must be an array when provided`);
  }
  return value2.map((entry, index2) => normalizeConditionalFormattingEntry(entry, index2));
}
function normalizeConditionalFormattingEntry(entry, index2) {
  if (!isObject2(entry)) {
    throw new Error(`${ERROR_PREFIX}cf[${index2}] must be an object`);
  }
  const range2 = ensureNonEmptyString(entry["range"], `cf[${index2}].range must be a non-empty string`);
  const sheetNameValue = entry["sheet"];
  const sheetName = typeof sheetNameValue === "string" && sheetNameValue.trim() ? sheetNameValue.trim() : undefined;
  const heatmapValue = entry["heatmap"];
  if (!isObject2(heatmapValue)) {
    throw new Error(`${ERROR_PREFIX}cf[${index2}].heatmap must be an object`);
  }
  const colorsValue = heatmapValue["colors"];
  if (!Array.isArray(colorsValue) || colorsValue.length !== 3) {
    throw new Error(`${ERROR_PREFIX}cf[${index2}].heatmap.colors must include exactly 3 colors`);
  }
  const colors = colorsValue.map((color3, colorIndex) => ensureNonEmptyString(color3, `cf[${index2}].heatmap.colors[${colorIndex}] must be a string`));
  const stopsValue = heatmapValue["stops"];
  let stops;
  if (stopsValue !== undefined) {
    if (!Array.isArray(stopsValue)) {
      throw new Error(`${ERROR_PREFIX}cf[${index2}].heatmap.stops must be an array when provided`);
    }
    stops = stopsValue;
  }
  return {
    sheetName,
    range: range2,
    heatmap: { colors, stops }
  };
}
function applyConditionalFormattingEntries(workbook, entries, sheetNames) {
  if (entries.length === 0) {
    return;
  }
  entries.forEach((entry, index2) => {
    const { sheetName, reference } = resolveSheetAndRange(entry, sheetNames, index2);
    const worksheet = workbook.worksheets.getItem(sheetName);
    const normalizedRange = normalizeRangeReference(reference, index2);
    const parsed = parseRangeAddress(normalizedRange);
    if (!parsed) {
      throw new Error(`${ERROR_PREFIX}cf[${index2}].range "${entry.range}" is invalid`);
    }
    const conditionalFormattings = worksheet.__getConditionalFormattings();
    const cfvos = normalizeHeatmapStops(entry.heatmap.stops, index2);
    const colors = normalizeHeatmapColors(entry.heatmap.colors, index2);
    const rule2 = buildHeatmapCfRule(cfvos, colors, conditionalFormattings.length + 1);
    const { startAddress, endAddress } = boundsToAddresses(parsed.bounds);
    const formatting = {
      ranges: [
        {
          sheetName,
          sheetId: worksheet.id ?? "",
          startAddress,
          endAddress
        }
      ],
      rules: [rule2]
    };
    conditionalFormattings.push(formatting);
  });
}
function resolveSheetAndRange(entry, sheetNames, index2) {
  const { sheet: sheetFromRange, reference } = splitSheetFromRange(entry.range);
  if (!reference) {
    throw new Error(`${ERROR_PREFIX}cf[${index2}].range must specify cells`);
  }
  if (sheetFromRange && entry.sheetName && sheetFromRange !== entry.sheetName) {
    throw new Error(`${ERROR_PREFIX}cf[${index2}] sheet reference mismatch between "sheet" and range qualifier`);
  }
  let sheetName = sheetFromRange ?? entry.sheetName;
  if (!sheetName) {
    if (sheetNames.length === 1) {
      sheetName = sheetNames[0];
    } else {
      throw new Error(`${ERROR_PREFIX}cf[${index2}] must specify a sheet when multiple sheets exist`);
    }
  }
  return { sheetName, reference };
}
function splitSheetFromRange(range2) {
  const trimmed = range2.trim();
  const index2 = trimmed.indexOf("!");
  if (index2 === -1) {
    return { reference: trimmed };
  }
  const sheet = trimmed.slice(0, index2).trim();
  const reference = trimmed.slice(index2 + 1).trim();
  return {
    sheet: sheet || undefined,
    reference
  };
}
function normalizeRangeReference(reference, index2) {
  if (!reference) {
    throw new Error(`${ERROR_PREFIX}cf[${index2}].range must not be empty`);
  }
  const parts = reference.split(":");
  const normalizedParts = parts.map((part) => {
    const normalized = normalizeAddress(part);
    if (!normalized) {
      throw new Error(`${ERROR_PREFIX}cf[${index2}].range "${reference}" is invalid`);
    }
    return normalized;
  });
  const first = normalizedParts[0];
  if (!first) {
    throw new Error(`${ERROR_PREFIX}cf[${index2}].range must not be empty`);
  }
  if (normalizedParts.length === 2) {
    const second = normalizedParts[1];
    if (!second) {
      throw new Error(`${ERROR_PREFIX}cf[${index2}].range "${reference}" is invalid`);
    }
    return `${first}:${second}`;
  }
  return first;
}
function boundsToAddresses(bounds) {
  return {
    startAddress: makeCellAddress(bounds.startRow, bounds.startCol),
    endAddress: makeCellAddress(bounds.endRow, bounds.endCol)
  };
}
function normalizeHeatmapColors(colors, cfIndex) {
  if (colors.length !== 3) {
    throw new Error(`${ERROR_PREFIX}cf[${cfIndex}].heatmap.colors must have exactly 3 entries`);
  }
  return colors.map((color3, colorIndex) => ({
    type: 1 /* COLOR_TYPE_RGB */,
    value: normalizeColorHex(color3, cfIndex, colorIndex),
    transform: undefined,
    lastColor: undefined
  }));
}
function normalizeColorHex(color3, cfIndex, colorIndex) {
  if (typeof color3 !== "string") {
    throw new Error(`${ERROR_PREFIX}cf[${cfIndex}].heatmap.colors[${colorIndex}] must be a string`);
  }
  const trimmed = color3.trim();
  const withoutPrefix = trimmed.startsWith("#") ? trimmed.slice(1) : trimmed;
  const upper = withoutPrefix.toUpperCase();
  if (/^[0-9A-F]{6}$/.test(upper)) {
    return `FF${upper}`;
  }
  if (/^[0-9A-F]{8}$/.test(upper)) {
    return upper;
  }
  throw new Error(`${ERROR_PREFIX}cf[${cfIndex}].heatmap.colors[${colorIndex}] must be 6 or 8 hex digits`);
}
function normalizeHeatmapStops(stops, cfIndex) {
  const source = stops && stops.length > 0 ? stops : ["min", "50%", "max"];
  if (source.length !== 3) {
    throw new Error(`${ERROR_PREFIX}cf[${cfIndex}].heatmap.stops must provide exactly 3 entries`);
  }
  return source.map((value2, stopIndex) => normalizeHeatmapStop(value2, cfIndex, stopIndex));
}
function normalizeHeatmapStop(value2, cfIndex, stopIndex) {
  if (typeof value2 === "number") {
    if (!Number.isFinite(value2)) {
      throw new Error(`${ERROR_PREFIX}cf[${cfIndex}].heatmap.stops[${stopIndex}] must be finite`);
    }
    return { type: "num", val: String(value2) };
  }
  const trimmed = value2.trim();
  if (!trimmed) {
    throw new Error(`${ERROR_PREFIX}cf[${cfIndex}].heatmap.stops[${stopIndex}] must not be empty`);
  }
  const lower = trimmed.toLowerCase();
  if (lower === "min" || lower === "max") {
    return { type: lower };
  }
  if (lower.endsWith("%")) {
    const numeric = lower.slice(0, -1).trim();
    if (!numeric) {
      throw new Error(`${ERROR_PREFIX}cf[${cfIndex}].heatmap.stops[${stopIndex}] must provide a percentile value`);
    }
    return { type: "percentile", val: numeric };
  }
  const numericValue = Number(trimmed);
  if (Number.isFinite(numericValue)) {
    return { type: "num", val: String(numericValue) };
  }
  throw new Error(`${ERROR_PREFIX}cf[${cfIndex}].heatmap.stops[${stopIndex}] must be "min", "max", a percentile, or a number`);
}
function buildHeatmapCfRule(cfvos, colors, priority) {
  return {
    type: "colorScale",
    priority,
    operator: "",
    formula: [],
    colorScale: {
      cfvos,
      colors
    }
  };
}
function ensureCategorySeries(value2, expectedLength) {
  if (!Array.isArray(value2) || value2.length === 0) {
    throw new Error(`${ERROR_PREFIX}"data.series" must be a non-empty array`);
  }
  return value2.map((entry, seriesIndex) => {
    if (!isObject2(entry)) {
      throw new Error(`${ERROR_PREFIX}data.series[${seriesIndex}] must be an object`);
    }
    const name2 = ensureNonEmptyString(entry["name"], `data.series[${seriesIndex}].name must be a non-empty string`);
    const rawValues = entry["values"];
    if (!Array.isArray(rawValues)) {
      throw new Error(`${ERROR_PREFIX}data.series[${seriesIndex}].values must be an array`);
    }
    const values2 = rawValues.map((valueItem, valueIndex) => toFiniteNumber2(valueItem, `data.series[${seriesIndex}].values[${valueIndex}]`));
    if (values2.length !== expectedLength) {
      throw new Error(`${ERROR_PREFIX}data.series[${seriesIndex}].values length (${values2.length}) must match data.categories length (${expectedLength})`);
    }
    return { name: name2, values: values2 };
  });
}
function selectSeries(series, selection) {
  if (selection === undefined) {
    return series.slice(0, 1);
  }
  if (typeof selection === "string") {
    if (selection === "all") {
      return series;
    }
    return [findSeriesByName(series, selection)];
  }
  if (Array.isArray(selection)) {
    if (selection.length === 0) {
      throw new Error(`${ERROR_PREFIX}encoding.y array must include at least one series name`);
    }
    return selection.map((item) => findSeriesByName(series, ensureNonEmptyString(item, "encoding.y value")));
  }
  throw new Error(`${ERROR_PREFIX}encoding.y must be a string, an array of strings, or "all"`);
}
function findSeriesByName(series, name2) {
  const match = series.find((entry) => entry.name === name2);
  if (!match) {
    throw new Error(`${ERROR_PREFIX}encoding.y references unknown series "${name2}"`);
  }
  return match;
}
function ensureScatterSeries(value2, opts = {}) {
  if (!Array.isArray(value2) || value2.length === 0) {
    throw new Error(`${ERROR_PREFIX}"data.series" must be a non-empty array for scatter charts`);
  }
  return value2.map((entry, seriesIndex) => {
    if (!isObject2(entry)) {
      throw new Error(`${ERROR_PREFIX}data.series[${seriesIndex}] must be an object`);
    }
    const name2 = ensureNonEmptyString(entry["name"], `data.series[${seriesIndex}].name must be a non-empty string`);
    const points = entry["points"];
    if (!Array.isArray(points) || points.length === 0) {
      throw new Error(`${ERROR_PREFIX}data.series[${seriesIndex}].points must be a non-empty array`);
    }
    const xValues = [];
    const yValues = [];
    const sizeValues = [];
    const labels = [];
    points.forEach((point5, pointIndex) => {
      if (!isObject2(point5)) {
        throw new Error(`${ERROR_PREFIX}data.series[${seriesIndex}].points[${pointIndex}] must be an object`);
      }
      yValues.push(toFiniteNumber2(point5["y"], `data.series[${seriesIndex}].points[${pointIndex}].y`));
      xValues.push(toScatterXValue(point5["x"], `data.series[${seriesIndex}].points[${pointIndex}].x`));
      if (opts.includeSize) {
        sizeValues.push(toFiniteNumber2(point5["size"], `data.series[${seriesIndex}].points[${pointIndex}].size`));
      }
      const labelValue = point5["label"];
      if (typeof labelValue === "string") {
        labels.push(labelValue.trim());
      } else if (labelValue === undefined || labelValue === null) {
        labels.push("");
      } else {
        throw new Error(`${ERROR_PREFIX}data.series[${seriesIndex}].points[${pointIndex}].label must be a string when provided`);
      }
    });
    const result = { name: name2, xValues, yValues };
    if (opts.includeSize) {
      result.sizeValues = sizeValues;
    }
    if (labels.some((label) => label.length > 0)) {
      result.labels = labels;
    }
    return result;
  });
}
function ensureTreemapPoints(value2) {
  if (!Array.isArray(value2) || value2.length === 0) {
    throw new Error(`${ERROR_PREFIX}"data.points" must be a non-empty array for treemap charts`);
  }
  return value2.map((entry, index2) => {
    if (!isObject2(entry)) {
      throw new Error(`${ERROR_PREFIX}data.points[${index2}] must be an object`);
    }
    const path4 = ensureStringArray(entry["path"], `data.points[${index2}].path must be an array of strings`);
    if (path4.length === 0) {
      throw new Error(`${ERROR_PREFIX}data.points[${index2}].path must contain at least one segment`);
    }
    const valueNumber = toFiniteNumber2(entry["value"], `data.points[${index2}].value`);
    return { path: path4, value: valueNumber };
  });
}
function ensureMapRegions(value2) {
  if (!Array.isArray(value2) || value2.length === 0) {
    throw new Error(`${ERROR_PREFIX}"data.regions" must be a non-empty array for map charts`);
  }
  return value2.map((entry, index2) => {
    if (!isObject2(entry)) {
      throw new Error(`${ERROR_PREFIX}data.regions[${index2}] must be an object`);
    }
    const key = ensureNonEmptyString(entry["key"], `data.regions[${index2}].key must be a non-empty string`);
    const valueNumber = toFiniteNumber2(entry["value"], `data.regions[${index2}].value`);
    return { key, value: valueNumber };
  });
}
function ensureHistogramValues(value2) {
  if (!Array.isArray(value2) || value2.length === 0) {
    throw new Error(`${ERROR_PREFIX}"data.values" must be a non-empty array of numbers for histogram charts`);
  }
  return value2.map((entry, index2) => toFiniteNumber2(entry, `data.values[${index2}]`));
}
function ensureBoxWhiskerSamples(value2) {
  if (!Array.isArray(value2) || value2.length === 0) {
    throw new Error(`${ERROR_PREFIX}"data.samples" must be a non-empty array for box-whisker charts`);
  }
  return value2.map((entry, index2) => {
    if (!isObject2(entry)) {
      throw new Error(`${ERROR_PREFIX}data.samples[${index2}] must be an object`);
    }
    const category = ensureNonEmptyString(entry["category"], `data.samples[${index2}].category must be a non-empty string`);
    const rawValues = entry["values"];
    if (!Array.isArray(rawValues) || rawValues.length === 0) {
      throw new Error(`${ERROR_PREFIX}data.samples[${index2}].values must be a non-empty array`);
    }
    const values2 = rawValues.map((valueItem, valueIndex) => toFiniteNumber2(valueItem, `data.samples[${index2}].values[${valueIndex}]`));
    return { category, values: values2 };
  });
}
function normalizeLegendPosition2(value2) {
  const trimmed = value2.trim();
  switch (trimmed) {
    case "top-right":
    case "top_right":
      return "topRight";
    case "left-overlay":
    case "leftOverlay":
      return "left";
    case "right-overlay":
    case "rightOverlay":
      return "right";
    case "top-overlay":
    case "topOverlay":
      return "top";
    case "bottom-overlay":
    case "bottomOverlay":
      return "bottom";
    default:
      return "topRight";
  }
}
function normalizeDataLabelPosition(value2) {
  const trimmed = value2.trim();
  switch (trimmed) {
    case "out":
    case "outside":
    case "outer":
      return "outEnd";
    case "in":
    case "inside":
      return "inEnd";
    case "center":
      return "center";
    default:
      return "center";
  }
}
function normalizeBarDirection(value2) {
  const normalized = value2.trim().toLowerCase();
  if (normalized === "column") {
    return "column";
  }
  if (normalized === "bar" || normalized === "row") {
    return "bar";
  }
  return;
}
function normalizeBarGrouping(value2) {
  const normalized = value2.trim().toLowerCase();
  switch (normalized) {
    case "clustered":
      return "clustered";
    case "stacked":
    case "normal":
      return "stacked";
    case "percent":
    case "percentstacked":
    case "percent-stacked":
      return "percentStacked";
    case "none":
      return "clustered";
    default:
      return;
  }
}
function normalizeLineGrouping(value2) {
  const normalized = value2.trim().toLowerCase();
  switch (normalized) {
    case "none":
    case "standard":
      return "standard";
    case "normal":
    case "stacked":
      return "stacked";
    case "percent":
    case "percentstacked":
    case "percent-stacked":
      return "percentStacked";
    default:
      return;
  }
}
function normalizeScatterStyle(value2) {
  const normalized = value2.trim();
  switch (normalized) {
    case "marker":
      return "marker";
    case "line":
      return "line";
    case "lineMarker":
    case "line-marker":
      return "lineWithMarkers";
    case "smooth":
      return "smooth";
    case "smoothMarker":
    case "smooth-marker":
      return "smoothWithMarkers";
    default:
      return;
  }
}
function normalizeMapArea(value2) {
  const normalized = value2.trim();
  if (normalized === "data-only") {
    return "dataOnly";
  }
  if (normalized === "auto" || normalized === "world" || normalized === "region" || normalized === "dataOnly") {
    return normalized;
  }
  return;
}
function normalizeMapProjection(value2) {
  const normalized = value2.trim().toLowerCase();
  switch (normalized) {
    case "auto":
    case "automatic":
      return "auto";
    case "mercator":
      return "mercator";
    case "miller":
      return "miller";
    case "albers":
      return "albers";
    default:
      return;
  }
}
function normalizeMapLabelLayout(value2) {
  const normalized = value2.trim();
  switch (normalized) {
    case "none":
      return "none";
    case "bestFit":
    case "best-fit":
      return "bestFit";
    case "showAll":
    case "show-all":
      return "showAll";
    default:
      return;
  }
}
function normalizeMapDataLevel(value2) {
  const normalized = value2.trim();
  switch (normalized) {
    case "country":
    case "countryOrRegion":
    case "country-or-region":
      return "countryOrRegion";
    case "state":
    case "stateOrProvince":
    case "state-or-province":
      return "stateOrProvince";
    case "county":
      return "county";
    case "postal-code":
    case "postalCode":
      return "postalCode";
    case "country-code":
      return "countryOrRegionCode";
    case "state-code":
      return "stateCode";
    case "county-code":
      return "countyCode";
    default:
      return;
  }
}
function normalizeHistogramInterval(value2) {
  if (value2 === null || value2 === undefined) {
    return;
  }
  if (typeof value2 === "number") {
    if (value2 === 1 /* INTERVAL_CLOSED_LEFT */ || value2 === 2 /* INTERVAL_CLOSED_RIGHT */ || value2 === 0 /* INTERVAL_CLOSED_UNSPECIFIED */) {
      return value2;
    }
  }
  if (typeof value2 !== "string") {
    throw new Error(`${ERROR_PREFIX}options.histogram.intervalClosed must be a string or enum value`);
  }
  const trimmed = value2.trim();
  const upper = trimmed.toUpperCase();
  switch (upper) {
    case "INTERVAL_CLOSED_LEFT":
      return 1 /* INTERVAL_CLOSED_LEFT */;
    case "INTERVAL_CLOSED_RIGHT":
      return 2 /* INTERVAL_CLOSED_RIGHT */;
    case "INTERVAL_CLOSED_UNSPECIFIED":
      return 0 /* INTERVAL_CLOSED_UNSPECIFIED */;
    default:
      break;
  }
  const lower = trimmed.toLowerCase();
  if (lower === "left" || lower === "closed-left" || lower === "interval_closed_left" || lower === "interval-closed-left" || lower === "l") {
    return 1 /* INTERVAL_CLOSED_LEFT */;
  }
  if (lower === "right" || lower === "closed-right" || lower === "interval_closed_right" || lower === "interval-closed-right" || lower === "r") {
    return 2 /* INTERVAL_CLOSED_RIGHT */;
  }
  if (lower === "none" || lower === "unspecified" || lower === "interval_closed_unspecified") {
    return 0 /* INTERVAL_CLOSED_UNSPECIFIED */;
  }
  throw new Error(`${ERROR_PREFIX}options.histogram.intervalClosed must be "left", "right", or "unspecified"`);
}
function normalizeQuartileMethod(value2) {
  if (value2 === null || value2 === undefined) {
    return;
  }
  if (typeof value2 !== "string") {
    throw new Error(`${ERROR_PREFIX}options.boxWhisker.quartileMethod must be a string or enum value`);
  }
  const normalized = value2.trim().toLowerCase();
  switch (normalized) {
    case "inclusive":
      return "inclusive";
    case "exclusive":
      return "exclusive";
    default:
      return;
  }
}
function ensureStringArray(value2, message) {
  if (!Array.isArray(value2) || value2.length === 0) {
    throw new Error(`${ERROR_PREFIX}${message}`);
  }
  return value2.map((item, index2) => ensureNonEmptyString(item, `${message} (found non-string at index ${index2})`));
}
function ensureNonEmptyString(value2, message) {
  if (typeof value2 !== "string") {
    throw new Error(`${ERROR_PREFIX}${message}`);
  }
  const trimmed = value2.trim();
  if (!trimmed) {
    throw new Error(`${ERROR_PREFIX}${message}`);
  }
  return trimmed;
}
function toFiniteNumber2(value2, context) {
  if (typeof value2 === "number") {
    if (!Number.isFinite(value2)) {
      throw new Error(`${ERROR_PREFIX}${context} must be a finite number`);
    }
    return value2;
  }
  if (typeof value2 === "string" && value2.trim() !== "") {
    const parsed = Number(value2);
    if (Number.isFinite(parsed)) {
      return parsed;
    }
  }
  throw new Error(`${ERROR_PREFIX}${context} must be a number`);
}
function toOptionalFiniteNumber(value2, context) {
  if (value2 === null || value2 === undefined) {
    return;
  }
  return toFiniteNumber2(value2, context);
}
function toScatterXValue(value2, context) {
  if (typeof value2 === "number") {
    if (!Number.isFinite(value2)) {
      throw new Error(`${ERROR_PREFIX}${context} must be a finite number`);
    }
    return value2;
  }
  if (value2 instanceof Date) {
    return value2.getTime();
  }
  if (typeof value2 === "string" && value2.trim() !== "") {
    const numeric = Number(value2);
    if (Number.isFinite(numeric)) {
      return numeric;
    }
    const parsedDate = Date.parse(value2);
    if (!Number.isNaN(parsedDate)) {
      return parsedDate;
    }
  }
  throw new Error(`${ERROR_PREFIX}${context} must be a number or a valid date string`);
}
function getObject(value2) {
  return isObject2(value2) ? value2 : undefined;
}
function isObject2(value2) {
  return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
}
function isSupportedType(value2) {
  return value2 in TYPE_CONFIG;
}
function errorMessage(error49) {
  return error49 instanceof Error ? error49.message : String(error49);
}
function isSpreadsheetType(value2) {
  return value2 === "sheet" || value2 === "workbook";
}
// node_modules/@oai/granola/dist/models/presentation/google-slides/client.js
var DEFAULT_BASE_URL = "https://slides.googleapis.com/";

class FetchGoogleSlidesClient {
  #accessToken;
  #apiKey;
  #baseUrl;
  constructor(options) {
    this.#accessToken = options.accessToken;
    this.#apiKey = options.apiKey;
    this.#baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
  }
  async getPresentation(presentationId, options) {
    const url2 = new URL(`v1/presentations/${encodeURIComponent(presentationId)}`, this.#baseUrl);
    if (this.#apiKey) {
      url2.searchParams.set("key", this.#apiKey);
    }
    if (options?.fields) {
      url2.searchParams.set("fields", options.fields);
    }
    const response = await fetch(url2.toString(), {
      method: "GET",
      headers: this.#authHeaders()
    });
    return this.#parseResponse(response);
  }
  async batchUpdate(presentationId, request) {
    const url2 = new URL(`v1/presentations/${encodeURIComponent(presentationId)}:batchUpdate`, this.#baseUrl);
    if (this.#apiKey) {
      url2.searchParams.set("key", this.#apiKey);
    }
    const response = await fetch(url2.toString(), {
      method: "POST",
      headers: {
        ...this.#authHeaders(),
        "Content-Type": "application/json"
      },
      body: JSON.stringify(request)
    });
    return this.#parseResponse(response);
  }
  #authHeaders() {
    return { Authorization: `Bearer ${this.#accessToken}` };
  }
  async#parseResponse(response) {
    const body = await response.json().catch(() => ({}));
    if (!response.ok) {
      const message = typeof body?.error?.message === "string" ? body.error.message : `Google Slides API error (${response.status})`;
      throw new Error(message);
    }
    return body;
  }
}

class GapiGoogleSlidesClient {
  #gapi;
  constructor(gapi) {
    this.#gapi = gapi;
  }
  async getPresentation(presentationId, options) {
    const response = await this.#gapi.client.slides.presentations.get({
      presentationId,
      fields: options?.fields
    });
    return response.result;
  }
  async batchUpdate(presentationId, request) {
    const response = await this.#gapi.client.slides.presentations.batchUpdate({
      presentationId,
      requests: request.requests,
      writeControl: request.writeControl,
      responseIncludeFields: request.responseIncludeFields
    });
    return response.result;
  }
}
// node_modules/@oai/granola/dist/models/spreadsheet/google-sheets/adapter/options.js
function splitResponseRanges(value2) {
  const ranges = [];
  let current = "";
  let inQuotedSheetName = false;
  for (let i = 0;i < value2.length; i += 1) {
    const char = value2[i];
    if (char === "'") {
      current += char;
      if (inQuotedSheetName && value2[i + 1] === "'") {
        current += value2[i + 1];
        i += 1;
        continue;
      }
      inQuotedSheetName = !inQuotedSheetName;
      continue;
    }
    if (char === "," && !inQuotedSheetName) {
      const trimmed2 = current.trim();
      if (trimmed2) {
        ranges.push(trimmed2);
      }
      current = "";
      continue;
    }
    current += char;
  }
  const trimmed = current.trim();
  if (trimmed) {
    ranges.push(trimmed);
  }
  return ranges;
}
function normalizeBatchUpdateOptions(options, warnings) {
  if (!options) {
    return;
  }
  const rawOptions = options;
  const normalized = {
    ...rawOptions
  };
  if (normalized.includeSpreadsheetInResponse === undefined && normalized.include_spreadsheet_in_response !== undefined) {
    normalized.includeSpreadsheetInResponse = Boolean(normalized.include_spreadsheet_in_response);
    warnings.push("googleSheets: normalized include_spreadsheet_in_response to includeSpreadsheetInResponse.");
  }
  if (normalized.responseRanges === undefined && normalized.response_ranges !== undefined) {
    normalized.responseRanges = normalized.response_ranges;
    warnings.push("googleSheets: normalized response_ranges to responseRanges.");
  }
  if (normalized.responseIncludeGridData === undefined && normalized.response_include_grid_data !== undefined) {
    normalized.responseIncludeGridData = Boolean(normalized.response_include_grid_data);
    warnings.push("googleSheets: normalized response_include_grid_data to responseIncludeGridData.");
  }
  if (typeof normalized.responseRanges === "string") {
    const responseRanges = splitResponseRanges(normalized.responseRanges);
    if (responseRanges.length === 0) {
      delete normalized.responseRanges;
      warnings.push("googleSheets: dropped empty responseRanges string; expected string[].");
    } else {
      normalized.responseRanges = responseRanges;
      warnings.push(responseRanges.length > 1 ? "googleSheets: normalized comma-delimited responseRanges string to discovery-doc array shape." : "googleSheets: normalized responseRanges string to discovery-doc array shape.");
    }
  } else if (normalized.responseRanges !== undefined && !Array.isArray(normalized.responseRanges)) {
    delete normalized.responseRanges;
    warnings.push("googleSheets: dropped invalid responseRanges; expected string[].");
  }
  delete normalized.include_spreadsheet_in_response;
  delete normalized.response_ranges;
  delete normalized.response_include_grid_data;
  return {
    includeSpreadsheetInResponse: normalized.includeSpreadsheetInResponse,
    responseRanges: normalized.responseRanges,
    responseIncludeGridData: normalized.responseIncludeGridData
  };
}
function buildConnectorArgs(payload, spreadsheetUrl) {
  return {
    spreadsheet_url: spreadsheetUrl ?? `https://docs.google.com/spreadsheets/d/${encodeURIComponent(payload.spreadsheetId)}/edit`,
    requests: payload.requests,
    ...payload.includeSpreadsheetInResponse !== undefined ? {
      include_spreadsheet_in_response: payload.includeSpreadsheetInResponse
    } : {},
    ...payload.responseRanges !== undefined ? {
      response_ranges: payload.responseRanges
    } : {},
    ...payload.responseIncludeGridData !== undefined ? {
      response_include_grid_data: payload.responseIncludeGridData
    } : {}
  };
}
// node_modules/@oai/granola/dist/models/spreadsheet/google-sheets/adapter/shared.js
init_address_utils();
var THEME_COLOR_MAP2 = {
  accent1: "ACCENT1",
  accent2: "ACCENT2",
  accent3: "ACCENT3",
  accent4: "ACCENT4",
  accent5: "ACCENT5",
  accent6: "ACCENT6",
  bg1: "BACKGROUND1",
  bg2: "BACKGROUND2",
  tx1: "TEXT1",
  tx2: "TEXT2",
  dk1: "DARK1",
  dk2: "DARK2",
  lt1: "LIGHT1",
  lt2: "LIGHT2",
  hlink: "HYPERLINK",
  folHlink: "FOLLOWED_HYPERLINK"
};
var A1_REFERENCE_OR_RANGE_RE = /^(?:(?:'[^']+'|[^'!]+)!)?\$?[A-Z]+\$?\d+(?::\$?[A-Z]+\$?\d+)?$/i;
var SHEET_QUALIFIED_RANGE_RE = /^(?:'[^']+'|[^'!]+)!\$?[A-Z]+\$?\d+(?::\$?[A-Z]+\$?\d+)?$/i;
var FUNCTION_LIKE_RE = /^[A-Z_][A-Z0-9_.]*\s*\(/i;
function toSheetId(value2) {
  const numeric = typeof value2 === "number" ? value2 : Number(value2);
  if (!Number.isFinite(numeric) || numeric < 0) {
    throw new Error(`googleSheets: invalid sheetId ${String(value2)}`);
  }
  return Math.floor(numeric);
}
function toGridRange(target) {
  const parsed = parseRangeAddress(target.range);
  if (!parsed) {
    throw new Error(`googleSheets: invalid range ${target.range}`);
  }
  return {
    sheetId: toSheetId(target.sheetId),
    startRowIndex: parsed.bounds.startRow,
    endRowIndex: parsed.bounds.endRow + 1,
    startColumnIndex: parsed.bounds.startCol,
    endColumnIndex: parsed.bounds.endCol + 1
  };
}
function toGridStart(target) {
  const parsed = parseRangeAddress(target.range);
  if (!parsed) {
    throw new Error(`googleSheets: invalid range ${target.range}`);
  }
  return {
    sheetId: toSheetId(target.sheetId),
    rowIndex: parsed.bounds.startRow,
    columnIndex: parsed.bounds.startCol
  };
}
function buildCellValue(value2) {
  if (value2 === null) {
    return;
  }
  if (typeof value2 === "string") {
    return { stringValue: value2 };
  }
  if (typeof value2 === "number") {
    return { numberValue: value2 };
  }
  if (typeof value2 === "boolean") {
    return { boolValue: value2 };
  }
  return;
}
function buildFormulaValue(value2) {
  if (value2.startsWith("=")) {
    return { formulaValue: value2 };
  }
  return { stringValue: value2 };
}
function toColorStyle(input) {
  if (input === undefined || input === null) {
    return;
  }
  const color4 = input instanceof Color4 ? input : new Color4(input);
  if (color4.type === "theme") {
    const themeColor = THEME_COLOR_MAP2[color4.value];
    if (themeColor) {
      return { themeColor };
    }
  }
  const hex4 = color4.hex;
  const normalized = hex4.startsWith("#") ? hex4.slice(1) : hex4;
  if (normalized.length !== 6) {
    return;
  }
  const red = Number.parseInt(normalized.slice(0, 2), 16) / 255;
  const green = Number.parseInt(normalized.slice(2, 4), 16) / 255;
  const blue = Number.parseInt(normalized.slice(4, 6), 16) / 255;
  return {
    rgbColor: {
      red,
      green,
      blue
    }
  };
}
function normalizeA1RangeValue(value2) {
  if (typeof value2 !== "string") {
    return null;
  }
  const trimmed = value2.trim().replace(/^=/, "");
  if (!trimmed) {
    return null;
  }
  if (A1_REFERENCE_OR_RANGE_RE.test(trimmed) || SHEET_QUALIFIED_RANGE_RE.test(trimmed)) {
    return trimmed;
  }
  return trimmed;
}
function looksLikeFormulaOrReference(value2) {
  return value2.startsWith("=") || value2.startsWith("+") || FUNCTION_LIKE_RE.test(value2) || A1_REFERENCE_OR_RANGE_RE.test(value2) || SHEET_QUALIFIED_RANGE_RE.test(value2);
}
function ensureLeadingFormulaPrefix(value2) {
  if (value2.startsWith("=") || value2.startsWith("+")) {
    return value2;
  }
  return `=${value2}`;
}
function toConditionValue(value2, options) {
  if (value2 === undefined || value2 === null) {
    return null;
  }
  if (typeof value2 === "number") {
    return { userEnteredValue: String(value2) };
  }
  const trimmed = value2.trim();
  if (!trimmed) {
    return null;
  }
  if (options?.coerceFormula) {
    return {
      userEnteredValue: ensureLeadingFormulaPrefix(trimmed)
    };
  }
  if (options?.coerceReferenceFormula && looksLikeFormulaOrReference(trimmed)) {
    return {
      userEnteredValue: ensureLeadingFormulaPrefix(trimmed)
    };
  }
  return {
    userEnteredValue: trimmed
  };
}
function normalizeRangeRef2(range2) {
  const parsed = parseRangeAddress(range2);
  if (!parsed) {
    throw new Error(`googleSheets: invalid range ${range2}`);
  }
  return parsed.ref;
}
function isNumericLiteralString(value2) {
  const trimmed = value2.trim();
  if (!trimmed) {
    return false;
  }
  const numeric = Number(trimmed);
  return Number.isFinite(numeric);
}
function isPlainTextConditionLiteral(value2) {
  return !looksLikeFormulaOrReference(value2) && !isNumericLiteralString(value2);
}
function normalizeDefinedName(name2) {
  return name2?.trim().toUpperCase() ?? "";
}
function cloneWorksheetLike(sheet) {
  return {
    name: sheet.name,
    index: sheet.index,
    sheetId: sheet.sheetId
  };
}
function cloneGridRange(range2) {
  return { ...range2 };
}
function quoteSheetName(sheetName) {
  return `'${sheetName.replace(/'/g, "''")}'`;
}
function normalizeTableName(name2) {
  return name2?.trim().toUpperCase() ?? "";
}

// node_modules/@oai/granola/dist/models/spreadsheet/google-sheets/adapter/conditional-formatting.js
var NUMBER_CONDITIONAL_FORMAT_OPERATOR_MAP = {
  between: "NUMBER_BETWEEN",
  notBetween: "NUMBER_NOT_BETWEEN",
  equal: "NUMBER_EQ",
  notEqual: "NUMBER_NOT_EQ",
  lessThan: "NUMBER_LESS",
  lessThanOrEqual: "NUMBER_LESS_THAN_EQ",
  greaterThan: "NUMBER_GREATER",
  greaterThanOrEqual: "NUMBER_GREATER_THAN_EQ"
};
var TEXT_CONDITIONAL_FORMAT_OPERATOR_MAP = {
  equal: "TEXT_EQ",
  notEqual: "TEXT_NOT_EQ"
};
function conditionalFormatRangeTargetToKey(target) {
  if (!target.startAddress) {
    return null;
  }
  return normalizeRangeRef2(target.endAddress && target.endAddress !== target.startAddress ? `${target.startAddress}:${target.endAddress}` : target.startAddress);
}
function buildConditionalFormatRule(sheetId, op, warnings) {
  const gridRange = toGridRange({ sheetId, range: op.target.range });
  const rule2 = op.props.rule;
  switch (rule2.type) {
    case "cellIs": {
      const booleanRule = buildConditionalFormatCellIsRule(rule2, warnings);
      return booleanRule ? {
        ranges: [gridRange],
        booleanRule
      } : null;
    }
    case "expression": {
      const booleanRule = buildConditionalFormatExpressionRule(rule2, warnings);
      return booleanRule ? {
        ranges: [gridRange],
        booleanRule
      } : null;
    }
    case "colorScale": {
      const gradientRule = buildConditionalFormatGradientRule(rule2, warnings);
      return gradientRule ? {
        ranges: [gridRange],
        gradientRule
      } : null;
    }
    case "dataBar":
      warnings.push("googleSheets: conditionalformat.add dataBar rules are not supported by the Sheets discovery-doc conditional-format payload and were dropped.");
      return null;
    case "iconSet":
      warnings.push("googleSheets: conditionalformat.add iconSet rules are not supported by the Sheets discovery-doc conditional-format payload and were dropped.");
      return null;
    default:
      warnings.push(`googleSheets: conditionalformat.add rule type ${rule2.type} is not supported yet.`);
      return null;
  }
}
function buildConditionalFormatCellIsRule(rule2, warnings) {
  const formulas2 = Array.isArray(rule2.formula) ? rule2.formula : [rule2.formula];
  const expectsTwoValues = rule2.operator === "between" || rule2.operator === "notBetween";
  const expectedValueCount = expectsTwoValues ? 2 : 1;
  if (formulas2.length < expectedValueCount) {
    warnings.push(`googleSheets: conditionalformat.add cellIs ${rule2.operator} requires ${expectedValueCount} value${expectedValueCount === 1 ? "" : "s"}.`);
    return null;
  }
  if (formulas2.length > expectedValueCount) {
    warnings.push(`googleSheets: conditionalformat.add cellIs ${rule2.operator} only uses ${expectedValueCount} value${expectedValueCount === 1 ? "" : "s"}; dropped extras.`);
  }
  const values2 = formulas2.slice(0, expectedValueCount);
  const useTextCondition = !expectsTwoValues && (rule2.operator === "equal" || rule2.operator === "notEqual") && typeof values2[0] === "string" && isPlainTextConditionLiteral(values2[0]);
  if (!useTextCondition && values2.some((value2) => typeof value2 === "string" && isPlainTextConditionLiteral(value2))) {
    warnings.push(`googleSheets: conditionalformat.add cellIs ${rule2.operator} only supports plain-text literals for equal/notEqual; dropped rule.`);
    return null;
  }
  const conditionType = useTextCondition ? TEXT_CONDITIONAL_FORMAT_OPERATOR_MAP[rule2.operator] : NUMBER_CONDITIONAL_FORMAT_OPERATOR_MAP[rule2.operator];
  if (!conditionType) {
    warnings.push(`googleSheets: conditionalformat.add cellIs ${rule2.operator} is not supported by Sheets BooleanCondition.`);
    return null;
  }
  const conditionValues = values2.map((value2) => useTextCondition ? toConditionValue(value2) : toConditionValue(value2, { coerceReferenceFormula: true })).filter((value2) => value2 !== null);
  if (conditionValues.length !== expectedValueCount) {
    warnings.push(`googleSheets: conditionalformat.add cellIs ${rule2.operator} could not be converted to Sheets condition values.`);
    return null;
  }
  const format3 = buildConditionalFormatCellFormat(rule2.format, warnings);
  return {
    condition: {
      type: conditionType,
      values: conditionValues
    },
    ...format3 ? { format: format3 } : {}
  };
}
function buildConditionalFormatExpressionRule(rule2, warnings) {
  const conditionValue = toConditionValue(rule2.formula, { coerceFormula: true });
  if (!conditionValue) {
    warnings.push("googleSheets: conditionalformat.add expression rules require a formula.");
    return null;
  }
  const format3 = buildConditionalFormatCellFormat(rule2.format, warnings);
  return {
    condition: {
      type: "CUSTOM_FORMULA",
      values: [conditionValue]
    },
    ...format3 ? { format: format3 } : {}
  };
}
function buildConditionalFormatCellFormat(format3, warnings) {
  if (!format3) {
    return;
  }
  const cellFormat = {};
  if (format3.fill !== undefined) {
    const fill3 = format3.fill instanceof Fill2 ? format3.fill : new Fill2(format3.fill);
    const fillProto = fill3.toProto();
    const isSolidFill = !!fillProto && !fillProto.pattern && !fillProto.relId && !fillProto.gradientStops?.length;
    if (isSolidFill) {
      const colorStyle = toColorStyle(fill3.color);
      if (colorStyle) {
        cellFormat.backgroundColorStyle = colorStyle;
      }
    } else {
      warnings.push("googleSheets: conditionalformat.add only solid fills are supported in Sheets booleanRule.format.");
    }
  }
  if (format3.font) {
    const textFormat = {};
    if (format3.font.bold !== undefined) {
      textFormat.bold = format3.font.bold;
    }
    if (format3.font.italic !== undefined) {
      textFormat.italic = format3.font.italic;
    }
    if (format3.font.color !== undefined) {
      textFormat.foregroundColorStyle = toColorStyle(format3.font.color);
    }
    if (format3.font.size !== undefined) {
      warnings.push("googleSheets: conditionalformat.add font.size is not supported by Sheets booleanRule.format and was dropped.");
    }
    if (format3.font.name !== undefined) {
      warnings.push("googleSheets: conditionalformat.add font.name is not supported by Sheets booleanRule.format and was dropped.");
    }
    if (Object.keys(textFormat).length > 0) {
      cellFormat.textFormat = textFormat;
    }
  }
  if (format3.border) {
    warnings.push("googleSheets: conditionalformat.add borders are not supported by Sheets booleanRule.format and were dropped.");
  }
  if (format3.numberFormat !== undefined) {
    warnings.push("googleSheets: conditionalformat.add numberFormat is not supported by Sheets booleanRule.format and was dropped.");
  }
  return Object.keys(cellFormat).length > 0 ? cellFormat : undefined;
}
function buildConditionalFormatGradientRule(rule2, warnings) {
  const colors = [...rule2.colors ?? []];
  if (colors.length < 2) {
    warnings.push("googleSheets: conditionalformat.add colorScale requires at least 2 colors.");
    return null;
  }
  if (colors.length > 3) {
    colors.splice(3);
    warnings.push("googleSheets: conditionalformat.add colorScale supports only 2 or 3 color stops; dropped extras.");
  }
  const thresholds = normalizeConditionalFormatThresholds(rule2.thresholds, colors.length, warnings);
  const points = colors.map((color4, index2) => toConditionalFormatInterpolationPoint(color4, thresholds[index2]));
  return {
    minpoint: points[0],
    ...points[1] ? { midpoint: points[1] } : {},
    maxpoint: points[points.length - 1]
  };
}
function normalizeConditionalFormatThresholds(thresholds, colorCount, warnings) {
  const defaults = colorCount <= 2 ? ["min", "max"] : ["min", { type: "percentile", value: 50 }, "max"];
  const normalized = thresholds ? [...thresholds] : [];
  if (normalized.length === 0) {
    return [...defaults];
  }
  if (normalized.length < colorCount) {
    warnings.push("googleSheets: conditionalformat.add colorScale thresholds were padded with default interpolation points.");
  }
  if (normalized.length > colorCount) {
    warnings.push("googleSheets: conditionalformat.add colorScale only uses as many thresholds as color stops; dropped extras.");
  }
  const filled = [...normalized.slice(0, colorCount)];
  while (filled.length < colorCount) {
    filled.push(defaults[filled.length]);
  }
  return filled;
}
function toConditionalFormatInterpolationPoint(color4, threshold) {
  const colorStyle = toColorStyle(color4);
  const point5 = {};
  if (colorStyle) {
    point5.colorStyle = colorStyle;
  }
  if (typeof threshold === "number") {
    point5.type = "NUMBER";
    point5.value = String(threshold);
    return point5;
  }
  if (typeof threshold === "string") {
    const trimmed = threshold.trim();
    if (trimmed === "min") {
      point5.type = "MIN";
      return point5;
    }
    if (trimmed === "max") {
      point5.type = "MAX";
      return point5;
    }
    if (trimmed.endsWith("%")) {
      point5.type = "PERCENTILE";
      point5.value = trimmed.slice(0, -1);
      return point5;
    }
    point5.type = "NUMBER";
    point5.value = looksLikeFormulaOrReference(trimmed) ? `=${trimmed.replace(/^=/, "")}` : trimmed;
    return point5;
  }
  switch (threshold.type) {
    case "min":
      point5.type = "MIN";
      return point5;
    case "max":
      point5.type = "MAX";
      return point5;
    case "num":
      point5.type = "NUMBER";
      break;
    case "percent":
      point5.type = "PERCENT";
      break;
    case "percentile":
      point5.type = "PERCENTILE";
      break;
  }
  if (threshold.value !== undefined) {
    point5.value = typeof threshold.value === "string" && looksLikeFormulaOrReference(threshold.value) ? `=${threshold.value.trim().replace(/^=/, "")}` : String(threshold.value);
  }
  return point5;
}

// node_modules/@oai/granola/dist/models/spreadsheet/google-sheets/adapter/charts.js
init_address_utils();
function buildChartStates(spreadsheet) {
  const states = new Map;
  for (const sheet of spreadsheet?.sheets ?? []) {
    const sheetName = sheet.properties?.title;
    if (!sheetName) {
      continue;
    }
    const chartStates = (sheet.charts ?? []).map((chart2) => buildChartStateFromEmbeddedChart(sheetName, chart2)).filter((state) => state !== null);
    states.set(sheetName, chartStates);
  }
  return states;
}
function moveChartStatesForSheet(states, from2, to) {
  if (from2 === to) {
    return;
  }
  const existing = states.get(from2);
  if (!existing) {
    if (!states.has(to)) {
      states.set(to, []);
    }
    return;
  }
  states.delete(from2);
  states.set(to, existing.map((state) => ({
    ...state,
    sheetName: to
  })));
}
function deleteChartStatesForSheet(states, sheetName) {
  states.delete(sheetName);
}
function shiftChartRequestIndexes(states, removedIndex) {
  for (const chartStates of states.values()) {
    for (const state of chartStates) {
      if (state.requestIndex !== undefined && state.requestIndex > removedIndex) {
        state.requestIndex -= 1;
      }
    }
  }
}
function resolveChartState(states, target) {
  const sheetStates = [...states.get(target.sheet) ?? []];
  const selector = target.selector;
  if (selector) {
    let matches = sheetStates;
    if (selector.anchor) {
      const anchorKey = serializeChartAnchor(selector.anchor);
      matches = narrowMatchesIfAny2(matches, (candidate) => serializeChartPosition(candidate.position) === anchorKey);
    }
    if (selector.chartType !== undefined) {
      matches = narrowMatchesIfAny2(matches, (candidate) => candidate.chartType === selector.chartType);
    }
    if (selector.title !== undefined) {
      matches = narrowMatchesIfAny2(matches, (candidate) => candidate.title === selector.title);
    }
    if (selector.seriesNames && selector.seriesNames.length > 0) {
      const namesKey = JSON.stringify(selector.seriesNames);
      matches = narrowMatchesIfAny2(matches, (candidate) => JSON.stringify(candidate.seriesNames ?? []) === namesKey);
    }
    if (selector.occurrence !== undefined) {
      return matches[selector.occurrence];
    }
    if (matches.length === 1) {
      return matches[0];
    }
  }
  if (target.id) {
    const numericId = parseChartNumericId(target.id);
    return sheetStates.find((candidate) => candidate.alias === target.id || candidate.localId === target.id || numericId !== undefined && candidate.chartId === numericId);
  }
  return;
}
function upsertChartState(states, sheetName, next2) {
  const chartStates = states.get(sheetName) ?? [];
  const requestIndex = next2.requestIndex;
  if (requestIndex !== undefined) {
    const byRequest = chartStates.findIndex((candidate) => candidate.requestIndex === requestIndex);
    if (byRequest >= 0) {
      chartStates[byRequest] = next2;
      states.set(sheetName, chartStates);
      return;
    }
  }
  const byIdentity = chartStates.findIndex((candidate) => next2.chartId !== undefined && candidate.chartId === next2.chartId || next2.alias !== undefined && candidate.alias === next2.alias || next2.localId !== undefined && candidate.localId === next2.localId);
  if (byIdentity >= 0) {
    chartStates[byIdentity] = next2;
  } else {
    chartStates.push(next2);
  }
  states.set(sheetName, chartStates);
}
function removeChartState(states, state) {
  const chartStates = states.get(state.sheetName);
  if (!chartStates) {
    return;
  }
  const remaining = chartStates.filter((candidate) => candidate !== state);
  if (remaining.length === 0) {
    states.delete(state.sheetName);
    return;
  }
  states.set(state.sheetName, remaining);
}
function buildEmbeddedChart(input) {
  const sheetName = input.op.op === "chart.add" ? input.op.sheet : input.op.target.sheet;
  const sheet = input.resolveSheet(sheetName);
  const spec = buildChartSpec({
    props: input.op.props,
    resolveSheet: input.resolveSheet,
    currentSheetName: sheet.name,
    warnings: input.warnings
  });
  if (!spec) {
    return null;
  }
  const chartId = parseChartNumericId(input.op.props.id);
  return {
    ...chartId !== undefined ? { chartId } : {},
    position: buildEmbeddedObjectPosition(sheet.sheetId, input.op.props.anchor),
    spec
  };
}
function buildChartStateFromProps(input) {
  return {
    alias: input.alias,
    chartId: input.chartId,
    chartType: input.props.chartType,
    localId: input.localId,
    position: buildEmbeddedObjectPosition(input.sheetId, input.props.anchor),
    requestIndex: input.requestIndex,
    seriesNames: normalizeSeriesNames2(input.props.series),
    sheetName: input.sheetName,
    title: input.props.title
  };
}
function buildUpdateChartSpecRequest(chartId, spec) {
  return {
    chartId,
    spec
  };
}
function buildUpdateChartPositionRequest(objectId, position3) {
  return {
    objectId,
    newPosition: position3,
    fields: "*"
  };
}
function buildDeleteChartRequest(chartId) {
  return {
    objectId: chartId
  };
}
function buildChartStateFromEmbeddedChart(sheetName, chart2) {
  const chartType = resolveGranolaChartType(chart2.spec);
  if (!chartType) {
    return null;
  }
  return {
    chartId: chart2.chartId,
    chartType,
    position: chart2.position,
    seriesNames: [],
    sheetName,
    title: chart2.spec?.title
  };
}
function buildChartSpec(input) {
  maybeWarnDroppedChartPresentationProps(input.props, input.warnings);
  switch (input.props.chartType) {
    case "line": {
      const basicChart = buildBasicChartSpec({
        chartType: "LINE",
        props: input.props,
        resolveSheet: input.resolveSheet,
        currentSheetName: input.currentSheetName,
        warnings: input.warnings
      });
      return basicChart ? {
        title: input.props.title,
        basicChart
      } : null;
    }
    case "area": {
      const basicChart = buildBasicChartSpec({
        chartType: "AREA",
        props: input.props,
        resolveSheet: input.resolveSheet,
        currentSheetName: input.currentSheetName,
        warnings: input.warnings
      });
      return basicChart ? {
        title: input.props.title,
        basicChart
      } : null;
    }
    case "bar": {
      const basicChart = buildBasicChartSpec({
        chartType: input.props.barOptions?.direction === "column" ? "COLUMN" : "BAR",
        props: input.props,
        resolveSheet: input.resolveSheet,
        currentSheetName: input.currentSheetName,
        warnings: input.warnings
      });
      return basicChart ? {
        title: input.props.title,
        basicChart
      } : null;
    }
    case "scatter": {
      const basicChart = buildScatterChartSpec({
        props: input.props,
        resolveSheet: input.resolveSheet,
        currentSheetName: input.currentSheetName,
        warnings: input.warnings
      });
      return basicChart ? {
        title: input.props.title,
        basicChart
      } : null;
    }
    case "pie": {
      const pieChart = buildPieChartSpec({
        props: input.props,
        resolveSheet: input.resolveSheet,
        currentSheetName: input.currentSheetName,
        warnings: input.warnings,
        isDoughnut: false
      });
      return pieChart ? {
        title: input.props.title,
        pieChart
      } : null;
    }
    case "doughnut": {
      const pieChart = buildPieChartSpec({
        props: input.props,
        resolveSheet: input.resolveSheet,
        currentSheetName: input.currentSheetName,
        warnings: input.warnings,
        isDoughnut: true
      });
      return pieChart ? {
        title: input.props.title,
        pieChart
      } : null;
    }
    default:
      input.warnings.push(`googleSheets: chart ${input.props.chartType} is not supported by the current Sheets chart lowering.`);
      return null;
  }
}
function buildBasicChartSpec(input) {
  const series = input.props.series ?? [];
  if (series.length === 0) {
    input.warnings.push(`googleSheets: chart.${input.props.chartType}.add requires at least one range-backed series.`);
    return;
  }
  const categoryFormula = resolveSharedDomainFormula(series.map((entry) => entry.categoryFormula), input.props.chartType, input.warnings);
  if (!categoryFormula) {
    if (input.props.categories?.length) {
      input.warnings.push(`googleSheets: chart ${input.props.chartType} inline categories are not supported by the current Sheets chart lowering; use range-backed categoryFormula data.`);
    }
    return;
  }
  const domain3 = buildChartDataFromFormula({
    formula: categoryFormula,
    resolveSheet: input.resolveSheet,
    fallbackSheetName: input.currentSheetName,
    warnings: input.warnings,
    context: `${input.props.chartType} chart domain`
  });
  if (!domain3) {
    return;
  }
  const seriesPayloads = series.map((entry, index2) => buildBasicSeriesData({
    formula: entry.formula,
    resolveSheet: input.resolveSheet,
    fallbackSheetName: input.currentSheetName,
    warnings: input.warnings,
    context: `${input.props.chartType} series ${index2 + 1}`
  })).filter((entry) => entry !== null);
  if (seriesPayloads.length === 0) {
    return;
  }
  return {
    chartType: input.chartType,
    domains: [{ domain: domain3 }],
    headerCount: 0,
    legendPosition: mapBasicLegendPosition(input.props, input.warnings),
    series: seriesPayloads,
    ...mapDisplayBlanksAs2(input.props.displayBlanksAs, input.warnings) ?? {},
    ...mapStackedType(input.props) ?? {}
  };
}
function buildScatterChartSpec(input) {
  const series = input.props.series ?? [];
  if (series.length === 0) {
    input.warnings.push("googleSheets: scatter charts require at least one range-backed series.");
    return;
  }
  const xFormula = resolveSharedDomainFormula(series.map((entry) => entry.xFormula), "scatter", input.warnings, "xFormula");
  if (!xFormula) {
    if (series.some((entry) => (entry.xValues?.length ?? 0) > 0)) {
      input.warnings.push("googleSheets: scatter inline xValues are not supported by the current Sheets chart lowering; use range-backed xFormula data.");
    }
    return;
  }
  const domain3 = buildChartDataFromFormula({
    formula: xFormula,
    resolveSheet: input.resolveSheet,
    fallbackSheetName: input.currentSheetName,
    warnings: input.warnings,
    context: "scatter chart domain"
  });
  if (!domain3) {
    return;
  }
  const seriesPayloads = series.map((entry, index2) => buildBasicSeriesData({
    formula: entry.formula,
    resolveSheet: input.resolveSheet,
    fallbackSheetName: input.currentSheetName,
    warnings: input.warnings,
    context: `scatter series ${index2 + 1}`
  })).filter((entry) => entry !== null);
  if (seriesPayloads.length === 0) {
    return;
  }
  return {
    chartType: "SCATTER",
    domains: [{ domain: domain3 }],
    headerCount: 0,
    legendPosition: mapBasicLegendPosition(input.props, input.warnings),
    series: seriesPayloads,
    ...mapDisplayBlanksAs2(input.props.displayBlanksAs, input.warnings) ?? {}
  };
}
function buildPieChartSpec(input) {
  const series = input.props.series ?? [];
  if (series.length !== 1) {
    input.warnings.push(`googleSheets: ${input.props.chartType} charts require exactly one range-backed series.`);
    return;
  }
  const firstSeries = series[0];
  const categoryFormula = firstSeries.categoryFormula;
  if (!categoryFormula) {
    if (input.props.categories?.length) {
      input.warnings.push(`googleSheets: chart ${input.props.chartType} inline categories are not supported by the current Sheets chart lowering; use range-backed categoryFormula data.`);
    }
    return;
  }
  const domain3 = buildChartDataFromFormula({
    formula: categoryFormula,
    resolveSheet: input.resolveSheet,
    fallbackSheetName: input.currentSheetName,
    warnings: input.warnings,
    context: `${input.props.chartType} chart domain`
  });
  const valueSeries = buildChartDataFromFormula({
    formula: firstSeries.formula,
    resolveSheet: input.resolveSheet,
    fallbackSheetName: input.currentSheetName,
    warnings: input.warnings,
    context: `${input.props.chartType} series`
  });
  if (!domain3 || !valueSeries) {
    return;
  }
  if (input.props.pieOptions?.firstSliceAngle !== undefined) {
    input.warnings.push("googleSheets: pie firstSliceAngle is not exposed by the Sheets discovery-doc PieChartSpec and was dropped.");
  }
  if (input.props.doughnutOptions?.firstSliceAngle !== undefined) {
    input.warnings.push("googleSheets: doughnut firstSliceAngle is not exposed by the Sheets discovery-doc PieChartSpec and was dropped.");
  }
  return {
    domain: domain3,
    series: valueSeries,
    legendPosition: mapPieLegendPosition(input.props, input.warnings),
    ...input.isDoughnut && input.props.doughnutOptions?.holeSize !== undefined ? {
      pieHole: Math.max(0, Math.min(1, input.props.doughnutOptions.holeSize / 100))
    } : {}
  };
}
function buildBasicSeriesData(input) {
  const series = buildChartDataFromFormula({
    formula: input.formula,
    resolveSheet: input.resolveSheet,
    fallbackSheetName: input.fallbackSheetName,
    warnings: input.warnings,
    context: input.context
  });
  if (!series) {
    return null;
  }
  return { series };
}
function buildChartDataFromFormula(input) {
  const rawFormula = input.formula?.trim();
  if (!rawFormula) {
    input.warnings.push(`googleSheets: ${input.context} must be range-backed for the current Sheets chart lowering.`);
    return null;
  }
  const formula = rawFormula.startsWith("=") ? rawFormula.slice(1).trim() : rawFormula;
  const { sheetName, ref: ref2 } = splitSheetAddress(formula);
  const resolvedSheetName = sheetName ?? input.fallbackSheetName;
  if (!resolvedSheetName) {
    input.warnings.push(`googleSheets: ${input.context} requires a sheet-qualified A1 range.`);
    return null;
  }
  const parsed = parseRangeAddress(ref2);
  if (!parsed) {
    input.warnings.push(`googleSheets: could not parse ${input.context} range ${rawFormula}.`);
    return null;
  }
  const sheet = input.resolveSheet(resolvedSheetName);
  return {
    sourceRange: {
      sources: [toGridRange({ sheetId: sheet.sheetId, range: parsed.ref })]
    }
  };
}
function resolveSharedDomainFormula(formulas2, chartType, warnings, fieldName = "categoryFormula") {
  const nonEmpty = formulas2.map((value2) => value2?.trim()).filter((value2) => Boolean(value2));
  if (nonEmpty.length === 0) {
    return null;
  }
  const first = nonEmpty[0];
  if (nonEmpty.some((value2) => value2 !== first)) {
    warnings.push(`googleSheets: ${chartType} charts require a shared ${fieldName} across series in the current Sheets chart lowering.`);
    return null;
  }
  return first;
}
function buildEmbeddedObjectPosition(sheetId, anchor) {
  return {
    overlayPosition: buildOverlayPosition(sheetId, anchor)
  };
}
function buildOverlayPosition(sheetId, anchor) {
  const from2 = anchor.from;
  const overlayPosition = {
    anchorCell: {
      sheetId: toSheetId(sheetId),
      rowIndex: from2.row,
      columnIndex: from2.col
    },
    offsetXPixels: from2.colOffsetPx ?? 0,
    offsetYPixels: from2.rowOffsetPx ?? 0
  };
  const dimensions = resolveAnchorDimensions(anchor);
  if (dimensions.widthPixels !== undefined) {
    overlayPosition.widthPixels = dimensions.widthPixels;
  }
  if (dimensions.heightPixels !== undefined) {
    overlayPosition.heightPixels = dimensions.heightPixels;
  }
  return overlayPosition;
}
function resolveAnchorDimensions(anchor) {
  if (anchor.extent?.widthPx !== undefined || anchor.extent?.heightPx !== undefined) {
    return {
      widthPixels: anchor.extent?.widthPx,
      heightPixels: anchor.extent?.heightPx
    };
  }
  if (!anchor.to) {
    return {};
  }
  const cols = Math.max(1, anchor.to.col - anchor.from.col);
  const rows = Math.max(1, anchor.to.row - anchor.from.row);
  return {
    widthPixels: Math.max(1, cols * FALLBACK_COL_W_PX_RAW + (anchor.to.colOffsetPx ?? 0) - (anchor.from.colOffsetPx ?? 0)),
    heightPixels: Math.max(1, rows * pointsToPx(FALLBACK_ROW_H_PT) + (anchor.to.rowOffsetPx ?? 0) - (anchor.from.rowOffsetPx ?? 0))
  };
}
function mapBasicLegendPosition(props, warnings) {
  if (props.hasLegend === false) {
    return "NO_LEGEND";
  }
  const legendPosition = props.legend?.position;
  if (!legendPosition) {
    return;
  }
  switch (legendPosition) {
    case "bottom":
      return "BOTTOM_LEGEND";
    case "left":
      return "LEFT_LEGEND";
    case "right":
      return "RIGHT_LEGEND";
    case "top":
      return "TOP_LEGEND";
    case "topRight":
      warnings.push("googleSheets: chart legend position topRight is not exposed by Sheets basic charts and was narrowed to RIGHT_LEGEND.");
      return "RIGHT_LEGEND";
  }
}
function mapPieLegendPosition(props, warnings) {
  if (props.hasLegend === false) {
    return "NO_LEGEND";
  }
  const legendPosition = props.legend?.position;
  if (!legendPosition) {
    return;
  }
  switch (legendPosition) {
    case "bottom":
      return "BOTTOM_LEGEND";
    case "left":
      return "LEFT_LEGEND";
    case "right":
      return "RIGHT_LEGEND";
    case "top":
      return "TOP_LEGEND";
    case "topRight":
      warnings.push("googleSheets: chart legend position topRight is not exposed by Sheets pie charts and was narrowed to RIGHT_LEGEND.");
      return "RIGHT_LEGEND";
  }
}
function mapStackedType(props) {
  if (props.chartType !== "area") {
    return null;
  }
  return {
    stackedType: "NOT_STACKED"
  };
}
function mapDisplayBlanksAs2(value2, warnings) {
  switch (value2) {
    case undefined:
    case "gap":
      return null;
    case "span":
      return { interpolateNulls: true };
    case "zero":
      warnings.push("googleSheets: chart displayBlanksAs=zero is not exposed by the current narrowed Sheets chart lowering and was dropped.");
      return null;
  }
}
function maybeWarnDroppedChartPresentationProps(props, warnings) {
  if (props.dataLabels) {
    warnings.push("googleSheets: chart dataLabels are not lowered yet in the current Sheets chart slice and were dropped.");
  }
  if (props.plotArea || props.chartArea) {
    warnings.push("googleSheets: chart plotArea/chartArea formatting is not lowered yet in the current Sheets chart slice and was dropped.");
  }
  if (props.series?.some((series) => series.fill !== undefined || series.stroke !== undefined || series.marker !== undefined)) {
    warnings.push("googleSheets: chart series styling is not lowered yet in the current Sheets chart slice and was dropped.");
  }
}
function resolveGranolaChartType(spec) {
  const basicType = spec?.basicChart?.chartType;
  switch (basicType) {
    case "LINE":
      return "line";
    case "AREA":
      return "area";
    case "SCATTER":
      return "scatter";
    case "BAR":
    case "COLUMN":
      return "bar";
  }
  if (spec?.pieChart) {
    return spec.pieChart.pieHole !== undefined && spec.pieChart.pieHole > 0 ? "doughnut" : "pie";
  }
  return null;
}
function normalizeSeriesNames2(series) {
  const names = series?.map((entry) => entry.name).filter((name2) => name2.length > 0) ?? [];
  return names.length > 0 ? names : undefined;
}
function serializeChartPosition(position3) {
  const overlay = position3?.overlayPosition;
  const anchorCell = overlay?.anchorCell;
  if (!overlay || !anchorCell) {
    return;
  }
  return JSON.stringify({
    from: {
      row: anchorCell.rowIndex,
      col: anchorCell.columnIndex,
      ...overlay.offsetYPixels ? { rowOffsetPx: overlay.offsetYPixels } : {},
      ...overlay.offsetXPixels ? { colOffsetPx: overlay.offsetXPixels } : {}
    },
    ...overlay.widthPixels !== undefined || overlay.heightPixels !== undefined ? {
      extent: {
        ...overlay.widthPixels !== undefined ? { widthPx: overlay.widthPixels } : {},
        ...overlay.heightPixels !== undefined ? { heightPx: overlay.heightPixels } : {}
      }
    } : {}
  });
}
function serializeChartAnchor(anchor) {
  return JSON.stringify(anchor);
}
function parseChartNumericId(value2) {
  if (!value2 || !/^\d+$/.test(value2.trim())) {
    return;
  }
  const numeric = Number(value2);
  if (!Number.isSafeInteger(numeric) || numeric < 0) {
    return;
  }
  return numeric;
}
function narrowMatchesIfAny2(matches, predicate) {
  return matches.filter(predicate);
}

// node_modules/@oai/granola/dist/models/spreadsheet/google-sheets/adapter/data-validation.js
var NUMBER_VALIDATION_OPERATOR_MAP = {
  between: "NUMBER_BETWEEN",
  notBetween: "NUMBER_NOT_BETWEEN",
  equal: "NUMBER_EQ",
  notEqual: "NUMBER_NOT_EQ",
  lessThan: "NUMBER_LESS",
  lessThanOrEqual: "NUMBER_LESS_THAN_EQ",
  greaterThan: "NUMBER_GREATER",
  greaterThanOrEqual: "NUMBER_GREATER_THAN_EQ"
};
var DATE_VALIDATION_OPERATOR_MAP = {
  between: "DATE_BETWEEN",
  notBetween: "DATE_NOT_BETWEEN",
  equal: "DATE_EQ",
  notEqual: "DATE_NOT_EQ",
  lessThan: "DATE_BEFORE",
  lessThanOrEqual: "DATE_ON_OR_BEFORE",
  greaterThan: "DATE_AFTER",
  greaterThanOrEqual: "DATE_ON_OR_AFTER"
};
function buildSetDataValidationRequest(sheetId, op, warnings) {
  const range2 = toGridRange({ sheetId, range: op.target.range });
  const rule2 = buildDataValidationRule(op, warnings);
  if (rule2 === null) {
    return null;
  }
  if (rule2 === undefined) {
    return {
      setDataValidation: {
        range: range2
      }
    };
  }
  return {
    setDataValidation: {
      range: range2,
      rule: rule2
    }
  };
}
function buildDataValidationRule(op, warnings) {
  if (op.props.rule.type === "none") {
    warnings.push("googleSheets: datavalidation.set rule type none is emitted as a clear.");
    return;
  }
  const condition = buildBooleanCondition(op, warnings);
  if (!condition) {
    return null;
  }
  const rule2 = {
    condition
  };
  const prompt = op.props.prompt;
  if (prompt?.show === false) {
    warnings.push("googleSheets: datavalidation.set prompt.show=false is not supported; dropped inputMessage.");
  } else if (prompt) {
    const parts = [prompt.title, prompt.message].filter((part) => typeof part === "string" && part.length > 0);
    if (parts.length > 0) {
      rule2.inputMessage = parts.join(`
`);
      if (prompt.title !== undefined && prompt.message !== undefined) {
        warnings.push("googleSheets: datavalidation.set prompt.title was folded into inputMessage because Sheets has no separate prompt title.");
      } else if (prompt.title !== undefined) {
        warnings.push("googleSheets: datavalidation.set prompt.title was mapped to inputMessage because Sheets has no separate prompt title.");
      }
    }
  }
  const errorAlert = op.props.errorAlert;
  if (errorAlert?.title !== undefined) {
    warnings.push("googleSheets: datavalidation.set errorAlert.title is not supported by Sheets and was dropped.");
  }
  if (errorAlert?.message !== undefined) {
    warnings.push("googleSheets: datavalidation.set errorAlert.message is not supported by Sheets and was dropped.");
  }
  if (errorAlert?.show === false) {
    warnings.push("googleSheets: datavalidation.set errorAlert.show is not supported by Sheets and was dropped.");
  }
  if (errorAlert?.style === "stop") {
    rule2.strict = true;
  } else if (errorAlert?.style === "warning" || errorAlert?.style === "information") {
    rule2.strict = false;
    warnings.push(`googleSheets: datavalidation.set errorAlert.style=${errorAlert.style} was narrowed to strict=false.`);
  }
  if (op.props.ignoreBlanks !== undefined) {
    warnings.push("googleSheets: datavalidation.set ignoreBlanks is not supported by Sheets and was dropped.");
  }
  if (op.props.inCellDropDown !== undefined) {
    if (condition.type === "ONE_OF_LIST" || condition.type === "ONE_OF_RANGE") {
      rule2.showCustomUi = op.props.inCellDropDown;
    } else {
      warnings.push("googleSheets: datavalidation.set inCellDropDown only applies to list validations and was dropped.");
    }
  }
  return rule2;
}
function buildBooleanCondition(op, warnings) {
  const rule2 = op.props.rule;
  switch (rule2.type) {
    case "whole":
      warnings.push("googleSheets: datavalidation.set rule type whole is narrowed to Sheets number validation and does not enforce integers.");
      return buildOperatorCondition({
        typeLabel: "whole",
        operatorMap: NUMBER_VALIDATION_OPERATOR_MAP,
        operator: rule2.operator,
        formula1: rule2.formula1,
        formula2: rule2.formula2,
        warnings
      });
    case "decimal":
      return buildOperatorCondition({
        typeLabel: "decimal",
        operatorMap: NUMBER_VALIDATION_OPERATOR_MAP,
        operator: rule2.operator,
        formula1: rule2.formula1,
        formula2: rule2.formula2,
        warnings
      });
    case "list": {
      if (rule2.operator !== undefined) {
        warnings.push("googleSheets: datavalidation.set list operator is not supported and was dropped.");
      }
      if (rule2.values && rule2.values.length > 0) {
        return {
          type: "ONE_OF_LIST",
          values: rule2.values.map((value2) => ({
            userEnteredValue: value2
          }))
        };
      }
      const a1Range = normalizeA1RangeValue(rule2.formula1);
      if (!a1Range) {
        warnings.push("googleSheets: datavalidation.set list rules require values[] or formula1 for a source range.");
        return null;
      }
      if (rule2.formula2 !== undefined) {
        warnings.push("googleSheets: datavalidation.set list formula2 is not supported and was dropped.");
      }
      return {
        type: "ONE_OF_RANGE",
        values: [{ userEnteredValue: a1Range }]
      };
    }
    case "date":
      if (rule2.operator === undefined) {
        if (rule2.formula1 !== undefined || rule2.formula2 !== undefined) {
          warnings.push("googleSheets: datavalidation.set date formulas were dropped because DATE_IS_VALID does not accept condition values.");
        }
        return { type: "DATE_IS_VALID" };
      }
      return buildOperatorCondition({
        typeLabel: "date",
        operatorMap: DATE_VALIDATION_OPERATOR_MAP,
        operator: rule2.operator,
        formula1: rule2.formula1,
        formula2: rule2.formula2,
        warnings
      });
    case "custom": {
      if (rule2.operator !== undefined) {
        warnings.push("googleSheets: datavalidation.set custom operator is not supported and was dropped.");
      }
      if (rule2.formula2 !== undefined) {
        warnings.push("googleSheets: datavalidation.set custom formula2 is not supported and was dropped.");
      }
      const conditionValue = toConditionValue(rule2.formula1, {
        coerceFormula: true
      });
      if (!conditionValue) {
        warnings.push("googleSheets: datavalidation.set custom rules require formula1.");
        return null;
      }
      return {
        type: "CUSTOM_FORMULA",
        values: [conditionValue]
      };
    }
    case "time":
      warnings.push("googleSheets: datavalidation.set rule type time is not supported by Sheets BooleanCondition.");
      return null;
    case "textLength":
      warnings.push("googleSheets: datavalidation.set rule type textLength is not supported by Sheets BooleanCondition.");
      return null;
    default:
      warnings.push(`googleSheets: datavalidation.set rule type ${rule2.type} is not supported by Sheets BooleanCondition.`);
      return null;
  }
}
function buildOperatorCondition(input) {
  const { typeLabel, operatorMap, operator, formula1, formula2, warnings } = input;
  if (!operator) {
    warnings.push(`googleSheets: datavalidation.set ${typeLabel} rules require an operator for Sheets.`);
    return null;
  }
  const conditionType = operatorMap[operator];
  const values2 = buildConditionValues(conditionType, formula1, formula2, warnings);
  if (values2 === null) {
    return null;
  }
  return {
    type: conditionType,
    ...values2.length > 0 ? { values: values2 } : {}
  };
}
function buildConditionValues(conditionType, formula1, formula2, warnings) {
  const expectsTwoValues = conditionType === "NUMBER_BETWEEN" || conditionType === "NUMBER_NOT_BETWEEN" || conditionType === "DATE_BETWEEN" || conditionType === "DATE_NOT_BETWEEN";
  const first = toConditionValue(formula1, { coerceReferenceFormula: true });
  if (!first) {
    warnings.push(`googleSheets: datavalidation.set ${conditionType} requires formula1.`);
    return null;
  }
  if (!expectsTwoValues) {
    if (formula2 !== undefined) {
      warnings.push(`googleSheets: datavalidation.set ${conditionType} only uses formula1; dropped formula2.`);
    }
    return [first];
  }
  const second = toConditionValue(formula2, { coerceReferenceFormula: true });
  if (!second) {
    warnings.push(`googleSheets: datavalidation.set ${conditionType} requires formula2.`);
    return null;
  }
  return [first, second];
}

// node_modules/@oai/granola/dist/models/spreadsheet/google-sheets/adapter/formatting.js
var HORIZONTAL_ALIGNMENT_MAP = {
  left: "LEFT",
  center: "CENTER",
  right: "RIGHT"
};
var VERTICAL_ALIGNMENT_MAP2 = {
  top: "TOP",
  middle: "MIDDLE",
  center: "MIDDLE",
  bottom: "BOTTOM"
};
var BORDER_STYLE_MAP = {
  none: "NONE",
  dotted: "DOTTED",
  dashed: "DASHED",
  solid: "SOLID",
  medium: "SOLID_MEDIUM",
  thick: "SOLID_THICK",
  double: "DOUBLE"
};
function inferNumberFormatType(pattern2) {
  const normalized = pattern2.trim();
  const upper = normalized.toUpperCase();
  if (!normalized) {
    return "NUMBER_FORMAT_TYPE_UNSPECIFIED";
  }
  if (normalized === "@") {
    return "TEXT";
  }
  if (upper.includes("%")) {
    return "PERCENT";
  }
  if (/[€£¥$]/.test(normalized)) {
    return "CURRENCY";
  }
  if (upper.includes("E+") || upper.includes("E-")) {
    return "SCIENTIFIC";
  }
  const hasDate = /Y|M|D/.test(upper);
  const hasTime = /H|S|AM\/PM/.test(upper);
  if (hasDate && hasTime) {
    return "DATE_TIME";
  }
  if (hasDate) {
    return "DATE";
  }
  if (hasTime) {
    return "TIME";
  }
  return "NUMBER";
}
function buildBorder2(input) {
  if (!input) {
    return;
  }
  const style2 = input.style && BORDER_STYLE_MAP[input.style] || (typeof input.weight === "number" && input.weight >= 2 ? "SOLID_MEDIUM" : undefined) || "SOLID";
  const border = {
    style: style2,
    colorStyle: toColorStyle(input.color)
  };
  if (typeof input.weight === "number" && Number.isFinite(input.weight)) {
    border.width = Math.max(1, Math.round(input.weight));
  }
  return border;
}
function buildBordersRequest(gridRange, borders, warnings) {
  if ("preset" in borders) {
    const border = buildBorder2({
      style: borders.style,
      color: borders.color
    });
    switch (borders.preset) {
      case "none":
        return {
          updateBorders: {
            range: gridRange,
            top: { style: "NONE" },
            bottom: { style: "NONE" },
            left: { style: "NONE" },
            right: { style: "NONE" },
            innerHorizontal: { style: "NONE" },
            innerVertical: { style: "NONE" }
          }
        };
      case "outside":
        return {
          updateBorders: {
            range: gridRange,
            top: border,
            bottom: border,
            left: border,
            right: border
          }
        };
      case "inside":
        return {
          updateBorders: {
            range: gridRange,
            innerHorizontal: border,
            innerVertical: border
          }
        };
      case "all":
        return {
          updateBorders: {
            range: gridRange,
            top: border,
            bottom: border,
            left: border,
            right: border,
            innerHorizontal: border,
            innerVertical: border
          }
        };
      case "doubleBottom":
        return {
          updateBorders: {
            range: gridRange,
            bottom: { ...border, style: "DOUBLE" }
          }
        };
      default:
        warnings.push(`googleSheets: unsupported border preset ${borders.preset}.`);
        return null;
    }
  }
  if (borders.diagonalUp || borders.diagonalDown) {
    warnings.push("googleSheets: diagonal borders are not supported.");
  }
  return {
    updateBorders: {
      range: gridRange,
      top: buildBorder2(borders.top),
      bottom: buildBorder2(borders.bottom),
      left: buildBorder2(borders.left),
      right: buildBorder2(borders.right),
      innerHorizontal: buildBorder2(borders.insideHorizontal ?? borders.inside),
      innerVertical: buildBorder2(borders.insideVertical ?? borders.inside)
    }
  };
}
function buildCellFormat(props, warnings) {
  const format3 = {};
  const fields = [];
  if (props.fill !== undefined) {
    if (props.fill === null) {
      warnings.push("googleSheets: range.format.set fill=null is not supported yet; use range.format.clear for full format reset.");
    } else {
      const fill3 = props.fill instanceof Fill2 ? props.fill : new Fill2(props.fill);
      const fillProto = fill3.toProto();
      const isSolidFill = !!fillProto && !fillProto.pattern && !fillProto.relId && !fillProto.gradientStops?.length;
      if (isSolidFill) {
        const colorStyle = toColorStyle(fill3.color);
        if (colorStyle) {
          format3.backgroundColorStyle = colorStyle;
          fields.push("backgroundColorStyle");
        }
      } else {
        warnings.push("googleSheets: only solid fills are supported.");
      }
    }
  }
  if (props.font) {
    const textFormat = {};
    if (props.font.bold !== undefined) {
      textFormat.bold = props.font.bold;
    }
    if (props.font.italic !== undefined) {
      textFormat.italic = props.font.italic;
    }
    if (props.font.size !== undefined) {
      textFormat.fontSize = props.font.size;
    }
    if (props.font.name !== undefined) {
      textFormat.fontFamily = props.font.name;
    }
    if (props.font.color !== undefined) {
      textFormat.foregroundColorStyle = toColorStyle(props.font.color);
    }
    if (Object.keys(textFormat).length > 0) {
      format3.textFormat = textFormat;
      fields.push("textFormat");
    }
  }
  if (props.numberFormat !== undefined) {
    format3.numberFormat = {
      type: inferNumberFormatType(props.numberFormat),
      pattern: props.numberFormat
    };
    fields.push("numberFormat");
  }
  if (props.wrapText !== undefined) {
    format3.wrapStrategy = props.wrapText ? "WRAP" : "OVERFLOW_CELL";
    fields.push("wrapStrategy");
  }
  if (props.horizontalAlignment !== undefined) {
    const horizontalAlignment = HORIZONTAL_ALIGNMENT_MAP[props.horizontalAlignment];
    if (horizontalAlignment) {
      format3.horizontalAlignment = horizontalAlignment;
      fields.push("horizontalAlignment");
    } else {
      warnings.push(`googleSheets: unsupported horizontalAlignment ${props.horizontalAlignment}.`);
    }
  }
  if (props.verticalAlignment !== undefined) {
    const verticalAlignment = VERTICAL_ALIGNMENT_MAP2[props.verticalAlignment];
    if (verticalAlignment) {
      format3.verticalAlignment = verticalAlignment;
      fields.push("verticalAlignment");
    } else {
      warnings.push(`googleSheets: unsupported verticalAlignment ${props.verticalAlignment}.`);
    }
  }
  return { format: format3, fields };
}

// node_modules/@oai/granola/dist/models/spreadsheet/google-sheets/adapter/named-ranges.js
init_address_utils();
function buildNamedRangeStates(spreadsheet) {
  const states = new Map;
  for (const namedRange of spreadsheet?.namedRanges ?? []) {
    if (!namedRange.name || !namedRange.range) {
      continue;
    }
    const key = normalizeDefinedName(namedRange.name);
    if (!key) {
      continue;
    }
    states.set(key, {
      name: namedRange.name,
      range: cloneGridRange(namedRange.range),
      namedRangeId: namedRange.namedRangeId
    });
  }
  return states;
}
function shiftNamedRangeRequestIndexes(namedRangeStates, removedIndex) {
  for (const state of namedRangeStates.values()) {
    if (state.requestIndex !== undefined && state.requestIndex > removedIndex) {
      state.requestIndex -= 1;
    }
  }
}
function buildNamedRangePayload(op, resolveSheet, warnings) {
  if (op.sheet) {
    warnings.push(`googleSheets: names.range.add sheet-scoped named ranges are not supported by the Sheets namedRanges payload; dropped ${op.name}.`);
    return null;
  }
  if (op.description !== undefined) {
    warnings.push(`googleSheets: names.range.add descriptions are not supported by Sheets namedRanges and were dropped for ${op.name}.`);
  }
  const rawFormula = op.formula.trim();
  const formula = rawFormula.startsWith("=") ? rawFormula.slice(1).trim() : rawFormula;
  if (!formula) {
    warnings.push(`googleSheets: names.range.add requires a sheet-qualified A1 range for ${op.name}.`);
    return null;
  }
  if (!SHEET_QUALIFIED_RANGE_RE.test(formula)) {
    warnings.push(`googleSheets: names.range.add only supports sheet-qualified A1 ranges for ${op.name}; dropped ${op.formula}.`);
    return null;
  }
  const { sheetName, ref: ref2 } = splitSheetAddress(formula);
  if (!sheetName) {
    warnings.push(`googleSheets: names.range.add requires a sheet-qualified A1 range for ${op.name}.`);
    return null;
  }
  const parsed = parseRangeAddress(ref2);
  if (!parsed) {
    warnings.push(`googleSheets: names.range.add could not parse range ${op.formula} for ${op.name}.`);
    return null;
  }
  const sheet = resolveSheet(sheetName);
  return {
    name: op.name,
    range: toGridRange({ sheetId: sheet.sheetId, range: parsed.ref })
  };
}

// node_modules/@oai/granola/dist/models/spreadsheet/google-sheets/adapter/state.js
function buildConditionalFormatStates(preApplyState) {
  const states = new Map;
  for (const sheet of preApplyState?.sheets ?? []) {
    const sheetName = sheet.name;
    if (!sheetName) {
      continue;
    }
    const rules = [];
    for (const group of sheet.conditionalFormattings ?? []) {
      const rangeKeys = (group.ranges ?? []).map((range2) => conditionalFormatRangeTargetToKey(range2)).filter((rangeKey) => typeof rangeKey === "string");
      for (let index2 = 0;index2 < group.ruleCount; index2 += 1) {
        rules.push({ rangeKeys });
      }
    }
    states.set(sheetName, rules);
  }
  return states;
}
function moveConditionalFormatState(states, from2, to) {
  if (from2 === to) {
    return;
  }
  const existing = states.get(from2);
  if (!existing) {
    if (!states.has(to)) {
      states.set(to, []);
    }
    return;
  }
  states.delete(from2);
  states.set(to, existing);
}
function findConditionalFormatInsertIndex(rules, rangeKey) {
  for (let index2 = rules.length - 1;index2 >= 0; index2 -= 1) {
    if (rules[index2]?.rangeKeys.includes(rangeKey)) {
      return index2 + 1;
    }
  }
  return rules.length;
}
function buildPatchedSheetStates(input) {
  const states = new Map;
  const sourceSheets = input.preApplyState?.sheets?.map((sheet) => ({
    name: sheet.name,
    index: sheet.index,
    sheetId: sheet.sheetId
  })) ?? input.workbook.worksheets.items;
  for (const sheet of sourceSheets) {
    if (!sheet.name) {
      continue;
    }
    states.set(sheet.name, {
      name: sheet.name,
      index: sheet.index ?? 0,
      sheetId: input.knownRemoteSheetNameToId.get(sheet.name) ?? sheet.sheetId
    });
  }
  return states;
}
function resolveSheet(input) {
  const aliased = input.aliasSheets.get(input.target);
  if (aliased) {
    return aliased;
  }
  const current = input.workbook.worksheets.items.find((sheet) => sheet.name === input.target);
  if (current) {
    const remoteId = input.knownRemoteSheetNameToId.get(current.name) ?? (input.fallbackName ? input.knownRemoteSheetNameToId.get(input.fallbackName) : undefined);
    if (remoteId && (!current.sheetId || !input.knownRemoteSheetIds.has(current.sheetId))) {
      return {
        ...current,
        sheetId: remoteId
      };
    }
    return current;
  }
  if (input.fallbackName) {
    const byFallback = input.workbook.worksheets.items.find((sheet) => sheet.name === input.fallbackName);
    if (byFallback) {
      return byFallback;
    }
  }
  const previousId = input.knownRemoteSheetNameToId.get(input.target) ?? (input.fallbackName ? input.knownRemoteSheetNameToId.get(input.fallbackName) : undefined);
  if (previousId) {
    return {
      name: input.fallbackName ?? input.target,
      index: 0,
      sheetId: previousId
    };
  }
  throw new Error(`googleSheets: worksheet not found: ${input.target}`);
}
function resolveAddedSheet(input) {
  const candidateNames = [
    input.op.as ? input.applyResult.idMap[input.op.as] : undefined,
    input.op.name
  ].filter((value2, index2, items) => {
    return typeof value2 === "string" && value2.length > 0 && items.indexOf(value2) === index2;
  });
  for (const name2 of candidateNames) {
    const sheet = input.workbook.worksheets.items.find((worksheet) => worksheet.name === name2);
    if (sheet) {
      return sheet;
    }
  }
  const remoteSheetNames = new Set((input.spreadsheet?.sheets ?? []).map((sheet) => sheet.properties?.title).filter((title) => typeof title === "string" && title.length > 0));
  const unmatchedSheets = input.workbook.worksheets.items.filter((sheet) => !remoteSheetNames.has(sheet.name));
  if (unmatchedSheets.length === 1) {
    return unmatchedSheets[0];
  }
  throw new Error(`googleSheets: added worksheet could not be resolved from patch metadata: ${candidateNames.join(", ") || "(missing name)"}`);
}
function refreshKnownSheets(input) {
  const knownRemoteSheetIds = new Set;
  const knownRemoteSheetNameToId = new Map;
  for (const sheet of input.spreadsheet?.sheets ?? []) {
    const title = sheet.properties?.title;
    const sheetId = sheet.properties?.sheetId;
    if (title === undefined || sheetId === undefined) {
      continue;
    }
    const asString = `${sheetId}`;
    knownRemoteSheetIds.add(asString);
    knownRemoteSheetNameToId.set(title, asString);
  }
  for (const sheet of input.workbook.worksheets.items) {
    if (!sheet.sheetId) {
      continue;
    }
    if (knownRemoteSheetNameToId.has(sheet.name)) {
      if (knownRemoteSheetIds.has(sheet.sheetId)) {
        knownRemoteSheetNameToId.set(sheet.name, sheet.sheetId);
      }
      continue;
    }
    knownRemoteSheetIds.add(sheet.sheetId);
    knownRemoteSheetNameToId.set(sheet.name, sheet.sheetId);
  }
  return {
    knownRemoteSheetIds,
    knownRemoteSheetNameToId
  };
}

// node_modules/@oai/granola/dist/models/spreadsheet/google-sheets/adapter/tables.js
init_address_utils();
function buildTableStateKey(sheetName, tableName) {
  return `${sheetName.trim().toUpperCase()}::${normalizeTableName(tableName)}`;
}
function cloneTableColumnProperties(columnProperties) {
  return (columnProperties ?? []).map((column2) => ({ ...column2 }));
}
function cloneTableState(state) {
  return {
    sheetName: state.sheetName,
    name: state.name,
    range: cloneGridRange(state.range),
    tableId: state.tableId,
    columnProperties: cloneTableColumnProperties(state.columnProperties),
    requestIndexes: state.requestIndexes ? [...state.requestIndexes] : undefined
  };
}
function buildTableStates(spreadsheet) {
  const states = new Map;
  for (const sheet of spreadsheet?.sheets ?? []) {
    const sheetName = sheet.properties?.title;
    if (!sheetName) {
      continue;
    }
    for (const table2 of sheet.tables ?? []) {
      if (!table2.name || !table2.range) {
        continue;
      }
      states.set(buildTableStateKey(sheetName, table2.name), {
        sheetName,
        name: table2.name,
        range: cloneGridRange(table2.range),
        tableId: table2.tableId,
        columnProperties: cloneTableColumnProperties(table2.columnProperties)
      });
    }
  }
  return states;
}
function moveTableStatesForSheet(tableStates, previousSheetName, nextSheetName) {
  const matchingStates = [...tableStates.entries()].filter(([, state]) => state.sheetName === previousSheetName);
  for (const [key, state] of matchingStates) {
    tableStates.delete(key);
    const nextState = cloneTableState(state);
    nextState.sheetName = nextSheetName;
    tableStates.set(buildTableStateKey(nextSheetName, nextState.name), nextState);
  }
}
function deleteTableStatesForSheet(tableStates, sheetName) {
  for (const [key, state] of [...tableStates.entries()]) {
    if (state.sheetName === sheetName) {
      tableStates.delete(key);
    }
  }
}
function findTableState(tableStates, targetName, sheetName) {
  if (sheetName) {
    return tableStates.get(buildTableStateKey(sheetName, targetName)) ?? null;
  }
  const matches = [...tableStates.values()].filter((state) => normalizeTableName(state.name) === normalizeTableName(targetName));
  if (matches.length === 1) {
    return matches[0] ?? null;
  }
  return null;
}
function buildTableColumnPropertiesFromWorksheet(sheet, range2) {
  const parsed = parseRangeAddress(range2);
  if (!parsed) {
    return [];
  }
  const columnCount = parsed.bounds.endCol - parsed.bounds.startCol + 1;
  const headerRange = buildRangeRef({
    startRow: parsed.bounds.startRow,
    endRow: parsed.bounds.startRow,
    startCol: parsed.bounds.startCol,
    endCol: parsed.bounds.endCol
  });
  const headerValues = sheet.getRange?.(headerRange).values?.[0] ?? [];
  return Array.from({ length: columnCount }, (_, index2) => {
    const value2 = headerValues[index2];
    return {
      columnIndex: index2,
      columnName: value2 !== undefined && value2 !== null && value2 !== "" ? String(value2) : `Column${index2 + 1}`
    };
  });
}
function buildTablePayload(op, resolveSheet2, warnings, workbook) {
  if (op.props.hasHeaders === false) {
    warnings.push("googleSheets: table.add without headers is not supported by the current Sheets table lowering and was dropped.");
    return null;
  }
  if (!op.props.name) {
    warnings.push("googleSheets: table.add requires a stable table name for Sheets table lowering and was dropped.");
    return null;
  }
  const sheet = resolveSheet2(op.props.range.sheet);
  const parsed = parseRangeAddress(op.props.range.range);
  if (!parsed) {
    warnings.push(`googleSheets: table.add could not parse range ${op.props.range.range} for ${op.props.name}.`);
    return null;
  }
  const worksheet = workbook.worksheets.getItem(sheet.name);
  return {
    sheetName: sheet.name,
    name: op.props.name,
    range: toGridRange({ sheetId: sheet.sheetId, range: parsed.ref }),
    columnProperties: buildTableColumnPropertiesFromWorksheet(worksheet, parsed.ref),
    requestIndexes: []
  };
}
function appendRequestIndex(state, requestIndex) {
  const nextState = cloneTableState(state);
  nextState.requestIndexes = [...nextState.requestIndexes ?? [], requestIndex];
  return nextState;
}
function removePendingRequests(requests, requestIndexes) {
  for (const index2 of [...requestIndexes ?? []].sort((a, b) => b - a)) {
    requests.splice(index2, 1);
  }
}
function shiftTableRequestIndexes(tableStates, removedIndex) {
  for (const [key, state] of tableStates.entries()) {
    const nextIndexes = (state.requestIndexes ?? []).filter((index2) => index2 !== removedIndex).map((index2) => index2 > removedIndex ? index2 - 1 : index2);
    if (nextIndexes.length !== (state.requestIndexes ?? []).length) {
      tableStates.set(key, {
        ...state,
        requestIndexes: nextIndexes.length > 0 ? nextIndexes : undefined
      });
      continue;
    }
    if (state.requestIndexes?.some((index2) => index2 > removedIndex)) {
      tableStates.set(key, {
        ...state,
        requestIndexes: nextIndexes.length > 0 ? nextIndexes : undefined
      });
    }
  }
}
function buildTableRowsUpdateCellsRequest(input) {
  const startRowIndex = input.table.range.endRowIndex;
  const startColumnIndex = input.table.range.startColumnIndex;
  const endColumnIndex = input.table.range.endColumnIndex;
  const columnCount = endColumnIndex - startColumnIndex;
  return {
    updateCells: {
      start: {
        sheetId: input.table.range.sheetId,
        rowIndex: startRowIndex,
        columnIndex: startColumnIndex
      },
      rows: input.values.map((row2) => ({
        values: Array.from({ length: columnCount }, (_, index2) => ({
          userEnteredValue: buildCellValue(row2[index2] ?? null)
        }))
      })),
      fields: "userEnteredValue"
    }
  };
}

// node_modules/@oai/granola/dist/models/spreadsheet/google-sheets/adapter/request-builder.js
function buildRequests(input) {
  const requests = [];
  const aliasSheets = new Map;
  const sheetStates = buildPatchedSheetStates({
    workbook: input.workbook,
    preApplyState: input.preApplyState,
    knownRemoteSheetNameToId: input.knownRemoteSheetNameToId
  });
  const conditionalFormatStates = buildConditionalFormatStates(input.preApplyState);
  const namedRangeStates = buildNamedRangeStates(input.spreadsheet);
  const tableStates = buildTableStates(input.spreadsheet);
  const chartStates = buildChartStates(input.spreadsheet);
  let inlineChartDataSheet;
  let inlineChartDataCursorRow = 0;
  const resolveSheetFromState = (target, fallbackName) => {
    const aliased = aliasSheets.get(target);
    if (aliased) {
      return aliased;
    }
    const current = sheetStates.get(target);
    if (current) {
      return current;
    }
    if (fallbackName) {
      const fallback = sheetStates.get(fallbackName);
      if (fallback) {
        return fallback;
      }
    }
    return resolveSheet({
      workbook: input.workbook,
      knownRemoteSheetIds: input.knownRemoteSheetIds,
      knownRemoteSheetNameToId: input.knownRemoteSheetNameToId,
      aliasSheets,
      target,
      fallbackName
    });
  };
  const moveTablesForSheet = (from2, to) => {
    moveTableStatesForSheet(tableStates, from2, to);
  };
  const ensureInlineChartDataSheet = () => {
    if (inlineChartDataSheet) {
      return inlineChartDataSheet;
    }
    const existingNames = new Set(sheetStates.keys());
    let name2 = "__Granola_Chart_Data";
    let suffix = 2;
    while (existingNames.has(name2)) {
      name2 = `__Granola_Chart_Data_${suffix}`;
      suffix += 1;
    }
    const usedIds = new Set([
      ...input.knownRemoteSheetIds,
      ...[...sheetStates.values()].map((sheet) => sheet.sheetId).filter((value2) => Boolean(value2))
    ]);
    let nextId = 900000000;
    while (usedIds.has(`${nextId}`)) {
      nextId += 1;
    }
    const maxIndex = Math.max(-1, ...[...sheetStates.values()].map((sheet) => sheet.index ?? 0));
    inlineChartDataSheet = {
      name: name2,
      index: maxIndex + 1,
      sheetId: `${nextId}`
    };
    sheetStates.set(name2, cloneWorksheetLike(inlineChartDataSheet));
    requests.push({
      addSheet: {
        properties: {
          sheetId: toSheetId(inlineChartDataSheet.sheetId),
          title: inlineChartDataSheet.name,
          index: inlineChartDataSheet.index,
          hidden: true
        }
      }
    });
    return inlineChartDataSheet;
  };
  for (const op of input.patch) {
    switch (op.op) {
      case "sheet.add": {
        const sheet = resolveAddedSheet({
          workbook: input.workbook,
          spreadsheet: input.spreadsheet,
          op,
          applyResult: input.applyResult
        });
        if (op.as) {
          aliasSheets.set(op.as, sheet);
        }
        sheetStates.set(sheet.name, cloneWorksheetLike(sheet));
        conditionalFormatStates.set(sheet.name, []);
        requests.push({
          addSheet: {
            properties: {
              sheetId: toSheetId(sheet.sheetId),
              title: sheet.name,
              index: sheet.index
            }
          }
        });
        break;
      }
      case "sheet.set": {
        const sheet = resolveSheetFromState(op.target, op.props.name);
        const properties = {
          sheetId: toSheetId(sheet.sheetId),
          title: op.props.name ?? sheet.name,
          index: op.props.index ?? sheet.index
        };
        const fields = [];
        if (op.props.name !== undefined) {
          fields.push("title");
        }
        if (op.props.index !== undefined) {
          fields.push("index");
        }
        if (fields.length > 0) {
          requests.push({
            updateSheetProperties: {
              properties,
              fields: fields.join(",")
            }
          });
        }
        const nextSheet = {
          name: op.props.name ?? sheet.name,
          index: op.props.index ?? sheet.index,
          sheetId: sheet.sheetId
        };
        sheetStates.delete(sheet.name);
        sheetStates.set(nextSheet.name, nextSheet);
        moveConditionalFormatState(conditionalFormatStates, sheet.name, nextSheet.name);
        moveTablesForSheet(sheet.name, nextSheet.name);
        moveChartStatesForSheet(chartStates, sheet.name, nextSheet.name);
        break;
      }
      case "sheet.remove": {
        const sheet = resolveSheetFromState(op.target);
        requests.push({
          deleteSheet: {
            sheetId: toSheetId(sheet.sheetId)
          }
        });
        sheetStates.delete(sheet.name);
        conditionalFormatStates.delete(sheet.name);
        deleteTableStatesForSheet(tableStates, sheet.name);
        deleteChartStatesForSheet(chartStates, sheet.name);
        break;
      }
      case "range.values.set": {
        const sheet = resolveSheetFromState(op.target.sheet);
        if (op.values === null) {
          requests.push({
            repeatCell: {
              range: toGridRange({
                sheetId: sheet.sheetId,
                range: op.target.range
              }),
              cell: {},
              fields: "userEnteredValue"
            }
          });
          break;
        }
        requests.push({
          updateCells: {
            start: toGridStart({
              sheetId: sheet.sheetId,
              range: op.target.range
            }),
            rows: op.values.map((row2) => ({
              values: row2.map((value2) => ({
                userEnteredValue: buildCellValue(value2)
              }))
            })),
            fields: "userEnteredValue"
          }
        });
        break;
      }
      case "range.formulas.set": {
        const sheet = resolveSheetFromState(op.target.sheet);
        requests.push({
          updateCells: {
            start: toGridStart({
              sheetId: sheet.sheetId,
              range: op.target.range
            }),
            rows: op.formulas.map((row2) => ({
              values: row2.map((value2) => ({
                userEnteredValue: buildFormulaValue(value2)
              }))
            })),
            fields: "userEnteredValue"
          }
        });
        break;
      }
      case "range.merge": {
        const sheet = resolveSheetFromState(op.target.sheet);
        requests.push({
          mergeCells: {
            range: toGridRange({
              sheetId: sheet.sheetId,
              range: op.target.range
            }),
            mergeType: op.across ? "MERGE_ROWS" : "MERGE_ALL"
          }
        });
        break;
      }
      case "range.unmerge": {
        const sheet = resolveSheetFromState(op.target.sheet);
        requests.push({
          unmergeCells: {
            range: toGridRange({
              sheetId: sheet.sheetId,
              range: op.target.range
            })
          }
        });
        break;
      }
      case "range.format.set": {
        const sheet = resolveSheetFromState(op.target.sheet);
        const gridRange = toGridRange({
          sheetId: sheet.sheetId,
          range: op.target.range
        });
        const { format: format3, fields } = buildCellFormat(op.props, input.warnings);
        if (fields.length > 0) {
          requests.push({
            repeatCell: {
              range: gridRange,
              cell: { userEnteredFormat: format3 },
              fields: fields.map((field) => `userEnteredFormat.${field}`).join(",")
            }
          });
        }
        if (op.props.borders) {
          const borderRequest = buildBordersRequest(gridRange, op.props.borders, input.warnings);
          if (borderRequest) {
            requests.push(borderRequest);
          }
        }
        if (op.props.rowHeight !== undefined) {
          requests.push({
            updateDimensionProperties: {
              range: {
                sheetId: toSheetId(sheet.sheetId),
                dimension: "ROWS",
                startIndex: gridRange.startRowIndex,
                endIndex: gridRange.endRowIndex
              },
              properties: {
                pixelSize: Math.max(1, Math.round(pointsToPx(op.props.rowHeight)))
              },
              fields: "pixelSize"
            }
          });
        }
        if (op.props.columnWidth !== undefined) {
          requests.push({
            updateDimensionProperties: {
              range: {
                sheetId: toSheetId(sheet.sheetId),
                dimension: "COLUMNS",
                startIndex: gridRange.startColumnIndex,
                endIndex: gridRange.endColumnIndex
              },
              properties: {
                pixelSize: Math.max(1, Math.round(colWidthToPx(op.props.columnWidth)))
              },
              fields: "pixelSize"
            }
          });
        }
        break;
      }
      case "range.format.clear": {
        const sheet = resolveSheetFromState(op.target.sheet);
        requests.push({
          repeatCell: {
            range: toGridRange({
              sheetId: sheet.sheetId,
              range: op.target.range
            }),
            cell: { userEnteredFormat: {} },
            fields: "userEnteredFormat"
          }
        });
        break;
      }
      case "conditionalformat.add": {
        const sheet = resolveSheetFromState(op.target.sheet);
        const rangeKey = normalizeRangeRef2(op.target.range);
        const rule2 = buildConditionalFormatRule(sheet.sheetId, op, input.warnings);
        if (rule2) {
          const sheetRules = conditionalFormatStates.get(sheet.name) ?? [];
          const index2 = findConditionalFormatInsertIndex(sheetRules, rangeKey);
          requests.push({
            addConditionalFormatRule: {
              index: index2,
              rule: rule2
            }
          });
          sheetRules.splice(index2, 0, { rangeKeys: [rangeKey] });
          conditionalFormatStates.set(sheet.name, sheetRules);
        }
        break;
      }
      case "conditionalformat.clear": {
        const sheet = resolveSheetFromState(op.target.sheet);
        const rangeKey = normalizeRangeRef2(op.target.range);
        const sheetRules = conditionalFormatStates.get(sheet.name) ?? [];
        const indexes = sheetRules.map((rule2, index2) => rule2.rangeKeys.includes(rangeKey) ? index2 : -1).filter((index2) => index2 >= 0);
        if (indexes.length === 0) {
          input.warnings.push(`googleSheets: conditionalformat.clear found no matching prior rules for ${sheet.name}!${rangeKey}.`);
          break;
        }
        for (const index2 of [...indexes].sort((a, b) => b - a)) {
          requests.push({
            deleteConditionalFormatRule: {
              sheetId: toSheetId(sheet.sheetId),
              index: index2
            }
          });
          sheetRules.splice(index2, 1);
        }
        conditionalFormatStates.set(sheet.name, sheetRules);
        break;
      }
      case "names.range.add": {
        const namedRange = buildNamedRangePayload(op, resolveSheetFromState, input.warnings);
        if (!namedRange?.name || !namedRange.range) {
          break;
        }
        const key = normalizeDefinedName(namedRange.name);
        const existing = namedRangeStates.get(key);
        if (existing?.namedRangeId) {
          requests.push({
            updateNamedRange: {
              namedRange: {
                namedRangeId: existing.namedRangeId,
                name: namedRange.name,
                range: cloneGridRange(namedRange.range)
              },
              fields: "name,range"
            }
          });
          namedRangeStates.set(key, {
            name: namedRange.name,
            range: cloneGridRange(namedRange.range),
            namedRangeId: existing.namedRangeId
          });
          break;
        }
        if (existing?.requestIndex !== undefined) {
          const request = requests[existing.requestIndex];
          if (request && "addNamedRange" in request) {
            request.addNamedRange.namedRange = {
              name: namedRange.name,
              range: cloneGridRange(namedRange.range)
            };
            namedRangeStates.set(key, {
              name: namedRange.name,
              range: cloneGridRange(namedRange.range),
              requestIndex: existing.requestIndex
            });
          }
          break;
        }
        requests.push({
          addNamedRange: {
            namedRange: {
              name: namedRange.name,
              range: cloneGridRange(namedRange.range)
            }
          }
        });
        namedRangeStates.set(key, {
          name: namedRange.name,
          range: cloneGridRange(namedRange.range),
          requestIndex: requests.length - 1
        });
        break;
      }
      case "names.function.add": {
        input.warnings.push(`googleSheets: names.function.add is not supported because the Sheets discovery doc does not expose named functions; dropped ${op.name}.`);
        break;
      }
      case "names.remove": {
        if (op.sheet) {
          input.warnings.push(`googleSheets: names.remove sheet-scoped named ranges are not supported by the Sheets namedRanges payload; dropped ${op.name}.`);
          break;
        }
        const key = normalizeDefinedName(op.name);
        const existing = namedRangeStates.get(key);
        if (!existing) {
          input.warnings.push(`googleSheets: names.remove could not find a matching Sheets namedRange for ${op.name}.`);
          break;
        }
        if (existing.requestIndex !== undefined && !existing.namedRangeId) {
          requests.splice(existing.requestIndex, 1);
          shiftNamedRangeRequestIndexes(namedRangeStates, existing.requestIndex);
          namedRangeStates.delete(key);
          break;
        }
        if (!existing.namedRangeId) {
          input.warnings.push(`googleSheets: names.remove requires namedRangeId metadata for ${op.name}; reconfigure with spreadsheet.namedRanges before deleting.`);
          break;
        }
        requests.push({
          deleteNamedRange: {
            namedRangeId: existing.namedRangeId
          }
        });
        namedRangeStates.delete(key);
        break;
      }
      case "table.add": {
        const table2 = buildTablePayload(op, resolveSheetFromState, input.warnings, input.workbook);
        if (!table2) {
          break;
        }
        const key = buildTableStateKey(table2.sheetName, table2.name);
        if (tableStates.has(key)) {
          input.warnings.push(`googleSheets: table.add found an existing table named ${table2.name} on ${table2.sheetName}; dropped duplicate add.`);
          break;
        }
        requests.push({
          addTable: {
            table: {
              name: table2.name,
              range: cloneGridRange(table2.range),
              columnProperties: cloneTableColumnProperties(table2.columnProperties)
            }
          }
        });
        tableStates.set(key, appendRequestIndex(table2, requests.length - 1));
        break;
      }
      case "table.rows.add": {
        if (op.props.index !== undefined && op.props.index !== null) {
          input.warnings.push(`googleSheets: table.rows.add only supports appending rows; dropped indexed insert for ${op.target.name}.`);
          break;
        }
        const table2 = findTableState(tableStates, op.target.name, op.target.sheet);
        if (!table2) {
          input.warnings.push(`googleSheets: table.rows.add could not resolve table ${op.target.name}.`);
          break;
        }
        if (table2.range.sheetId === undefined || table2.range.endRowIndex === undefined || table2.range.startColumnIndex === undefined || table2.range.endColumnIndex === undefined) {
          input.warnings.push(`googleSheets: table.rows.add is missing range metadata for ${table2.name}.`);
          break;
        }
        const rowCount = op.props.values.length;
        if (rowCount === 0) {
          break;
        }
        requests.push(buildTableRowsUpdateCellsRequest({
          table: table2,
          values: op.props.values
        }));
        const startRowIndex = table2.range.endRowIndex;
        const nextRange = {
          ...cloneGridRange(table2.range),
          endRowIndex: startRowIndex + rowCount
        };
        const nextKey = buildTableStateKey(table2.sheetName, table2.name);
        let nextState = appendRequestIndex({
          ...table2,
          range: nextRange
        }, requests.length - 1);
        const pendingAddIndex = nextState.requestIndexes?.find((index2) => {
          const request = requests[index2];
          return request ? "addTable" in request : false;
        });
        if (pendingAddIndex !== undefined) {
          const request = requests[pendingAddIndex];
          if (request && "addTable" in request && request.addTable.table) {
            request.addTable.table.range = cloneGridRange(nextRange);
          }
          tableStates.set(nextKey, nextState);
          break;
        }
        if (!table2.tableId) {
          input.warnings.push(`googleSheets: table.rows.add requires tableId metadata for ${table2.name}; reconfigure with spreadsheet sheet.tables before appending rows.`);
          requests.pop();
          break;
        }
        requests.push({
          updateTable: {
            table: {
              tableId: table2.tableId,
              range: cloneGridRange(nextRange)
            },
            fields: "range"
          }
        });
        nextState = appendRequestIndex(nextState, requests.length - 1);
        tableStates.set(nextKey, nextState);
        break;
      }
      case "table.set": {
        const table2 = findTableState(tableStates, op.target.name, op.target.sheet);
        if (!table2) {
          input.warnings.push(`googleSheets: table.set could not resolve table ${op.target.name}.`);
          break;
        }
        const nextName = op.props.name ?? table2.name;
        const nextKey = buildTableStateKey(table2.sheetName, nextName);
        if (nextName !== table2.name && tableStates.has(nextKey)) {
          input.warnings.push(`googleSheets: table.set found an existing table named ${nextName} on ${table2.sheetName}; dropped rename.`);
          break;
        }
        const currentKey = buildTableStateKey(table2.sheetName, table2.name);
        const nextState = {
          ...cloneTableState(table2),
          name: nextName
        };
        const pendingAddIndex = nextState.requestIndexes?.find((index2) => {
          const request = requests[index2];
          return request ? "addTable" in request : false;
        });
        if (pendingAddIndex !== undefined) {
          const request = requests[pendingAddIndex];
          if (request && "addTable" in request && request.addTable.table) {
            request.addTable.table.name = nextName;
          }
          tableStates.delete(currentKey);
          tableStates.set(nextKey, nextState);
          break;
        }
        if (op.props.name !== undefined) {
          if (!table2.tableId) {
            input.warnings.push(`googleSheets: table.set requires tableId metadata for ${table2.name}; reconfigure with spreadsheet sheet.tables before renaming.`);
            break;
          }
          requests.push({
            updateTable: {
              table: {
                tableId: table2.tableId,
                name: nextName
              },
              fields: "name"
            }
          });
          nextState.requestIndexes = [
            ...nextState.requestIndexes ?? [],
            requests.length - 1
          ];
        }
        tableStates.delete(currentKey);
        tableStates.set(nextKey, nextState);
        break;
      }
      case "table.remove": {
        const table2 = findTableState(tableStates, op.target.name, op.target.sheet);
        if (!table2) {
          input.warnings.push(`googleSheets: table.remove could not resolve table ${op.target.name}.`);
          break;
        }
        if (!table2.tableId && !table2.requestIndexes?.length) {
          input.warnings.push(`googleSheets: table.remove requires tableId metadata for ${table2.name}; reconfigure with spreadsheet sheet.tables before deleting.`);
          break;
        }
        removePendingRequests(requests, table2.requestIndexes);
        for (const index2 of [...table2.requestIndexes ?? []].sort((a, b) => b - a)) {
          shiftTableRequestIndexes(tableStates, index2);
        }
        const key = buildTableStateKey(table2.sheetName, table2.name);
        tableStates.delete(key);
        if (!table2.tableId) {
          break;
        }
        requests.push({
          deleteTable: {
            tableId: table2.tableId
          }
        });
        break;
      }
      case "chart.add": {
        const materialized = materializeInlineChartData({
          op,
          ensureDataSheet: ensureInlineChartDataSheet,
          nextStartRow: inlineChartDataCursorRow,
          requests
        });
        if (materialized) {
          inlineChartDataCursorRow = materialized.nextStartRow;
        }
        const chart2 = buildEmbeddedChart({
          op: materialized?.op ?? op,
          resolveSheet: resolveSheetFromState,
          warnings: input.warnings
        });
        if (!chart2) {
          break;
        }
        const sheet = resolveSheetFromState(op.sheet);
        requests.push({
          addChart: {
            chart: chart2
          }
        });
        upsertChartState(chartStates, sheet.name, buildChartStateFromProps({
          sheetName: sheet.name,
          sheetId: sheet.sheetId,
          props: op.props,
          chartId: chart2.chartId,
          requestIndex: requests.length - 1,
          localId: op.props.id,
          alias: op.as
        }));
        break;
      }
      case "chart.set": {
        const chartState = resolveChartState(chartStates, op.target);
        if (!chartState) {
          input.warnings.push(`googleSheets: chart.set could not resolve chart ${JSON.stringify(op.target)}.`);
          break;
        }
        const chart2 = buildEmbeddedChart({
          op,
          resolveSheet: resolveSheetFromState,
          warnings: input.warnings
        });
        if (!chart2?.spec || !chart2.position) {
          break;
        }
        if (chartState.requestIndex !== undefined) {
          const request = requests[chartState.requestIndex];
          if (request && "addChart" in request) {
            request.addChart.chart = {
              ...request.addChart.chart ?? {},
              spec: chart2.spec,
              position: chart2.position
            };
            upsertChartState(chartStates, chartState.sheetName, buildChartStateFromProps({
              sheetName: chartState.sheetName,
              sheetId: chart2.position.overlayPosition?.anchorCell?.sheetId,
              props: op.props,
              chartId: chartState.chartId,
              requestIndex: chartState.requestIndex,
              localId: chartState.localId,
              alias: chartState.alias
            }));
          }
          break;
        }
        if (chartState.chartId === undefined) {
          input.warnings.push(`googleSheets: chart.set requires chartId metadata for ${JSON.stringify(op.target)}.`);
          break;
        }
        requests.push({
          updateChartSpec: buildUpdateChartSpecRequest(chartState.chartId, chart2.spec)
        });
        requests.push({
          updateEmbeddedObjectPosition: buildUpdateChartPositionRequest(chartState.chartId, chart2.position)
        });
        upsertChartState(chartStates, chartState.sheetName, buildChartStateFromProps({
          sheetName: chartState.sheetName,
          sheetId: chart2.position.overlayPosition?.anchorCell?.sheetId,
          props: op.props,
          chartId: chartState.chartId,
          localId: chartState.localId,
          alias: chartState.alias
        }));
        break;
      }
      case "chart.remove": {
        const chartState = resolveChartState(chartStates, op.target);
        if (!chartState) {
          input.warnings.push(`googleSheets: chart.remove could not resolve chart ${JSON.stringify(op.target)}.`);
          break;
        }
        if (chartState.requestIndex !== undefined) {
          requests.splice(chartState.requestIndex, 1);
          shiftChartRequestIndexes(chartStates, chartState.requestIndex);
          removeChartState(chartStates, chartState);
          break;
        }
        if (chartState.chartId === undefined) {
          input.warnings.push(`googleSheets: chart.remove requires chartId metadata for ${JSON.stringify(op.target)}.`);
          break;
        }
        requests.push({
          deleteEmbeddedObject: buildDeleteChartRequest(chartState.chartId)
        });
        removeChartState(chartStates, chartState);
        break;
      }
      case "datavalidation.set": {
        const sheet = resolveSheetFromState(op.target.sheet);
        const request = buildSetDataValidationRequest(sheet.sheetId, op, input.warnings);
        if (request) {
          requests.push(request);
        }
        break;
      }
      case "datavalidation.clear": {
        const sheet = resolveSheetFromState(op.target.sheet);
        requests.push({
          setDataValidation: {
            range: toGridRange({
              sheetId: sheet.sheetId,
              range: op.target.range
            })
          }
        });
        break;
      }
      default: {
        input.warnings.push(`googleSheets: ${op.op} is not implemented yet.`);
        break;
      }
    }
  }
  return requests;
}
function materializeInlineChartData(input) {
  const props = input.op.props;
  const series = props.series ?? [];
  if (series.length === 0) {
    return;
  }
  if (props.chartType === "scatter") {
    const hasInlineScatter = series.every((entry) => (entry.xValues?.length ?? 0) > 0 && (entry.values?.length ?? 0) > 0 && !entry.xFormula && !entry.formula);
    if (!hasInlineScatter) {
      return;
    }
    const rowCount2 = Math.max(0, ...series.map((entry) => entry.xValues?.length ?? 0), ...series.map((entry) => entry.values?.length ?? 0));
    if (rowCount2 === 0) {
      return;
    }
    const sheet2 = input.ensureDataSheet();
    const startRow2 = input.nextStartRow;
    const rows2 = [];
    const xValues = series[0]?.xValues ?? [];
    for (let index2 = 0;index2 < rowCount2; index2 += 1) {
      rows2.push([
        xValues[index2] ?? null,
        ...series.map((entry) => entry.values?.[index2] ?? null)
      ]);
    }
    appendInlineChartDataRequest({
      requests: input.requests,
      sheet: sheet2,
      startRow: startRow2,
      rows: rows2
    });
    const nextSeries2 = series.map((entry, index2) => ({
      ...entry,
      xValues: undefined,
      values: undefined,
      xFormula: `${quoteSheetName(sheet2.name)}!$A$${startRow2 + 1}:$A$${startRow2 + rows2.length}`,
      formula: `${quoteSheetName(sheet2.name)}!$${columnLabel2(index2 + 2)}$${startRow2 + 1}:$${columnLabel2(index2 + 2)}$${startRow2 + rows2.length}`
    }));
    return {
      op: {
        ...input.op,
        props: {
          ...props,
          series: nextSeries2
        }
      },
      nextStartRow: startRow2 + rows2.length + 1
    };
  }
  const hasInlineCategories = (props.categories?.length ?? 0) > 0 && series.every((entry) => (entry.values?.length ?? 0) > 0 && !entry.formula);
  if (!hasInlineCategories) {
    return;
  }
  if ((props.chartType === "pie" || props.chartType === "doughnut") && series.length !== 1) {
    return;
  }
  const rowCount = Math.max(props.categories?.length ?? 0, ...series.map((entry) => entry.values?.length ?? 0));
  if (rowCount === 0) {
    return;
  }
  const sheet = input.ensureDataSheet();
  const startRow = input.nextStartRow;
  const rows = [];
  for (let index2 = 0;index2 < rowCount; index2 += 1) {
    rows.push([
      props.categories?.[index2] ?? null,
      ...series.map((entry) => entry.values?.[index2] ?? null)
    ]);
  }
  appendInlineChartDataRequest({
    requests: input.requests,
    sheet,
    startRow,
    rows
  });
  const nextSeries = series.map((entry, index2) => ({
    ...entry,
    values: undefined,
    categoryFormula: `${quoteSheetName(sheet.name)}!$A$${startRow + 1}:$A$${startRow + rows.length}`,
    formula: `${quoteSheetName(sheet.name)}!$${columnLabel2(index2 + 2)}$${startRow + 1}:$${columnLabel2(index2 + 2)}$${startRow + rows.length}`
  }));
  return {
    op: {
      ...input.op,
      props: {
        ...props,
        categories: undefined,
        series: nextSeries
      }
    },
    nextStartRow: startRow + rows.length + 1
  };
}
function appendInlineChartDataRequest(input) {
  input.requests.push({
    updateCells: {
      start: {
        sheetId: toSheetId(input.sheet.sheetId),
        rowIndex: input.startRow,
        columnIndex: 0
      },
      rows: input.rows.map((row2) => ({
        values: row2.map((value2) => ({
          userEnteredValue: buildCellValue(value2)
        }))
      })),
      fields: "userEnteredValue"
    }
  });
}
function columnLabel2(index2) {
  let n = index2;
  let label = "";
  while (n > 0) {
    const remainder = (n - 1) % 26;
    label = String.fromCharCode(65 + remainder) + label;
    n = Math.floor((n - 1) / 26);
  }
  return label;
}

// node_modules/@oai/granola/dist/models/spreadsheet/google-sheets/adapter.js
var DEFAULT_GET_FIELDS = "spreadsheetId,properties(title,timeZone,locale),sheets(properties(sheetId,title,index,hidden,rightToLeft),charts(chartId,position(sheetId,newSheet,overlayPosition(anchorCell(sheetId,rowIndex,columnIndex),offsetXPixels,offsetYPixels,widthPixels,heightPixels)),spec(title,altText,maximized,basicChart(chartType,legendPosition,headerCount,interpolateNulls,compareMode,lineSmoothing,stackedType,domains(domain(sourceRange(sources(sheetId,startRowIndex,endRowIndex,startColumnIndex,endColumnIndex))),reversed),series(series(sourceRange(sources(sheetId,startRowIndex,endRowIndex,startColumnIndex,endColumnIndex))),targetAxis),axis(position,title)),pieChart(domain(sourceRange(sources(sheetId,startRowIndex,endRowIndex,startColumnIndex,endColumnIndex))),series(sourceRange(sources(sheetId,startRowIndex,endRowIndex,startColumnIndex,endColumnIndex))),pieHole,legendPosition,threeDimensional))),tables(tableId,name,range(sheetId,startRowIndex,endRowIndex,startColumnIndex,endColumnIndex),columnProperties(columnIndex,columnName,columnType))),namedRanges(namedRangeId,name,range(sheetId,startRowIndex,endRowIndex,startColumnIndex,endColumnIndex))";

class GoogleSheetsAdapter {
  #workbook;
  #client;
  #spreadsheetId;
  #fields;
  #batchUpdateOptions;
  #spreadsheet;
  #knownRemoteSheetIds = new Set;
  #knownRemoteSheetNameToId = new Map;
  constructor(workbook, config3) {
    this.#workbook = workbook;
    this.#client = config3.client;
    this.#spreadsheetId = config3.spreadsheetId;
    this.#fields = config3.fields;
    this.#batchUpdateOptions = config3.batchUpdateOptions;
    this.#spreadsheet = config3.spreadsheet;
    this.#refreshKnownSheets();
  }
  get spreadsheetId() {
    return this.#spreadsheetId;
  }
  get fields() {
    return this.#fields;
  }
  async getSpreadsheet() {
    if (!this.#client) {
      throw new Error("Google Sheets client is not configured.");
    }
    return this.#client.getSpreadsheet(this.#spreadsheetId, {
      fields: this.#fields ?? DEFAULT_GET_FIELDS
    });
  }
  async applyPatch(patch, applyResult, preApplyState) {
    const warnings = [...applyResult.warnings];
    const requests = buildRequests({
      workbook: this.#workbook,
      spreadsheet: this.#spreadsheet,
      patch,
      applyResult,
      warnings,
      preApplyState,
      knownRemoteSheetIds: this.#knownRemoteSheetIds,
      knownRemoteSheetNameToId: this.#knownRemoteSheetNameToId
    });
    const request = {
      requests,
      ...normalizeBatchUpdateOptions(this.#batchUpdateOptions, warnings)
    };
    this.#refreshKnownSheets();
    return {
      ...applyResult,
      warnings,
      googleSheetsBatchUpdate: {
        spreadsheetId: this.#spreadsheetId,
        ...request
      },
      googleSheetsBatchUpdateConnectorArgs: buildConnectorArgs({
        spreadsheetId: this.#spreadsheetId,
        ...request
      }, this.#spreadsheet?.spreadsheetUrl)
    };
  }
  #refreshKnownSheets() {
    const next2 = refreshKnownSheets({
      spreadsheet: this.#spreadsheet,
      workbook: this.#workbook
    });
    this.#knownRemoteSheetIds = next2.knownRemoteSheetIds;
    this.#knownRemoteSheetNameToId = next2.knownRemoteSheetNameToId;
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/google-sheets/client.js
var DEFAULT_BASE_URL2 = "https://sheets.googleapis.com/";

class FetchGoogleSheetsClient {
  #accessToken;
  #apiKey;
  #baseUrl;
  constructor(options) {
    this.#accessToken = options.accessToken;
    this.#apiKey = options.apiKey;
    this.#baseUrl = options.baseUrl ?? DEFAULT_BASE_URL2;
  }
  async getSpreadsheet(spreadsheetId, options) {
    const url2 = new URL(`v4/spreadsheets/${encodeURIComponent(spreadsheetId)}`, this.#baseUrl);
    if (this.#apiKey) {
      url2.searchParams.set("key", this.#apiKey);
    }
    if (options?.fields) {
      url2.searchParams.set("fields", options.fields);
    }
    const response = await fetch(url2.toString(), {
      method: "GET",
      headers: this.#authHeaders()
    });
    return this.#parseResponse(response);
  }
  async batchUpdate(spreadsheetId, request) {
    const url2 = new URL(`v4/spreadsheets/${encodeURIComponent(spreadsheetId)}:batchUpdate`, this.#baseUrl);
    if (this.#apiKey) {
      url2.searchParams.set("key", this.#apiKey);
    }
    const response = await fetch(url2.toString(), {
      method: "POST",
      headers: {
        ...this.#authHeaders(),
        "Content-Type": "application/json"
      },
      body: JSON.stringify(request)
    });
    return this.#parseResponse(response);
  }
  #authHeaders() {
    return { Authorization: `Bearer ${this.#accessToken}` };
  }
  async#parseResponse(response) {
    const body = await response.json().catch(() => ({}));
    if (!response.ok) {
      const message = typeof body?.error?.message === "string" ? body.error.message : `Google Sheets API error (${response.status})`;
      throw new Error(message);
    }
    return body;
  }
}

class GapiGoogleSheetsClient {
  #gapi;
  constructor(gapi) {
    this.#gapi = gapi;
  }
  async getSpreadsheet(spreadsheetId, options) {
    const response = await this.#gapi.client.sheets.spreadsheets.get({
      spreadsheetId,
      fields: options?.fields
    });
    return response.result;
  }
  async batchUpdate(spreadsheetId, request) {
    const response = await this.#gapi.client.sheets.spreadsheets.batchUpdate({
      spreadsheetId,
      requests: request.requests,
      includeSpreadsheetInResponse: request.includeSpreadsheetInResponse,
      responseRanges: request.responseRanges,
      responseIncludeGridData: request.responseIncludeGridData
    });
    return response.result;
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/pivots/pivot-cache-index.js
function normalizeCacheKey(value2) {
  if (value2 == null)
    return "";
  return String(value2);
}

class PivotCacheIndex {
  fields;
  constructor(fields) {
    this.fields = fields;
  }
  static buildFromSource(source) {
    const fields = source.headers.map((header, fieldIndex) => {
      const unique = [];
      const seen = new Map;
      for (const row2 of source.rows) {
        const key = normalizeCacheKey(row2[fieldIndex] ?? null);
        if (seen.has(key))
          continue;
        seen.set(key, unique.length);
        unique.push(key);
      }
      return {
        fieldIndex,
        header,
        uniqueItems: unique,
        valueToItemIndex: seen
      };
    });
    return new PivotCacheIndex(fields);
  }
}

// node_modules/@oai/granola/dist/models/spreadsheet/pivots/pivot-source-table.js
class PivotSourceTable {
  headers;
  rows;
  constructor(options) {
    this.headers = options.headers;
    this.rows = options.rows;
  }
  get rowCount() {
    return this.rows.length;
  }
  get colCount() {
    return this.headers.length;
  }
  getColumnIndex(header) {
    const idx = this.headers.indexOf(header);
    if (idx === -1) {
      throw new Error(`Pivot source column not found: ${header}`);
    }
    return idx;
  }
  getCell(rowIndex2, colIndex) {
    const row2 = this.rows[rowIndex2];
    if (!row2) {
      throw new Error(`Pivot source row out of bounds: ${rowIndex2}`);
    }
    return row2[colIndex] ?? null;
  }
}

// node_modules/@oai/granola/dist/events/hitTester.js
class GeometryHitTester {
  getTargets;
  constructor(getTargets) {
    this.getTargets = getTargets;
  }
  hitTest(point5) {
    const targets = this.getTargets();
    let best = null;
    let bestZ = -Infinity;
    for (const target of targets) {
      if (!isRectValid(target.bounds)) {
        continue;
      }
      if (!containsPoint(target.bounds, point5)) {
        continue;
      }
      if (typeof target.hitTest === "function" && !target.hitTest(point5)) {
        continue;
      }
      if (best && target.zIndex < bestZ) {
        continue;
      }
      const local = {
        x: point5.x - target.bounds.x,
        y: point5.y - target.bounds.y
      };
      best = {
        targetId: target.id,
        kind: target.kind,
        world: { x: point5.x, y: point5.y },
        local,
        path: [target.id]
      };
      bestZ = target.zIndex;
    }
    return best;
  }
}
function isRectValid(rect) {
  return Number.isFinite(rect.x) && Number.isFinite(rect.y) && Number.isFinite(rect.width) && Number.isFinite(rect.height) && rect.width > 0 && rect.height > 0;
}
function containsPoint(rect, point5) {
  const withinX = point5.x >= rect.x && point5.x <= rect.x + rect.width;
  const withinY = point5.y >= rect.y && point5.y <= rect.y + rect.height;
  return withinX && withinY;
}
// node_modules/@oai/granola/dist/events/eventsBus.js
class InMemoryEngineEventBus {
  listeners = new Map;
  on(type, listener) {
    let listeners = this.listeners.get(type);
    if (!listeners) {
      listeners = new Set;
      this.listeners.set(type, listeners);
    }
    listeners.add(listener);
    return () => {
      listeners?.delete(listener);
      if (listeners?.size === 0) {
        this.listeners.delete(type);
      }
    };
  }
  emit(event) {
    const listeners = this.listeners.get(event.type);
    if (!listeners) {
      return;
    }
    for (const listener of Array.from(listeners)) {
      listener(event);
    }
  }
}
// node_modules/@oai/granola/dist/events/inputController.js
var DEFAULT_CLICK_DISTANCE_THRESHOLD = 5;
var DEFAULT_CLICK_TIME_THRESHOLD_MS = 250;

class InputController {
  hitTester;
  events;
  clickDistanceThreshold;
  clickTimeThresholdMs;
  lastHit = null;
  activePointerId = null;
  downPosition = null;
  downTime = null;
  lastClickTime = null;
  lastClickTargetId = null;
  constructor(options) {
    this.hitTester = options.hitTester;
    this.events = options.events;
    this.clickDistanceThreshold = options.clickDistanceThreshold ?? DEFAULT_CLICK_DISTANCE_THRESHOLD;
    this.clickTimeThresholdMs = options.clickTimeThresholdMs ?? DEFAULT_CLICK_TIME_THRESHOLD_MS;
  }
  handlePointerEvent(ev) {
    switch (ev.type) {
      case "pointerMove":
        this.handlePointerMove(ev);
        break;
      case "pointerDown":
        this.handlePointerDown(ev);
        break;
      case "pointerUp":
        this.handlePointerUp(ev);
        break;
      case "pointerLeave":
        this.handlePointerLeave();
        break;
      default:
        break;
    }
  }
  handlePointerMove(ev) {
    const hit = this.hitTester.hitTest(ev.world);
    this.updateHover(hit);
  }
  handlePointerDown(ev) {
    if (this.activePointerId !== null && this.activePointerId !== ev.pointerId) {
      return;
    }
    this.activePointerId = ev.pointerId;
    this.downPosition = { x: ev.world.x, y: ev.world.y };
    this.downTime = ev.time;
  }
  handlePointerUp(ev) {
    if (this.activePointerId === null || ev.pointerId !== this.activePointerId) {
      return;
    }
    const hit = this.hitTester.hitTest(ev.world);
    this.updateHover(hit);
    const isClick = this.shouldEmitClick(ev, hit);
    if (isClick && hit) {
      if (ev.button === 2) {
        this.events.emit({ type: "contextMenu", hit });
      } else {
        const clicks = this.computeClickCount(ev, hit);
        this.events.emit({ type: "click", hit, clicks });
      }
      this.lastClickTime = ev.time;
      this.lastClickTargetId = hit.targetId;
    }
    this.activePointerId = null;
    this.downPosition = null;
    this.downTime = null;
  }
  handlePointerLeave() {
    this.clearHover();
  }
  updateHover(hit) {
    const previous4 = this.lastHit;
    if (previous4?.targetId === hit?.targetId) {
      this.lastHit = hit;
      return;
    }
    if (previous4) {
      this.events.emit({ type: "pointerLeave", hit: previous4 });
    }
    if (hit) {
      this.events.emit({ type: "pointerEnter", hit });
    }
    this.lastHit = hit;
    this.events.emit({ type: "hoverChanged", hit });
  }
  clearHover() {
    if (!this.lastHit) {
      return;
    }
    const previous4 = this.lastHit;
    this.lastHit = null;
    this.events.emit({ type: "pointerLeave", hit: previous4 });
    this.events.emit({ type: "hoverChanged", hit: null });
  }
  shouldEmitClick(ev, hit) {
    if (!hit || !this.downPosition || this.downTime === null) {
      return false;
    }
    const dx = ev.world.x - this.downPosition.x;
    const dy = ev.world.y - this.downPosition.y;
    const distanceSq = dx * dx + dy * dy;
    if (distanceSq > this.clickDistanceThreshold ** 2) {
      return false;
    }
    const elapsed = ev.time - this.downTime;
    return elapsed <= this.clickTimeThresholdMs;
  }
  computeClickCount(ev, hit) {
    if (this.lastClickTime !== null && this.lastClickTargetId === hit.targetId && ev.time - this.lastClickTime <= this.clickTimeThresholdMs) {
      return 2;
    }
    return 1;
  }
}
// node_modules/@oai/granola/dist/events/tools/selectionTool.js
class SelectionTool {
  events;
  selected = null;
  unsubscribeClick = null;
  constructor(events) {
    this.events = events;
    this.unsubscribeClick = this.events.on("click", (event) => {
      if (event.clicks !== 1) {
        return;
      }
      this.setSelected(event.hit.targetId);
    });
  }
  getSelected() {
    return this.selected;
  }
  dispose() {
    this.unsubscribeClick?.();
    this.unsubscribeClick = null;
  }
  setSelected(targetId) {
    if (this.selected === targetId) {
      return;
    }
    this.selected = targetId;
    this.events.emit({ type: "selectionChanged", targetId });
  }
}
// node_modules/@oai/granola/dist/spreadsheet/keyboard-event-bus.js
init_address_utils();
var MAX_ROW_COUNT2 = 1048576;
var MAX_COL_COUNT2 = 16384;

class SpreadsheetKeyboardEventBus {
  handle(workbook, event) {
    const awareness = workbook.awareness;
    const chord = resolveChord(event);
    const chordLabel = event.chord ?? formatChord(chord);
    const sheetName = resolveActiveSheetName(workbook, awareness);
    if (!sheetName) {
      return buildKeyboardEventResult({
        handled: false,
        workbookMutated: false,
        awareness
      });
    }
    let sheet;
    try {
      sheet = workbook.worksheets.getItem(sheetName);
    } catch {
      return buildKeyboardEventResult({
        handled: false,
        workbookMutated: false,
        awareness
      });
    }
    const sheetState = awareness.getSheetState(sheetName);
    const shouldCheckForMutation = chordCouldMutateWorkbook(chord, sheetState.mode);
    const maxVisibleRows = event.maxVisibleRows ?? MAX_ROW_COUNT2;
    const maxVisibleCols = event.maxVisibleCols ?? MAX_COL_COUNT2;
    const beforeWorkbookSnapshot = shouldCheckForMutation ? JSON.stringify(workbook.toProto()) : null;
    let handled = false;
    if (sheetState.mode === "editCell") {
      handled = handleEditMode({
        workbook,
        sheet,
        sheetState,
        awareness,
        chord,
        chordLabel,
        maxVisibleRows,
        maxVisibleCols
      });
    }
    if (!handled) {
      handled = handleGridMode({
        workbook,
        sheet,
        sheetState,
        awareness,
        chord,
        chordLabel,
        maxVisibleRows,
        maxVisibleCols
      });
    }
    const workbookMutated = handled && beforeWorkbookSnapshot != null && beforeWorkbookSnapshot !== JSON.stringify(workbook.toProto());
    return buildKeyboardEventResult({
      handled,
      workbookMutated,
      awareness
    });
  }
}
function handleEditMode(args2) {
  const { workbook, sheet, sheetState, awareness, chord, chordLabel, maxVisibleRows, maxVisibleCols } = args2;
  if (isChord(chord, { key: "Escape" })) {
    exitEditMode(sheetState);
    return true;
  }
  if (isChord(chord, { key: "Enter", alt: true })) {
    if (sheetState.editBuffer) {
      sheetState.editBuffer.text = sheetState.editBuffer.text.slice(0, sheetState.editBuffer.caret) + `
` + sheetState.editBuffer.text.slice(sheetState.editBuffer.caret);
      sheetState.editBuffer.caret += 1;
    }
    return true;
  }
  if (isChord(chord, { key: "Enter", meta: true })) {
    fillSelectionFromEdit({
      workbook,
      sheet,
      sheetState,
      awareness
    });
    return true;
  }
  if (isEditCommitNavigationChord(chord)) {
    commitEditAndContinue({
      workbook,
      sheet,
      sheetState,
      awareness,
      chord,
      maxVisibleRows,
      maxVisibleCols
    });
    return true;
  }
  if (isChord(chord, { key: "F4" }) || isChord(chord, { key: "T", meta: true })) {
    toggleFormulaReferenceStyle(sheetState);
    return true;
  }
  if (isChord(chord, { key: "Delete" }) || isChord(chord, { key: "Backspace" })) {
    if (sheetState.editBuffer && sheetState.editBuffer.caret > 0) {
      const buffer = sheetState.editBuffer;
      buffer.text = buffer.text.slice(0, buffer.caret - 1) + buffer.text.slice(buffer.caret);
      buffer.caret -= 1;
    }
    return true;
  }
  if (chord.key === "=" && !chord.meta && !chord.ctrl && !chord.alt) {
    appendToEditBuffer(sheetState, "=");
    return true;
  }
  if (chord.key.length === 1 && !chord.meta && !chord.ctrl && !chord.alt) {
    appendToEditBuffer(sheetState, chord.key);
    return true;
  }
  if (isChord(chord, { key: "CmdOrCtrl+Z" })) {
    undoLastMutation(awareness);
    return true;
  }
  if (isChord(chord, { key: "CmdOrCtrl+Y" }) || isChord(chord, { key: "CmdOrCtrl+Shift+Z" })) {
    redoLastMutation(awareness);
    return true;
  }
  recordMissingAction(awareness, {
    chord: chordLabel,
    action: "editModeShortcut",
    detail: "Unhandled shortcut while editing."
  });
  return true;
}
function handleGridMode(args2) {
  const { workbook, sheet, sheetState, awareness, chord, chordLabel, maxVisibleRows, maxVisibleCols } = args2;
  if (isChord(chord, { key: "0", meta: true, alt: true })) {
    setOutlineBorders(workbook, sheet, sheetState, awareness);
    return true;
  }
  if (isChord(chord, { key: "-", meta: true, alt: true })) {
    clearOutlineBorders(workbook, sheet, sheetState, awareness);
    return true;
  }
  if (isChord(chord, { key: "ArrowUp", meta: true, alt: true, shift: true })) {
    setBorderEdge(workbook, sheet, sheetState, awareness, "top");
    return true;
  }
  if (isChord(chord, { key: "ArrowDown", meta: true, alt: true, shift: true })) {
    setBorderEdge(workbook, sheet, sheetState, awareness, "bottom");
    return true;
  }
  if (isChord(chord, { key: "ArrowLeft", meta: true, alt: true, shift: true })) {
    setBorderEdge(workbook, sheet, sheetState, awareness, "left");
    return true;
  }
  if (isChord(chord, { key: "ArrowRight", meta: true, alt: true, shift: true })) {
    setBorderEdge(workbook, sheet, sheetState, awareness, "right");
    return true;
  }
  if (isChord(chord, { key: "ArrowLeft", meta: true, alt: true })) {
    switchWorksheet(workbook, awareness, -1);
    return true;
  }
  if (isChord(chord, { key: "ArrowRight", meta: true, alt: true })) {
    switchWorksheet(workbook, awareness, 1);
    return true;
  }
  if (isChord(chord, { key: "ArrowDown", alt: true })) {
    recordMissingAction(awareness, {
      chord: chordLabel,
      action: "openFilterDropdown",
      detail: "Open filter dropdown for the active header cell."
    });
    return true;
  }
  if (isArrowKey(chord.key)) {
    const move = arrowToDelta(chord.key);
    const extend4 = chord.shift || sheetState.extendSelection;
    const jump = chord.meta || chord.ctrl;
    if (jump) {
      const dest = jumpToDataEdge(sheet, sheetState.activeCell, move, maxVisibleRows, maxVisibleCols);
      updateSelection(sheetState, dest, extend4);
      resetSelectAllStage(sheetState, false);
      return true;
    }
    const next2 = {
      row: clampIndex2(sheetState.activeCell.row + move.row, maxVisibleRows),
      col: clampIndex2(sheetState.activeCell.col + move.col, maxVisibleCols)
    };
    updateSelection(sheetState, next2, extend4);
    resetSelectAllStage(sheetState, false);
    return true;
  }
  if (isChord(chord, { key: "Home", ctrl: true })) {
    updateSelection(sheetState, { row: 0, col: 0 }, false);
    resetSelectAllStage(sheetState, false);
    return true;
  }
  if (isChord(chord, { key: "Home" })) {
    const next2 = { row: sheetState.activeCell.row, col: 0 };
    updateSelection(sheetState, next2, false);
    resetSelectAllStage(sheetState, false);
    return true;
  }
  if (isChord(chord, { key: "End", ctrl: true })) {
    const used = getUsedBounds(sheet);
    const dest = used.hasData ? { row: used.maxRow, col: used.maxCol } : { row: 0, col: 0 };
    updateSelection(sheetState, dest, false);
    resetSelectAllStage(sheetState, false);
    return true;
  }
  if (isChord(chord, { key: "PageDown", alt: true })) {
    sheetState.scroll.col = clampIndex2(sheetState.scroll.col + 10, MAX_COL_COUNT2);
    return true;
  }
  if (isChord(chord, { key: "PageUp", alt: true })) {
    sheetState.scroll.col = clampIndex2(sheetState.scroll.col - 10, MAX_COL_COUNT2);
    return true;
  }
  if (isChord(chord, { key: "PageDown" })) {
    sheetState.scroll.row = clampIndex2(sheetState.scroll.row + 20, MAX_ROW_COUNT2);
    return true;
  }
  if (isChord(chord, { key: "PageUp" })) {
    sheetState.scroll.row = clampIndex2(sheetState.scroll.row - 20, MAX_ROW_COUNT2);
    return true;
  }
  if (isChord(chord, { key: "Delete", ctrl: true })) {
    sheetState.scroll = {
      row: sheetState.activeCell.row,
      col: sheetState.activeCell.col
    };
    return true;
  }
  if (isChord(chord, { key: "F2", meta: true, shift: true })) {
    recordMissingAction(awareness, {
      chord: chordLabel,
      action: "insertComment",
      detail: "Insert or reply to a threaded comment on the active cell."
    });
    return true;
  }
  if (isChord(chord, { key: "F2", shift: true })) {
    recordMissingAction(awareness, {
      chord: chordLabel,
      action: "insertNote",
      detail: "Insert or edit a note attached to the active cell."
    });
    return true;
  }
  if (isChord(chord, { key: "F2" })) {
    enterEditMode(sheet, sheetState);
    return true;
  }
  if (isChord(chord, { key: "Enter", meta: true })) {
    fillSelectionFromActiveCell({
      workbook,
      sheet,
      sheetState,
      awareness
    });
    return true;
  }
  if (isChord(chord, { key: "Enter", shift: true })) {
    moveWithinSelection(sheetState, { row: -1, col: 0 }, maxVisibleRows, maxVisibleCols);
    resetSelectAllStage(sheetState, false);
    return true;
  }
  if (isChord(chord, { key: "Tab", shift: true })) {
    moveWithinSelection(sheetState, { row: 0, col: -1 }, maxVisibleRows, maxVisibleCols);
    resetSelectAllStage(sheetState, false);
    return true;
  }
  if (isChord(chord, { key: "Enter" }) || isChord(chord, { key: "Return" })) {
    moveWithinSelection(sheetState, { row: 1, col: 0 }, maxVisibleRows, maxVisibleCols);
    resetSelectAllStage(sheetState, false);
    return true;
  }
  if (isChord(chord, { key: "Tab" })) {
    moveWithinSelection(sheetState, { row: 0, col: 1 }, maxVisibleRows, maxVisibleCols);
    resetSelectAllStage(sheetState, false);
    return true;
  }
  if (isChord(chord, { key: "Escape" })) {
    sheetState.copyOutline = null;
    return true;
  }
  if (isChord(chord, { key: "Delete", shift: true })) {
    const selection = getActiveSelection(sheetState);
    if (!isSingleCell(selection)) {
      updateSelection(sheetState, sheetState.activeCell, false);
    }
    return true;
  }
  if (isChord(chord, { key: "Delete" }) || isChord(chord, { key: "Backspace" })) {
    const selection = getActiveSelection(sheetState, sheet);
    recordRangeMutation({
      workbook,
      awareness,
      sheetName: sheetState.sheetName,
      rects: [selection],
      label: "Clear contents",
      apply: () => {
        const address = buildRangeRefFromRect(selection);
        sheet.getRange(address).clear({ applyTo: "contents" });
      }
    });
    resetSelectAllStage(sheetState, false);
    return true;
  }
  if (isChord(chord, { key: "CmdOrCtrl+Z" })) {
    undoLastMutation(awareness);
    return true;
  }
  if (isChord(chord, { key: "CmdOrCtrl+Y" }) || isChord(chord, { key: "CmdOrCtrl+Shift+Z" })) {
    redoLastMutation(awareness);
    return true;
  }
  if (isChord(chord, { key: "F", meta: true, shift: true }) || isChord(chord, { key: "L", ctrl: true, shift: true })) {
    recordMissingAction(awareness, {
      chord: chordLabel,
      action: "toggleAutoFilter",
      detail: "Toggle AutoFilter for the current region or table."
    });
    return true;
  }
  if (isChord(chord, { key: "F5" }) || isChord(chord, { key: "G", ctrl: true })) {
    awareness.setDialog({
      name: "goTo",
      args: { sheetName: sheetState.sheetName }
    });
    sheetState.mode = "dialog";
    return true;
  }
  if (isChord(chord, { key: "F", meta: true }) || isChord(chord, { key: "F", ctrl: true })) {
    awareness.setDialog({
      name: "find",
      args: { sheetName: sheetState.sheetName }
    });
    sheetState.mode = "dialog";
    return true;
  }
  if (isChord(chord, { key: "H", ctrl: true }) || isChord(chord, { key: "H", meta: true, shift: true })) {
    awareness.setDialog({
      name: "replace",
      args: { sheetName: sheetState.sheetName }
    });
    sheetState.mode = "dialog";
    return true;
  }
  if (isChord(chord, { key: "X", meta: true, shift: true })) {
    recordMissingAction(awareness, {
      chord: chordLabel,
      action: "toggleStrikethrough",
      detail: "Toggle strikethrough formatting on selection."
    });
    return true;
  }
  if (isChord(chord, { key: "C", meta: true }) || isChord(chord, { key: "C", ctrl: true })) {
    copySelection(sheet, sheetState, awareness, "copy");
    return true;
  }
  if (isChord(chord, { key: "X", meta: true }) || isChord(chord, { key: "X", ctrl: true })) {
    copySelection(sheet, sheetState, awareness, "cut");
    return true;
  }
  if (isChord(chord, { key: "V", meta: true, ctrl: true }) || isChord(chord, { key: "V", meta: true, alt: true })) {
    awareness.setDialog({
      name: "pasteSpecial",
      args: { sheetName: sheetState.sheetName }
    });
    sheetState.mode = "dialog";
    return true;
  }
  if (isChord(chord, { key: "V", meta: true }) || isChord(chord, { key: "V", ctrl: true })) {
    pasteClipboard({
      workbook,
      sheet,
      sheetState,
      awareness,
      chordLabel
    });
    return true;
  }
  if (isChord(chord, { key: " ", ctrl: true })) {
    selectWholeColumns(sheet, sheetState);
    resetSelectAllStage(sheetState, false);
    return true;
  }
  if (isChord(chord, { key: " ", shift: true })) {
    selectWholeRows(sheet, sheetState);
    resetSelectAllStage(sheetState, false);
    return true;
  }
  if (isChord(chord, { key: "A", meta: true }) || isChord(chord, { key: "A", ctrl: true })) {
    toggleSelectAll(sheet, sheetState);
    return true;
  }
  if (isChord(chord, { key: "*", meta: true, shift: true })) {
    sheetState.selectionVisibility = "visible";
    return true;
  }
  if (isChord(chord, { key: "F8", shift: true })) {
    addSelectionRange(sheetState);
    return true;
  }
  if (isChord(chord, { key: "F8" })) {
    sheetState.extendSelection = !sheetState.extendSelection;
    return true;
  }
  if (isChord(chord, { key: ".", ctrl: true })) {
    moveToSelectionCorner(sheetState);
    return true;
  }
  if (isChord(chord, { key: "=", ctrl: true, shift: true })) {
    awareness.setDialog({
      name: "insertCells",
      args: { sheetName: sheetState.sheetName }
    });
    sheetState.mode = "dialog";
    recordMissingAction(awareness, {
      chord: chordLabel,
      action: "insertCells",
      detail: "Insert cells and shift contents based on selection context."
    });
    return true;
  }
  if (isChord(chord, { key: "-", meta: true }) || isChord(chord, { key: "-", ctrl: true })) {
    awareness.setDialog({
      name: "deleteCells",
      args: { sheetName: sheetState.sheetName }
    });
    sheetState.mode = "dialog";
    recordMissingAction(awareness, {
      chord: chordLabel,
      action: "deleteCells",
      detail: "Delete cells and shift contents based on selection context."
    });
    return true;
  }
  if (isChord(chord, { key: "D", meta: true }) || isChord(chord, { key: "D", ctrl: true })) {
    fillDown(workbook, sheet, sheetState, awareness);
    return true;
  }
  if (isChord(chord, { key: "R", meta: true, shift: true })) {
    awareness.setDialog({
      name: "sort",
      args: { sheetName: sheetState.sheetName }
    });
    sheetState.mode = "dialog";
    return true;
  }
  if (isChord(chord, { key: "R", meta: true }) || isChord(chord, { key: "R", ctrl: true })) {
    fillRight(workbook, sheet, sheetState, awareness);
    return true;
  }
  if (isChord(chord, { key: '"', ctrl: true, shift: true })) {
    copyValueFromAbove(workbook, sheet, sheetState, awareness);
    return true;
  }
  if (isChord(chord, { key: "'", ctrl: true })) {
    copyFormulaFromAbove(workbook, sheet, sheetState, awareness);
    return true;
  }
  if (isChord(chord, { key: "1", meta: true }) || isChord(chord, { key: "1", ctrl: true })) {
    awareness.setDialog({
      name: "formatCells",
      args: { sheetName: sheetState.sheetName }
    });
    sheetState.mode = "dialog";
    return true;
  }
  if (isChord(chord, { key: "B", meta: true })) {
    toggleFontStyle(workbook, sheet, sheetState, awareness, "bold");
    return true;
  }
  if (isChord(chord, { key: "I", meta: true })) {
    toggleFontStyle(workbook, sheet, sheetState, awareness, "italic");
    return true;
  }
  if (isChord(chord, { key: "U", meta: true })) {
    recordMissingAction(awareness, {
      chord: chordLabel,
      action: "toggleUnderline",
      detail: "Toggle underline formatting on selection."
    });
    return true;
  }
  if (isChord(chord, { key: ">", meta: true, shift: true })) {
    adjustFontSize(workbook, sheet, sheetState, awareness, 1);
    return true;
  }
  if (isChord(chord, { key: "<", meta: true, shift: true })) {
    adjustFontSize(workbook, sheet, sheetState, awareness, -1);
    return true;
  }
  if (isChord(chord, { key: "E", meta: true })) {
    setHorizontalAlignment(workbook, sheet, sheetState, awareness, "center");
    return true;
  }
  if (isChord(chord, { key: "L", meta: true })) {
    setHorizontalAlignment(workbook, sheet, sheetState, awareness, "left");
    return true;
  }
  if (isChord(chord, { key: "~", ctrl: true, shift: true })) {
    setNumberFormat(workbook, sheet, sheetState, awareness, "General");
    return true;
  }
  if (isChord(chord, { key: "$", ctrl: true, shift: true })) {
    setNumberFormat(workbook, sheet, sheetState, awareness, "$#,##0.00");
    return true;
  }
  if (isChord(chord, { key: "%", ctrl: true, shift: true })) {
    setNumberFormat(workbook, sheet, sheetState, awareness, "0%");
    return true;
  }
  if (isChord(chord, { key: "^", ctrl: true, shift: true })) {
    setNumberFormat(workbook, sheet, sheetState, awareness, "0.00E+00");
    return true;
  }
  if (isChord(chord, { key: "#", ctrl: true, shift: true })) {
    setNumberFormat(workbook, sheet, sheetState, awareness, "m/d/yy");
    return true;
  }
  if (isChord(chord, { key: "@", ctrl: true, shift: true })) {
    setNumberFormat(workbook, sheet, sheetState, awareness, "h:mm:ss");
    return true;
  }
  if (isChord(chord, { key: "!", ctrl: true, shift: true })) {
    setNumberFormat(workbook, sheet, sheetState, awareness, "#,##0.00");
    return true;
  }
  if (isChord(chord, { key: "0", meta: true, shift: true }) || isChord(chord, { key: "0", ctrl: true, shift: true })) {
    recordMissingAction(awareness, {
      chord: chordLabel,
      action: "unhideColumns",
      detail: "Unhide selected columns."
    });
    return true;
  }
  if (isChord(chord, { key: "0", meta: true }) || isChord(chord, { key: "0", ctrl: true })) {
    recordMissingAction(awareness, {
      chord: chordLabel,
      action: "hideColumns",
      detail: "Hide selected columns."
    });
    return true;
  }
  if (isChord(chord, { key: "9", meta: true, shift: true }) || isChord(chord, { key: "9", ctrl: true, shift: true })) {
    recordMissingAction(awareness, {
      chord: chordLabel,
      action: "unhideRows",
      detail: "Unhide selected rows."
    });
    return true;
  }
  if (isChord(chord, { key: "9", meta: true }) || isChord(chord, { key: "9", ctrl: true })) {
    recordMissingAction(awareness, {
      chord: chordLabel,
      action: "hideRows",
      detail: "Hide selected rows."
    });
    return true;
  }
  if (chord.key === "=" && !chord.meta && !chord.ctrl && !chord.alt) {
    enterEditModeWithText(sheetState, "=");
    return true;
  }
  if (isChord(chord, { key: "F4" })) {
    recordMissingAction(awareness, {
      chord: chordLabel,
      action: "toggleFormulaReference",
      detail: "Toggle reference style in formula edit mode."
    });
    return true;
  }
  if (isChord(chord, { key: "T", meta: true, shift: true })) {
    autoSumAdjacent(workbook, sheet, sheetState, awareness);
    return true;
  }
  if (isChord(chord, { key: "T", meta: true })) {
    createTableFromSelection(workbook, sheet, sheetState, awareness);
    return true;
  }
  if (isChord(chord, { key: ";", ctrl: true })) {
    insertDateTime(workbook, sheet, sheetState, awareness, "date");
    return true;
  }
  if (isChord(chord, { key: ";", meta: true })) {
    insertDateTime(workbook, sheet, sheetState, awareness, "time");
    return true;
  }
  if (isChord(chord, { key: "`", ctrl: true })) {
    awareness.showFormulas = !awareness.showFormulas;
    return true;
  }
  if (isChord(chord, { key: "F9", shift: true })) {
    workbook.recalculate();
    recordMissingAction(awareness, {
      chord: chordLabel,
      action: "recalculateSheet",
      detail: "Recalculate active sheet only."
    });
    return true;
  }
  if (isChord(chord, { key: "F9" })) {
    workbook.recalculate();
    return true;
  }
  if (isChord(chord, { key: "=", meta: true })) {
    workbook.recalculate();
    return true;
  }
  return false;
}
function resolveChord(event) {
  if (event.chord) {
    return parseChordString(event.chord);
  }
  const key = normalizeKey(event.key ?? "");
  return {
    key,
    meta: !!event.metaKey,
    ctrl: !!event.ctrlKey,
    alt: !!event.altKey,
    shift: !!event.shiftKey
  };
}
function normalizeKey(key) {
  if (key === " ")
    return " ";
  const trimmed = key.trim();
  if (!trimmed)
    return "";
  if (trimmed === "Return")
    return "Enter";
  if (trimmed === "Esc")
    return "Escape";
  if (trimmed === "ArrowUp" || trimmed === "ArrowDown")
    return trimmed;
  if (trimmed === "ArrowLeft" || trimmed === "ArrowRight")
    return trimmed;
  if (trimmed === "Up")
    return "ArrowUp";
  if (trimmed === "Down")
    return "ArrowDown";
  if (trimmed === "Left")
    return "ArrowLeft";
  if (trimmed === "Right")
    return "ArrowRight";
  if (trimmed === "PageUp" || trimmed === "Page Up")
    return "PageUp";
  if (trimmed === "PageDown" || trimmed === "Page Down")
    return "PageDown";
  if (trimmed === "Space")
    return " ";
  if (trimmed === " ")
    return " ";
  return trimmed.length === 1 ? trimmed.toUpperCase() : trimmed;
}
function parseChordString(chord) {
  let key = chord.trim();
  const meta3 = key.includes("⌘");
  const ctrl = key.includes("⌃");
  const alt = key.includes("⌥");
  const shift = key.includes("⇧");
  key = key.replace(/[⌘⌃⌥⇧]/g, "");
  key = key.replace(/\+/g, "").trim();
  if (key === "↑")
    key = "ArrowUp";
  if (key === "↓")
    key = "ArrowDown";
  if (key === "←")
    key = "ArrowLeft";
  if (key === "→")
    key = "ArrowRight";
  if (key === "Return")
    key = "Enter";
  if (key === "Page Down")
    key = "PageDown";
  if (key === "Page Up")
    key = "PageUp";
  return {
    key: normalizeKey(key),
    meta: meta3,
    ctrl,
    alt,
    shift
  };
}
function formatChord(chord) {
  const parts = [];
  if (chord.meta)
    parts.push("⌘");
  if (chord.ctrl)
    parts.push("⌃");
  if (chord.alt)
    parts.push("⌥");
  if (chord.shift)
    parts.push("⇧");
  const key = formatChordKey(chord.key);
  return `${parts.join("")}${key}`;
}
function formatChordKey(key) {
  switch (key) {
    case "ArrowUp":
      return "↑";
    case "ArrowDown":
      return "↓";
    case "ArrowLeft":
      return "←";
    case "ArrowRight":
      return "→";
    case "PageUp":
      return "Page Up";
    case "PageDown":
      return "Page Down";
    default:
      return key;
  }
}
function isChord(chord, expected) {
  if (expected.key === "CmdOrCtrl+Z") {
    return chord.key === "Z" && (chord.meta && !chord.ctrl || chord.ctrl && !chord.meta) && !chord.shift;
  }
  if (expected.key === "CmdOrCtrl+Y") {
    return chord.key === "Y" && (chord.meta && !chord.ctrl || chord.ctrl && !chord.meta) && !chord.shift;
  }
  if (expected.key === "CmdOrCtrl+Shift+Z") {
    return chord.key === "Z" && (chord.meta && !chord.ctrl || chord.ctrl && !chord.meta) && chord.shift;
  }
  if (chord.key !== normalizeKey(expected.key))
    return false;
  if (expected.meta !== undefined && chord.meta !== expected.meta)
    return false;
  if (expected.ctrl !== undefined && chord.ctrl !== expected.ctrl)
    return false;
  if (expected.alt !== undefined && chord.alt !== expected.alt)
    return false;
  if (expected.shift !== undefined && chord.shift !== expected.shift)
    return false;
  return true;
}
function isArrowKey(key) {
  return key === "ArrowUp" || key === "ArrowDown" || key === "ArrowLeft" || key === "ArrowRight";
}
function arrowToDelta(key) {
  switch (key) {
    case "ArrowUp":
      return { row: -1, col: 0 };
    case "ArrowDown":
      return { row: 1, col: 0 };
    case "ArrowLeft":
      return { row: 0, col: -1 };
    case "ArrowRight":
      return { row: 0, col: 1 };
    default:
      return { row: 0, col: 0 };
  }
}
function resolveActiveSheetName(workbook, awareness) {
  if (awareness.activeSheetName) {
    return awareness.activeSheetName;
  }
  const name2 = workbook.worksheets.getSheetNameByIndex(0);
  awareness.setActiveSheetName(name2 ?? null);
  return name2 ?? null;
}
function updateSelection(sheetState, next2, extend4) {
  const anchor = extend4 ? sheetState.anchorCell : next2;
  const rect = normalizeRect({
    r1: anchor.row,
    c1: anchor.col,
    r2: next2.row,
    c2: next2.col
  });
  sheetState.activeCell = { ...next2 };
  sheetState.anchorCell = { ...anchor };
  sheetState.selection = rect;
  sheetState.selectionRanges = [rect];
  sheetState.activeRangeIndex = 0;
  sheetState.selectionVisibility = "all";
}
function normalizeRect(rect) {
  return {
    r1: Math.min(rect.r1, rect.r2),
    c1: Math.min(rect.c1, rect.c2),
    r2: Math.max(rect.r1, rect.r2),
    c2: Math.max(rect.c1, rect.c2)
  };
}
function clampIndex2(value2, maxCount) {
  return Math.max(0, Math.min(value2, maxCount - 1));
}
function getActiveSelection(sheetState, sheet) {
  if (sheet && sheetState.selectAllStage === 2) {
    return getWholeSheetOperableRect(sheet, sheetState.activeCell);
  }
  const range2 = sheetState.selectionRanges[sheetState.activeRangeIndex];
  return range2 ?? sheetState.selection;
}
function isSingleCell(selection) {
  return selection.r1 === selection.r2 && selection.c1 === selection.c2;
}
function buildRangeRefFromRect(rect) {
  return buildRangeRef({
    startRow: rect.r1,
    startCol: rect.c1,
    endRow: rect.r2,
    endCol: rect.c2
  });
}
function getCurrentRegionRect(sheet, activeCell) {
  const region = sheet.getCell(activeCell.row, activeCell.col).getCurrentRegion();
  return {
    r1: region.rowIndex,
    c1: region.columnIndex,
    r2: region.rowIndex + region.rowCount - 1,
    c2: region.columnIndex + region.columnCount - 1
  };
}
function moveWithinSelection(sheetState, move, maxVisibleRows, maxVisibleCols) {
  const selection = getActiveSelection(sheetState);
  const rows = selection.r2 - selection.r1 + 1;
  const cols = selection.c2 - selection.c1 + 1;
  if (rows === 1 && cols === 1) {
    const next2 = {
      row: clampIndex2(sheetState.activeCell.row + move.row, maxVisibleRows),
      col: clampIndex2(sheetState.activeCell.col + move.col, maxVisibleCols)
    };
    updateSelection(sheetState, next2, false);
    return;
  }
  const order2 = [];
  if (move.row !== 0) {
    for (let c = selection.c1;c <= selection.c2; c += 1) {
      for (let r = selection.r1;r <= selection.r2; r += 1) {
        order2.push({ row: r, col: c });
      }
    }
  } else {
    for (let r = selection.r1;r <= selection.r2; r += 1) {
      for (let c = selection.c1;c <= selection.c2; c += 1) {
        order2.push({ row: r, col: c });
      }
    }
  }
  const currentIndex = order2.findIndex((cell) => cell.row === sheetState.activeCell.row && cell.col === sheetState.activeCell.col);
  const delta = move.row !== 0 || move.col !== 0 ? Math.sign(move.row + move.col) : 1;
  const nextIndex = currentIndex >= 0 ? (currentIndex + delta + order2.length) % order2.length : 0;
  updateSelection(sheetState, order2[nextIndex] ?? order2[0], false);
}
function resetSelectAllStage(sheetState, reset) {
  if (reset) {
    sheetState.selectAllStage = 0;
    return;
  }
  if (sheetState.selectAllStage !== 0) {
    sheetState.selectAllStage = 0;
  }
}
function switchWorksheet(workbook, awareness, offset) {
  const sheetCount = workbook.worksheets.getSheetCount();
  if (sheetCount === 0) {
    return;
  }
  const activeName = awareness.activeSheetName ?? workbook.worksheets.getSheetNameByIndex(0);
  const activeIndex = activeName ? workbook.worksheets.getSheetIndex(activeName) ?? 0 : 0;
  const nextIndex = (activeIndex + offset + sheetCount) % sheetCount;
  const nextName = workbook.worksheets.getSheetNameByIndex(nextIndex);
  if (!nextName) {
    return;
  }
  workbook.worksheets.setActiveWorksheet(nextName);
  awareness.setActiveSheetName(nextName);
  awareness.getSheetState(nextName);
}
function enterEditMode(sheet, sheetState) {
  const address = makeCellAddress(sheetState.activeCell.row, sheetState.activeCell.col);
  const range2 = sheet.getRange(address);
  const formula = range2.formulas[0]?.[0] ?? "";
  const value2 = range2.values[0]?.[0];
  const text8 = formula || (value2 == null ? "" : String(value2));
  sheetState.mode = "editCell";
  sheetState.editBuffer = { text: text8, caret: text8.length };
}
function enterEditModeWithText(sheetState, text8) {
  sheetState.mode = "editCell";
  sheetState.editBuffer = { text: text8, caret: text8.length };
}
function exitEditMode(sheetState) {
  sheetState.mode = "grid";
  sheetState.editBuffer = null;
}
function appendToEditBuffer(sheetState, value2) {
  if (!sheetState.editBuffer) {
    sheetState.editBuffer = { text: value2, caret: value2.length };
    return;
  }
  const buffer = sheetState.editBuffer;
  buffer.text = buffer.text.slice(0, buffer.caret) + value2 + buffer.text.slice(buffer.caret);
  buffer.caret += value2.length;
}
function commitEdit(args2) {
  const { workbook, sheet, sheetState, awareness, move, maxVisibleRows = MAX_ROW_COUNT2, maxVisibleCols = MAX_COL_COUNT2 } = args2;
  const buffer = sheetState.editBuffer;
  if (!buffer) {
    moveWithinSelection(sheetState, move, maxVisibleRows, maxVisibleCols);
    return;
  }
  const text8 = buffer.text;
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [getActiveSelection(sheetState)],
    label: "Commit edit",
    apply: () => {
      const address = makeCellAddress(sheetState.activeCell.row, sheetState.activeCell.col);
      if (text8.startsWith("=")) {
        sheet.getRange(address).formulas = [[text8]];
        workbook.recalculate();
      } else {
        sheet.getRange(address).values = [[text8]];
      }
    }
  });
  exitEditMode(sheetState);
  moveWithinSelection(sheetState, move, maxVisibleRows, maxVisibleCols);
}
function isEditCommitNavigationChord(chord) {
  return isArrowKey(chord.key) || isChord(chord, { key: "Enter" }) || isChord(chord, { key: "Return" }) || isChord(chord, { key: "Tab" });
}
function commitEditAndContinue(args2) {
  const { workbook, sheet, sheetState, awareness, chord, maxVisibleRows, maxVisibleCols } = args2;
  if (isChord(chord, { key: "Enter", shift: true })) {
    commitEdit({
      workbook,
      sheet,
      sheetState,
      awareness,
      move: { row: -1, col: 0 },
      maxVisibleRows,
      maxVisibleCols
    });
    return;
  }
  if (isChord(chord, { key: "Tab", shift: true })) {
    commitEdit({
      workbook,
      sheet,
      sheetState,
      awareness,
      move: { row: 0, col: -1 },
      maxVisibleRows,
      maxVisibleCols
    });
    return;
  }
  if (isChord(chord, { key: "Enter" }) || isChord(chord, { key: "Return" })) {
    commitEdit({
      workbook,
      sheet,
      sheetState,
      awareness,
      move: { row: 1, col: 0 },
      maxVisibleRows,
      maxVisibleCols
    });
    return;
  }
  if (isChord(chord, { key: "Tab" })) {
    commitEdit({
      workbook,
      sheet,
      sheetState,
      awareness,
      move: { row: 0, col: 1 },
      maxVisibleRows,
      maxVisibleCols
    });
    return;
  }
  const continueWithSelection = () => {
    if (isArrowKey(chord.key)) {
      const move = arrowToDelta(chord.key);
      const extend4 = chord.shift || sheetState.extendSelection;
      const jump = chord.meta || chord.ctrl;
      if (jump) {
        const dest = jumpToDataEdge(sheet, sheetState.activeCell, move, maxVisibleRows, maxVisibleCols);
        updateSelection(sheetState, dest, extend4);
        return;
      }
      const next2 = {
        row: clampIndex2(sheetState.activeCell.row + move.row, maxVisibleRows),
        col: clampIndex2(sheetState.activeCell.col + move.col, maxVisibleCols)
      };
      updateSelection(sheetState, next2, extend4);
      return;
    }
  };
  const buffer = sheetState.editBuffer;
  if (!buffer) {
    continueWithSelection();
    return;
  }
  const text8 = buffer.text;
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [getActiveSelection(sheetState, sheet)],
    label: "Commit edit",
    apply: () => {
      const address = makeCellAddress(sheetState.activeCell.row, sheetState.activeCell.col);
      if (text8.startsWith("=")) {
        sheet.getRange(address).formulas = [[text8]];
        workbook.recalculate();
      } else {
        sheet.getRange(address).values = [[text8]];
      }
    }
  });
  exitEditMode(sheetState);
  continueWithSelection();
}
function fillSelectionFromEdit(args2) {
  const { workbook, sheet, sheetState, awareness } = args2;
  const buffer = sheetState.editBuffer;
  if (!buffer) {
    return;
  }
  const text8 = buffer.text;
  const selection = getActiveSelection(sheetState);
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [selection],
    label: "Fill selection",
    apply: () => {
      for (let r = selection.r1;r <= selection.r2; r += 1) {
        for (let c = selection.c1;c <= selection.c2; c += 1) {
          const address = makeCellAddress(r, c);
          if (text8.startsWith("=")) {
            sheet.getRange(address).formulas = [[text8]];
          } else {
            sheet.getRange(address).values = [[text8]];
          }
        }
      }
      if (text8.startsWith("=")) {
        workbook.recalculate();
      }
    }
  });
  exitEditMode(sheetState);
}
function fillSelectionFromActiveCell(args2) {
  const { workbook, sheet, sheetState, awareness } = args2;
  const selection = getActiveSelection(sheetState);
  const sourceAddress = makeCellAddress(sheetState.activeCell.row, sheetState.activeCell.col);
  const sourceFormula = sheet.getRange(sourceAddress).formulas[0]?.[0] ?? "";
  const sourceValue = sheet.getRange(sourceAddress).values[0]?.[0];
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [selection],
    label: "Fill selection from active cell",
    apply: () => {
      for (let r = selection.r1;r <= selection.r2; r += 1) {
        for (let c = selection.c1;c <= selection.c2; c += 1) {
          const address = makeCellAddress(r, c);
          if (sourceFormula) {
            sheet.getRange(address).formulas = [[sourceFormula]];
          } else {
            sheet.getRange(address).values = [[sourceValue ?? null]];
          }
        }
      }
      if (sourceFormula) {
        workbook.recalculate();
      }
    }
  });
}
function toggleFormulaReferenceStyle(sheetState) {
  const buffer = sheetState.editBuffer;
  if (!buffer || !buffer.text.startsWith("=")) {
    return;
  }
  const updated = toggleLastReference(buffer.text);
  buffer.text = updated;
  buffer.caret = updated.length;
}
function toggleLastReference(formula) {
  const refRegex = /(\$?)([A-Z]{1,3})(\$?)(\d{1,7})/g;
  const matches = Array.from(formula.matchAll(refRegex));
  const last2 = matches[matches.length - 1];
  if (!last2 || last2.index == null) {
    return formula;
  }
  const [full, colAbs, colLabel, rowAbs, rowText] = last2;
  if (full == null || colAbs == null || colLabel == null || rowAbs == null || rowText == null) {
    return formula;
  }
  const row2 = Number(rowText);
  const col = columnLabelToNumber(colLabel);
  if (!row2 || !col) {
    return formula;
  }
  const next2 = cycleReferenceStyle({ colAbs, rowAbs, colLabel, row: row2 });
  const replacement = `${next2.colAbs}${next2.colLabel}${next2.rowAbs}${next2.row}`;
  return formula.slice(0, last2.index) + replacement + formula.slice(last2.index + full.length);
}
function cycleReferenceStyle(args2) {
  const { colAbs, rowAbs, colLabel, row: row2 } = args2;
  const hasColAbs = colAbs === "$";
  const hasRowAbs = rowAbs === "$";
  if (!hasColAbs && !hasRowAbs) {
    return { colAbs: "$", rowAbs: "$", colLabel, row: row2 };
  }
  if (hasColAbs && hasRowAbs) {
    return { colAbs: "", rowAbs: "$", colLabel, row: row2 };
  }
  if (!hasColAbs && hasRowAbs) {
    return { colAbs: "$", rowAbs: "", colLabel, row: row2 };
  }
  return { colAbs: "", rowAbs: "", colLabel, row: row2 };
}
function copySelection(sheet, sheetState, awareness, kind) {
  const selection = getActiveSelection(sheetState);
  const address = buildRangeRefFromRect(selection);
  const range2 = sheet.getRange(address);
  const values2 = range2.values;
  const formulas2 = range2.formulas;
  const sheetIndex = sheet.workbook.worksheets.getSheetIndex(sheetState.sheetName);
  const clipboard = {
    kind,
    source: { sheetName: sheetState.sheetName, range: selection },
    payload: {
      values: values2,
      formulas: formulas2,
      plainText: buildPlainText(values2),
      html: sheetIndex == null ? undefined : sheet.workbook.toHTML(sheetIndex, address)
    }
  };
  awareness.clipboard = clipboard;
  sheetState.copyOutline = selection;
}
function pasteClipboard(args2) {
  const { workbook, sheet, sheetState, awareness, chordLabel } = args2;
  const clipboard = awareness.clipboard;
  if (!clipboard) {
    return;
  }
  if (sheetState.mode === "editCell") {
    appendToEditBuffer(sheetState, clipboard.payload.plainText ?? "");
    return;
  }
  const selection = getActiveSelection(sheetState);
  const source = clipboard.source.range;
  const sourceRows = source.r2 - source.r1 + 1;
  const sourceCols = source.c2 - source.c1 + 1;
  const selectionRows = selection.r2 - selection.r1 + 1;
  const selectionCols = selection.c2 - selection.c1 + 1;
  const useSelectionSize = selectionRows > 1 || selectionCols > 1 ? selectionRows !== sourceRows || selectionCols !== sourceCols : false;
  let targetRect = useSelectionSize ? selection : {
    r1: sheetState.activeCell.row,
    c1: sheetState.activeCell.col,
    r2: sheetState.activeCell.row + sourceRows - 1,
    c2: sheetState.activeCell.col + sourceCols - 1
  };
  const rects = [targetRect];
  if (clipboard.kind === "cut" && clipboard.source.sheetName === sheetState.sheetName) {
    rects.push(source);
  }
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects,
    label: "Paste",
    apply: () => {
      const shouldOverlayHtml = typeof clipboard.payload.html === "string" && clipboard.payload.html.length > 0 && clipboard.source.sheetName.length > 0;
      const shouldImportHtml = clipboard.kind === "copy" && typeof clipboard.payload.html === "string" && clipboard.payload.html.length > 0 && clipboard.source.sheetName.length === 0;
      if (!shouldImportHtml) {
        for (let r = 0;r <= targetRect.r2 - targetRect.r1; r += 1) {
          for (let c = 0;c <= targetRect.c2 - targetRect.c1; c += 1) {
            const srcRow = source.r1 + r % sourceRows;
            const srcCol = source.c1 + c % sourceCols;
            const srcValue = clipboard.payload.values[srcRow - source.r1]?.[srcCol - source.c1];
            const srcFormula = clipboard.payload.formulas[srcRow - source.r1]?.[srcCol - source.c1];
            const destRow = targetRect.r1 + r;
            const destCol = targetRect.c1 + c;
            const address = makeCellAddress(destRow, destCol);
            if (srcFormula) {
              const shifted = shiftFormulaRefs2(srcFormula, destRow - srcRow, destCol - srcCol);
              sheet.getRange(address).formulas = [[shifted]];
            } else {
              sheet.getRange(address).values = [[srcValue ?? null]];
            }
          }
        }
        workbook.recalculate();
      }
      if (shouldOverlayHtml || shouldImportHtml) {
        const sheetIndex = workbook.worksheets.getSheetIndex(sheetState.sheetName);
        if (sheetIndex != null) {
          const imported = workbook.fromHTML(sheetIndex, clipboard.payload.html ?? "", buildRangeRefFromRect(targetRect), {
            applyValues: shouldImportHtml
          });
          targetRect = imported.selectionRect;
        }
      }
      if (clipboard.kind === "cut") {
        if (clipboard.source.sheetName === sheetState.sheetName) {
          const sourceAddress = buildRangeRefFromRect(source);
          sheet.getRange(sourceAddress).values = null;
        }
        awareness.clipboard = null;
        sheetState.copyOutline = null;
      }
      if (!shouldOverlayHtml && !shouldImportHtml) {
        recordMissingAction(awareness, {
          chord: chordLabel,
          action: "pasteFormats",
          detail: "Paste should also apply per-cell formats from clipboard."
        });
      }
    }
  });
  updateSelection(sheetState, { row: targetRect.r1, col: targetRect.c1 }, false);
}
function buildPlainText(values2) {
  return values2.map((row2) => row2.map((cell) => cell == null ? "" : String(cell)).join("\t")).join(`
`);
}
function recordRangeMutation(args2) {
  const { workbook, awareness, label, apply } = args2;
  workbook.record(apply);
  awareness.pushUndoEntry({
    label,
    undo: () => {
      workbook.undo();
      workbook.recalculate();
    },
    redo: () => {
      workbook.redo();
      workbook.recalculate();
    }
  });
}
function undoLastMutation(awareness) {
  const entry = awareness.popUndoEntry();
  if (!entry) {
    return;
  }
  entry.undo();
  awareness.pushRedoEntry(entry);
}
function redoLastMutation(awareness) {
  const entry = awareness.popRedoEntry();
  if (!entry) {
    return;
  }
  entry.redo();
  awareness.pushUndoEntry(entry);
}
function jumpToDataEdge(sheet, start, move, maxVisibleRows, maxVisibleCols) {
  const bounds = {
    minRow: 0,
    minCol: 0,
    maxRow: clampIndex2(maxVisibleRows - 1, MAX_ROW_COUNT2),
    maxCol: clampIndex2(maxVisibleCols - 1, MAX_COL_COUNT2)
  };
  const first = {
    row: start.row + move.row,
    col: start.col + move.col
  };
  if (!isWithinBounds(first, bounds)) {
    return start;
  }
  const firstHasData = cellHasData(sheet, first.row, first.col);
  if (firstHasData) {
    let current2 = { ...first };
    while (true) {
      const next2 = { row: current2.row + move.row, col: current2.col + move.col };
      if (!isWithinBounds(next2, bounds) || !cellHasData(sheet, next2.row, next2.col)) {
        return current2;
      }
      current2 = next2;
    }
  }
  let current = { ...first };
  while (isWithinBounds(current, bounds) && !cellHasData(sheet, current.row, current.col)) {
    const nextBlank = { ...current };
    current = { row: current.row + move.row, col: current.col + move.col };
    if (!isWithinBounds(current, bounds)) {
      return nextBlank;
    }
  }
  return current;
}
function cellHasData(sheet, row2, col) {
  const address = makeCellAddress(row2, col);
  const range2 = sheet.getRange(address);
  const formula = range2.formulas[0]?.[0] ?? "";
  if (formula) {
    return true;
  }
  const value2 = range2.values[0]?.[0];
  return value2 !== null && value2 !== undefined && value2 !== "";
}
function getUsedBounds(sheet) {
  let minRow = Number.POSITIVE_INFINITY;
  let minCol = Number.POSITIVE_INFINITY;
  let maxRow = -1;
  let maxCol = -1;
  for (const cell of sheet.cells) {
    const addr = cell.address;
    const row2 = rowIndex(addr);
    const col = columnIndex(addr);
    minRow = Math.min(minRow, row2);
    minCol = Math.min(minCol, col);
    maxRow = Math.max(maxRow, row2);
    maxCol = Math.max(maxCol, col);
  }
  if (maxRow < 0 || maxCol < 0) {
    return { minRow: 0, minCol: 0, maxRow: 0, maxCol: 0, hasData: false };
  }
  return { minRow, minCol, maxRow, maxCol, hasData: true };
}
function isWithinBounds(pos, bounds) {
  return pos.row >= bounds.minRow && pos.row <= bounds.maxRow && pos.col >= bounds.minCol && pos.col <= bounds.maxCol;
}
function selectWholeColumns(sheet, sheetState) {
  const active = sheetState.activeCell;
  const anchor = sheetState.anchorCell;
  const startCol = Math.min(anchor.col, active.col);
  const endCol = Math.max(anchor.col, active.col);
  const used = getUsedBounds(sheet);
  const maxRow = used.hasData ? used.maxRow : active.row;
  const rect = normalizeRect({
    r1: 0,
    c1: startCol,
    r2: maxRow,
    c2: endCol
  });
  sheetState.selection = rect;
  sheetState.selectionRanges = [rect];
  sheetState.activeRangeIndex = 0;
  sheetState.anchorCell = { ...active };
  sheetState.activeCell = { row: active.row, col: startCol };
}
function selectWholeRows(sheet, sheetState) {
  const active = sheetState.activeCell;
  const anchor = sheetState.anchorCell;
  const startRow = Math.min(anchor.row, active.row);
  const endRow = Math.max(anchor.row, active.row);
  const used = getUsedBounds(sheet);
  const maxCol = used.hasData ? used.maxCol : active.col;
  const rect = normalizeRect({
    r1: startRow,
    c1: 0,
    r2: endRow,
    c2: maxCol
  });
  sheetState.selection = rect;
  sheetState.selectionRanges = [rect];
  sheetState.activeRangeIndex = 0;
  sheetState.anchorCell = { ...active };
  sheetState.activeCell = { row: startRow, col: active.col };
}
function toggleSelectAll(sheet, sheetState) {
  const selection = getActiveSelection(sheetState);
  const localRegion = inferLocalTableRegion(sheet, selection);
  const shouldExpandToWholeSheet = sheetState.selectAllStage === 1 || rectEquals(selection, localRegion);
  if (shouldExpandToWholeSheet) {
    const rect = getWholeSheetOperableRect(sheet, sheetState.activeCell);
    sheetState.selection = rect;
    sheetState.selectionRanges = [rect];
    sheetState.activeRangeIndex = 0;
    sheetState.selectAllStage = 2;
    return;
  }
  sheetState.selection = localRegion;
  sheetState.selectionRanges = [localRegion];
  sheetState.activeRangeIndex = 0;
  sheetState.selectAllStage = 1;
}
function inferLocalTableRegion(sheet, seed) {
  const seedRect = normalizeRect(seed);
  const used = getUsedBounds(sheet);
  if (!used.hasData) {
    return seedRect;
  }
  let rect = seedRect;
  let changed = true;
  while (changed) {
    changed = false;
    if (rect.r1 > used.minRow && rowHasContentInWindow(sheet, rect.r1 - 1, rect.c1, rect.c2)) {
      rect = { ...rect, r1: rect.r1 - 1 };
      changed = true;
    }
    if (rect.r2 < used.maxRow && rowHasContentInWindow(sheet, rect.r2 + 1, rect.c1, rect.c2)) {
      rect = { ...rect, r2: rect.r2 + 1 };
      changed = true;
    }
    if (rect.c1 > used.minCol && columnHasContentInWindow(sheet, rect.c1 - 1, rect.r1, rect.r2)) {
      rect = { ...rect, c1: rect.c1 - 1 };
      changed = true;
    }
    if (rect.c2 < used.maxCol && columnHasContentInWindow(sheet, rect.c2 + 1, rect.r1, rect.r2)) {
      rect = { ...rect, c2: rect.c2 + 1 };
      changed = true;
    }
  }
  return normalizeRect(rect);
}
function getWholeSheetOperableRect(sheet, activeCell) {
  const used = getUsedBounds(sheet);
  if (!used.hasData) {
    return {
      r1: activeCell.row,
      c1: activeCell.col,
      r2: activeCell.row,
      c2: activeCell.col
    };
  }
  return normalizeRect({
    r1: 0,
    c1: 0,
    r2: used.maxRow,
    c2: used.maxCol
  });
}
function addSelectionRange(sheetState) {
  const selection = getActiveSelection(sheetState);
  sheetState.selectionRanges = [...sheetState.selectionRanges, selection];
  sheetState.activeRangeIndex = sheetState.selectionRanges.length - 1;
}
function buildKeyboardEventResult(args2) {
  const { handled, workbookMutated, awareness } = args2;
  const activeSheetName = awareness.activeSheetName;
  const activeSheetState = activeSheetName ? awareness.getSheetState(activeSheetName) : null;
  return {
    handled,
    workbookMutated,
    activeSheetName,
    showFormulas: awareness.showFormulas,
    sheetState: activeSheetState ? {
      sheetName: activeSheetState.sheetName,
      mode: activeSheetState.mode,
      activeCell: { ...activeSheetState.activeCell },
      anchorCell: { ...activeSheetState.anchorCell },
      selection: { ...activeSheetState.selection },
      selectionRanges: activeSheetState.selectionRanges.map((range2) => ({
        ...range2
      })),
      activeRangeIndex: activeSheetState.activeRangeIndex,
      selectAllStage: activeSheetState.selectAllStage
    } : null
  };
}
function chordCouldMutateWorkbook(chord, mode) {
  if (isChord(chord, { key: "CmdOrCtrl+Z" }) || isChord(chord, { key: "CmdOrCtrl+Y" }) || isChord(chord, { key: "CmdOrCtrl+Shift+Z" })) {
    return true;
  }
  if (mode === "editCell") {
    return isChord(chord, { key: "ArrowUp" }) || isChord(chord, { key: "ArrowDown" }) || isChord(chord, { key: "ArrowLeft" }) || isChord(chord, { key: "ArrowRight" }) || isChord(chord, { key: "ArrowUp", shift: true }) || isChord(chord, { key: "ArrowDown", shift: true }) || isChord(chord, { key: "ArrowLeft", shift: true }) || isChord(chord, { key: "ArrowRight", shift: true }) || isChord(chord, { key: "ArrowUp", meta: true }) || isChord(chord, { key: "ArrowDown", meta: true }) || isChord(chord, { key: "ArrowLeft", meta: true }) || isChord(chord, { key: "ArrowRight", meta: true }) || isChord(chord, { key: "ArrowUp", ctrl: true }) || isChord(chord, { key: "ArrowDown", ctrl: true }) || isChord(chord, { key: "ArrowLeft", ctrl: true }) || isChord(chord, { key: "ArrowRight", ctrl: true }) || isChord(chord, { key: "ArrowUp", meta: true, shift: true }) || isChord(chord, { key: "ArrowDown", meta: true, shift: true }) || isChord(chord, { key: "ArrowLeft", meta: true, shift: true }) || isChord(chord, { key: "ArrowRight", meta: true, shift: true }) || isChord(chord, { key: "ArrowUp", ctrl: true, shift: true }) || isChord(chord, { key: "ArrowDown", ctrl: true, shift: true }) || isChord(chord, { key: "ArrowLeft", ctrl: true, shift: true }) || isChord(chord, { key: "ArrowRight", ctrl: true, shift: true }) || isChord(chord, { key: "Enter", meta: true }) || isChord(chord, { key: "Enter", shift: true }) || isChord(chord, { key: "Tab", shift: true }) || isChord(chord, { key: "Enter" }) || isChord(chord, { key: "Return" }) || isChord(chord, { key: "Tab" });
  }
  return isChord(chord, { key: "0", meta: true, alt: true }) || isChord(chord, { key: "-", meta: true, alt: true }) || isChord(chord, { key: "ArrowUp", meta: true, alt: true, shift: true }) || isChord(chord, { key: "ArrowDown", meta: true, alt: true, shift: true }) || isChord(chord, { key: "ArrowLeft", meta: true, alt: true, shift: true }) || isChord(chord, { key: "ArrowRight", meta: true, alt: true, shift: true }) || isChord(chord, { key: "Enter", meta: true }) || isChord(chord, { key: "Delete" }) || isChord(chord, { key: "Backspace" }) || isChord(chord, { key: "V", meta: true }) || isChord(chord, { key: "V", ctrl: true }) || isChord(chord, { key: "D", meta: true }) || isChord(chord, { key: "D", ctrl: true }) || isChord(chord, { key: "R", meta: true }) || isChord(chord, { key: "R", ctrl: true }) || isChord(chord, { key: '"', ctrl: true, shift: true }) || isChord(chord, { key: "'", ctrl: true }) || isChord(chord, { key: "B", meta: true }) || isChord(chord, { key: "I", meta: true }) || isChord(chord, { key: ">", meta: true, shift: true }) || isChord(chord, { key: "<", meta: true, shift: true }) || isChord(chord, { key: "E", meta: true }) || isChord(chord, { key: "L", meta: true }) || isChord(chord, { key: "~", ctrl: true, shift: true }) || isChord(chord, { key: "$", ctrl: true, shift: true }) || isChord(chord, { key: "%", ctrl: true, shift: true }) || isChord(chord, { key: "^", ctrl: true, shift: true }) || isChord(chord, { key: "#", ctrl: true, shift: true }) || isChord(chord, { key: "@", ctrl: true, shift: true }) || isChord(chord, { key: "!", ctrl: true, shift: true }) || isChord(chord, { key: "T", meta: true, shift: true }) || isChord(chord, { key: "T", meta: true }) || isChord(chord, { key: ";", ctrl: true }) || isChord(chord, { key: ";", meta: true }) || isChord(chord, { key: "F9", shift: true }) || isChord(chord, { key: "F9" }) || isChord(chord, { key: "=", meta: true });
}
function rowHasContentInWindow(sheet, row2, startCol, endCol) {
  for (let col = startCol;col <= endCol; col += 1) {
    if (cellHasData(sheet, row2, col)) {
      return true;
    }
  }
  return false;
}
function columnHasContentInWindow(sheet, col, startRow, endRow) {
  for (let row2 = startRow;row2 <= endRow; row2 += 1) {
    if (cellHasData(sheet, row2, col)) {
      return true;
    }
  }
  return false;
}
function rectEquals(left, right) {
  return left.r1 === right.r1 && left.c1 === right.c1 && left.r2 === right.r2 && left.c2 === right.c2;
}
function moveToSelectionCorner(sheetState) {
  const selection = getActiveSelection(sheetState);
  const corners = [
    { row: selection.r1, col: selection.c1 },
    { row: selection.r1, col: selection.c2 },
    { row: selection.r2, col: selection.c2 },
    { row: selection.r2, col: selection.c1 }
  ];
  const nextIndex = (sheetState.selectionCornerIndex + 1) % corners.length;
  sheetState.selectionCornerIndex = nextIndex;
  const next2 = corners[nextIndex] ?? corners[0];
  sheetState.activeCell = { ...next2 };
}
function fillDown(workbook, sheet, sheetState, awareness) {
  const selection = getActiveSelection(sheetState);
  if (selection.r1 === selection.r2) {
    return;
  }
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [selection],
    label: "Fill down",
    apply: () => {
      for (let c = selection.c1;c <= selection.c2; c += 1) {
        const srcAddress = makeCellAddress(selection.r1, c);
        const srcFormula = sheet.getRange(srcAddress).formulas[0]?.[0] ?? "";
        const srcValue = sheet.getRange(srcAddress).values[0]?.[0];
        for (let r = selection.r1 + 1;r <= selection.r2; r += 1) {
          const destAddress = makeCellAddress(r, c);
          if (srcFormula) {
            const shifted = shiftFormulaRefs2(srcFormula, r - selection.r1, 0);
            sheet.getRange(destAddress).formulas = [[shifted]];
          } else {
            sheet.getRange(destAddress).values = [[srcValue ?? null]];
          }
        }
      }
      workbook.recalculate();
    }
  });
}
function fillRight(workbook, sheet, sheetState, awareness) {
  const selection = getActiveSelection(sheetState);
  if (selection.c1 === selection.c2) {
    return;
  }
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [selection],
    label: "Fill right",
    apply: () => {
      for (let r = selection.r1;r <= selection.r2; r += 1) {
        const srcAddress = makeCellAddress(r, selection.c1);
        const srcFormula = sheet.getRange(srcAddress).formulas[0]?.[0] ?? "";
        const srcValue = sheet.getRange(srcAddress).values[0]?.[0];
        for (let c = selection.c1 + 1;c <= selection.c2; c += 1) {
          const destAddress = makeCellAddress(r, c);
          if (srcFormula) {
            const shifted = shiftFormulaRefs2(srcFormula, 0, c - selection.c1);
            sheet.getRange(destAddress).formulas = [[shifted]];
          } else {
            sheet.getRange(destAddress).values = [[srcValue ?? null]];
          }
        }
      }
      workbook.recalculate();
    }
  });
}
function copyValueFromAbove(workbook, sheet, sheetState, awareness) {
  const selection = getActiveSelection(sheetState);
  if (selection.r1 === 0) {
    return;
  }
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [selection],
    label: "Copy value from above",
    apply: () => {
      for (let r = selection.r1;r <= selection.r2; r += 1) {
        for (let c = selection.c1;c <= selection.c2; c += 1) {
          const aboveAddress = makeCellAddress(r - 1, c);
          const value2 = sheet.getRange(aboveAddress).values[0]?.[0] ?? null;
          const destAddress = makeCellAddress(r, c);
          sheet.getRange(destAddress).values = [[value2]];
        }
      }
    }
  });
}
function copyFormulaFromAbove(workbook, sheet, sheetState, awareness) {
  const selection = getActiveSelection(sheetState);
  if (selection.r1 === 0) {
    return;
  }
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [selection],
    label: "Copy formula from above",
    apply: () => {
      for (let r = selection.r1;r <= selection.r2; r += 1) {
        for (let c = selection.c1;c <= selection.c2; c += 1) {
          const aboveAddress = makeCellAddress(r - 1, c);
          const formula = sheet.getRange(aboveAddress).formulas[0]?.[0] ?? "";
          const destAddress = makeCellAddress(r, c);
          if (formula) {
            const shifted = shiftFormulaRefs2(formula, 1, 0);
            sheet.getRange(destAddress).formulas = [[shifted]];
          }
        }
      }
      workbook.recalculate();
    }
  });
}
function toggleFontStyle(workbook, sheet, sheetState, awareness, style2) {
  const selection = getActiveSelection(sheetState);
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [selection],
    label: `Toggle ${style2}`,
    apply: () => {
      const address = buildRangeRefFromRect(selection);
      const range2 = sheet.getRange(address);
      if (style2 === "bold") {
        const current = range2.format.font.bold;
        range2.format.font.bold = current === undefined ? true : !current;
      } else {
        const current = range2.format.font.italic;
        range2.format.font.italic = current === undefined ? true : !current;
      }
    }
  });
}
function adjustFontSize(workbook, sheet, sheetState, awareness, delta) {
  const selection = getActiveSelection(sheetState);
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [selection],
    label: "Adjust font size",
    apply: () => {
      const address = buildRangeRefFromRect(selection);
      const range2 = sheet.getRange(address);
      const current = range2.format.font.size ?? 11;
      range2.format.font.size = Math.max(1, current + delta);
    }
  });
}
function setHorizontalAlignment(workbook, sheet, sheetState, awareness, alignment) {
  const selection = getActiveSelection(sheetState);
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [selection],
    label: "Set alignment",
    apply: () => {
      const address = buildRangeRefFromRect(selection);
      const range2 = sheet.getRange(address);
      range2.format.horizontalAlignment = alignment === "left" ? "left" : "center";
    }
  });
}
function setNumberFormat(workbook, sheet, sheetState, awareness, format3) {
  const selection = getActiveSelection(sheetState);
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [selection],
    label: "Set number format",
    apply: () => {
      const address = buildRangeRefFromRect(selection);
      sheet.getRange(address).format.numberFormat = format3;
    }
  });
}
function setOutlineBorders(workbook, sheet, sheetState, awareness) {
  const selection = getActiveSelection(sheetState);
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [selection],
    label: "Set outline border",
    apply: () => {
      const address = buildRangeRefFromRect(selection);
      sheet.getRange(address).format.borders = {
        preset: "outside",
        style: "thin"
      };
    }
  });
}
function clearOutlineBorders(workbook, sheet, sheetState, awareness) {
  const selection = getActiveSelection(sheetState);
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [selection],
    label: "Clear borders",
    apply: () => {
      const address = buildRangeRefFromRect(selection);
      sheet.getRange(address).format.borders = {
        preset: "none"
      };
    }
  });
}
function setBorderEdge(workbook, sheet, sheetState, awareness, edge) {
  const selection = getActiveSelection(sheetState);
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [selection],
    label: "Set border edge",
    apply: () => {
      const address = buildRangeRefFromRect(selection);
      const borders = sheet.getRange(address).format.borders;
      if (edge === "top")
        borders.top = { style: "thin" };
      if (edge === "bottom")
        borders.bottom = { style: "thin" };
      if (edge === "left")
        borders.left = { style: "thin" };
      if (edge === "right")
        borders.right = { style: "thin" };
    }
  });
}
function createTableFromSelection(workbook, sheet, sheetState, awareness) {
  const selection = getActiveSelection(sheetState);
  const rect = isSingleCell(selection) ? getCurrentRegionRect(sheet, sheetState.activeCell) : selection;
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [rect],
    label: "Create table",
    apply: () => {
      const address = buildRangeRefFromRect(rect);
      sheet.tables.add(address, true);
    }
  });
}
function autoSumAdjacent(workbook, sheet, sheetState, awareness) {
  const active = sheetState.activeCell;
  const col = active.col;
  let startRow = active.row - 1;
  while (startRow >= 0 && isNumericCell2(sheet, startRow, col)) {
    startRow -= 1;
  }
  startRow += 1;
  if (startRow > active.row - 1) {
    return;
  }
  const address = buildRangeRef({
    startRow,
    startCol: col,
    endRow: active.row - 1,
    endCol: col
  });
  const formula = `=SUM(${address})`;
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [{ r1: active.row, c1: active.col, r2: active.row, c2: active.col }],
    label: "AutoSum",
    apply: () => {
      const destAddress = makeCellAddress(active.row, active.col);
      sheet.getRange(destAddress).formulas = [[formula]];
      workbook.recalculate();
    }
  });
}
function insertDateTime(workbook, sheet, sheetState, awareness, mode) {
  const selection = getActiveSelection(sheetState);
  const value2 = new Date;
  recordRangeMutation({
    workbook,
    awareness,
    sheetName: sheetState.sheetName,
    rects: [selection],
    label: `Insert ${mode}`,
    apply: () => {
      for (let r = selection.r1;r <= selection.r2; r += 1) {
        for (let c = selection.c1;c <= selection.c2; c += 1) {
          const address = makeCellAddress(r, c);
          sheet.getRange(address).values = [[value2]];
        }
      }
    }
  });
}
function isNumericCell2(sheet, row2, col) {
  const address = makeCellAddress(row2, col);
  const value2 = sheet.getRange(address).values[0]?.[0];
  return typeof value2 === "number" && Number.isFinite(value2);
}
function shiftFormulaRefs2(formula, rowDelta, colDelta) {
  if (!formula)
    return formula;
  const refRegex = /(\$?)([A-Z]{1,3})(\$?)(\d{1,7})/g;
  return formula.replace(refRegex, (match, colAbs, colLabel, rowAbs, rowText) => {
    const col = columnLabelToNumber(colLabel);
    const row2 = Number(rowText);
    if (!col || !row2) {
      return match;
    }
    let nextCol = col;
    let nextRow = row2;
    if (!colAbs) {
      nextCol = col + colDelta;
    }
    if (!rowAbs) {
      nextRow = row2 + rowDelta;
    }
    if (nextCol < 1 || nextRow < 1 || nextCol > MAX_COL_COUNT2 || nextRow > MAX_ROW_COUNT2) {
      return match;
    }
    const nextLabel = columnNumberToLabel(nextCol);
    return `${colAbs}${nextLabel}${rowAbs}${nextRow}`;
  });
}
function recordMissingAction(awareness, action) {
  awareness.recordMissingAction(action);
}

// node_modules/@oai/granola/dist/text-edit/text-layout-index.js
class TextLayoutIndex {
  snapshot;
  blocksById;
  hitOrder;
  constructor(snapshot) {
    this.snapshot = snapshot;
    this.blocksById = new Map;
    for (const block of snapshot.blocks) {
      this.blocksById.set(block.id, block);
    }
    this.hitOrder = [...snapshot.blocks].sort((a, b) => (b.zIndex ?? 0) - (a.zIndex ?? 0));
  }
  getBlock(id2) {
    return this.blocksById.get(id2);
  }
}

// node_modules/@oai/granola/dist/text-edit/text-geometry.js
function lineStartX(block, line2) {
  const containerWidth = block.unrotatedWidth ?? block.width;
  if (line2.align === "center") {
    return (containerWidth - line2.widthPx) / 2;
  }
  if (line2.align === "right") {
    return containerWidth - line2.widthPx;
  }
  return line2.offsetPx;
}
function lineTop(block, lineIndex) {
  let acc = 0;
  for (let i = 0;i < lineIndex; i++) {
    acc += block.lines[i]?.heightPx ?? 0;
  }
  return acc;
}
function caretRectFromCaret(layout2, caret) {
  const pos = findSegmentForCaret(layout2, caret);
  if (!pos)
    return null;
  const { line: line2, segment, lineIndex } = pos;
  let x2 = lineStartX(layout2, line2);
  for (const seg of line2.segments) {
    if (seg === segment)
      break;
    x2 += seg.widthPx;
  }
  const offset = caret.charIndex - segment.charStart;
  const clamped = Math.max(0, Math.min(segment.advance.length - 1, offset));
  const localX = segment.advance[clamped] ?? 0;
  return {
    x: x2 + localX,
    y: lineTop(layout2, lineIndex),
    height: line2.heightPx
  };
}
function findSegmentForCaret(layout2, caret) {
  for (let li = 0;li < layout2.lines.length; li++) {
    const ln2 = layout2.lines[li];
    if (!ln2)
      continue;
    for (let si = 0;si < ln2.segments.length; si++) {
      const seg = ln2.segments[si];
      if (!seg)
        continue;
      if (seg.paraIndex === caret.paraIndex && seg.runIndex === caret.runIndex && caret.charIndex >= seg.charStart && caret.charIndex <= seg.charEnd) {
        return { line: ln2, segment: seg, lineIndex: li, segmentIndex: si };
      }
    }
  }
  return null;
}
function clampCaretToRun(caret, block) {
  const text8 = block.getRunText?.(caret.paraIndex, caret.runIndex);
  if (!text8)
    return caret;
  const graphemeCount = splitGraphemes(text8).length;
  const clampedIdx = Math.max(0, Math.min(graphemeCount, caret.charIndex));
  if (clampedIdx === caret.charIndex)
    return caret;
  return { ...caret, charIndex: clampedIdx };
}

// node_modules/@oai/granola/dist/text-edit/text-hit-test.js
function hitTestCaret(index2, point5, opts) {
  const candidates = opts?.restrictToBlockId != null ? [index2.getBlock(opts.restrictToBlockId)].filter(Boolean) : index2.hitOrder;
  for (const block of candidates) {
    if (!block)
      continue;
    if (!isPointInHitBox(block, point5))
      continue;
    const caret = hitBlock(block, point5);
    if (caret) {
      return clampCaretToRun(caret, block);
    }
  }
  return null;
}
function hitBlock(block, point5) {
  const rotationRad = block.rotationDeg * Math.PI / 180;
  const originX = block.layout.x;
  const originY = block.layout.y;
  let localX = point5.x - originX;
  let localY = point5.y - originY;
  if (rotationRad !== 0) {
    const cos3 = Math.cos(-rotationRad);
    const sin3 = Math.sin(-rotationRad);
    const rx = localX * cos3 - localY * sin3;
    const ry = localX * sin3 + localY * cos3;
    localX = rx;
    localY = ry;
  }
  const lineHeights = block.layout.lines.map((ln2) => ln2.heightPx);
  if (!lineHeights.length)
    return null;
  const blockHeight = lineHeights.reduce((acc, h) => acc + h, 0);
  let lineIndex = -1;
  if (localY < 0) {
    lineIndex = 0;
  } else if (localY > blockHeight) {
    lineIndex = block.layout.lines.length - 1;
  } else {
    for (let i = 0;i < block.layout.lines.length; i++) {
      const top = lineTop(block.layout, i);
      const bottom = top + lineHeights[i];
      if (localY >= top && localY <= bottom) {
        lineIndex = i;
        break;
      }
    }
  }
  if (lineIndex < 0)
    return null;
  const line2 = block.layout.lines[lineIndex];
  if (!line2)
    return null;
  const startX = lineStartX(block.layout, line2);
  let cursorX = startX;
  for (const seg of line2.segments) {
    const segEndX = cursorX + seg.widthPx;
    if (localX <= segEndX) {
      const local = localX - cursorX;
      const charIndex = measureCharIndexAtX(seg, local);
      return {
        blockId: block.id,
        paraIndex: seg.paraIndex,
        runIndex: seg.runIndex,
        charIndex
      };
    }
    cursorX += seg.widthPx;
  }
  const lastSeg = line2.segments.at(-1);
  if (lastSeg) {
    return {
      blockId: block.id,
      paraIndex: lastSeg.paraIndex,
      runIndex: lastSeg.runIndex,
      charIndex: lastSeg.charEnd
    };
  }
  return null;
}
function isPointInHitBox(block, pt) {
  const hb = block.hitBox;
  return pt.x >= hb.x && pt.x <= hb.x + hb.width && pt.y >= hb.y && pt.y <= hb.y + hb.height;
}
function measureCharIndexAtX(seg, xWithinSeg) {
  const adv = seg.advance;
  let lo = 0;
  let hi = adv.length - 1;
  while (lo < hi) {
    const mid = lo + hi >>> 1;
    if (adv[mid] && adv[mid] < xWithinSeg)
      lo = mid + 1;
    else
      hi = mid;
  }
  const i = lo;
  const left = adv[i - 1] ?? 0;
  const right = adv[i] ?? 0;
  const choosePrev = xWithinSeg < left + (right - left) / 2;
  const localIndex = choosePrev ? i - 1 : i;
  const clamped = Math.max(0, Math.min(seg.advance.length - 1, localIndex));
  return seg.charStart + clamped;
}

// node_modules/@oai/granola/dist/text-edit/text-selection-model.js
class TextSelectionModel {
  activeBlockId = null;
  caret = null;
  anchor = null;
  setActiveCaret(next2, opts) {
    this.activeBlockId = next2.blockId;
    this.caret = next2;
    if (!opts?.preserveAnchor) {
      this.anchor = next2;
    }
  }
  clear() {
    this.activeBlockId = null;
    this.caret = null;
    this.anchor = null;
  }
  collapseTo(caret) {
    this.activeBlockId = caret.blockId;
    this.caret = caret;
    this.anchor = caret;
  }
  hasSelection() {
    return !!this.anchor && !!this.caret && (this.anchor.blockId !== this.caret.blockId || this.anchor.paraIndex !== this.caret.paraIndex || this.anchor.runIndex !== this.caret.runIndex || this.anchor.charIndex !== this.caret.charIndex);
  }
  getRanges(index2) {
    if (!this.activeBlockId || !this.caret || !this.anchor)
      return [];
    const block = index2.getBlock(this.activeBlockId);
    if (!block)
      return [];
    return computeRanges(block.layout, this.anchor, this.caret, (para, run) => block.getRunText?.(para, run));
  }
}
function computeRanges(layout2, anchor, caret, getRunText) {
  const [start, end] = sortCarets(anchor, caret);
  const runOrder = [];
  const runLast = new Map;
  for (const ln2 of layout2.lines) {
    for (const seg of ln2.segments) {
      const key = runKey(seg.paraIndex, seg.runIndex);
      if (!runLast.has(key)) {
        runOrder.push({
          key,
          paraIndex: seg.paraIndex,
          runIndex: seg.runIndex,
          first: seg.charStart,
          last: seg.charEnd
        });
        runLast.set(key, seg.charEnd);
      } else {
        const prev = runLast.get(key) ?? 0;
        runLast.set(key, Math.max(prev, seg.charEnd));
      }
    }
  }
  for (const info of runOrder) {
    const last2 = runLast.get(info.key);
    if (last2 != null)
      info.last = last2;
  }
  const startIdx = runOrder.findIndex((r) => r.paraIndex === start.paraIndex && r.runIndex === start.runIndex);
  const endIdx = runOrder.findIndex((r) => r.paraIndex === end.paraIndex && r.runIndex === end.runIndex);
  if (startIdx === -1 || endIdx === -1)
    return [];
  const ranges = [];
  for (let i = startIdx;i <= endIdx; i++) {
    const info = runOrder[i];
    if (!info)
      continue;
    const runText = getRunText?.(info.paraIndex, info.runIndex);
    const graphemeLength = runText != null ? splitGraphemes(runText).length : info.last;
    const runStart = i === startIdx ? clampIndex3(start.charIndex, info.first, graphemeLength) : info.first;
    const runEnd = i === endIdx ? clampIndex3(end.charIndex, info.first, graphemeLength) : info.last;
    if (runEnd <= runStart)
      continue;
    ranges.push({
      paraIndex: info.paraIndex,
      runIndex: info.runIndex,
      start: runStart,
      end: runEnd
    });
  }
  return ranges;
}
function sortCarets(a, b) {
  if (compareCaret(a, b) <= 0)
    return [a, b];
  return [b, a];
}
function compareCaret(a, b) {
  if (a.paraIndex !== b.paraIndex)
    return a.paraIndex - b.paraIndex;
  if (a.runIndex !== b.runIndex)
    return a.runIndex - b.runIndex;
  return a.charIndex - b.charIndex;
}
function runKey(paraIndex, runIndex) {
  return `${paraIndex}:${runIndex}`;
}
function clampIndex3(value2, min4, max5) {
  return Math.max(min4, Math.min(max5, value2));
}

// node_modules/@oai/granola/dist/text-edit/text-overlay-painter.js
class TextOverlayPainter {
  draw(ctx, index2, selection, opts = {}) {
    if (!selection.activeBlockId)
      return;
    const block = index2.getBlock(selection.activeBlockId);
    if (!block)
      return;
    const rotationRad = block.rotationDeg * Math.PI / 180;
    const selectionRanges = selection.getRanges(index2);
    const caretRect = selection.caret && selection.activeBlockId === selection.caret.blockId ? caretRectFromCaret(block.layout, selection.caret) : null;
    const drawImpl = (offsetX, offsetY) => {
      drawSelection(ctx, block.layout, selectionRanges, offsetX, offsetY, opts.selectionFill ?? "rgba(51, 108, 255, 0.25)");
      if (caretRect) {
        drawCaret(ctx, caretRect, offsetX, offsetY, opts.caretColor ?? "#336CFF", opts.caretWidthPx ?? 1, opts.caretAlpha ?? 1);
      }
    };
    if (rotationRad !== 0) {
      ctx.save();
      ctx.translate(block.layout.x, block.layout.y);
      ctx.rotate(rotationRad);
      drawImpl(0, 0);
      ctx.restore();
    } else {
      drawImpl(block.layout.x, block.layout.y);
    }
  }
}
function drawSelection(ctx, layout2, ranges, offsetX, offsetY, fill3) {
  if (!ranges.length)
    return;
  ctx.save();
  ctx.fillStyle = fill3;
  for (let li = 0;li < layout2.lines.length; li++) {
    const ln2 = layout2.lines[li];
    if (!ln2)
      continue;
    const lineTopY = lineTop(layout2, li);
    const lineStart = lineStartX(layout2, ln2);
    for (const range2 of ranges) {
      let xMin = null;
      let xMax = null;
      for (const seg of ln2.segments) {
        if (seg.paraIndex !== range2.paraIndex || seg.runIndex !== range2.runIndex) {
          continue;
        }
        const segStart = seg.charStart;
        const segEnd = seg.charEnd;
        const rStart = Math.max(range2.start, segStart);
        const rEnd = Math.min(range2.end, segEnd);
        if (rEnd <= rStart)
          continue;
        let xAtSegStart = lineStart;
        for (const s2 of ln2.segments) {
          if (s2 === seg)
            break;
          xAtSegStart += s2.widthPx;
        }
        const localStart = Math.max(0, rStart - segStart);
        const localEnd = Math.max(localStart, Math.min(seg.advance.length - 1, rEnd - segStart));
        const xA = xAtSegStart + (seg.advance[localStart] ?? 0);
        const xB = xAtSegStart + (seg.advance[localEnd] ?? 0);
        const left = Math.min(xA, xB);
        const right = Math.max(xA, xB);
        xMin = xMin == null ? left : Math.min(xMin, left);
        xMax = xMax == null ? right : Math.max(xMax, right);
      }
      if (xMin != null && xMax != null && xMax - xMin > 0.25) {
        const w = Math.max(1, Math.ceil(xMax - xMin));
        ctx.fillRect(Math.floor(offsetX + xMin), Math.floor(offsetY + lineTopY), w, Math.ceil(ln2.heightPx));
      }
    }
  }
  ctx.restore();
}
function drawCaret(ctx, caret, offsetX, offsetY, color4, width, alpha) {
  if (alpha <= 0) {
    return;
  }
  ctx.save();
  ctx.strokeStyle = color4;
  ctx.globalAlpha = Math.max(0, Math.min(1, alpha));
  ctx.lineWidth = width;
  ctx.lineCap = "round";
  const x2 = Math.round(offsetX + caret.x) + 0.5 * (width % 2 === 0 ? 0 : 1);
  const y2 = Math.floor(offsetY + caret.y);
  const h = Math.ceil(caret.height);
  ctx.beginPath();
  ctx.moveTo(x2, y2);
  ctx.lineTo(x2, y2 + h);
  ctx.stroke();
  ctx.restore();
}

// node_modules/@oai/granola/dist/text-edit/text-edit-controller.js
class TextEditController {
  adapter;
  overlayPainter;
  selection;
  index = null;
  snapshot = null;
  bridge;
  isDragging = false;
  caretXGoal = null;
  constructor(opts) {
    this.adapter = opts.adapter;
    this.overlayPainter = opts.overlayPainter ?? new TextOverlayPainter;
    this.selection = new TextSelectionModel;
    this.bridge = opts.textareaBridge;
  }
  updateSnapshot(snapshot) {
    this.snapshot = snapshot;
    this.index = new TextLayoutIndex(snapshot);
    if (this.selection.activeBlockId) {
      const block = this.index.getBlock(this.selection.activeBlockId);
      if (!block) {
        this.selection.clear();
      } else if (this.selection.caret) {
        this.selection.caret = this.clampCaret(this.selection.caret);
        this.selection.anchor = this.selection.anchor ? this.clampCaret(this.selection.anchor) : this.selection.anchor;
      }
    }
  }
  attachTextarea(bridge) {
    this.bridge = bridge;
  }
  pointerDown(point5, opts) {
    if (!this.index)
      return false;
    const caret = hitTestCaret(this.index, point5);
    if (!caret)
      return false;
    const preserveAnchor = Boolean(opts?.shiftKey && this.selection.anchor && this.selection.anchor.blockId === caret.blockId);
    this.selection.setActiveCaret(caret, { preserveAnchor });
    this.isDragging = true;
    this.caretXGoal = null;
    this.focusTextarea();
    this.syncTextareaPosition();
    return true;
  }
  selectWordAtPoint(point5) {
    if (!this.index)
      return false;
    const caret = hitTestCaret(this.index, point5);
    if (!caret)
      return false;
    return this.selectWordAtCaret(caret);
  }
  selectParagraphAtPoint(point5) {
    if (!this.index)
      return false;
    const caret = hitTestCaret(this.index, point5);
    if (!caret)
      return false;
    return this.selectParagraphAtCaret(caret);
  }
  pointerMove(point5) {
    if (!this.index)
      return false;
    if (!this.isDragging || !this.selection.caret)
      return false;
    const caret = hitTestCaret(this.index, point5, {
      restrictToBlockId: this.selection.activeBlockId ?? undefined
    });
    if (!caret)
      return false;
    this.selection.caret = caret;
    this.syncTextareaPosition();
    return true;
  }
  pointerUp() {
    this.isDragging = false;
  }
  keyDown(evt) {
    if (!this.selection.caret || !this.index)
      return false;
    if ((evt.metaKey || evt.ctrlKey) && evt.key.toLowerCase() === "a") {
      this.selectAll();
      this.syncTextareaPosition();
      return true;
    }
    switch (evt.key) {
      case "ArrowLeft":
        this.moveHorizontal(-1, evt.shiftKey);
        this.syncTextareaPosition();
        return true;
      case "ArrowRight":
        this.moveHorizontal(1, evt.shiftKey);
        this.syncTextareaPosition();
        return true;
      case "ArrowUp":
        this.moveVertical(-1, evt.shiftKey);
        this.syncTextareaPosition();
        return true;
      case "ArrowDown":
        this.moveVertical(1, evt.shiftKey);
        this.syncTextareaPosition();
        return true;
      case "Home":
        this.moveToLineBoundary("start", evt.shiftKey);
        this.syncTextareaPosition();
        return true;
      case "End":
        this.moveToLineBoundary("end", evt.shiftKey);
        this.syncTextareaPosition();
        return true;
      case "Backspace":
        this.deleteBackward();
        this.syncTextareaPosition();
        return true;
      case "Delete":
        this.deleteForward();
        this.syncTextareaPosition();
        return true;
      case "Enter":
        this.splitParagraph();
        this.syncTextareaPosition();
        return true;
      default:
        return false;
    }
  }
  beforeInput(evt) {
    const type = evt.inputType;
    if (type === "deleteContentBackward") {
      this.deleteBackward();
      this.syncTextareaPosition();
      return true;
    }
    if (type === "deleteContentForward") {
      this.deleteForward();
      this.syncTextareaPosition();
      return true;
    }
    if (type === "insertLineBreak") {
      this.splitParagraph();
      this.syncTextareaPosition();
      return true;
    }
    if ((type === "insertText" || type === "insertReplacementText" || type === "insertFromPaste") && evt.data && evt.data.length > 0) {
      this.insertText(evt.data);
      this.syncTextareaPosition();
      return true;
    }
    return false;
  }
  input(evt) {
    if (evt.data && evt.data.length > 0) {
      this.insertText(evt.data);
      this.syncTextareaPosition();
      return true;
    }
    return false;
  }
  compositionStart() {}
  compositionEnd(evt) {
    if (evt.data) {
      this.insertText(evt.data);
    }
  }
  drawOverlay(ctx, opts) {
    if (!this.index)
      return;
    this.overlayPainter.draw(ctx, this.index, this.selection, {
      caretColor: opts?.caretColor
    });
  }
  isActive() {
    return !!this.selection.caret;
  }
  getSelectionModel() {
    return this.selection;
  }
  getSelectionSnapshot() {
    if (!this.index)
      return null;
    const blockId = this.selection.activeBlockId;
    if (!blockId)
      return null;
    const ranges = this.selection.getRanges(this.index);
    if (!ranges.length) {
      return null;
    }
    return {
      blockId,
      ranges: ranges.map((range2) => ({ ...range2 }))
    };
  }
  getCaretClientRect() {
    if (!this.index || !this.selection.caret)
      return null;
    const caret = this.selection.caret;
    const block = this.index.getBlock(caret.blockId);
    if (!block)
      return null;
    const local = caretRectFromCaret(block.layout, caret);
    if (!local)
      return null;
    const rotationRad = block.rotationDeg * Math.PI / 180;
    const toCanvas = (pt) => {
      if (rotationRad === 0) {
        return { x: block.layout.x + pt.x, y: block.layout.y + pt.y };
      }
      const cos3 = Math.cos(rotationRad);
      const sin3 = Math.sin(rotationRad);
      return {
        x: block.layout.x + pt.x * cos3 - pt.y * sin3,
        y: block.layout.y + pt.x * sin3 + pt.y * cos3
      };
    };
    const p1 = toCanvas({ x: local.x, y: local.y });
    const p2 = toCanvas({ x: local.x, y: local.y + local.height });
    const left = Math.min(p1.x, p2.x);
    const top = Math.min(p1.y, p2.y);
    const width = Math.abs(p1.x - p2.x) || 1;
    const height = Math.abs(p1.y - p2.y) || local.height;
    if (this.snapshot?.canvasPointToClient) {
      const c1 = this.snapshot.canvasPointToClient({ x: left, y: top });
      return { left: c1.x, top: c1.y, width, height };
    }
    return { left, top, width, height };
  }
  focusTextarea() {
    this.bridge?.focus();
  }
  clampCaret(caret) {
    if (!this.index)
      return caret;
    const block = this.index.getBlock(caret.blockId);
    if (!block)
      return caret;
    return clampCaretToRun(caret, block);
  }
  moveHorizontal(delta, extend4) {
    if (!this.selection.caret || !this.index)
      return;
    const previousCaret = this.selection.caret;
    const next2 = delta < 0 ? this.stepLeft(previousCaret) : this.stepRight(previousCaret);
    this.updateSelectionAfterMove(next2, extend4, previousCaret);
    this.caretXGoal = null;
  }
  updateSelectionAfterMove(nextCaret, extend4, previousCaret) {
    this.selection.caret = nextCaret;
    if (!extend4) {
      this.selection.anchor = nextCaret;
      return;
    }
    if (!this.selection.anchor) {
      this.selection.anchor = previousCaret;
    }
  }
  moveVertical(delta, extend4) {
    if (!this.selection.caret || !this.index)
      return;
    const previousCaret = this.selection.caret;
    const block = this.index.getBlock(previousCaret.blockId);
    if (!block)
      return;
    const currentRect = caretRectFromCaret(block.layout, previousCaret);
    const xGoal = this.caretXGoal ?? (currentRect ? currentRect.x : lineStartX(block.layout, block.layout.lines[0]));
    const target = this.stepVertical(block.layout, previousCaret, delta, xGoal);
    this.updateSelectionAfterMove(target ?? previousCaret, extend4, previousCaret);
    this.caretXGoal = xGoal;
  }
  moveToLineBoundary(boundary, extend4) {
    if (!this.selection.caret || !this.index)
      return;
    const previousCaret = this.selection.caret;
    const block = this.index.getBlock(this.selection.caret.blockId);
    if (!block)
      return;
    const position3 = findSegmentForCaret(block.layout, this.selection.caret);
    if (!position3)
      return;
    const boundarySegment = boundary === "start" ? position3.line.segments[0] : position3.line.segments.at(-1);
    if (!boundarySegment)
      return;
    const nextCaret = {
      blockId: this.selection.caret.blockId,
      paraIndex: boundarySegment.paraIndex,
      runIndex: boundarySegment.runIndex,
      charIndex: boundary === "start" ? boundarySegment.charStart : boundarySegment.charEnd
    };
    this.updateSelectionAfterMove(nextCaret, extend4, previousCaret);
    this.caretXGoal = null;
  }
  selectAll() {
    if (!this.index)
      return;
    const blockId = this.selection.activeBlockId;
    if (!blockId)
      return;
    const block = this.index.getBlock(blockId);
    if (!block)
      return;
    const firstLine = block.layout.lines[0];
    const lastLine = block.layout.lines.at(-1);
    const firstSegment = firstLine?.segments[0];
    const lastSegment = lastLine?.segments.at(-1);
    if (!firstSegment || !lastSegment) {
      return;
    }
    this.selection.activeBlockId = blockId;
    this.selection.anchor = {
      blockId,
      paraIndex: firstSegment.paraIndex,
      runIndex: firstSegment.runIndex,
      charIndex: firstSegment.charStart
    };
    this.selection.caret = {
      blockId,
      paraIndex: lastSegment.paraIndex,
      runIndex: lastSegment.runIndex,
      charIndex: lastSegment.charEnd
    };
    this.caretXGoal = null;
  }
  stepVertical(layout2, caret, delta, xGoal) {
    const pos = findSegmentForCaret(layout2, caret);
    if (!pos)
      return null;
    let { lineIndex } = pos;
    lineIndex += delta;
    if (lineIndex < 0 || lineIndex >= layout2.lines.length)
      return caret;
    const targetLine = layout2.lines[lineIndex];
    if (!targetLine)
      return caret;
    return caretAtXInLine(layout2, targetLine, xGoal, caret.blockId);
  }
  stepRight(caret) {
    if (!this.index)
      return caret;
    const block = this.index.getBlock(caret.blockId);
    if (!block)
      return caret;
    const layout2 = block.layout;
    const pos = findSegmentForCaret(layout2, caret);
    if (!pos)
      return caret;
    const { line: line2, lineIndex, segment, segmentIndex } = pos;
    if (caret.charIndex < segment.charEnd) {
      return { ...caret, charIndex: caret.charIndex + 1 };
    }
    const nextSeg = line2.segments[segmentIndex + 1];
    if (nextSeg) {
      return {
        blockId: caret.blockId,
        paraIndex: nextSeg.paraIndex,
        runIndex: nextSeg.runIndex,
        charIndex: nextSeg.charStart
      };
    }
    const nextLine = layout2.lines[lineIndex + 1];
    if (nextLine) {
      const first = nextLine.segments[0];
      if (first) {
        return {
          blockId: caret.blockId,
          paraIndex: first.paraIndex,
          runIndex: first.runIndex,
          charIndex: first.charStart
        };
      }
    }
    return caret;
  }
  stepLeft(caret) {
    if (!this.index)
      return caret;
    const block = this.index.getBlock(caret.blockId);
    if (!block)
      return caret;
    const layout2 = block.layout;
    const pos = findSegmentForCaret(layout2, caret);
    if (!pos)
      return caret;
    const { line: line2, lineIndex, segment, segmentIndex } = pos;
    if (caret.charIndex > segment.charStart) {
      return { ...caret, charIndex: caret.charIndex - 1 };
    }
    const prevSeg = line2.segments[segmentIndex - 1];
    if (prevSeg) {
      const targetIndex = Math.max(prevSeg.charStart, prevSeg.charEnd - 1);
      return {
        blockId: caret.blockId,
        paraIndex: prevSeg.paraIndex,
        runIndex: prevSeg.runIndex,
        charIndex: targetIndex
      };
    }
    const prevLine = layout2.lines[lineIndex - 1];
    if (prevLine) {
      const last2 = prevLine.segments.at(-1);
      if (last2) {
        const targetIndex = Math.max(last2.charStart, last2.charEnd - 1);
        return {
          blockId: caret.blockId,
          paraIndex: last2.paraIndex,
          runIndex: last2.runIndex,
          charIndex: targetIndex
        };
      }
    }
    return caret;
  }
  deleteBackward() {
    if (!this.selection.caret || !this.index)
      return;
    if (this.selection.hasSelection()) {
      this.deleteSelection();
      return;
    }
    const caret = this.selection.caret;
    if (caret.charIndex === 0 && caret.runIndex === 0 && caret.paraIndex > 0 && this.adapter.mergeParagraphBackward) {
      const mergedCaret = this.adapter.mergeParagraphBackward(caret);
      if (mergedCaret) {
        this.selection.collapseTo(mergedCaret);
        return;
      }
    }
    const start = this.stepLeft(caret);
    if (!start)
      return;
    this.applyDelete(start, caret);
  }
  deleteForward() {
    if (!this.selection.caret || !this.index)
      return;
    if (this.selection.hasSelection()) {
      this.deleteSelection();
      return;
    }
    const end = this.stepRight(this.selection.caret);
    if (!end)
      return;
    this.applyDelete(this.selection.caret, end);
  }
  deleteSelection() {
    if (!this.selection.caret || !this.selection.anchor || !this.index)
      return;
    this.applyDelete(this.selection.anchor, this.selection.caret);
  }
  applyDelete(start, end) {
    if (!this.index)
      return;
    const [s, e] = compareCaretPositions(start, end) <= 0 ? [start, end] : [end, start];
    const block = this.index.getBlock(s.blockId);
    if (!block)
      return;
    const ranges = computeRanges(block.layout, s, e, (para, run) => block.getRunText?.(para, run));
    if (ranges.length === 0) {
      const mergedCaret = this.adapter.mergeParagraphBackward?.(e);
      if (mergedCaret) {
        this.selection.collapseTo(mergedCaret);
        return;
      }
    }
    for (const r of ranges) {
      this.adapter.deleteRange(block.id, r.paraIndex, r.runIndex, r.start, r.end);
    }
    this.selection.collapseTo(s);
    this.caretXGoal = null;
  }
  splitParagraph() {
    if (!this.selection.caret)
      return;
    const nextCaret = this.adapter.splitParagraph(this.selection.caret);
    this.selection.collapseTo(nextCaret);
    this.caretXGoal = null;
  }
  insertText(text8) {
    if (!this.selection.caret || !this.index)
      return;
    if (this.selection.hasSelection()) {
      this.deleteSelection();
    }
    const caret = this.selection.caret;
    this.adapter.insertText(caret, text8);
    const advanceBy = splitGraphemes(text8).length;
    const nextCaret = { ...caret, charIndex: caret.charIndex + advanceBy };
    this.selection.collapseTo(nextCaret);
    this.caretXGoal = null;
  }
  selectWordAtCaret(caret) {
    if (!this.index)
      return false;
    const block = this.index.getBlock(caret.blockId);
    if (!block)
      return false;
    const position3 = findSegmentForCaret(block.layout, caret);
    if (!position3)
      return false;
    const { segment } = position3;
    const runText = block.getRunText?.(segment.paraIndex, segment.runIndex) ?? segment.text;
    const bounds = getTokenBounds(runText, caret.charIndex);
    if (!bounds)
      return false;
    this.selection.activeBlockId = caret.blockId;
    this.selection.anchor = {
      blockId: caret.blockId,
      paraIndex: segment.paraIndex,
      runIndex: segment.runIndex,
      charIndex: bounds.start
    };
    this.selection.caret = {
      blockId: caret.blockId,
      paraIndex: segment.paraIndex,
      runIndex: segment.runIndex,
      charIndex: bounds.end
    };
    this.caretXGoal = null;
    this.focusTextarea();
    this.syncTextareaPosition();
    return true;
  }
  selectParagraphAtCaret(caret) {
    if (!this.index)
      return false;
    const block = this.index.getBlock(caret.blockId);
    if (!block)
      return false;
    let firstSegment = null;
    let lastSegment = null;
    for (const line2 of block.layout.lines) {
      for (const segment of line2.segments) {
        if (segment.paraIndex !== caret.paraIndex) {
          continue;
        }
        firstSegment ??= segment;
        lastSegment = segment;
      }
    }
    if (!firstSegment || !lastSegment) {
      return false;
    }
    this.selection.activeBlockId = caret.blockId;
    this.selection.anchor = {
      blockId: caret.blockId,
      paraIndex: firstSegment.paraIndex,
      runIndex: firstSegment.runIndex,
      charIndex: firstSegment.charStart
    };
    this.selection.caret = {
      blockId: caret.blockId,
      paraIndex: lastSegment.paraIndex,
      runIndex: lastSegment.runIndex,
      charIndex: lastSegment.charEnd
    };
    this.caretXGoal = null;
    this.focusTextarea();
    this.syncTextareaPosition();
    return true;
  }
  syncTextareaPosition() {
    if (!this.bridge)
      return;
    const caretRect = this.getCaretClientRect();
    if (caretRect) {
      this.bridge.setAnchorRect({
        x: caretRect.left,
        y: caretRect.top,
        width: caretRect.width,
        height: caretRect.height
      });
    }
  }
}
function caretAtXInLine(layout2, line2, xGoal, blockId) {
  const start = lineStartX(layout2, line2);
  let cursorX = start;
  for (const seg of line2.segments) {
    const segEndX = cursorX + seg.widthPx;
    if (xGoal <= segEndX) {
      const localX = Math.max(0, xGoal - cursorX);
      const charIndex = seg.charStart + measureIndex(seg, localX);
      return {
        blockId,
        paraIndex: seg.paraIndex,
        runIndex: seg.runIndex,
        charIndex
      };
    }
    cursorX += seg.widthPx;
  }
  const segments = line2.segments;
  const lastIndex = segments.length - 1;
  if (lastIndex < 0) {
    return {
      blockId,
      paraIndex: 0,
      runIndex: 0,
      charIndex: 0
    };
  }
  const last2 = segments[lastIndex];
  if (!last2) {
    return {
      blockId,
      paraIndex: 0,
      runIndex: 0,
      charIndex: 0
    };
  }
  return {
    blockId,
    paraIndex: last2.paraIndex,
    runIndex: last2.runIndex,
    charIndex: last2.charEnd
  };
}
function measureIndex(seg, x2) {
  if (!seg)
    return 0;
  const adv = seg.advance;
  let lo = 0;
  let hi = adv.length - 1;
  while (lo < hi) {
    const mid = lo + hi >>> 1;
    const midValue = adv[mid] ?? 0;
    if (midValue < x2)
      lo = mid + 1;
    else
      hi = mid;
  }
  const i = lo;
  const left = adv[i - 1] ?? 0;
  const right = adv[i] ?? 0;
  const choosePrev = x2 < left + (right - left) / 2;
  const localIndex = choosePrev ? i - 1 : i;
  const maxIdx = Math.max(0, Math.min(seg.charEnd - seg.charStart, localIndex));
  return maxIdx;
}
function compareCaretPositions(a, b) {
  if (a.blockId !== b.blockId)
    return a.blockId.localeCompare(b.blockId);
  if (a.paraIndex !== b.paraIndex)
    return a.paraIndex - b.paraIndex;
  if (a.runIndex !== b.runIndex)
    return a.runIndex - b.runIndex;
  return a.charIndex - b.charIndex;
}
function getTokenBounds(text8, charIndex) {
  const graphemes = splitGraphemes(text8);
  if (graphemes.length === 0) {
    return null;
  }
  let probeIndex = Math.max(0, Math.min(charIndex, graphemes.length - 1));
  const probeGrapheme = graphemes[probeIndex];
  if (!probeGrapheme) {
    return null;
  }
  if (charIndex > 0 && charIndex < graphemes.length && classifyTokenGrapheme(probeGrapheme) === "whitespace") {
    probeIndex = Math.max(0, charIndex - 1);
  }
  const targetGrapheme = graphemes[probeIndex];
  if (!targetGrapheme) {
    return null;
  }
  const targetType = classifyTokenGrapheme(targetGrapheme);
  let start = probeIndex;
  let end = probeIndex + 1;
  while (start > 0 && graphemes[start - 1] != null && classifyTokenGrapheme(graphemes[start - 1]) === targetType) {
    start -= 1;
  }
  while (end < graphemes.length && graphemes[end] != null && classifyTokenGrapheme(graphemes[end]) === targetType) {
    end += 1;
  }
  return { start, end };
}
function classifyTokenGrapheme(value2) {
  if (/^\s$/u.test(value2)) {
    return "whitespace";
  }
  if (/^[\p{L}\p{N}_]$/u.test(value2)) {
    return "word";
  }
  return "punctuation";
}

// node_modules/@oai/granola/dist/text-edit/browser/hidden-textarea-bridge.js
class HiddenTextareaBridge {
  textarea;
  disposed = false;
  container;
  opts;
  constructor(opts = {}) {
    const container = opts.container;
    if (!container) {
      throw new Error("HiddenTextareaBridge requires a container element");
    }
    const doc2 = container.ownerDocument;
    this.opts = opts;
    this.container = container;
    this.textarea = doc2.createElement("textarea");
    this.configureStyles();
    this.attach();
  }
  focus() {
    if (this.disposed)
      return;
    this.textarea.focus({ preventScroll: true });
  }
  blur() {
    if (this.disposed)
      return;
    this.textarea.blur();
  }
  setAnchorRect(rect) {
    if (this.disposed)
      return;
    const w = rect.width ?? 1;
    const h = rect.height ?? 16;
    this.textarea.style.left = `${rect.x}px`;
    this.textarea.style.top = `${rect.y}px`;
    this.textarea.style.width = `${Math.max(1, w)}px`;
    this.textarea.style.height = `${Math.max(1, h)}px`;
  }
  dispose() {
    if (this.disposed)
      return;
    this.disposed = true;
    this.detach();
    this.textarea.remove();
  }
  attach() {
    this.container.appendChild(this.textarea);
    this.textarea.addEventListener("beforeinput", (e) => {
      this.opts.onBeforeInput?.(e);
    });
    this.textarea.addEventListener("input", (e) => {
      this.opts.onInput?.(e);
      this.textarea.value = "";
    });
    this.textarea.addEventListener("keydown", (e) => {
      this.opts.onKeyDown?.(e);
    });
    this.textarea.addEventListener("compositionstart", (e) => {
      this.opts.onCompositionStart?.(e);
    });
    this.textarea.addEventListener("compositionupdate", (e) => {
      this.opts.onCompositionUpdate?.(e);
    });
    this.textarea.addEventListener("compositionend", (e) => {
      this.opts.onCompositionEnd?.(e);
      this.textarea.value = "";
    });
    this.textarea.addEventListener("copy", (e) => {
      this.opts.onCopy?.(e);
    });
    this.textarea.addEventListener("cut", (e) => {
      this.opts.onCut?.(e);
    });
    this.textarea.addEventListener("paste", (e) => {
      this.opts.onPaste?.(e);
    });
  }
  detach() {
    this.textarea.remove();
  }
  configureStyles() {
    const style2 = this.textarea.style;
    style2.position = "absolute";
    style2.opacity = "0";
    style2.pointerEvents = "none";
    style2.zIndex = "1";
    style2.fontSize = "16px";
    style2.lineHeight = "20px";
    style2.width = "1px";
    style2.height = "1px";
    style2.resize = "none";
    style2.overflow = "hidden";
    style2.padding = "0";
    style2.margin = "0";
    style2.border = "0";
    style2.outline = "none";
    style2.transform = "translate3d(0,0,0)";
    this.textarea.setAttribute("autocomplete", "off");
    this.textarea.setAttribute("autocorrect", "off");
    this.textarea.setAttribute("autocapitalize", "off");
    this.textarea.setAttribute("spellcheck", "false");
    this.textarea.setAttribute("aria-hidden", "true");
  }
}

// oai_js_artifact_tool/extensions/utils.ts
import fs2 from "node:fs/promises";

class FileBlob {
  data;
  mime;
  constructor(data2, mime) {
    this.data = data2;
    this.mime = mime;
  }
  static async load(path4) {
    const data2 = await fs2.readFile(path4);
    const extension2 = path4.split(".").pop() || "";
    const mime = fileExtensions.get(extension2);
    return new FileBlob(data2, mime);
  }
  async save(path4) {
    await fs2.writeFile(path4, this.data);
  }
}
var fileExtensions = new Map([
  ["png", "image/png"],
  ["jpg", "image/jpeg"],
  ["jpeg", "image/jpeg"],
  ["webp", "image/webp"],
  ["svg", "image/svg+xml"],
  ["gif", "image/gif"],
  ["bmp", "image/bmp"],
  ["tiff", "image/tiff"],
  ["ico", "image/x-icon"],
  ["pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"],
  ["xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
  ["docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
  ["pdf", "application/pdf"],
  ["txt", "text/plain"],
  ["csv", "text/csv"],
  ["json", "application/json"],
  ["xml", "application/xml"],
  ["html", "text/html"],
  ["css", "text/css"],
  ["js", "application/javascript"],
  ["ts", "application/typescript"],
  ["jsx", "application/javascript"],
  ["tsx", "application/typescript"],
  ["md", "text/markdown"],
  ["yml", "text/yaml"],
  ["yaml", "text/yaml"],
  ["toml", "text/toml"]
]);
// oai_js_artifact_tool/extensions/presentation.ts
class PresentationFile {
  static async importPptx(file2) {
    let fileBytes;
    if (file2 instanceof FileBlob) {
      fileBytes = file2.data;
    } else {
      fileBytes = new Uint8Array(file2);
    }
    const walnut = await loadWalnut();
    const protoBytes = walnut.PptxReader.ExtractSlidesProto(fileBytes);
    const presentationProto = Presentation.decode(protoBytes);
    return Presentation2.load(presentationProto);
  }
  static async exportPptx(presentation2) {
    const walnut = await loadWalnut();
    const presentationProto = presentation2.toProto();
    const presentationBytes = Presentation.encode(presentationProto).finish();
    return new FileBlob(new Uint8Array(walnut.PptxExport.ExportProtoToPptx(presentationBytes)), fileExtensions.get("pptx"));
  }
}
// oai_js_artifact_tool/extensions/spreadsheet.ts
class SpreadsheetFile {
  static async importXlsx(file2) {
    let fileBytes;
    if (file2 instanceof FileBlob) {
      fileBytes = file2.data;
    } else {
      fileBytes = new Uint8Array(file2);
    }
    const walnut = await loadWalnut();
    const protoBytes = walnut.XlsxReader.ExtractXlsxProto(fileBytes);
    const workbookProto = Workbook.decode(protoBytes);
    return Workbook2.load(workbookProto);
  }
  static async exportXlsx(workbook) {
    const walnut = await loadWalnut();
    const workbookProto = workbook.toProto();
    const workbookBytes = Workbook.encode(workbookProto).finish();
    return new FileBlob(new Uint8Array(walnut.XlsxExport.ExportProtoToXlsx(workbookBytes)), fileExtensions.get("xlsx"));
  }
}
// rpc_server/registry.ts
import { Buffer as Buffer3 } from "node:buffer";

// rpc_server/generated/registry.ts
var classes = {
  AutoLayout,
  AnnotationTarget: AnnotationTarget3,
  Comment: Comment2,
  Comments,
  PeopleCollection,
  Person: Person2,
  Thread: Thread2,
  ThreadsCollection,
  DefinedNames: DefinedNames2,
  DocumentModel,
  Note: Note2,
  NotesCollection,
  PivotCacheDefinition,
  PivotDataHierarchy,
  PivotDataHierarchyCollection,
  PivotField: PivotField2,
  PivotFieldCollection,
  PivotHierarchy,
  PivotHierarchyCollection,
  PivotItem,
  PivotItemCollection,
  PivotLayout,
  PivotTable: PivotTable2,
  PivotTableCollection,
  PresentationCell: Cell2,
  Tables,
  PresentationTheme: Theme2,
  SlideBackground,
  BoundingBox: BoundingBox2,
  CStarMini,
  ChartCollection,
  ChartElementCollection,
  ChartAreaOptions,
  ChartAxisTitle,
  ChartAxis,
  ChartBarOptions,
  ChartBoxWhiskerOptions,
  ChartDataTable,
  ChartDataLabels,
  ChartDoughnutOptions,
  ChartFunnelOptions,
  ChartLegend,
  ChartLineOptions,
  ChartMapOptions,
  ChartPieOptions,
  ChartScatterOptions,
  ChartSeries,
  ChartSeriesCollection,
  ChartSeriesDataLabelOverride,
  ChartSeriesDataLabelOverrideCollection,
  ChartSeriesMarker,
  ChartSeriesPoint,
  ChartSeriesPointCollection,
  ChartErrorBars,
  ChartStyleOptions,
  ChartTreemapOptions,
  ChartTrendlineLabel,
  ChartTrendline,
  ChartTrendlineCollection,
  ChartView3d,
  Chart: Chart2,
  CitationsCollection,
  Citation,
  Color: Color4,
  SlideComposeThemeFacade,
  Element: Element2,
  ElementsCollection,
  Fill: Fill2,
  GoogleSlidesAdapter,
  FetchGoogleSlidesClient,
  GapiGoogleSlidesClient,
  Image: Image2,
  ImageCollection,
  ImageElementCollection,
  Layout: Layout2,
  LayoutCollection,
  Line: Line4,
  Masters,
  ParagraphCollection,
  Paragraph: Paragraph2,
  Pattern,
  PlaceholderCollection,
  Position,
  Presentation: Presentation2,
  PresentationAwarenessState,
  Scripts,
  ShapeCollection,
  ShapePlaceholder,
  SlideCollection,
  Slide: Slide2,
  SpeakerNotes,
  Style,
  StylesCollection,
  TableBorders,
  TableCellRange,
  TableColumn: TableColumn2,
  TableColumns,
  TextRunCollection,
  TextRun: TextRun2,
  Text,
  TextRange,
  TextStyle: TextStyle2,
  Range,
  RangeFormat,
  Row: Row2,
  ShowAs,
  Slicer: Slicer2,
  SlicerCollection,
  CellStore,
  Cell: Cell3,
  ConditionalFormat,
  WorksheetConditionalFormattingCollection,
  RangeConditionalFormats,
  WorksheetDataValidationCollection,
  RangeDataValidation,
  WorksheetDataTableCollection,
  WorksheetChartOfficeCompat,
  WorksheetChartCollection,
  WorksheetShapeCollection,
  WorksheetImage,
  WorksheetImageCollection,
  WorksheetDrawingCollection,
  SpillManager,
  GoogleSheetsAdapter,
  FetchGoogleSheetsClient,
  GapiGoogleSheetsClient,
  WorkbookRecorder,
  SparklineAxis,
  SparklineGroupCollection,
  SparklineMarkers,
  SparklinePreview,
  SparklineGroup: SparklineGroup2,
  StyleRegistry,
  TextStyleModel,
  BorderLineModel,
  BorderModel,
  WorkbookAwarenessState,
  WorksheetFreezePanes,
  Worksheet,
  WorksheetCells,
  WorksheetCollection,
  PivotCacheIndex,
  PivotSourceTable,
  Table: Table3,
  TableRowCollection,
  TableCollection,
  Theme: Theme3,
  Workbook: Workbook2,
  GeometryHitTester,
  InMemoryEngineEventBus,
  InputController,
  SelectionTool,
  FontMetricsProvider,
  SpreadsheetKeyboardEventBus,
  TextLayoutIndex,
  TextSelectionModel,
  TextOverlayPainter,
  TextEditController,
  HiddenTextareaBridge,
  WorksheetChart,
  Shape: Shape2,
  PresentationTable: Table2,
  ChartElement,
  ImageElement: ImageElement2,
  NullWorksheet,
  NullTable,
  WorksheetShape,
  PresentationFile,
  SpreadsheetFile
};

// rpc_server/spreadsheet_realtime_session.ts
import { Buffer as Buffer2 } from "node:buffer";

// node_modules/y-protocols/sync.js
var messageYjsUpdate = 2;
var writeUpdate = (encoder, update) => {
  writeVarUint(encoder, messageYjsUpdate);
  writeVarUint8Array(encoder, update);
};

// rpc_server/spreadsheet_realtime_session.ts
var messageSync = 0;

class SpreadsheetRealtimeSession {
  workbook;
  #doc;
  #backendOrigin = { source: "artifact-tool-realtime-backend" };
  #activeDispatch = null;
  constructor(workbook) {
    this.workbook = workbook;
    this.#doc = this.workbook.getCrdtDoc();
    this.#doc.on("update", (update, origin) => {
      if (origin === this.#backendOrigin) {
        return;
      }
      this.#queueBroadcast(this.#encodeSyncUpdate(update));
    });
  }
  static createEmpty() {
    return new SpreadsheetRealtimeSession(Workbook2.create());
  }
  static async fromXlsx(file2) {
    const walnut = await loadWalnut();
    const protoBytes = walnut.XlsxReader.ExtractXlsxProto(new Uint8Array(file2));
    const workbookProto = Workbook.decode(protoBytes);
    const workbook = Workbook2.load(workbookProto);
    workbook.hydrateCrdtFromProto();
    workbook.__flushPendingCollaborativePublishes();
    return new SpreadsheetRealtimeSession(workbook);
  }
  static fromProtoAndYdocBase64(protoBase64, ydocBase64) {
    const workbookProto = Workbook.decode(Buffer2.from(protoBase64, "base64"));
    const workbook = Workbook2.load(workbookProto);
    const ydocState = new Uint8Array(Buffer2.from(ydocBase64, "base64"));
    workbook.loadInitialCrdtStateV2(ydocState, { recalculate: true });
    workbook.__flushPendingCollaborativePublishes();
    return new SpreadsheetRealtimeSession(workbook);
  }
  static getWorkbookProtoBase64(workbook) {
    const workbookProto = workbook.toProto();
    return Buffer2.from(Workbook.encode(workbookProto).finish()).toString("base64");
  }
  static getWorkbookCrdtStateUpdateV2(workbook) {
    return encodeStateAsUpdateV2(workbook.getCrdtDoc());
  }
  getSummary() {
    return {
      worksheetCount: this.workbook.worksheets.items.length,
      worksheetNames: this.workbook.worksheets.items.map((sheet) => sheet.name)
    };
  }
  getCrdtStateUpdateV2() {
    return encodeStateAsUpdateV2(this.#doc);
  }
  #coerceUint8Array(payload) {
    return payload instanceof Uint8Array ? payload : new Uint8Array(payload);
  }
  #decodeBase64Payload(payloadBase64) {
    return new Uint8Array(Buffer2.from(payloadBase64, "base64"));
  }
  applyToolCrdtUpdateV2(update) {
    return this.#runWithDispatch(() => {
      const normalizedUpdate = this.#coerceUint8Array(update);
      this.workbook.applyCrdtUpdateV2(normalizedUpdate, { recalculate: true });
    });
  }
  applyToolCrdtUpdateV2Base64(updateBase64) {
    return this.applyToolCrdtUpdateV2(this.#decodeBase64Payload(updateBase64));
  }
  #runWithDispatch(fn) {
    if (this.#activeDispatch) {
      throw new Error("Nested realtime dispatch is not supported.");
    }
    const dispatch = {
      broadcastPayloads: [],
      directPayloads: []
    };
    this.#activeDispatch = dispatch;
    try {
      fn();
      return dispatch;
    } finally {
      this.#activeDispatch = null;
    }
  }
  #queueBroadcast(payload) {
    if (!this.#activeDispatch) {
      throw new Error("No active realtime dispatch for broadcast payload.");
    }
    this.#activeDispatch.broadcastPayloads.push(payload);
  }
  #encodeSyncUpdate(update) {
    const encoder = createEncoder();
    writeVarUint(encoder, messageSync);
    writeUpdate(encoder, update);
    return toUint8Array(encoder);
  }
}

// rpc_server/registry.ts
classes["Workbook"].fromProtoAndYdocBase64 = (protoBase64, ydocBase64) => {
  const workbookProto = Workbook.decode(Buffer3.from(protoBase64, "base64"));
  const workbook = classes["Workbook"].load(workbookProto);
  const ydocState = new Uint8Array(Buffer3.from(ydocBase64, "base64"));
  workbook.loadInitialCrdtStateV2(ydocState, { recalculate: true });
  return workbook;
};
var classes2 = {
  ...classes,
  SpreadsheetRealtimeSession
};
var classNamesByCtor = new Map;
for (const [name2, ctor] of Object.entries(classes2)) {
  classNamesByCtor.set(ctor, name2);
}
function lookupClassName(obj) {
  const ctor = obj?.constructor;
  if (!ctor)
    return;
  return classNamesByCtor.get(ctor);
}

// rpc_server/dispatcher.ts
var objects = new Map;
var artifactContextByObjectId = new Map;
var artifactContextByRoot = new WeakMap;
var artifactHandleByRoot = new WeakMap;
var lastArtifactHandleByClass = new Map;
var lastArtifactHandle;
var nextId = 1;
var RPC_DATE_KEY = "__rpcDate";
function isArtifactClassName(name2) {
  return name2 === "Presentation" || name2 === "Workbook";
}
function normalizeClassName(name2) {
  if (!name2)
    return;
  return name2.replace(/^_/, "").replace(/\d+$/, "");
}
function resolveStableClassName(obj, className) {
  if (className)
    return className;
  return lookupClassName(obj) ?? normalizeClassName(obj?.constructor?.name);
}
function artifactContextForObjectId(objectId) {
  return artifactContextByObjectId.get(objectId);
}
function getOrCreateArtifactContext(artifact, classHint) {
  if (!artifact || typeof artifact !== "object") {
    return;
  }
  const className = resolveStableClassName(artifact, classHint);
  if (!isArtifactClassName(className)) {
    return;
  }
  const existing = artifactContextByRoot.get(artifact);
  if (existing) {
    return existing;
  }
  const context = {
    artifact,
    artifactClass: className
  };
  artifactContextByRoot.set(artifact, context);
  return context;
}
function findArtifactContextInValue(value2) {
  if (!value2 || typeof value2 !== "object") {
    return;
  }
  if (Array.isArray(value2)) {
    for (const item of value2) {
      const context = findArtifactContextInValue(item);
      if (context)
        return context;
    }
    return;
  }
  const record2 = value2;
  const keys2 = Object.keys(record2);
  const isRefOnly = "$ref" in record2 && keys2.length === 1;
  if (isRefOnly && typeof record2["$ref"] === "string") {
    return artifactContextByObjectId.get(record2["$ref"]);
  }
  for (const child of Object.values(record2)) {
    const context = findArtifactContextInValue(child);
    if (context)
      return context;
  }
  return;
}
function artifactContextForArgs(args2) {
  return findArtifactContextInValue(args2);
}
function normalizeCrdtUpdateV2(value2) {
  if (value2 instanceof Uint8Array) {
    return value2;
  }
  if (value2 instanceof ArrayBuffer) {
    return new Uint8Array(value2);
  }
  if (ArrayBuffer.isView(value2)) {
    return new Uint8Array(value2.buffer, value2.byteOffset, value2.byteLength);
  }
  return;
}
function isRecordableArtifact(value2) {
  return !!value2 && typeof value2 === "object" && "record" in value2 && typeof value2.record === "function";
}
async function recordWithArtifact(context, fn) {
  if (!context || !isRecordableArtifact(context.artifact)) {
    return { result: await fn(), operations: [] };
  }
  const recorded = context.artifact.record(() => fn());
  return {
    result: await recorded.result,
    operations: recorded.patch,
    crdtUpdateV2: normalizeCrdtUpdateV2(recorded.crdtUpdateV2)
  };
}
function registerArtifactHandle(context, handle2) {
  artifactHandleByRoot.set(context.artifact, handle2);
  lastArtifactHandleByClass.set(context.artifactClass, handle2);
  lastArtifactHandle = handle2;
}
function resolveArtifactHandle(context, serialized, preferredClass) {
  const fallbackClass = preferredClass ?? context?.artifactClass;
  if (context) {
    const handle3 = artifactHandleByRoot.get(context.artifact);
    if (handle3)
      return handle3;
  }
  if (isObjectHandle(serialized) && isArtifactClassName(serialized.class)) {
    if (context) {
      registerArtifactHandle(context, serialized);
    } else {
      lastArtifactHandleByClass.set(serialized.class, serialized);
      lastArtifactHandle = serialized;
    }
    return serialized;
  }
  if (context) {
    const handle3 = makeHandle(context.artifact, context.artifactClass);
    registerArtifactHandle(context, handle3);
    artifactContextByObjectId.set(handle3.objectId, context);
    return handle3;
  }
  if (fallbackClass) {
    const handle3 = lastArtifactHandleByClass.get(fallbackClass);
    if (handle3)
      return handle3;
  }
  if (lastArtifactHandle) {
    return lastArtifactHandle;
  }
  const handle2 = makeHandle({ _unknownArtifact: true }, fallbackClass ?? "Artifact");
  if (fallbackClass) {
    lastArtifactHandleByClass.set(fallbackClass, handle2);
  }
  lastArtifactHandle = handle2;
  return handle2;
}
function isObjectHandle(value2) {
  return !!value2 && typeof value2 === "object" && "objectId" in value2 && typeof value2.objectId === "string";
}
function isPlainObject4(value2) {
  if (!value2 || typeof value2 !== "object") {
    return false;
  }
  const proto = Object.getPrototypeOf(value2);
  return proto === Object.prototype || proto === null;
}
function associateSerializedResultWithArtifact(value2, context) {
  if (!context)
    return;
  if (Array.isArray(value2)) {
    for (const item of value2) {
      associateSerializedResultWithArtifact(item, context);
    }
    return;
  }
  if (isObjectHandle(value2)) {
    artifactContextByObjectId.set(value2.objectId, context);
    return;
  }
  if (value2 && typeof value2 === "object") {
    for (const child of Object.values(value2)) {
      associateSerializedResultWithArtifact(child, context);
    }
  }
}
function resolveResultContext(result, baseContext, resolver2) {
  return resolver2?.(result) ?? getOrCreateArtifactContext(result) ?? baseContext;
}
async function dispatchFromInvocation(context, fn, contextForResult, options = {}) {
  const invocation = options.record === false ? { result: await fn(), operations: [] } : await recordWithArtifact(context, fn);
  const { result, operations, crdtUpdateV2 } = invocation;
  const resolvedContext = resolveResultContext(result, context, contextForResult);
  const serialized = await serializeResult(result);
  if (resolvedContext && result === resolvedContext.artifact && isObjectHandle(serialized)) {
    registerArtifactHandle(resolvedContext, serialized);
  }
  const artifactHandle = resolveArtifactHandle(resolvedContext, serialized, resolvedContext?.artifactClass);
  associateSerializedResultWithArtifact(serialized, resolvedContext);
  return {
    result: serialized,
    operations: {
      artifactHandle,
      operations,
      ...crdtUpdateV2 ? {
        crdtUpdateV2: Buffer4.from(crdtUpdateV2.buffer, crdtUpdateV2.byteOffset, crdtUpdateV2.byteLength).toString("base64")
      } : {}
    }
  };
}
async function dispatchFromValue(context, value2) {
  const serialized = await serializeResult(value2);
  return dispatchFromSerializedValue(context, serialized);
}
function dispatchFromSerializedValue(context, serialized) {
  const artifactHandle = resolveArtifactHandle(context, serialized, context?.artifactClass);
  associateSerializedResultWithArtifact(serialized, context);
  return { result: serialized, operations: { artifactHandle, operations: [] } };
}
async function snapshotValue(value2, options) {
  const depth = options.depth ?? 0;
  const seen = options.seen ?? new WeakSet;
  if (depth >= options.maxDepth) {
    return serializeResult(value2);
  }
  if (Array.isArray(value2)) {
    return Promise.all(value2.map((item) => snapshotValue(item, {
      maxDepth: options.maxDepth,
      depth: depth + 1,
      seen
    })));
  }
  if (!value2 || typeof value2 !== "object") {
    return serializeResult(value2);
  }
  if (!isPlainObject4(value2)) {
    return serializeResult(value2);
  }
  if (seen.has(value2)) {
    return { __cycle: true };
  }
  seen.add(value2);
  const out = {};
  for (const [key, child] of Object.entries(value2)) {
    out[key] = await snapshotValue(child, {
      maxDepth: options.maxDepth,
      depth: depth + 1,
      seen
    });
  }
  return out;
}
function artifactCreateOperation(artifactClass) {
  if (artifactClass === "Presentation") {
    return { op: "presentation.create" };
  }
  return { op: "workbook.create" };
}
async function dispatchArtifactCreate(artifactClass, fn) {
  const result = await fn();
  const context = getOrCreateArtifactContext(result, artifactClass);
  const serialized = await serializeResult(result);
  if (context && result === context.artifact && isObjectHandle(serialized)) {
    registerArtifactHandle(context, serialized);
  }
  const artifactHandle = resolveArtifactHandle(context, serialized, artifactClass);
  associateSerializedResultWithArtifact(serialized, context);
  return {
    result: serialized,
    operations: {
      artifactHandle,
      operations: [artifactCreateOperation(artifactClass)]
    }
  };
}
function makeHandle(obj, className) {
  const id2 = `obj_${nextId++}`;
  objects.set(id2, obj);
  const stableName = resolveStableClassName(obj, className);
  return { objectId: id2, class: stableName };
}
function resolveValue(v) {
  if (Array.isArray(v)) {
    return v.map(resolveValue);
  }
  if (v && typeof v === "object") {
    if (v.__rpcUndefined === true && Object.keys(v).length === 1) {
      return;
    }
    if (typeof v[RPC_DATE_KEY] === "string" && Object.keys(v).length === 1) {
      const parsed = new Date(v[RPC_DATE_KEY]);
      if (Number.isNaN(parsed.getTime())) {
        throw new Error(`Invalid RPC datetime payload: ${v[RPC_DATE_KEY]}`);
      }
      return parsed;
    }
    if (v.__blob && typeof v.data === "string") {
      const buffer = Buffer4.from(v.data, "base64");
      return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
    }
    const keys2 = Object.keys(v);
    const isRefOnly = "$ref" in v && keys2.length === 1;
    if (isRefOnly) {
      const obj = objects.get(v.$ref);
      if (!obj) {
        throw new Error(`Invalid object reference ${v.$ref}`);
      }
      return obj;
    }
    const out = {};
    for (const key of keys2) {
      out[key] = resolveValue(v[key]);
    }
    return out;
  }
  return v;
}
function resolveArgs(args2) {
  return args2.map(resolveValue);
}
async function serializeResult(result) {
  if (Array.isArray(result)) {
    return Promise.all(result.map(serializeResult));
  }
  if (result instanceof Date) {
    return { [RPC_DATE_KEY]: result.toISOString() };
  }
  if (typeof Blob !== "undefined" && result instanceof Blob) {
    const arrayBuffer = await result.arrayBuffer();
    return {
      __blob: true,
      mime: result.type || undefined,
      data: Buffer4.from(arrayBuffer).toString("base64")
    };
  }
  if (result instanceof ArrayBuffer) {
    return {
      __blob: true,
      mime: undefined,
      data: Buffer4.from(result).toString("base64")
    };
  }
  if (ArrayBuffer.isView(result)) {
    return {
      __blob: true,
      mime: undefined,
      data: Buffer4.from(result.buffer, result.byteOffset, result.byteLength).toString("base64")
    };
  }
  if (result instanceof FileBlob) {
    return {
      __blob: true,
      mime: result.mime,
      data: Buffer4.from(result.data).toString("base64")
    };
  }
  if (typeof result === "object" && result !== null) {
    return makeHandle(result);
  }
  return result;
}
function _debugGetObjects() {
  return Array.from(objects.entries()).map(([id2, obj]) => ({
    id: id2,
    class: obj?.constructor?.name,
    obj
  }));
}
async function dispatch(dispatchArgs) {
  const { method, params: params2 } = dispatchArgs;
  switch (method) {
    case "construct": {
      const { class: className, args: args2 = [] } = params2;
      const Cls = classes2[className];
      if (!Cls)
        throw new Error(`Unknown class ${className}`);
      const artifactContext = artifactContextForArgs(args2);
      const resolvedArgs = resolveArgs(args2);
      return dispatchFromInvocation(artifactContext, () => new Cls(...resolvedArgs), (result) => getOrCreateArtifactContext(result, className));
    }
    case "call": {
      const { target, method: methodName, args: args2 = [] } = params2;
      const obj = objects.get(target);
      if (!obj)
        throw new Error(`Invalid object ${target}`);
      const fn = obj[methodName];
      if (typeof fn !== "function") {
        throw new Error(`Method ${methodName} not found`);
      }
      const artifactContext = artifactContextForObjectId(target);
      const resolvedArgs = resolveArgs(args2);
      return dispatchFromInvocation(artifactContext, () => fn.apply(obj, resolvedArgs), undefined, {
        record: !["loadInitialCrdtStateV2", "applyCrdtUpdateV2"].includes(methodName)
      });
    }
    case "callStatic": {
      const { class: className, method: methodName, args: args2 = [] } = params2;
      const Cls = classes2[className];
      if (!Cls)
        throw new Error(`Unknown class ${className}`);
      const fn = Cls[methodName];
      if (typeof fn !== "function") {
        throw new Error(`Static method ${methodName} not found`);
      }
      const resolvedArgs = resolveArgs(args2);
      if (methodName === "create" && isArtifactClassName(className)) {
        return dispatchArtifactCreate(className, () => fn(...resolvedArgs));
      }
      const artifactContext = artifactContextForArgs(args2);
      return dispatchFromInvocation(artifactContext, () => fn(...resolvedArgs), (result) => getOrCreateArtifactContext(result));
    }
    case "getAttr": {
      const { target, attr } = params2;
      const obj = objects.get(target);
      if (!obj)
        throw new Error(`Invalid object ${target}`);
      const value2 = obj[attr];
      const artifactContext = artifactContextForObjectId(target);
      return dispatchFromValue(artifactContext, value2);
    }
    case "setAttr": {
      const { target, attr, value: value2 } = params2;
      const obj = objects.get(target);
      if (!obj)
        throw new Error(`Invalid object ${target}`);
      const artifactContext = artifactContextForObjectId(target);
      const resolved = resolveValue(value2);
      let proto = obj;
      while (proto) {
        const desc = Object.getOwnPropertyDescriptor(proto, attr);
        if (desc) {
          if (typeof desc.set === "function") {
            const descSet = desc.set;
            return dispatchFromInvocation(artifactContext, () => descSet.call(obj, resolved));
          }
          if ("writable" in desc && desc.writable) {
            return dispatchFromInvocation(artifactContext, () => {
              obj[attr] = resolved;
            });
          }
        }
        proto = Object.getPrototypeOf(proto);
      }
      if (isPlainObject4(obj) && Object.isExtensible(obj)) {
        return dispatchFromInvocation(artifactContext, () => {
          obj[attr] = resolved;
        });
      }
      throw new Error(`Attribute ${String(attr)} is not settable`);
    }
    case "snapshot": {
      const { target, maxDepth } = params2;
      const obj = objects.get(target);
      if (!obj)
        throw new Error(`Invalid object ${target}`);
      const artifactContext = artifactContextForObjectId(target);
      const normalizedMaxDepth = typeof maxDepth === "number" && Number.isFinite(maxDepth) ? Math.max(1, Math.floor(maxDepth)) : 8;
      const serialized = await snapshotValue(obj, { maxDepth: normalizedMaxDepth });
      return dispatchFromSerializedValue(artifactContext, serialized);
    }
    case "dispose": {
      const { target } = params2;
      const artifactContext = artifactContextForObjectId(target);
      objects.delete(target);
      artifactContextByObjectId.delete(target);
      return dispatchFromValue(artifactContext, true);
    }
    default:
      throw new Error(`Unknown RPC method ${method}`);
  }
}

// rpc_server/daemon.ts
var setup = () => {
  installPresetShapeDefinitions();
  installWorkbookExport();
  installWorkbookHelp({ language: "python" });
};
setup();
var ARTIFACT_TOOL_RPC_SOCKET = process.env["ARTIFACT_TOOL_RPC_SOCKET"];
if (!ARTIFACT_TOOL_RPC_SOCKET) {
  throw new Error("ARTIFACT_TOOL_RPC_SOCKET is not set");
}
var ARTIFACT_TOOL_RPC_READY_FILE = process.env["ARTIFACT_TOOL_RPC_READY_FILE"];
var tcpMatch = /^tcp:\/\/([^:]+):(\d+)$/.exec(ARTIFACT_TOOL_RPC_SOCKET);
var DEBUG2 = process.env["DEBUG"] === "true" || process.env["DEBUG"] === "1";
var MONITOR_INTERVAL_MS = 60000;
var REQUEST_TIMEOUT_MS = process.env["REQUEST_TIMEOUT_MS"] ? Number(process.env["REQUEST_TIMEOUT_MS"]) : null;
function serializeError(err) {
  return {
    name: err.name || "Error",
    message: err.message || String(err),
    stack: err.stack || null,
    code: err.code || "JS_ERROR"
  };
}
function withTimeout(promise2, label) {
  if (REQUEST_TIMEOUT_MS === null || !Number.isFinite(REQUEST_TIMEOUT_MS) || REQUEST_TIMEOUT_MS <= 0) {
    return promise2;
  }
  return new Promise((resolve2, reject) => {
    const timer = setTimeout(() => {
      reject(new Error(`RPC timeout after ${REQUEST_TIMEOUT_MS}ms (${label})`));
    }, REQUEST_TIMEOUT_MS);
    promise2.then((result) => {
      clearTimeout(timer);
      resolve2(result);
    }).catch((err) => {
      clearTimeout(timer);
      reject(err);
    });
  });
}
if (tcpMatch == null && fs3.existsSync(ARTIFACT_TOOL_RPC_SOCKET)) {
  fs3.unlinkSync(ARTIFACT_TOOL_RPC_SOCKET);
}
var server = net.createServer((socket) => {
  let buffer = "";
  socket.on("data", async (chunk) => {
    buffer += chunk.toString("utf8");
    let idx;
    while ((idx = buffer.indexOf(`
`)) >= 0) {
      const line2 = buffer.slice(0, idx);
      buffer = buffer.slice(idx + 1);
      if (!line2.trim())
        continue;
      let msg;
      try {
        msg = JSON.parse(line2);
      } catch (e) {
        const response = {
          jsonrpc: "2.0",
          error: { code: -32700, message: "Parse error" },
          id: null
        };
        if (DEBUG2) {
          console.error("<xx", response);
        }
        socket.write(JSON.stringify(response) + `
`);
        continue;
      }
      if (DEBUG2) {
        console.log("-->", msg);
      }
      const { id: id2, method, params: params2 } = msg;
      try {
        const dispatchArgs = { method, params: params2 };
        const { result, operations } = await withTimeout(dispatch(dispatchArgs), method);
        const response = {
          jsonrpc: "2.0",
          id: id2,
          result,
          operations
        };
        if (DEBUG2) {
          console.log("<--", response);
        }
        socket.write(JSON.stringify(response) + `
`);
      } catch (err) {
        const response = {
          jsonrpc: "2.0",
          id: id2,
          error: {
            code: -32000,
            message: "Server error",
            data: serializeError(err)
          }
        };
        if (DEBUG2) {
          console.error("<xx", response);
        }
        socket.write(JSON.stringify(response) + `
`);
      }
    }
  });
});
if (DEBUG2) {
  const monitor = setInterval(() => {
    const objects2 = _debugGetObjects();
    const summary = objects2.map((o) => `${o.id}:${o.class ?? "Unknown"}`).join(", ");
    console.debug(`[rpc-monitor] ${objects2.length} objects`, summary);
  }, MONITOR_INTERVAL_MS);
  monitor.unref?.();
}
var listenTarget = tcpMatch == null ? [ARTIFACT_TOOL_RPC_SOCKET] : [Number(tcpMatch[2]), tcpMatch[1]];
server.listen(...listenTarget, () => {
  let actualSocket = ARTIFACT_TOOL_RPC_SOCKET;
  if (tcpMatch != null) {
    const address = server.address();
    if (address == null || typeof address === "string" || typeof address.port !== "number") {
      throw new Error("Could not resolve TCP daemon address");
    }
    actualSocket = `tcp://${tcpMatch[1]}:${address.port}`;
  }
  if (ARTIFACT_TOOL_RPC_READY_FILE) {
    fs3.writeFileSync(ARTIFACT_TOOL_RPC_READY_FILE, actualSocket);
  }
  if (DEBUG2) {
    console.debug(`JSON-RPC daemon listening on ${actualSocket}`);
    console.debug("DEBUG mode is enabled");
  }
});
